#define DEBUG using System; using System.Buffers; using System.Buffers.Binary; using System.Buffers.Text; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Configuration.Assemblies; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Diagnostics.Tracing; using System.Globalization; using System.IO; using System.IO.Enumeration; using System.IO.Strategies; using System.Numerics; using System.Private.CoreLib; using System.Reflection; using System.Reflection.Emit; using System.Reflection.Metadata; using System.Resources; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.Arm; using System.Runtime.Intrinsics.X86; using System.Runtime.Loader; using System.Runtime.Remoting; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Security.Principal; using System.StubHelpers; using System.Text; using System.Text.Unicode; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Sources; using Internal; using Internal.Runtime.CompilerServices; using Internal.Win32; using Internal.Win32.SafeHandles; using Microsoft.CodeAnalysis; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: MetadataUpdateHandler(typeof(RuntimeTypeMetadataUpdateHandler))] [assembly: CLSCompliant(true)] [assembly: ComVisible(false)] [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)] [assembly: AssemblyMetadata("Serviceable", "True")] [assembly: AssemblyMetadata(".NETFrameworkAssembly", "")] [assembly: AssemblyMetadata("IsTrimmable", "True")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")] [assembly: AssemblyDescription("System.Private.CoreLib")] [assembly: AssemblyFileVersion("6.0.722.32202")] [assembly: AssemblyInformationalVersion("6.0.7+0ec02c8c96e2eda06dc5b5edfdbdba0f36415082")] [assembly: AssemblyProduct("Microsoft® .NET")] [assembly: AssemblyTitle("System.Private.CoreLib")] [assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")] [assembly: AssemblyVersion("6.0.0.0")] [module: NullablePublicOnly(false)] [module: SkipLocalsInit] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class NullablePublicOnlyAttribute : Attribute { public readonly bool IncludesInternals; public NullablePublicOnlyAttribute(bool P_0) { IncludesInternals = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.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; } } } internal static class Interop { internal static class OleAut32 { [DllImport("oleaut32.dll")] internal static extern void VariantClear(IntPtr variant); [DllImport("oleaut32.dll")] internal static extern IntPtr SysAllocStringByteLen(byte[] str, uint len); [DllImport("oleaut32.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr SysAllocStringLen(IntPtr src, uint len); [DllImport("oleaut32.dll")] internal static extern void SysFreeString(IntPtr bstr); } internal static class Globalization { internal enum ResultCode { Success, UnknownError, InsufficentBuffer, OutOfMemory } [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetCalendars")] internal static extern int GetCalendars(string localeName, CalendarId[] calendars, int calendarsCapacity); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetCalendarInfo")] internal unsafe static extern ResultCode GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType calendarDataType, char* result, int resultCapacity); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_EnumCalendarInfo")] internal unsafe static extern bool EnumCalendarInfo(delegate* unmanaged callback, string localeName, CalendarId calendarId, CalendarDataType calendarDataType, IntPtr context); [DllImport("System.Globalization.Native", EntryPoint = "GlobalizationNative_GetLatestJapaneseEra")] internal static extern int GetLatestJapaneseEra(); [DllImport("System.Globalization.Native", EntryPoint = "GlobalizationNative_GetJapaneseEraStartDate")] internal static extern bool GetJapaneseEraStartDate(int era, out int startYear, out int startMonth, out int startDay); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ChangeCase")] internal unsafe static extern void ChangeCase(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ChangeCaseInvariant")] internal unsafe static extern void ChangeCaseInvariant(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ChangeCaseTurkish")] internal unsafe static extern void ChangeCaseTurkish(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_InitOrdinalCasingPage")] internal unsafe static extern void InitOrdinalCasingPage(int pageNumber, char* pTarget); [DllImport("System.Globalization.Native", CharSet = CharSet.Ansi, EntryPoint = "GlobalizationNative_GetSortHandle")] internal static extern ResultCode GetSortHandle(string localeName, out IntPtr sortHandle); [DllImport("System.Globalization.Native", EntryPoint = "GlobalizationNative_CloseSortHandle")] internal static extern void CloseSortHandle(IntPtr handle); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_CompareString")] internal unsafe static extern int CompareString(IntPtr sortHandle, char* lpStr1, int cwStr1Len, char* lpStr2, int cwStr2Len, CompareOptions options); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IndexOf")] internal unsafe static extern int IndexOf(IntPtr sortHandle, char* target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options, int* matchLengthPtr); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_LastIndexOf")] internal unsafe static extern int LastIndexOf(IntPtr sortHandle, char* target, int cwTargetLength, char* pSource, int cwSourceLength, CompareOptions options, int* matchLengthPtr); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_StartsWith")] [return: MarshalAs(UnmanagedType.Bool)] internal unsafe static extern bool StartsWith(IntPtr sortHandle, char* target, int cwTargetLength, char* source, int cwSourceLength, CompareOptions options, int* matchedLength); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_EndsWith")] [return: MarshalAs(UnmanagedType.Bool)] internal unsafe static extern bool EndsWith(IntPtr sortHandle, char* target, int cwTargetLength, char* source, int cwSourceLength, CompareOptions options, int* matchedLength); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetSortKey")] internal unsafe static extern int GetSortKey(IntPtr sortHandle, char* str, int strLength, byte* sortKey, int sortKeyLength, CompareOptions options); [DllImport("System.Globalization.Native", EntryPoint = "GlobalizationNative_GetSortVersion")] internal static extern int GetSortVersion(IntPtr sortHandle); [DllImport("System.Globalization.Native", EntryPoint = "GlobalizationNative_LoadICU")] internal static extern int LoadICU(); internal static void InitICUFunctions(IntPtr icuuc, IntPtr icuin, ReadOnlySpan version, ReadOnlySpan suffix) { InitICUFunctions(icuuc, icuin, version.ToString(), (suffix.Length > 0) ? suffix.ToString() : null); } [DllImport("System.Globalization.Native", EntryPoint = "GlobalizationNative_InitICUFunctions")] internal static extern void InitICUFunctions(IntPtr icuuc, IntPtr icuin, string version, string suffix); [DllImport("System.Globalization.Native", EntryPoint = "GlobalizationNative_GetICUVersion")] internal static extern int GetICUVersion(); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ToAscii")] internal unsafe static extern int ToAscii(uint flags, char* src, int srcLen, char* dstBuffer, int dstBufferCapacity); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ToUnicode")] internal unsafe static extern int ToUnicode(uint flags, char* src, int srcLen, char* dstBuffer, int dstBufferCapacity); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleName")] [return: MarshalAs(UnmanagedType.Bool)] internal unsafe static extern bool GetLocaleName(string localeName, char* value, int valueLength); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleInfoString")] [return: MarshalAs(UnmanagedType.Bool)] internal unsafe static extern bool GetLocaleInfoString(string localeName, uint localeStringData, char* value, int valueLength, string uiLocaleName = null); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IsPredefinedLocale")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool IsPredefinedLocale(string localeName); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleTimeFormat")] [return: MarshalAs(UnmanagedType.Bool)] internal unsafe static extern bool GetLocaleTimeFormat(string localeName, bool shortFormat, char* value, int valueLength); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleInfoInt")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetLocaleInfoInt(string localeName, uint localeNumberData, ref int value); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleInfoGroupingSizes")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetLocaleInfoGroupingSizes(string localeName, uint localeGroupingData, ref int primaryGroupSize, ref int secondaryGroupSize); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocales")] internal static extern int GetLocales([Out] char[] value, int valueLength); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IsNormalized")] internal unsafe static extern int IsNormalized(NormalizationForm normalizationForm, char* src, int srcLen); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_NormalizeString")] internal unsafe static extern int NormalizeString(NormalizationForm normalizationForm, char* src, int srcLen, char* dstBuffer, int dstBufferCapacity); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_WindowsIdToIanaId")] internal unsafe static extern int WindowsIdToIanaId(string windowsId, IntPtr region, char* ianaId, int ianaIdLength); [DllImport("System.Globalization.Native", CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IanaIdToWindowsId")] internal unsafe static extern int IanaIdToWindowsId(string ianaId, char* windowsId, int windowsIdLength); } internal enum BOOL { FALSE, TRUE } internal static class Kernel32 { internal struct NlsVersionInfoEx { internal int dwNLSVersionInfoSize; internal int dwNLSVersion; internal int dwDefinedVersion; internal int dwEffectiveId; internal Guid guidCustomVersion; } internal struct CONDITION_VARIABLE { private IntPtr Ptr; } internal struct CRITICAL_SECTION { private IntPtr DebugInfo; private int LockCount; private int RecursionCount; private IntPtr OwningThread; private IntPtr LockSemaphore; private UIntPtr SpinCount; } internal struct FILE_BASIC_INFO { internal long CreationTime; internal long LastAccessTime; internal long LastWriteTime; internal long ChangeTime; internal uint FileAttributes; } internal struct FILE_ALLOCATION_INFO { internal long AllocationSize; } internal struct FILE_END_OF_FILE_INFO { internal long EndOfFile; } internal struct FILE_STANDARD_INFO { internal long AllocationSize; internal long EndOfFile; internal uint NumberOfLinks; internal BOOL DeletePending; internal BOOL Directory; } internal struct FILE_TIME { internal uint dwLowDateTime; internal uint dwHighDateTime; internal long ToTicks() { return (long)(((ulong)dwHighDateTime << 32) + dwLowDateTime); } internal DateTimeOffset ToDateTimeOffset() { return DateTimeOffset.FromFileTime(ToTicks()); } } internal enum FINDEX_INFO_LEVELS : uint { FindExInfoStandard, FindExInfoBasic, FindExInfoMaxInfoLevel } internal enum FINDEX_SEARCH_OPS : uint { FindExSearchNameMatch, FindExSearchLimitToDirectories, FindExSearchLimitToDevices, FindExSearchMaxSearchOp } internal enum GET_FILEEX_INFO_LEVELS : uint { GetFileExInfoStandard, GetFileExMaxInfoLevel } internal struct CPINFO { internal int MaxCharSize; internal unsafe fixed byte DefaultChar[2]; internal unsafe fixed byte LeadByte[12]; } internal struct PROCESS_MEMORY_COUNTERS { public uint cb; public uint PageFaultCount; public UIntPtr PeakWorkingSetSize; public UIntPtr WorkingSetSize; public UIntPtr QuotaPeakPagedPoolUsage; public UIntPtr QuotaPagedPoolUsage; public UIntPtr QuotaPeakNonPagedPoolUsage; public UIntPtr QuotaNonPagedPoolUsage; public UIntPtr PagefileUsage; public UIntPtr PeakPagefileUsage; } internal struct MEMORY_BASIC_INFORMATION { internal unsafe void* BaseAddress; internal unsafe void* AllocationBase; internal uint AllocationProtect; internal UIntPtr RegionSize; internal uint State; internal uint Protect; internal uint Type; } internal struct MEMORYSTATUSEX { internal uint dwLength; internal uint dwMemoryLoad; internal ulong ullTotalPhys; internal ulong ullAvailPhys; internal ulong ullTotalPageFile; internal ulong ullAvailPageFile; internal ulong ullTotalVirtual; internal ulong ullAvailVirtual; internal ulong ullAvailExtendedVirtual; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct OSVERSIONINFOEX { public int dwOSVersionInfoSize; public int dwMajorVersion; public int dwMinorVersion; public int dwBuildNumber; public int dwPlatformId; public unsafe fixed char szCSDVersion[128]; public ushort wServicePackMajor; public ushort wServicePackMinor; public ushort wSuiteMask; public byte wProductType; public byte wReserved; } internal struct SymbolicLinkReparseBuffer { internal uint ReparseTag; internal ushort ReparseDataLength; internal ushort Reserved; internal ushort SubstituteNameOffset; internal ushort SubstituteNameLength; internal ushort PrintNameOffset; internal ushort PrintNameLength; internal uint Flags; } internal struct MountPointReparseBuffer { public uint ReparseTag; public ushort ReparseDataLength; public ushort Reserved; public ushort SubstituteNameOffset; public ushort SubstituteNameLength; public ushort PrintNameOffset; public ushort PrintNameLength; } internal struct SECURITY_ATTRIBUTES { internal uint nLength; internal IntPtr lpSecurityDescriptor; internal BOOL bInheritHandle; } internal struct SYSTEM_INFO { internal ushort wProcessorArchitecture; internal ushort wReserved; internal int dwPageSize; internal IntPtr lpMinimumApplicationAddress; internal IntPtr lpMaximumApplicationAddress; internal IntPtr dwActiveProcessorMask; internal int dwNumberOfProcessors; internal int dwProcessorType; internal int dwAllocationGranularity; internal short wProcessorLevel; internal short wProcessorRevision; } internal struct SYSTEMTIME { internal ushort Year; internal ushort Month; internal ushort DayOfWeek; internal ushort Day; internal ushort Hour; internal ushort Minute; internal ushort Second; internal ushort Milliseconds; internal bool Equals(in SYSTEMTIME other) { if (Year == other.Year && Month == other.Month && DayOfWeek == other.DayOfWeek && Day == other.Day && Hour == other.Hour && Minute == other.Minute && Second == other.Second) { return Milliseconds == other.Milliseconds; } return false; } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct TIME_DYNAMIC_ZONE_INFORMATION { internal int Bias; internal unsafe fixed char StandardName[32]; internal SYSTEMTIME StandardDate; internal int StandardBias; internal unsafe fixed char DaylightName[32]; internal SYSTEMTIME DaylightDate; internal int DaylightBias; internal unsafe fixed char TimeZoneKeyName[128]; internal byte DynamicDaylightTimeDisabled; internal unsafe string GetTimeZoneKeyName() { fixed (char* value = TimeZoneKeyName) { return new string(value); } } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct TIME_ZONE_INFORMATION { internal int Bias; internal unsafe fixed char StandardName[32]; internal SYSTEMTIME StandardDate; internal int StandardBias; internal unsafe fixed char DaylightName[32]; internal SYSTEMTIME DaylightDate; internal int DaylightBias; internal unsafe TIME_ZONE_INFORMATION(in TIME_DYNAMIC_ZONE_INFORMATION dtzi) { fixed (TIME_ZONE_INFORMATION* ptr = &this) { fixed (TIME_DYNAMIC_ZONE_INFORMATION* ptr2 = &dtzi) { *ptr = *(TIME_ZONE_INFORMATION*)ptr2; } } } internal unsafe string GetStandardName() { fixed (char* value = StandardName) { return new string(value); } } internal unsafe string GetDaylightName() { fixed (char* value = DaylightName) { return new string(value); } } } internal struct REG_TZI_FORMAT { internal int Bias; internal int StandardBias; internal int DaylightBias; internal SYSTEMTIME StandardDate; internal SYSTEMTIME DaylightDate; internal REG_TZI_FORMAT(in TIME_ZONE_INFORMATION tzi) { Bias = tzi.Bias; StandardDate = tzi.StandardDate; StandardBias = tzi.StandardBias; DaylightDate = tzi.DaylightDate; DaylightBias = tzi.DaylightBias; } } internal struct WIN32_FILE_ATTRIBUTE_DATA { internal int dwFileAttributes; internal FILE_TIME ftCreationTime; internal FILE_TIME ftLastAccessTime; internal FILE_TIME ftLastWriteTime; internal uint nFileSizeHigh; internal uint nFileSizeLow; internal void PopulateFrom(ref WIN32_FIND_DATA findData) { dwFileAttributes = (int)findData.dwFileAttributes; ftCreationTime = findData.ftCreationTime; ftLastAccessTime = findData.ftLastAccessTime; ftLastWriteTime = findData.ftLastWriteTime; nFileSizeHigh = findData.nFileSizeHigh; nFileSizeLow = findData.nFileSizeLow; } } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct WIN32_FIND_DATA { internal uint dwFileAttributes; internal FILE_TIME ftCreationTime; internal FILE_TIME ftLastAccessTime; internal FILE_TIME ftLastWriteTime; internal uint nFileSizeHigh; internal uint nFileSizeLow; internal uint dwReserved0; internal uint dwReserved1; private unsafe fixed char _cFileName[260]; private unsafe fixed char _cAlternateFileName[14]; internal unsafe ReadOnlySpan cFileName { get { fixed (char* pointer = _cFileName) { return new ReadOnlySpan(pointer, 260); } } } } [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal unsafe static extern int LCIDToLocaleName(int locale, char* pLocaleName, int cchName, uint dwFlags); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern int LocaleNameToLCID(string lpName, uint dwFlags); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal unsafe static extern int LCMapStringEx(string lpLocaleName, uint dwMapFlags, char* lpSrcStr, int cchSrc, void* lpDestStr, int cchDest, void* lpVersionInformation, void* lpReserved, IntPtr sortHandle); [DllImport("kernel32.dll")] internal unsafe static extern int FindNLSStringEx(char* lpLocaleName, uint dwFindNLSStringFlags, char* lpStringSource, int cchSource, char* lpStringValue, int cchValue, int* pcchFound, void* lpVersionInformation, void* lpReserved, IntPtr sortHandle); [DllImport("kernel32.dll")] internal unsafe static extern int CompareStringEx(char* lpLocaleName, uint dwCmpFlags, char* lpString1, int cchCount1, char* lpString2, int cchCount2, void* lpVersionInformation, void* lpReserved, IntPtr lParam); [DllImport("kernel32.dll")] internal unsafe static extern int CompareStringOrdinal(char* lpString1, int cchCount1, char* lpString2, int cchCount2, bool bIgnoreCase); [DllImport("kernel32.dll")] internal unsafe static extern int FindStringOrdinal(uint dwFindStringOrdinalFlags, char* lpStringSource, int cchSource, char* lpStringValue, int cchValue, BOOL bIgnoreCase); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal unsafe static extern bool IsNLSDefinedString(int Function, uint dwFlags, IntPtr lpVersionInformation, char* lpString, int cchStr); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] internal unsafe static extern BOOL GetUserPreferredUILanguages(uint dwFlags, uint* pulNumLanguages, char* pwszLanguagesBuffer, uint* pcchLanguagesBuffer); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal unsafe static extern int GetLocaleInfoEx(string lpLocaleName, uint LCType, void* lpLCData, int cchData); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal unsafe static extern bool EnumSystemLocalesEx(delegate* unmanaged lpLocaleEnumProcEx, uint dwFlags, void* lParam, IntPtr reserved); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal unsafe static extern bool EnumTimeFormatsEx(delegate* unmanaged lpTimeFmtEnumProcEx, string lpLocaleName, uint dwFlags, void* lParam); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, out int lpValue); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern int GetCalendarInfoEx(string lpLocaleName, uint Calendar, IntPtr lpReserved, uint CalType, IntPtr lpCalData, int cchData, IntPtr lpValue); [DllImport("kernel32.dll")] internal static extern int GetUserGeoID(int geoClass); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal unsafe static extern int GetGeoInfo(int location, int geoType, char* lpGeoData, int cchData, int LangId); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal unsafe static extern bool EnumCalendarInfoExEx(delegate* unmanaged pCalInfoEnumProcExEx, string lpLocaleName, uint Calendar, string lpReserved, uint CalType, void* lParam); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal unsafe static extern bool GetNLSVersionEx(int function, string localeName, NlsVersionInfoEx* lpVersionInformation); [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal unsafe static extern int ResolveLocaleName(string lpNameToResolve, char* lpLocaleName, int cchLocaleName); [DllImport("kernel32.dll", SetLastError = true)] internal unsafe static extern bool CancelIoEx(SafeHandle handle, NativeOverlapped* lpOverlapped); [DllImport("kernel32.dll", SetLastError = true)] internal static extern IntPtr CreateIoCompletionPort(IntPtr FileHandle, IntPtr ExistingCompletionPort, UIntPtr CompletionKey, int NumberOfConcurrentThreads); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool PostQueuedCompletionStatus(IntPtr CompletionPort, int dwNumberOfBytesTransferred, UIntPtr CompletionKey, IntPtr lpOverlapped); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetQueuedCompletionStatus(IntPtr CompletionPort, out int lpNumberOfBytes, out UIntPtr CompletionKey, out IntPtr lpOverlapped, int dwMilliseconds); [DllImport("kernel32.dll", ExactSpelling = true)] internal unsafe static extern void InitializeConditionVariable(CONDITION_VARIABLE* ConditionVariable); [DllImport("kernel32.dll", ExactSpelling = true)] internal unsafe static extern void WakeConditionVariable(CONDITION_VARIABLE* ConditionVariable); [DllImport("kernel32.dll", ExactSpelling = true)] internal unsafe static extern bool SleepConditionVariableCS(CONDITION_VARIABLE* ConditionVariable, CRITICAL_SECTION* CriticalSection, int dwMilliseconds); internal static int CopyFile(string src, string dst, bool failIfExists) { int flags = (failIfExists ? 1 : 0); int cancel = 0; if (!CopyFileEx(src, dst, IntPtr.Zero, IntPtr.Zero, ref cancel, flags)) { return Marshal.GetLastWin32Error(); } return 0; } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CopyFileExW", SetLastError = true)] private static extern bool CopyFileExPrivate(string src, string dst, IntPtr progressRoutine, IntPtr progressData, ref int cancel, int flags); internal static bool CopyFileEx(string src, string dst, IntPtr progressRoutine, IntPtr progressData, ref int cancel, int flags) { src = PathInternal.EnsureExtendedPrefixIfNeeded(src); dst = PathInternal.EnsureExtendedPrefixIfNeeded(dst); return CopyFileExPrivate(src, dst, progressRoutine, progressData, ref cancel, flags); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateDirectoryW", SetLastError = true)] private static extern bool CreateDirectoryPrivate(string path, ref SECURITY_ATTRIBUTES lpSecurityAttributes); internal static bool CreateDirectory(string path, ref SECURITY_ATTRIBUTES lpSecurityAttributes) { path = PathInternal.EnsureExtendedPrefix(path); return CreateDirectoryPrivate(path, ref lpSecurityAttributes); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateFileW", ExactSpelling = true, SetLastError = true)] private unsafe static extern SafeFileHandle CreateFilePrivate(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES* lpSecurityAttributes, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); internal unsafe static SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES* lpSecurityAttributes, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile) { lpFileName = PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName); return CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile); } internal unsafe static SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition, int dwFlagsAndAttributes) { lpFileName = PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName); return CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, null, dwCreationDisposition, dwFlagsAndAttributes, IntPtr.Zero); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "DeleteFileW", SetLastError = true)] private static extern bool DeleteFilePrivate(string path); internal static bool DeleteFile(string path) { path = PathInternal.EnsureExtendedPrefixIfNeeded(path); return DeleteFilePrivate(path); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "DeleteVolumeMountPointW", SetLastError = true)] internal static extern bool DeleteVolumeMountPointPrivate(string mountPoint); internal static bool DeleteVolumeMountPoint(string mountPoint) { mountPoint = PathInternal.EnsureExtendedPrefixIfNeeded(mountPoint); return DeleteVolumeMountPointPrivate(mountPoint); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateFileW", ExactSpelling = true, SetLastError = true)] private unsafe static extern IntPtr CreateFilePrivate_IntPtr(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES* lpSecurityAttributes, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); internal unsafe static IntPtr CreateFile_IntPtr(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition, int dwFlagsAndAttributes) { lpFileName = PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName); return CreateFilePrivate_IntPtr(lpFileName, dwDesiredAccess, dwShareMode, null, dwCreationDisposition, dwFlagsAndAttributes, IntPtr.Zero); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateSymbolicLinkW", ExactSpelling = true, SetLastError = true)] private static extern bool CreateSymbolicLinkPrivate(string lpSymlinkFileName, string lpTargetFileName, int dwFlags); internal static void CreateSymbolicLink(string symlinkFileName, string targetFileName, bool isDirectory) { string path = symlinkFileName; symlinkFileName = PathInternal.EnsureExtendedPrefixIfNeeded(symlinkFileName); targetFileName = PathInternal.EnsureExtendedPrefixIfNeeded(targetFileName); int num = 0; bool flag = (Environment.OSVersion.Version.Major == 10 && Environment.OSVersion.Version.Build >= 14972) || Environment.OSVersion.Version.Major >= 11; if (flag) { num = 2; } if (isDirectory) { num |= 1; } if (!CreateSymbolicLinkPrivate(symlinkFileName, targetFileName, num)) { throw Win32Marshal.GetExceptionForLastWin32Error(path); } int lastWin32Error; if (!flag && (lastWin32Error = Marshal.GetLastWin32Error()) != 0) { throw Win32Marshal.GetExceptionForWin32Error(lastWin32Error, path); } } [DllImport("kernel32.dll", ExactSpelling = true)] internal unsafe static extern void InitializeCriticalSection(CRITICAL_SECTION* lpCriticalSection); [DllImport("kernel32.dll", ExactSpelling = true)] internal unsafe static extern void EnterCriticalSection(CRITICAL_SECTION* lpCriticalSection); [DllImport("kernel32.dll", ExactSpelling = true)] internal unsafe static extern void LeaveCriticalSection(CRITICAL_SECTION* lpCriticalSection); [DllImport("kernel32.dll", ExactSpelling = true)] internal unsafe static extern void DeleteCriticalSection(CRITICAL_SECTION* lpCriticalSection); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern bool DeviceIoControl(SafeHandle hDevice, uint dwIoControlCode, IntPtr lpInBuffer, uint nInBufferSize, byte[] lpOutBuffer, uint nOutBufferSize, out uint lpBytesReturned, IntPtr lpOverlapped); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "ExpandEnvironmentStringsW", ExactSpelling = true, SetLastError = true)] internal static extern uint ExpandEnvironmentStrings(string lpSrc, ref char lpDst, uint nSize); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "FindNextFileW", SetLastError = true)] internal static extern bool FindNextFile(SafeFindHandle hndFindFile, ref WIN32_FIND_DATA lpFindFileData); [DllImport("kernel32.dll")] [SuppressGCTransition] internal unsafe static extern BOOL FileTimeToSystemTime(ulong* lpFileTime, SYSTEMTIME* lpSystemTime); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool FindClose(IntPtr hFindFile); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "FindFirstFileExW", ExactSpelling = true, SetLastError = true)] private static extern SafeFindHandle FindFirstFileExPrivate(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, ref WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, int dwAdditionalFlags); internal static SafeFindHandle FindFirstFile(string fileName, ref WIN32_FIND_DATA data) { fileName = PathInternal.EnsureExtendedPrefixIfNeeded(fileName); return FindFirstFileExPrivate(fileName, FINDEX_INFO_LEVELS.FindExInfoBasic, ref data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, 0); } [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool FlushFileBuffers(SafeHandle hHandle); [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] internal static extern bool FreeLibrary(IntPtr hModule); [DllImport("kernel32.dll")] [SuppressGCTransition] internal static extern int GetLastError(); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetComputerNameW", ExactSpelling = true)] private static extern int GetComputerName(ref char lpBuffer, ref uint nSize); internal static string GetComputerName() { Span span = stackalloc char[16]; uint nSize = (uint)span.Length; if (GetComputerName(ref MemoryMarshal.GetReference(span), ref nSize) == 0) { return null; } return span.Slice(0, (int)nSize).ToString(); } [DllImport("kernel32.dll")] internal unsafe static extern BOOL GetCPInfo(uint codePage, CPINFO* lpCpInfo); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "GetCurrentDirectoryW", ExactSpelling = true, SetLastError = true)] internal static extern uint GetCurrentDirectory(uint nBufferLength, ref char lpBuffer); [DllImport("kernel32.dll")] internal static extern IntPtr GetCurrentProcess(); [DllImport("kernel32.dll")] internal static extern uint GetCurrentProcessId(); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetFileAttributesExW", ExactSpelling = true, SetLastError = true)] private static extern bool GetFileAttributesExPrivate(string name, GET_FILEEX_INFO_LEVELS fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation); internal static bool GetFileAttributesEx(string name, GET_FILEEX_INFO_LEVELS fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation) { name = PathInternal.EnsureExtendedPrefixIfNeeded(name); return GetFileAttributesExPrivate(name, fileInfoLevel, ref lpFileInformation); } [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] internal unsafe static extern bool GetFileInformationByHandleEx(SafeFileHandle hFile, int FileInformationClass, void* lpFileInformation, uint dwBufferSize); [DllImport("kernel32.dll", SetLastError = true)] internal static extern int GetFileType(SafeHandle hFile); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetFinalPathNameByHandleW", ExactSpelling = true, SetLastError = true)] internal unsafe static extern uint GetFinalPathNameByHandle(SafeFileHandle hFile, char* lpszFilePath, uint cchFilePath, uint dwFlags); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern uint GetFullPathNameW(ref char lpFileName, uint nBufferLength, ref char lpBuffer, IntPtr lpFilePart); [DllImport("kernel32.dll", SetLastError = true)] internal static extern int GetLogicalDrives(); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern uint GetLongPathNameW(ref char lpszShortPath, ref char lpszLongPath, uint cchBuffer); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetModuleFileNameW", ExactSpelling = true, SetLastError = true)] internal static extern uint GetModuleFileName(IntPtr hModule, ref char lpFilename, uint nSize); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal unsafe static extern bool GetOverlappedResult(SafeFileHandle hFile, NativeOverlapped* lpOverlapped, ref int lpNumberOfBytesTransferred, bool bWait); [DllImport("kernel32.dll", EntryPoint = "K32GetProcessMemoryInfo")] internal static extern bool GetProcessMemoryInfo(IntPtr Process, ref PROCESS_MEMORY_COUNTERS ppsmemCounters, uint cb); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool GetProcessTimes(IntPtr handleProcess, out long creation, out long exit, out long kernel, out long user); [DllImport("kernel32.dll")] [SuppressGCTransition] internal static extern IntPtr GetStdHandle(int nStdHandle); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern uint GetSystemDirectoryW(ref char lpBuffer, uint uSize); [DllImport("kernel32.dll")] internal static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo); [DllImport("kernel32.dll")] [SuppressGCTransition] internal unsafe static extern void GetSystemTime(SYSTEMTIME* lpSystemTime); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool GetSystemTimes(out long idle, out long kernel, out long user); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern uint GetTempFileNameW(ref char lpPathName, string lpPrefixString, uint uUnique, ref char lpTempFileName); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, ExactSpelling = true)] internal static extern uint GetTempPathW(int bufferLen, ref char buffer); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "GetVolumeInformationW", SetLastError = true)] internal unsafe static extern bool GetVolumeInformation(string drive, char* volumeName, int volumeNameBufLen, int* volSerialNumber, int* maxFileNameLen, out int fileSystemFlags, char* fileSystemName, int fileSystemNameBufLen); [DllImport("kernel32.dll")] internal unsafe static extern BOOL GlobalMemoryStatusEx(MEMORYSTATUSEX* lpBuffer); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool IsWow64Process(IntPtr hProcess, out bool Wow64Process); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "LoadLibraryExW", ExactSpelling = true, SetLastError = true)] internal static extern IntPtr LoadLibraryEx(string libFilename, IntPtr reserved, int flags); [DllImport("kernel32.dll")] internal static extern IntPtr LocalAlloc(uint uFlags, nuint uBytes); [DllImport("kernel32.dll")] internal static extern IntPtr LocalReAlloc(IntPtr hMem, nuint uBytes, uint uFlags); [DllImport("kernel32.dll")] internal static extern IntPtr LocalFree(IntPtr hMem); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool LockFile(SafeFileHandle handle, int offsetLow, int offsetHigh, int countLow, int countHigh); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool UnlockFile(SafeFileHandle handle, int offsetLow, int offsetHigh, int countLow, int countHigh); [DllImport("kernel32.dll")] internal unsafe static extern int MultiByteToWideChar(uint CodePage, uint dwFlags, byte* lpMultiByteStr, int cbMultiByte, char* lpWideCharStr, int cchWideChar); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "MoveFileExW", SetLastError = true)] private static extern bool MoveFileExPrivate(string src, string dst, uint flags); internal static bool MoveFile(string src, string dst, bool overwrite) { src = PathInternal.EnsureExtendedPrefixIfNeeded(src); dst = PathInternal.EnsureExtendedPrefixIfNeeded(dst); uint num = 2u; if (overwrite) { num |= 1u; } return MoveFileExPrivate(src, dst, num); } [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "OutputDebugStringW", ExactSpelling = true)] internal static extern void OutputDebugString(string message); [DllImport("kernel32.dll", ExactSpelling = true)] [SuppressGCTransition] internal unsafe static extern BOOL QueryPerformanceCounter(long* lpPerformanceCount); [DllImport("kernel32.dll", ExactSpelling = true)] internal unsafe static extern BOOL QueryPerformanceFrequency(long* lpFrequency); [DllImport("kernel32.dll")] internal static extern bool QueryUnbiasedInterruptTime(out ulong UnbiasedTime); [DllImport("kernel32.dll", SetLastError = true)] internal unsafe static extern int ReadFile(SafeHandle handle, byte* bytes, int numBytesToRead, IntPtr numBytesRead_mustBeZero, NativeOverlapped* overlapped); [DllImport("kernel32.dll", SetLastError = true)] internal unsafe static extern int ReadFile(SafeHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, NativeOverlapped* overlapped); [DllImport("kernel32.dll", SetLastError = true)] internal unsafe static extern int ReadFileScatter(SafeHandle hFile, long* aSegmentArray, int nNumberOfBytesToRead, IntPtr lpReserved, NativeOverlapped* lpOverlapped); [DllImport("kernel32.dll", SetLastError = true)] internal unsafe static extern int WriteFileGather(SafeHandle hFile, long* aSegmentArray, int nNumberOfBytesToWrite, IntPtr lpReserved, NativeOverlapped* lpOverlapped); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RemoveDirectoryW", SetLastError = true)] private static extern bool RemoveDirectoryPrivate(string path); internal static bool RemoveDirectory(string path) { path = PathInternal.EnsureExtendedPrefixIfNeeded(path); return RemoveDirectoryPrivate(path); } [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "ReplaceFileW", SetLastError = true)] private static extern bool ReplaceFilePrivate(string replacedFileName, string replacementFileName, string backupFileName, int dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved); internal static bool ReplaceFile(string replacedFileName, string replacementFileName, string backupFileName, int dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved) { replacedFileName = PathInternal.EnsureExtendedPrefixIfNeeded(replacedFileName); replacementFileName = PathInternal.EnsureExtendedPrefixIfNeeded(replacementFileName); backupFileName = PathInternal.EnsureExtendedPrefixIfNeeded(backupFileName); return ReplaceFilePrivate(replacedFileName, replacementFileName, backupFileName, dwReplaceFlags, lpExclude, lpReserved); } [DllImport("kernel32.dll", SetLastError = true)] internal unsafe static extern bool SetConsoleCtrlHandler(delegate* unmanaged HandlerRoutine, bool Add); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "SetCurrentDirectoryW", ExactSpelling = true, SetLastError = true)] internal static extern bool SetCurrentDirectory(string path); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "SetFileAttributesW", SetLastError = true)] private static extern bool SetFileAttributesPrivate(string name, int attr); internal static bool SetFileAttributes(string name, int attr) { name = PathInternal.EnsureExtendedPrefixIfNeeded(name); return SetFileAttributesPrivate(name, attr); } [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] internal unsafe static extern bool SetFileInformationByHandle(SafeFileHandle hFile, int FileInformationClass, void* lpFileInformation, uint dwBufferSize); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool SetFilePointerEx(SafeFileHandle hFile, long liDistanceToMove, out long lpNewFilePointer, uint dwMoveMethod); [DllImport("kernel32.dll")] [SuppressGCTransition] internal static extern void SetLastError(int errorCode); [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] [SuppressGCTransition] internal static extern bool SetThreadErrorMode(uint dwNewMode, out uint lpOldMode); [DllImport("kernel32.dll")] [SuppressGCTransition] internal unsafe static extern BOOL SystemTimeToFileTime(SYSTEMTIME* lpSystemTime, ulong* lpFileTime); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern uint GetDynamicTimeZoneInformation(out TIME_DYNAMIC_ZONE_INFORMATION pTimeZoneInformation); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern uint GetTimeZoneInformation(out TIME_ZONE_INFORMATION lpTimeZoneInformation); [DllImport("kernel32.dll")] internal unsafe static extern BOOL TzSpecificLocalTimeToSystemTime(IntPtr lpTimeZoneInformation, SYSTEMTIME* lpLocalTime, SYSTEMTIME* lpUniversalTime); [DllImport("kernel32.dll")] internal static extern bool VerifyVersionInfoW(ref OSVERSIONINFOEX lpVersionInfo, uint dwTypeMask, ulong dwlConditionMask); [DllImport("kernel32.dll")] internal static extern ulong VerSetConditionMask(ulong ConditionMask, uint TypeMask, byte Condition); [DllImport("kernel32.dll", ExactSpelling = true)] internal unsafe static extern void* VirtualAlloc(void* lpAddress, UIntPtr dwSize, int flAllocationType, int flProtect); [DllImport("kernel32.dll", ExactSpelling = true)] internal unsafe static extern bool VirtualFree(void* lpAddress, UIntPtr dwSize, int dwFreeType); [DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)] internal unsafe static extern UIntPtr VirtualQuery(void* lpAddress, ref MEMORY_BASIC_INFORMATION lpBuffer, UIntPtr dwLength); [DllImport("kernel32.dll")] internal unsafe static extern int WideCharToMultiByte(uint CodePage, uint dwFlags, char* lpWideCharStr, int cchWideChar, byte* lpMultiByteStr, int cbMultiByte, IntPtr lpDefaultChar, IntPtr lpUsedDefaultChar); [DllImport("kernel32.dll", SetLastError = true)] internal unsafe static extern int WriteFile(SafeHandle handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWritten_mustBeZero, NativeOverlapped* lpOverlapped); [DllImport("kernel32.dll", SetLastError = true)] internal unsafe static extern int WriteFile(SafeHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, NativeOverlapped* lpOverlapped); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool CloseHandle(IntPtr handle); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool SetEvent(SafeWaitHandle handle); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool ResetEvent(SafeWaitHandle handle); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "CreateEventExW", ExactSpelling = true, SetLastError = true)] internal static extern SafeWaitHandle CreateEventEx(IntPtr lpSecurityAttributes, string name, uint flags, uint desiredAccess); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "OpenEventW", ExactSpelling = true, SetLastError = true)] internal static extern SafeWaitHandle OpenEvent(uint desiredAccess, bool inheritHandle, string name); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetEnvironmentVariableW", ExactSpelling = true, SetLastError = true)] internal static extern uint GetEnvironmentVariable(string lpName, ref char lpBuffer, uint nSize); [DllImport("kernel32.dll", ExactSpelling = true)] internal unsafe static extern char* GetEnvironmentStringsW(); [DllImport("kernel32.dll", ExactSpelling = true)] internal unsafe static extern BOOL FreeEnvironmentStringsW(char* lpszEnvironmentBlock); [DllImport("kernel32.dll", BestFitMapping = true, CharSet = CharSet.Unicode, EntryPoint = "FormatMessageW", ExactSpelling = true, SetLastError = true)] private unsafe static extern int FormatMessage(int dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, void* lpBuffer, int nSize, IntPtr arguments); internal static string GetMessage(int errorCode) { return GetMessage(errorCode, IntPtr.Zero); } internal unsafe static string GetMessage(int errorCode, IntPtr moduleHandle) { int num = 12800; if (moduleHandle != IntPtr.Zero) { num |= 0x800; } Span span = stackalloc char[256]; fixed (char* lpBuffer = span) { int num2 = FormatMessage(num, moduleHandle, (uint)errorCode, 0, lpBuffer, span.Length, IntPtr.Zero); if (num2 > 0) { return GetAndTrimString(span.Slice(0, num2)); } } if (Marshal.GetLastWin32Error() == 122) { IntPtr intPtr = default(IntPtr); try { int num3 = FormatMessage(num | 0x100, moduleHandle, (uint)errorCode, 0, &intPtr, 0, IntPtr.Zero); if (num3 > 0) { return GetAndTrimString(new Span((void*)intPtr, num3)); } } finally { Marshal.FreeHGlobal(intPtr); } } return $"Unknown error (0x{errorCode:x})"; } private static string GetAndTrimString(Span buffer) { int num = buffer.Length; while (num > 0 && buffer[num - 1] <= ' ') { num--; } return buffer.Slice(0, num).ToString(); } [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "OpenMutexW", ExactSpelling = true, SetLastError = true)] internal static extern SafeWaitHandle OpenMutex(uint desiredAccess, bool inheritHandle, string name); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "CreateMutexExW", ExactSpelling = true, SetLastError = true)] internal static extern SafeWaitHandle CreateMutexEx(IntPtr lpMutexAttributes, string name, uint flags, uint desiredAccess); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool ReleaseMutex(SafeWaitHandle handle); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "OpenSemaphoreW", ExactSpelling = true, SetLastError = true)] internal static extern SafeWaitHandle OpenSemaphore(uint desiredAccess, bool inheritHandle, string name); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "CreateSemaphoreExW", ExactSpelling = true, SetLastError = true)] internal static extern SafeWaitHandle CreateSemaphoreEx(IntPtr lpSecurityAttributes, int initialCount, int maximumCount, string name, uint flags, uint desiredAccess); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool ReleaseSemaphore(SafeWaitHandle handle, int releaseCount, out int previousCount); [DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "SetEnvironmentVariableW", ExactSpelling = true, SetLastError = true)] internal static extern bool SetEnvironmentVariable(string lpName, string lpValue); [DllImport("kernel32.dll", SetLastError = true)] internal unsafe static extern int WriteFile(IntPtr handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero); } internal static class Normaliz { [DllImport("Normaliz.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal unsafe static extern int IdnToAscii(uint dwFlags, char* lpUnicodeCharStr, int cchUnicodeChar, char* lpASCIICharStr, int cchASCIIChar); [DllImport("Normaliz.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal unsafe static extern int IdnToUnicode(uint dwFlags, char* lpASCIICharStr, int cchASCIIChar, char* lpUnicodeCharStr, int cchUnicodeChar); [DllImport("Normaliz.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal unsafe static extern BOOL IsNormalizedString(NormalizationForm normForm, char* source, int length); [DllImport("Normaliz.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal unsafe static extern int NormalizeString(NormalizationForm normForm, char* source, int sourceLength, char* destination, int destinationLength); } internal static class HostPolicy { [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Auto)] internal delegate void corehost_resolve_component_dependencies_result_fn(string assemblyPaths, string nativeSearchPaths, string resourceSearchPaths); [UnmanagedFunctionPointer(CallingConvention.Cdecl, CharSet = CharSet.Auto)] internal delegate void corehost_error_writer_fn(string message); [DllImport("hostpolicy.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] internal static extern int corehost_resolve_component_dependencies(string componentMainAssemblyPath, corehost_resolve_component_dependencies_result_fn result); [DllImport("hostpolicy.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Auto)] internal static extern IntPtr corehost_set_error_writer(IntPtr errorWriter); } internal static class Advapi32 { internal enum ActivityControl : uint { EVENT_ACTIVITY_CTRL_GET_ID = 1u, EVENT_ACTIVITY_CTRL_SET_ID, EVENT_ACTIVITY_CTRL_CREATE_ID, EVENT_ACTIVITY_CTRL_GET_SET_ID, EVENT_ACTIVITY_CTRL_CREATE_SET_ID } internal struct EVENT_FILTER_DESCRIPTOR { public long Ptr; public int Size; public int Type; } internal unsafe delegate void EtwEnableCallback(in Guid sourceId, int isEnabled, byte level, long matchAnyKeywords, long matchAllKeywords, EVENT_FILTER_DESCRIPTOR* filterData, void* callbackContext); internal enum EVENT_INFO_CLASS { BinaryTrackInfo, SetEnableAllKeywords, SetTraits } internal enum TRACE_QUERY_INFO_CLASS { TraceGuidQueryList, TraceGuidQueryInfo, TraceGuidQueryProcess, TraceStackTracingInfo, MaxTraceSetInfoClass } internal struct TRACE_GUID_INFO { public int InstanceCount; public int Reserved; } internal struct TRACE_PROVIDER_INSTANCE_INFO { public int NextOffset; public int EnableCount; public int Pid; public int Flags; } internal struct TRACE_ENABLE_INFO { public int IsEnabled; public byte Level; public byte Reserved1; public ushort LoggerId; public int EnableProperty; public int Reserved2; public long MatchAnyKeyword; public long MatchAllKeyword; } [DllImport("advapi32.dll", CharSet = CharSet.Unicode, EntryPoint = "EncryptFileW", SetLastError = true)] private static extern bool EncryptFilePrivate(string lpFileName); internal static bool EncryptFile(string path) { path = PathInternal.EnsureExtendedPrefixIfNeeded(path); return EncryptFilePrivate(path); } [DllImport("advapi32.dll", CharSet = CharSet.Unicode, EntryPoint = "DecryptFileW", SetLastError = true)] private static extern bool DecryptFileFilePrivate(string lpFileName, int dwReserved); internal static bool DecryptFile(string path) { path = PathInternal.EnsureExtendedPrefixIfNeeded(path); return DecryptFileFilePrivate(path, 0); } [DllImport("advapi32.dll", ExactSpelling = true)] internal static extern int EventActivityIdControl(ActivityControl ControlCode, ref Guid ActivityId); [DllImport("advapi32.dll", ExactSpelling = true)] internal unsafe static extern uint EventRegister(in Guid providerId, EtwEnableCallback enableCallback, void* callbackContext, ref long registrationHandle); [DllImport("advapi32.dll", ExactSpelling = true)] internal unsafe static extern int EventSetInformation(long registrationHandle, EVENT_INFO_CLASS informationClass, void* eventInformation, uint informationLength); [DllImport("advapi32.dll", ExactSpelling = true)] internal unsafe static extern int EnumerateTraceGuidsEx(TRACE_QUERY_INFO_CLASS TraceQueryInfoClass, void* InBuffer, int InBufferSize, void* OutBuffer, int OutBufferSize, out int ReturnLength); [DllImport("advapi32.dll", ExactSpelling = true)] internal static extern uint EventUnregister(long registrationHandle); internal unsafe static int EventWriteTransfer(long registrationHandle, in EventDescriptor eventDescriptor, Guid* activityId, Guid* relatedActivityId, int userDataCount, EventProvider.EventData* userData) { int num = EventWriteTransfer_PInvoke(registrationHandle, in eventDescriptor, activityId, relatedActivityId, userDataCount, userData); if (num == 87 && relatedActivityId == null) { Guid empty = Guid.Empty; num = EventWriteTransfer_PInvoke(registrationHandle, in eventDescriptor, activityId, &empty, userDataCount, userData); } return num; } [DllImport("advapi32.dll", EntryPoint = "EventWriteTransfer", ExactSpelling = true)] private unsafe static extern int EventWriteTransfer_PInvoke(long registrationHandle, in EventDescriptor eventDescriptor, Guid* activityId, Guid* relatedActivityId, int userDataCount, EventProvider.EventData* userData); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern bool LookupAccountNameW(string lpSystemName, ref char lpAccountName, ref byte Sid, ref uint cbSid, ref char ReferencedDomainName, ref uint cchReferencedDomainName, out uint peUse); [DllImport("advapi32.dll")] internal static extern int RegCloseKey(IntPtr hKey); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegDeleteValueW", ExactSpelling = true)] internal static extern int RegDeleteValue(SafeRegistryHandle hKey, string lpValueName); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegEnumKeyExW", ExactSpelling = true)] internal static extern int RegEnumKeyEx(SafeRegistryHandle hKey, int dwIndex, char[] lpName, ref int lpcbName, int[] lpReserved, [Out] char[] lpClass, int[] lpcbClass, long[] lpftLastWriteTime); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegEnumValueW", ExactSpelling = true)] internal static extern int RegEnumValue(SafeRegistryHandle hKey, int dwIndex, char[] lpValueName, ref int lpcbValueName, IntPtr lpReserved_MustBeZero, int[] lpType, byte[] lpData, int[] lpcbData); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegOpenKeyExW", ExactSpelling = true)] internal static extern int RegOpenKeyEx(SafeRegistryHandle hKey, string lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW", ExactSpelling = true)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName, int[] lpReserved, ref int lpType, [Out] byte[] lpData, ref int lpcbData); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW", ExactSpelling = true)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName, int[] lpReserved, ref int lpType, ref int lpData, ref int lpcbData); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW", ExactSpelling = true)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName, int[] lpReserved, ref int lpType, ref long lpData, ref int lpcbData); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegQueryValueExW", ExactSpelling = true)] internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, string lpValueName, int[] lpReserved, ref int lpType, [Out] char[] lpData, ref int lpcbData); [DllImport("advapi32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RegSetValueExW", ExactSpelling = true)] internal static extern int RegSetValueEx(SafeRegistryHandle hKey, string lpValueName, int Reserved, int dwType, string lpData, int cbData); } internal static class BCrypt { internal enum NTSTATUS : uint { STATUS_SUCCESS = 0u, STATUS_NOT_FOUND = 3221226021u, STATUS_INVALID_PARAMETER = 3221225485u, STATUS_NO_MEMORY = 3221225495u, STATUS_AUTH_TAG_MISMATCH = 3221266434u } [DllImport("BCrypt.dll", CharSet = CharSet.Unicode)] internal unsafe static extern NTSTATUS BCryptGenRandom(IntPtr hAlgorithm, byte* pbBuffer, int cbBuffer, int dwFlags); } internal static class Crypt32 { [DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool CryptProtectMemory(SafeBuffer pData, uint cbData, uint dwFlags); [DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern bool CryptUnprotectMemory(SafeBuffer pData, uint cbData, uint dwFlags); } internal enum BOOLEAN : byte { FALSE, TRUE } internal static class NtDll { public enum CreateDisposition : uint { FILE_SUPERSEDE, FILE_OPEN, FILE_CREATE, FILE_OPEN_IF, FILE_OVERWRITE, FILE_OVERWRITE_IF } public enum CreateOptions : uint { FILE_DIRECTORY_FILE = 1u, FILE_WRITE_THROUGH = 2u, FILE_SEQUENTIAL_ONLY = 4u, FILE_NO_INTERMEDIATE_BUFFERING = 8u, FILE_SYNCHRONOUS_IO_ALERT = 0x10u, FILE_SYNCHRONOUS_IO_NONALERT = 0x20u, FILE_NON_DIRECTORY_FILE = 0x40u, FILE_CREATE_TREE_CONNECTION = 0x80u, FILE_COMPLETE_IF_OPLOCKED = 0x100u, FILE_NO_EA_KNOWLEDGE = 0x200u, FILE_RANDOM_ACCESS = 0x800u, FILE_DELETE_ON_CLOSE = 0x1000u, FILE_OPEN_BY_FILE_ID = 0x2000u, FILE_OPEN_FOR_BACKUP_INTENT = 0x4000u, FILE_NO_COMPRESSION = 0x8000u, FILE_OPEN_REQUIRING_OPLOCK = 0x10000u, FILE_DISALLOW_EXCLUSIVE = 0x20000u, FILE_SESSION_AWARE = 0x40000u, FILE_RESERVE_OPFILTER = 0x100000u, FILE_OPEN_REPARSE_POINT = 0x200000u, FILE_OPEN_NO_RECALL = 0x400000u } [Flags] public enum DesiredAccess : uint { FILE_READ_DATA = 1u, FILE_LIST_DIRECTORY = 1u, FILE_WRITE_DATA = 2u, FILE_ADD_FILE = 2u, FILE_APPEND_DATA = 4u, FILE_ADD_SUBDIRECTORY = 4u, FILE_CREATE_PIPE_INSTANCE = 4u, FILE_READ_EA = 8u, FILE_WRITE_EA = 0x10u, FILE_EXECUTE = 0x20u, FILE_TRAVERSE = 0x20u, FILE_DELETE_CHILD = 0x40u, FILE_READ_ATTRIBUTES = 0x80u, FILE_WRITE_ATTRIBUTES = 0x100u, FILE_ALL_ACCESS = 0xF01FFu, DELETE = 0x10000u, READ_CONTROL = 0x20000u, WRITE_DAC = 0x40000u, WRITE_OWNER = 0x80000u, SYNCHRONIZE = 0x100000u, STANDARD_RIGHTS_READ = 0x20000u, STANDARD_RIGHTS_WRITE = 0x20000u, STANDARD_RIGHTS_EXECUTE = 0x20000u, FILE_GENERIC_READ = 0x80000000u, FILE_GENERIC_WRITE = 0x40000000u, FILE_GENERIC_EXECUTE = 0x20000000u } public struct IO_STATUS_BLOCK { [StructLayout(LayoutKind.Explicit)] public struct IO_STATUS { [FieldOffset(0)] public uint Status; [FieldOffset(0)] public IntPtr Pointer; } public IO_STATUS Status; public IntPtr Information; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct FILE_FULL_DIR_INFORMATION { public uint NextEntryOffset; public uint FileIndex; public LongFileTime CreationTime; public LongFileTime LastAccessTime; public LongFileTime LastWriteTime; public LongFileTime ChangeTime; public long EndOfFile; public long AllocationSize; public FileAttributes FileAttributes; public uint FileNameLength; public uint EaSize; private char _fileName; public unsafe ReadOnlySpan FileName { get { fixed (char* pointer = &_fileName) { return new ReadOnlySpan(pointer, (int)FileNameLength / 2); } } } public unsafe static FILE_FULL_DIR_INFORMATION* GetNextInfo(FILE_FULL_DIR_INFORMATION* info) { if (info == null) { return null; } uint nextEntryOffset = info->NextEntryOffset; if (nextEntryOffset == 0) { return null; } return (FILE_FULL_DIR_INFORMATION*)((byte*)info + nextEntryOffset); } } public enum FILE_INFORMATION_CLASS : uint { FileDirectoryInformation = 1u, FileFullDirectoryInformation, FileBothDirectoryInformation, FileBasicInformation, FileStandardInformation, FileInternalInformation, FileEaInformation, FileAccessInformation, FileNameInformation, FileRenameInformation, FileLinkInformation, FileNamesInformation, FileDispositionInformation, FilePositionInformation, FileFullEaInformation, FileModeInformation, FileAlignmentInformation, FileAllInformation, FileAllocationInformation, FileEndOfFileInformation, FileAlternateNameInformation, FileStreamInformation, FilePipeInformation, FilePipeLocalInformation, FilePipeRemoteInformation, FileMailslotQueryInformation, FileMailslotSetInformation, FileCompressionInformation, FileObjectIdInformation, FileCompletionInformation, FileMoveClusterInformation, FileQuotaInformation, FileReparsePointInformation, FileNetworkOpenInformation, FileAttributeTagInformation, FileTrackingInformation, FileIdBothDirectoryInformation, FileIdFullDirectoryInformation, FileValidDataLengthInformation, FileShortNameInformation, FileIoCompletionNotificationInformation, FileIoStatusBlockRangeInformation, FileIoPriorityHintInformation, FileSfioReserveInformation, FileSfioVolumeInformation, FileHardLinkInformation, FileProcessIdsUsingFileInformation, FileNormalizedNameInformation, FileNetworkPhysicalNameInformation, FileIdGlobalTxDirectoryInformation, FileIsRemoteDeviceInformation, FileUnusedInformation, FileNumaNodeInformation, FileStandardLinkInformation, FileRemoteProtocolInformation, FileRenameInformationBypassAccessCheck, FileLinkInformationBypassAccessCheck, FileVolumeNameInformation, FileIdInformation, FileIdExtdDirectoryInformation, FileReplaceCompletionInformation, FileHardLinkFullIdInformation, FileIdExtdBothDirectoryInformation, FileDispositionInformationEx, FileRenameInformationEx, FileRenameInformationExBypassAccessCheck, FileDesiredStorageClassInformation, FileStatInformation } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct RTL_OSVERSIONINFOEX { internal uint dwOSVersionInfoSize; internal uint dwMajorVersion; internal uint dwMinorVersion; internal uint dwBuildNumber; internal uint dwPlatformId; internal unsafe fixed char szCSDVersion[128]; } internal struct SYSTEM_LEAP_SECOND_INFORMATION { public BOOLEAN Enabled; public uint Flags; } [DllImport("ntdll.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] private unsafe static extern uint NtCreateFile(IntPtr* FileHandle, DesiredAccess DesiredAccess, OBJECT_ATTRIBUTES* ObjectAttributes, IO_STATUS_BLOCK* IoStatusBlock, long* AllocationSize, FileAttributes FileAttributes, FileShare ShareAccess, CreateDisposition CreateDisposition, CreateOptions CreateOptions, void* EaBuffer, uint EaLength); internal unsafe static (uint status, IntPtr handle) CreateFile(ReadOnlySpan path, IntPtr rootDirectory, CreateDisposition createDisposition, DesiredAccess desiredAccess = DesiredAccess.SYNCHRONIZE | DesiredAccess.FILE_GENERIC_READ, FileShare shareAccess = FileShare.ReadWrite | FileShare.Delete, FileAttributes fileAttributes = (FileAttributes)0, CreateOptions createOptions = CreateOptions.FILE_SYNCHRONOUS_IO_NONALERT, ObjectAttributes objectAttributes = ObjectAttributes.OBJ_CASE_INSENSITIVE, void* eaBuffer = null, uint eaLength = 0u, long* preallocationSize = null, SECURITY_QUALITY_OF_SERVICE* securityQualityOfService = null) { checked { fixed (char* ptr = &MemoryMarshal.GetReference(path)) { UNICODE_STRING uNICODE_STRING = default(UNICODE_STRING); uNICODE_STRING.Length = (ushort)(path.Length * 2); uNICODE_STRING.MaximumLength = (ushort)(path.Length * 2); uNICODE_STRING.Buffer = (IntPtr)ptr; UNICODE_STRING uNICODE_STRING2 = uNICODE_STRING; OBJECT_ATTRIBUTES oBJECT_ATTRIBUTES = new OBJECT_ATTRIBUTES(&uNICODE_STRING2, objectAttributes, rootDirectory, securityQualityOfService); System.Runtime.CompilerServices.Unsafe.SkipInit(out IntPtr item); System.Runtime.CompilerServices.Unsafe.SkipInit(out IO_STATUS_BLOCK iO_STATUS_BLOCK); uint item2 = NtCreateFile(&item, desiredAccess, &oBJECT_ATTRIBUTES, &iO_STATUS_BLOCK, preallocationSize, fileAttributes, shareAccess, createDisposition, createOptions, eaBuffer, eaLength); return (item2, item); } } } [DllImport("ntdll.dll", ExactSpelling = true)] public static extern uint RtlNtStatusToDosError(int Status); [DllImport("ntdll.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] public unsafe static extern int NtQueryDirectoryFile(IntPtr FileHandle, IntPtr Event, IntPtr ApcRoutine, IntPtr ApcContext, IO_STATUS_BLOCK* IoStatusBlock, IntPtr FileInformation, uint Length, FILE_INFORMATION_CLASS FileInformationClass, BOOLEAN ReturnSingleEntry, UNICODE_STRING* FileName, BOOLEAN RestartScan); [DllImport("ntdll.dll", ExactSpelling = true)] internal unsafe static extern int NtQueryInformationFile(SafeFileHandle FileHandle, out IO_STATUS_BLOCK IoStatusBlock, void* FileInformation, uint Length, uint FileInformationClass); [DllImport("ntdll.dll", ExactSpelling = true)] internal unsafe static extern uint NtQuerySystemInformation(int SystemInformationClass, void* SystemInformation, uint SystemInformationLength, uint* ReturnLength); [DllImport("ntdll.dll", ExactSpelling = true)] private static extern int RtlGetVersion(ref RTL_OSVERSIONINFOEX lpVersionInformation); internal unsafe static int RtlGetVersionEx(out RTL_OSVERSIONINFOEX osvi) { osvi = default(RTL_OSVERSIONINFOEX); osvi.dwOSVersionInfoSize = (uint)sizeof(RTL_OSVERSIONINFOEX); return RtlGetVersion(ref osvi); } } internal struct UNICODE_STRING { internal ushort Length; internal ushort MaximumLength; internal IntPtr Buffer; } internal struct SECURITY_QUALITY_OF_SERVICE { public uint Length; public ImpersonationLevel ImpersonationLevel; public ContextTrackingMode ContextTrackingMode; public BOOLEAN EffectiveOnly; } public enum ImpersonationLevel : uint { Anonymous, Identification, Impersonation, Delegation } public enum ContextTrackingMode : byte { Static, Dynamic } internal struct OBJECT_ATTRIBUTES { public uint Length; public IntPtr RootDirectory; public unsafe UNICODE_STRING* ObjectName; public ObjectAttributes Attributes; public unsafe void* SecurityDescriptor; public unsafe SECURITY_QUALITY_OF_SERVICE* SecurityQualityOfService; public unsafe OBJECT_ATTRIBUTES(UNICODE_STRING* objectName, ObjectAttributes attributes, IntPtr rootDirectory, SECURITY_QUALITY_OF_SERVICE* securityQualityOfService = null) { Length = (uint)sizeof(OBJECT_ATTRIBUTES); RootDirectory = rootDirectory; ObjectName = objectName; Attributes = attributes; SecurityDescriptor = null; SecurityQualityOfService = securityQualityOfService; } } [Flags] public enum ObjectAttributes : uint { OBJ_INHERIT = 2u, OBJ_PERMANENT = 0x10u, OBJ_EXCLUSIVE = 0x20u, OBJ_CASE_INSENSITIVE = 0x40u, OBJ_OPENIF = 0x80u, OBJ_OPENLINK = 0x100u } internal static class Ole32 { [DllImport("ole32.dll", CharSet = CharSet.Unicode)] internal static extern int CLSIDFromProgID(string lpszProgID, out Guid lpclsid); [DllImport("ole32.dll")] internal static extern int CoCreateGuid(out Guid guid); [DllImport("ole32.dll")] internal static extern int CoGetStandardMarshal(ref Guid riid, IntPtr pv, int dwDestContext, IntPtr pvDestContext, int mshlflags, out IntPtr ppMarshal); [DllImport("ole32.dll")] internal static extern IntPtr CoTaskMemAlloc(nuint cb); [DllImport("ole32.dll")] internal static extern IntPtr CoTaskMemRealloc(IntPtr pv, nuint cb); [DllImport("ole32.dll")] internal static extern void CoTaskMemFree(IntPtr ptr); } internal static class Secur32 { [DllImport("secur32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] internal static extern BOOLEAN GetUserNameExW(int NameFormat, ref char lpNameBuffer, ref uint lpnSize); } internal static class Shell32 { [DllImport("shell32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, ExactSpelling = true)] internal static extern int SHGetKnownFolderPath([MarshalAs(UnmanagedType.LPStruct)] Guid rfid, uint dwFlags, IntPtr hToken, out string ppszPath); } internal static class Ucrtbase { [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] internal unsafe static extern void* _aligned_malloc(nuint size, nuint alignment); [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] internal unsafe static extern void _aligned_free(void* ptr); [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] internal unsafe static extern void* _aligned_realloc(void* ptr, nuint size, nuint alignment); [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] internal unsafe static extern void* calloc(nuint num, nuint size); [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] internal unsafe static extern void free(void* ptr); [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] internal unsafe static extern void* malloc(nuint size); [DllImport("ucrtbase.dll", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)] internal unsafe static extern void* realloc(void* ptr, nuint new_size); } internal static class User32 { internal struct USEROBJECTFLAGS { public int fInherit; public int fReserved; public int dwFlags; } [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "LoadStringW", ExactSpelling = true, SetLastError = true)] internal unsafe static extern int LoadString(IntPtr hInstance, uint uID, char* lpBuffer, int cchBufferMax); [DllImport("user32.dll", EntryPoint = "SendMessageTimeoutW")] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam, int flags, int timeout, out IntPtr pdwResult); [DllImport("user32.dll", ExactSpelling = true)] internal static extern IntPtr GetProcessWindowStation(); [DllImport("user32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] public unsafe static extern bool GetUserObjectInformationW(IntPtr hObj, int nIndex, void* pvBuffer, uint nLength, ref uint lpnLengthNeeded); } internal struct LongFileTime { internal long TicksSince1601; internal DateTimeOffset ToDateTimeOffset() { return new DateTimeOffset(DateTime.FromFileTimeUtc(TicksSince1601)); } } internal static bool CallStringMethod(SpanFunc interopCall, TArg1 arg1, TArg2 arg2, TArg3 arg3, out string result) { Span span = stackalloc char[256]; switch (interopCall(span, arg1, arg2, arg3)) { case Globalization.ResultCode.Success: result = span.Slice(0, span.IndexOf('\0')).ToString(); return true; case Globalization.ResultCode.InsufficentBuffer: span = new char[1280]; if (interopCall(span, arg1, arg2, arg3) == Globalization.ResultCode.Success) { result = span.Slice(0, span.IndexOf('\0')).ToString(); return true; } break; } result = null; return false; } internal unsafe static void GetRandomBytes(byte* buffer, int length) { switch (BCrypt.BCryptGenRandom(IntPtr.Zero, buffer, length, 2)) { case BCrypt.NTSTATUS.STATUS_NO_MEMORY: throw new OutOfMemoryException(); default: throw new InvalidOperationException(); case BCrypt.NTSTATUS.STATUS_SUCCESS: break; } } } namespace Microsoft.Win32 { internal static class OAVariantLib { internal static readonly Type[] ClassTypes = new Type[23] { typeof(Empty), typeof(void), typeof(bool), typeof(char), typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(string), typeof(void), typeof(DateTime), typeof(TimeSpan), typeof(object), typeof(decimal), null, typeof(Missing), typeof(DBNull) }; internal static System.Variant ChangeType(System.Variant source, Type targetClass, short options, CultureInfo culture) { if (targetClass == null) { throw new ArgumentNullException("targetClass"); } if (culture == null) { throw new ArgumentNullException("culture"); } System.Variant result = default(System.Variant); ChangeTypeEx(ref result, ref source, culture.LCID, targetClass.TypeHandle.Value, GetCVTypeFromClass(targetClass), options); return result; } private static int GetCVTypeFromClass(Type ctype) { int num = -1; for (int i = 0; i < ClassTypes.Length; i++) { if (ctype.Equals(ClassTypes[i])) { num = i; break; } } if (num == -1) { num = 18; } return num; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ChangeTypeEx(ref System.Variant result, ref System.Variant source, int lcid, IntPtr typeHandle, int cvType, short flags); } } namespace Microsoft.Win32.SafeHandles { public abstract class CriticalHandleMinusOneIsInvalid : CriticalHandle { public override bool IsInvalid => handle == new IntPtr(-1); protected CriticalHandleMinusOneIsInvalid() : base(new IntPtr(-1)) { } } public abstract class CriticalHandleZeroOrMinusOneIsInvalid : CriticalHandle { public override bool IsInvalid { get { if (!(handle == IntPtr.Zero)) { return handle == new IntPtr(-1); } return true; } } protected CriticalHandleZeroOrMinusOneIsInvalid() : base(IntPtr.Zero) { } } public abstract class SafeHandleMinusOneIsInvalid : SafeHandle { public override bool IsInvalid => handle == new IntPtr(-1); protected SafeHandleMinusOneIsInvalid(bool ownsHandle) : base(new IntPtr(-1), ownsHandle) { } } public abstract class SafeHandleZeroOrMinusOneIsInvalid : SafeHandle { public override bool IsInvalid { get { if (!(handle == IntPtr.Zero)) { return handle == new IntPtr(-1); } return true; } } protected SafeHandleZeroOrMinusOneIsInvalid(bool ownsHandle) : base(IntPtr.Zero, ownsHandle) { } } public sealed class SafeFileHandle : SafeHandleZeroOrMinusOneIsInvalid { internal sealed class ThreadPoolValueTaskSource : IThreadPoolWorkItem, IValueTaskSource, IValueTaskSource, IValueTaskSource { private enum Operation : byte { None, Read, Write, ReadScatter, WriteGather } private readonly SafeFileHandle _fileHandle; private ManualResetValueTaskSourceCore _source; private Operation _operation; private ExecutionContext _context; private OSFileStreamStrategy _strategy; private long _fileOffset; private CancellationToken _cancellationToken; private ReadOnlyMemory _singleSegment; private IReadOnlyList> _readScatterBuffers; private IReadOnlyList> _writeGatherBuffers; internal ThreadPoolValueTaskSource(SafeFileHandle fileHandle) { _fileHandle = fileHandle; } public ValueTaskSourceStatus GetStatus(short token) { return _source.GetStatus(token); } public void OnCompleted(Action continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { _source.OnCompleted(continuation, state, token, flags); } void IValueTaskSource.GetResult(short token) { GetResult(token); } int IValueTaskSource.GetResult(short token) { return (int)GetResult(token); } public long GetResult(short token) { try { return _source.GetResult(token); } finally { _source.Reset(); Volatile.Write(ref _fileHandle._reusableThreadPoolValueTaskSource, this); } } private void ExecuteInternal() { long num = 0L; Exception ex = null; try { if (_cancellationToken.IsCancellationRequested) { ex = new OperationCanceledException(_cancellationToken); } else { switch (_operation) { case Operation.Read: { Memory memory = MemoryMarshal.AsMemory(_singleSegment); num = RandomAccess.ReadAtOffset(_fileHandle, memory.Span, _fileOffset); break; } case Operation.Write: RandomAccess.WriteAtOffset(_fileHandle, _singleSegment.Span, _fileOffset); break; case Operation.ReadScatter: num = RandomAccess.ReadScatterAtOffset(_fileHandle, _readScatterBuffers, _fileOffset); break; case Operation.WriteGather: RandomAccess.WriteGatherAtOffset(_fileHandle, _writeGatherBuffers, _fileOffset); break; } } } catch (Exception ex2) { ex = ex2; } finally { if (_strategy != null) { if (ex != null) { _strategy.OnIncompleteOperation(_singleSegment.Length, 0); } else if (_operation == Operation.Read && num != _singleSegment.Length) { _strategy.OnIncompleteOperation(_singleSegment.Length, (int)num); } } _operation = Operation.None; _context = null; _strategy = null; _cancellationToken = default(CancellationToken); _singleSegment = default(ReadOnlyMemory); _readScatterBuffers = null; _writeGatherBuffers = null; } if (ex == null) { _source.SetResult(num); } else { _source.SetException(ex); } } void IThreadPoolWorkItem.Execute() { if (_context == null || _context.IsDefault) { ExecuteInternal(); return; } ExecutionContext.RunForThreadPoolUnsafe(_context, delegate(ThreadPoolValueTaskSource x) { x.ExecuteInternal(); }, in this); } private void QueueToThreadPool() { _context = ExecutionContext.Capture(); ThreadPool.UnsafeQueueUserWorkItem(this, preferLocal: true); } public ValueTask QueueRead(Memory buffer, long fileOffset, CancellationToken cancellationToken, OSFileStreamStrategy strategy) { _operation = Operation.Read; _singleSegment = buffer; _fileOffset = fileOffset; _cancellationToken = cancellationToken; _strategy = strategy; QueueToThreadPool(); return new ValueTask(this, _source.Version); } public ValueTask QueueWrite(ReadOnlyMemory buffer, long fileOffset, CancellationToken cancellationToken, OSFileStreamStrategy strategy) { _operation = Operation.Write; _singleSegment = buffer; _fileOffset = fileOffset; _cancellationToken = cancellationToken; _strategy = strategy; QueueToThreadPool(); return new ValueTask(this, _source.Version); } public ValueTask QueueReadScatter(IReadOnlyList> buffers, long fileOffset, CancellationToken cancellationToken) { _operation = Operation.ReadScatter; _readScatterBuffers = buffers; _fileOffset = fileOffset; _cancellationToken = cancellationToken; QueueToThreadPool(); return new ValueTask(this, _source.Version); } public ValueTask QueueWriteGather(IReadOnlyList> buffers, long fileOffset, CancellationToken cancellationToken) { _operation = Operation.WriteGather; _writeGatherBuffers = buffers; _fileOffset = fileOffset; _cancellationToken = cancellationToken; QueueToThreadPool(); return new ValueTask(this, _source.Version); } } internal sealed class OverlappedValueTaskSource : IValueTaskSource, IValueTaskSource { internal unsafe static readonly IOCompletionCallback s_ioCallback = IOCallback; internal readonly PreAllocatedOverlapped _preallocatedOverlapped; internal readonly SafeFileHandle _fileHandle; private OSFileStreamStrategy _strategy; internal MemoryHandle _memoryHandle; private int _bufferSize; internal ManualResetValueTaskSourceCore _source; private unsafe NativeOverlapped* _overlapped; private CancellationTokenRegistration _cancellationRegistration; internal ulong _result; internal short Version => _source.Version; internal OverlappedValueTaskSource(SafeFileHandle fileHandle) { _fileHandle = fileHandle; _source.RunContinuationsAsynchronously = true; _preallocatedOverlapped = PreAllocatedOverlapped.UnsafeCreate(s_ioCallback, this, null); } internal void Dispose() { ReleaseResources(); _preallocatedOverlapped.Dispose(); } internal static Exception GetIOError(int errorCode, string path) { if (errorCode != 38) { return Win32Marshal.GetExceptionForWin32Error(errorCode, path); } return ThrowHelper.CreateEndOfFileException(); } internal unsafe NativeOverlapped* PrepareForOperation(ReadOnlyMemory memory, long fileOffset, OSFileStreamStrategy strategy = null) { _result = 0uL; _strategy = strategy; _bufferSize = memory.Length; _memoryHandle = memory.Pin(); _overlapped = _fileHandle.ThreadPoolBinding.AllocateNativeOverlapped(_preallocatedOverlapped); if (_fileHandle.CanSeek) { _overlapped->OffsetLow = (int)fileOffset; _overlapped->OffsetHigh = (int)(fileOffset >> 32); } return _overlapped; } public ValueTaskSourceStatus GetStatus(short token) { return _source.GetStatus(token); } public void OnCompleted(Action continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { _source.OnCompleted(continuation, state, token, flags); } void IValueTaskSource.GetResult(short token) { GetResult(token); } public int GetResult(short token) { try { return _source.GetResult(token); } finally { _fileHandle.TryToReuse(this); } } internal unsafe void RegisterForCancellation(CancellationToken cancellationToken) { if (!cancellationToken.CanBeCanceled) { return; } try { _cancellationRegistration = cancellationToken.UnsafeRegister(delegate(object s, CancellationToken token) { OverlappedValueTaskSource overlappedValueTaskSource = (OverlappedValueTaskSource)s; if (!overlappedValueTaskSource._fileHandle.IsInvalid) { try { Interop.Kernel32.CancelIoEx(overlappedValueTaskSource._fileHandle, overlappedValueTaskSource._overlapped); } catch (ObjectDisposedException) { } } }, this); } catch (OutOfMemoryException) { } } private unsafe void ReleaseResources() { _strategy = null; _cancellationRegistration.Dispose(); _memoryHandle.Dispose(); if (_overlapped != null) { _fileHandle.ThreadPoolBinding.FreeNativeOverlapped(_overlapped); _overlapped = null; } } internal void FinishedScheduling() { ulong num = Interlocked.Exchange(ref _result, 1uL); if (num != 0L) { Complete((uint)num, (uint)(int)(num >> 32) & 0x7FFFFFFFu); } } private unsafe static void IOCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped) { OverlappedValueTaskSource overlappedValueTaskSource = (OverlappedValueTaskSource)ThreadPoolBoundHandle.GetNativeOverlappedState(pOverlapped); if (Interlocked.Exchange(ref overlappedValueTaskSource._result, 0x8000000000000000uL | ((ulong)numBytes << 32) | errorCode) != 0L) { overlappedValueTaskSource.Complete(errorCode, numBytes); } } internal void Complete(uint errorCode, uint numBytes) { OSFileStreamStrategy strategy = _strategy; ReleaseResources(); switch (errorCode) { case 0u: case 38u: case 109u: case 232u: if (_bufferSize != numBytes) { strategy?.OnIncompleteOperation(_bufferSize, (int)numBytes); } _source.SetResult((int)numBytes); break; case 995u: { strategy?.OnIncompleteOperation(_bufferSize, 0); CancellationToken token = _cancellationRegistration.Token; _source.SetException(token.IsCancellationRequested ? new OperationCanceledException(token) : new OperationCanceledException()); break; } default: strategy?.OnIncompleteOperation(_bufferSize, 0); _source.SetException(Win32Marshal.GetExceptionForWin32Error((int)errorCode)); break; } } } private string _path; private ThreadPoolValueTaskSource _reusableThreadPoolValueTaskSource; private volatile FileOptions _fileOptions = (FileOptions)(-1); private volatile int _fileType = -1; private OverlappedValueTaskSource _reusableOverlappedValueTaskSource; internal string? Path => _path; public bool IsAsync => (GetFileOptions() & FileOptions.Asynchronous) != 0; internal bool CanSeek { get { if (!base.IsClosed) { return GetFileType() == 1; } return false; } } internal ThreadPoolBoundHandle? ThreadPoolBinding { get; set; } public SafeFileHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) { SetHandle(preexistingHandle); } internal ThreadPoolValueTaskSource GetThreadPoolValueTaskSource() { return Interlocked.Exchange(ref _reusableThreadPoolValueTaskSource, null) ?? new ThreadPoolValueTaskSource(this); } public SafeFileHandle() : base(ownsHandle: true) { } internal static SafeFileHandle Open(string fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, long preallocationSize) { using (DisableMediaInsertionPrompt.Create()) { SafeFileHandle safeFileHandle = CreateFile(fullPath, mode, access, share, options); if (preallocationSize > 0) { Preallocate(fullPath, preallocationSize, safeFileHandle); } if ((options & FileOptions.Asynchronous) != 0) { safeFileHandle.InitThreadPoolBinding(); } return safeFileHandle; } } private unsafe static SafeFileHandle CreateFile(string fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options) { Interop.Kernel32.SECURITY_ATTRIBUTES sECURITY_ATTRIBUTES = default(Interop.Kernel32.SECURITY_ATTRIBUTES); if ((share & FileShare.Inheritable) != 0) { Interop.Kernel32.SECURITY_ATTRIBUTES sECURITY_ATTRIBUTES2 = default(Interop.Kernel32.SECURITY_ATTRIBUTES); sECURITY_ATTRIBUTES2.nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES); sECURITY_ATTRIBUTES2.bInheritHandle = Interop.BOOL.TRUE; sECURITY_ATTRIBUTES = sECURITY_ATTRIBUTES2; } int dwDesiredAccess = (((access & FileAccess.Read) == FileAccess.Read) ? int.MinValue : 0) | (((access & FileAccess.Write) == FileAccess.Write) ? 1073741824 : 0); share &= ~FileShare.Inheritable; if (mode == FileMode.Append) { mode = FileMode.OpenOrCreate; } int num = (int)options; num |= 0x100000; SafeFileHandle safeFileHandle = Interop.Kernel32.CreateFile(fullPath, dwDesiredAccess, share, &sECURITY_ATTRIBUTES, mode, num, IntPtr.Zero); if (safeFileHandle.IsInvalid) { int num2 = Marshal.GetLastPInvokeError(); if (num2 == 3 && fullPath.Length == PathInternal.GetRootLength(fullPath)) { num2 = 5; } throw Win32Marshal.GetExceptionForWin32Error(num2, fullPath); } safeFileHandle._path = fullPath; safeFileHandle._fileOptions = options; return safeFileHandle; } private unsafe static void Preallocate(string fullPath, long preallocationSize, SafeFileHandle fileHandle) { Interop.Kernel32.FILE_ALLOCATION_INFO fILE_ALLOCATION_INFO = default(Interop.Kernel32.FILE_ALLOCATION_INFO); fILE_ALLOCATION_INFO.AllocationSize = preallocationSize; Interop.Kernel32.FILE_ALLOCATION_INFO fILE_ALLOCATION_INFO2 = fILE_ALLOCATION_INFO; if (!Interop.Kernel32.SetFileInformationByHandle(fileHandle, 5, &fILE_ALLOCATION_INFO2, (uint)sizeof(Interop.Kernel32.FILE_ALLOCATION_INFO))) { int lastPInvokeError = Marshal.GetLastPInvokeError(); if (lastPInvokeError == 112 || lastPInvokeError == 223) { fileHandle.Dispose(); Interop.Kernel32.DeleteFile(fullPath); throw new IOException(SR.Format((lastPInvokeError == 112) ? SR.IO_DiskFull_Path_AllocationSize : SR.IO_FileTooLarge_Path_AllocationSize, fullPath, preallocationSize)); } } } internal void EnsureThreadPoolBindingInitialized() { if (IsAsync && ThreadPoolBinding == null) { Init(); } void Init() { lock (this) { if (ThreadPoolBinding == null) { InitThreadPoolBinding(); } } } } private void InitThreadPoolBinding() { try { ThreadPoolBinding = ThreadPoolBoundHandle.BindHandle(this); } catch (ArgumentException innerException) { if (base.OwnsHandle) { Dispose(); } throw new IOException(SR.IO_BindHandleFailed, innerException); } } internal unsafe FileOptions GetFileOptions() { FileOptions fileOptions = _fileOptions; if (fileOptions != (FileOptions)(-1)) { return fileOptions; } Interop.NtDll.IO_STATUS_BLOCK IoStatusBlock; System.Runtime.CompilerServices.Unsafe.SkipInit(out Interop.NtDll.CreateOptions createOptions); int num = Interop.NtDll.NtQueryInformationFile(this, out IoStatusBlock, &createOptions, 4u, 16u); if (num != 0L) { int errorCode = (int)Interop.NtDll.RtlNtStatusToDosError(num); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } FileOptions fileOptions2 = FileOptions.None; if ((createOptions & (Interop.NtDll.CreateOptions)48u) == 0) { fileOptions2 |= FileOptions.Asynchronous; } if ((createOptions & Interop.NtDll.CreateOptions.FILE_WRITE_THROUGH) != 0) { fileOptions2 |= FileOptions.WriteThrough; } if ((createOptions & Interop.NtDll.CreateOptions.FILE_RANDOM_ACCESS) != 0) { fileOptions2 |= FileOptions.RandomAccess; } if ((createOptions & Interop.NtDll.CreateOptions.FILE_SEQUENTIAL_ONLY) != 0) { fileOptions2 |= FileOptions.SequentialScan; } if ((createOptions & Interop.NtDll.CreateOptions.FILE_DELETE_ON_CLOSE) != 0) { fileOptions2 |= FileOptions.DeleteOnClose; } if ((createOptions & Interop.NtDll.CreateOptions.FILE_NO_INTERMEDIATE_BUFFERING) != 0) { fileOptions2 |= (FileOptions)536870912; } return _fileOptions = fileOptions2; } internal int GetFileType() { int num = _fileType; if (num == -1) { num = (_fileType = Interop.Kernel32.GetFileType(this)); } return num; } internal OverlappedValueTaskSource GetOverlappedValueTaskSource() { return Interlocked.Exchange(ref _reusableOverlappedValueTaskSource, null) ?? new OverlappedValueTaskSource(this); } protected override bool ReleaseHandle() { bool result = Interop.Kernel32.CloseHandle(handle); Interlocked.Exchange(ref _reusableOverlappedValueTaskSource, null)?.Dispose(); return result; } private void TryToReuse(OverlappedValueTaskSource source) { source._source.Reset(); if (Interlocked.CompareExchange(ref _reusableOverlappedValueTaskSource, source, null) != null) { source._preallocatedOverlapped.Dispose(); } } } public sealed class SafeWaitHandle : SafeHandleZeroOrMinusOneIsInvalid { public SafeWaitHandle() : base(ownsHandle: true) { } public SafeWaitHandle(IntPtr existingHandle, bool ownsHandle) : base(ownsHandle) { SetHandle(existingHandle); } protected override bool ReleaseHandle() { return Interop.Kernel32.CloseHandle(handle); } } internal sealed class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid { public SafeFindHandle() : base(ownsHandle: true) { } protected override bool ReleaseHandle() { return Interop.Kernel32.FindClose(handle); } } } namespace System { [ClassInterface(ClassInterfaceType.None)] [ComVisible(true)] internal class __Canon { } public ref struct ArgIterator { private IntPtr ArgCookie; private IntPtr sigPtr; private IntPtr sigPtrLen; private IntPtr ArgPtr; private int RemainingArgs; [MethodImpl(MethodImplOptions.InternalCall)] private extern ArgIterator(IntPtr arglist); public ArgIterator(RuntimeArgumentHandle arglist) : this(arglist.Value) { } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe extern ArgIterator(IntPtr arglist, void* ptr); [CLSCompliant(false)] public unsafe ArgIterator(RuntimeArgumentHandle arglist, void* ptr) : this(arglist.Value, ptr) { } [CLSCompliant(false)] public unsafe TypedReference GetNextArg() { TypedReference result = default(TypedReference); FCallGetNextArg(&result); return result; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe extern void FCallGetNextArg(void* result); [CLSCompliant(false)] public unsafe TypedReference GetNextArg(RuntimeTypeHandle rth) { if (sigPtr != IntPtr.Zero) { return GetNextArg(); } if (ArgPtr == IntPtr.Zero) { throw new ArgumentNullException(); } TypedReference result = default(TypedReference); InternalGetNextArg(&result, rth.GetRuntimeType()); return result; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe extern void InternalGetNextArg(void* result, RuntimeType rt); public void End() { } [MethodImpl(MethodImplOptions.InternalCall)] public extern int GetRemainingCount(); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe extern void* _GetNextArgType(); public unsafe RuntimeTypeHandle GetNextArgType() { return new RuntimeTypeHandle(Type.GetTypeFromHandleUnsafe((IntPtr)_GetNextArgType())); } public override int GetHashCode() { return ValueType.GetHashCodeOfPtr(ArgCookie); } public override bool Equals(object? o) { throw new NotSupportedException(SR.NotSupported_NYI); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class Array : ICloneable, IList, ICollection, System.Collections.IEnumerable, IStructuralComparable, IStructuralEquatable { private static class EmptyArray { internal static readonly T[] Value = new T[0]; } private readonly struct SorterObjectArray { private readonly object[] keys; private readonly object[] items; private readonly IComparer comparer; internal SorterObjectArray(object[] keys, object[] items, IComparer comparer) { this.keys = keys; this.items = items; this.comparer = comparer; } internal void SwapIfGreater(int a, int b) { if (a != b && comparer.Compare(keys[a], keys[b]) > 0) { object obj = keys[a]; keys[a] = keys[b]; keys[b] = obj; if (items != null) { object obj2 = items[a]; items[a] = items[b]; items[b] = obj2; } } } private void Swap(int i, int j) { object obj = keys[i]; keys[i] = keys[j]; keys[j] = obj; if (items != null) { object obj2 = items[i]; items[i] = items[j]; items[j] = obj2; } } internal void Sort(int left, int length) { IntrospectiveSort(left, length); } private void IntrospectiveSort(int left, int length) { if (length < 2) { return; } try { IntroSort(left, length + left - 1, 2 * (BitOperations.Log2((uint)length) + 1)); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private void IntroSort(int lo, int hi, int depthLimit) { while (hi > lo) { int num = hi - lo + 1; if (num <= 16) { switch (num) { case 2: SwapIfGreater(lo, hi); break; case 3: SwapIfGreater(lo, hi - 1); SwapIfGreater(lo, hi); SwapIfGreater(hi - 1, hi); break; default: InsertionSort(lo, hi); break; } break; } if (depthLimit == 0) { Heapsort(lo, hi); break; } depthLimit--; int num2 = PickPivotAndPartition(lo, hi); IntroSort(num2 + 1, hi, depthLimit); hi = num2 - 1; } } private int PickPivotAndPartition(int lo, int hi) { int num = lo + (hi - lo) / 2; SwapIfGreater(lo, num); SwapIfGreater(lo, hi); SwapIfGreater(num, hi); object obj = keys[num]; Swap(num, hi - 1); int num2 = lo; int num3 = hi - 1; while (num2 < num3) { while (comparer.Compare(keys[++num2], obj) < 0) { } while (comparer.Compare(obj, keys[--num3]) < 0) { } if (num2 >= num3) { break; } Swap(num2, num3); } if (num2 != hi - 1) { Swap(num2, hi - 1); } return num2; } private void Heapsort(int lo, int hi) { int num = hi - lo + 1; for (int num2 = num / 2; num2 >= 1; num2--) { DownHeap(num2, num, lo); } for (int num3 = num; num3 > 1; num3--) { Swap(lo, lo + num3 - 1); DownHeap(1, num3 - 1, lo); } } private void DownHeap(int i, int n, int lo) { object obj = keys[lo + i - 1]; object[] array = items; object obj2 = ((array != null) ? array[lo + i - 1] : null); while (i <= n / 2) { int num = 2 * i; if (num < n && comparer.Compare(keys[lo + num - 1], keys[lo + num]) < 0) { num++; } if (comparer.Compare(obj, keys[lo + num - 1]) >= 0) { break; } keys[lo + i - 1] = keys[lo + num - 1]; if (items != null) { items[lo + i - 1] = items[lo + num - 1]; } i = num; } keys[lo + i - 1] = obj; if (items != null) { items[lo + i - 1] = obj2; } } private void InsertionSort(int lo, int hi) { for (int i = lo; i < hi; i++) { int num = i; object obj = keys[i + 1]; object[] array = items; object obj2 = ((array != null) ? array[i + 1] : null); while (num >= lo && comparer.Compare(obj, keys[num]) < 0) { keys[num + 1] = keys[num]; if (items != null) { items[num + 1] = items[num]; } num--; } keys[num + 1] = obj; if (items != null) { items[num + 1] = obj2; } } } } private readonly struct SorterGenericArray { private readonly Array keys; private readonly Array items; private readonly IComparer comparer; internal SorterGenericArray(Array keys, Array items, IComparer comparer) { this.keys = keys; this.items = items; this.comparer = comparer; } internal void SwapIfGreater(int a, int b) { if (a != b && comparer.Compare(keys.GetValue(a), keys.GetValue(b)) > 0) { object value = keys.GetValue(a); keys.SetValue(keys.GetValue(b), a); keys.SetValue(value, b); if (items != null) { object value2 = items.GetValue(a); items.SetValue(items.GetValue(b), a); items.SetValue(value2, b); } } } private void Swap(int i, int j) { object value = keys.GetValue(i); keys.SetValue(keys.GetValue(j), i); keys.SetValue(value, j); if (items != null) { object value2 = items.GetValue(i); items.SetValue(items.GetValue(j), i); items.SetValue(value2, j); } } internal void Sort(int left, int length) { IntrospectiveSort(left, length); } private void IntrospectiveSort(int left, int length) { if (length < 2) { return; } try { IntroSort(left, length + left - 1, 2 * (BitOperations.Log2((uint)length) + 1)); } catch (IndexOutOfRangeException) { ThrowHelper.ThrowArgumentException_BadComparer(comparer); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); } } private void IntroSort(int lo, int hi, int depthLimit) { while (hi > lo) { int num = hi - lo + 1; if (num <= 16) { switch (num) { case 2: SwapIfGreater(lo, hi); break; case 3: SwapIfGreater(lo, hi - 1); SwapIfGreater(lo, hi); SwapIfGreater(hi - 1, hi); break; default: InsertionSort(lo, hi); break; } break; } if (depthLimit == 0) { Heapsort(lo, hi); break; } depthLimit--; int num2 = PickPivotAndPartition(lo, hi); IntroSort(num2 + 1, hi, depthLimit); hi = num2 - 1; } } private int PickPivotAndPartition(int lo, int hi) { int num = lo + (hi - lo) / 2; SwapIfGreater(lo, num); SwapIfGreater(lo, hi); SwapIfGreater(num, hi); object value = keys.GetValue(num); Swap(num, hi - 1); int num2 = lo; int num3 = hi - 1; while (num2 < num3) { while (comparer.Compare(keys.GetValue(++num2), value) < 0) { } while (comparer.Compare(value, keys.GetValue(--num3)) < 0) { } if (num2 >= num3) { break; } Swap(num2, num3); } if (num2 != hi - 1) { Swap(num2, hi - 1); } return num2; } private void Heapsort(int lo, int hi) { int num = hi - lo + 1; for (int num2 = num / 2; num2 >= 1; num2--) { DownHeap(num2, num, lo); } for (int num3 = num; num3 > 1; num3--) { Swap(lo, lo + num3 - 1); DownHeap(1, num3 - 1, lo); } } private void DownHeap(int i, int n, int lo) { object value = keys.GetValue(lo + i - 1); object value2 = items?.GetValue(lo + i - 1); while (i <= n / 2) { int num = 2 * i; if (num < n && comparer.Compare(keys.GetValue(lo + num - 1), keys.GetValue(lo + num)) < 0) { num++; } if (comparer.Compare(value, keys.GetValue(lo + num - 1)) >= 0) { break; } keys.SetValue(keys.GetValue(lo + num - 1), lo + i - 1); if (items != null) { items.SetValue(items.GetValue(lo + num - 1), lo + i - 1); } i = num; } keys.SetValue(value, lo + i - 1); if (items != null) { items.SetValue(value2, lo + i - 1); } } private void InsertionSort(int lo, int hi) { for (int i = lo; i < hi; i++) { int num = i; object value = keys.GetValue(i + 1); object value2 = items?.GetValue(i + 1); while (num >= lo && comparer.Compare(value, keys.GetValue(num)) < 0) { keys.SetValue(keys.GetValue(num), num + 1); if (items != null) { items.SetValue(items.GetValue(num), num + 1); } num--; } keys.SetValue(value, num + 1); if (items != null) { items.SetValue(value2, num + 1); } } } } public int Length => checked((int)Unsafe.As(this).Length); internal nuint NativeLength => Unsafe.As(this).Length; public long LongLength => (long)NativeLength; public int Rank { get { int multiDimensionalArrayRank = RuntimeHelpers.GetMultiDimensionalArrayRank(this); if (multiDimensionalArrayRank == 0) { return 1; } return multiDimensionalArrayRank; } } int ICollection.Count => Length; public object SyncRoot => this; public bool IsReadOnly => false; public bool IsFixedSize => true; public bool IsSynchronized => false; object? IList.this[int index] { get { return GetValue(index); } set { SetValue(value, index); } } public static int MaxLength => 2147483591; public unsafe static Array CreateInstance(Type elementType, int length) { if ((object)elementType == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); } if (length < 0) { ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); } RuntimeType runtimeType = elementType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); } return InternalCreate((void*)runtimeType.TypeHandle.Value, 1, &length, null); } public unsafe static Array CreateInstance(Type elementType, int length1, int length2) { if ((object)elementType == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); } if (length1 < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length1, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (length2 < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length2, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } RuntimeType runtimeType = elementType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); } int* ptr = stackalloc int[2]; *ptr = length1; ptr[1] = length2; return InternalCreate((void*)runtimeType.TypeHandle.Value, 2, ptr, null); } public unsafe static Array CreateInstance(Type elementType, int length1, int length2, int length3) { if ((object)elementType == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); } if (length1 < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length1, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (length2 < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length2, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (length3 < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length3, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } RuntimeType runtimeType = elementType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); } int* ptr = stackalloc int[3]; *ptr = length1; ptr[1] = length2; ptr[2] = length3; return InternalCreate((void*)runtimeType.TypeHandle.Value, 3, ptr, null); } public unsafe static Array CreateInstance(Type elementType, params int[] lengths) { if ((object)elementType == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); } if (lengths == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); } if (lengths.Length == 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank); } RuntimeType runtimeType = elementType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); } for (int i = 0; i < lengths.Length; i++) { if (lengths[i] < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } } fixed (int* pLengths = &lengths[0]) { return InternalCreate((void*)runtimeType.TypeHandle.Value, lengths.Length, pLengths, null); } } public unsafe static Array CreateInstance(Type elementType, int[] lengths, int[] lowerBounds) { if (elementType == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.elementType); } if (lengths == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); } if (lowerBounds == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lowerBounds); } if (lengths.Length != lowerBounds.Length) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RanksAndBounds); } if (lengths.Length == 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank); } RuntimeType runtimeType = elementType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_MustBeType, ExceptionArgument.elementType); } for (int i = 0; i < lengths.Length; i++) { if (lengths[i] < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.lengths, i, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } } fixed (int* pLengths = &lengths[0]) { fixed (int* pLowerBounds = &lowerBounds[0]) { return InternalCreate((void*)runtimeType.TypeHandle.Value, lengths.Length, pLengths, pLowerBounds); } } } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern Array InternalCreate(void* elementType, int rank, int* pLengths, int* pLowerBounds); public unsafe static void Copy(Array sourceArray, Array destinationArray, int length) { if (sourceArray == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.sourceArray); } if (destinationArray == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destinationArray); } MethodTable* methodTable = RuntimeHelpers.GetMethodTable(sourceArray); if (methodTable == RuntimeHelpers.GetMethodTable(destinationArray) && !methodTable->IsMultiDimensionalArray && (uint)length <= sourceArray.NativeLength && (uint)length <= destinationArray.NativeLength) { nuint num = (nuint)(uint)length * (nuint)methodTable->ComponentSize; ref byte data = ref Unsafe.As(sourceArray).Data; ref byte data2 = ref Unsafe.As(destinationArray).Data; if (methodTable->ContainsGCPointers) { Buffer.BulkMoveWithWriteBarrier(ref data2, ref data, num); } else { Buffer.Memmove(ref data2, ref data, num); } } else { Copy(sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), length, reliable: false); } } public unsafe static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) { if (sourceArray != null && destinationArray != null) { MethodTable* methodTable = RuntimeHelpers.GetMethodTable(sourceArray); if (methodTable == RuntimeHelpers.GetMethodTable(destinationArray) && !methodTable->IsMultiDimensionalArray && length >= 0 && sourceIndex >= 0 && destinationIndex >= 0 && (uint)(sourceIndex + length) <= sourceArray.NativeLength && (uint)(destinationIndex + length) <= destinationArray.NativeLength) { nuint num = methodTable->ComponentSize; nuint num2 = (uint)length * num; ref byte reference = ref Unsafe.AddByteOffset(ref Unsafe.As(sourceArray).Data, (uint)sourceIndex * num); ref byte reference2 = ref Unsafe.AddByteOffset(ref Unsafe.As(destinationArray).Data, (uint)destinationIndex * num); if (methodTable->ContainsGCPointers) { Buffer.BulkMoveWithWriteBarrier(ref reference2, ref reference, num2); } else { Buffer.Memmove(ref reference2, ref reference, num2); } return; } } Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length, reliable: false); } private unsafe static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, bool reliable) { if (sourceArray == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.sourceArray); } if (destinationArray == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destinationArray); } if (sourceArray.GetType() != destinationArray.GetType() && sourceArray.Rank != destinationArray.Rank) { throw new RankException(SR.Rank_MustMatch); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NeedNonNegNum); } int lowerBound = sourceArray.GetLowerBound(0); if (sourceIndex < lowerBound || sourceIndex - lowerBound < 0) { throw new ArgumentOutOfRangeException("sourceIndex", SR.ArgumentOutOfRange_ArrayLB); } sourceIndex -= lowerBound; int lowerBound2 = destinationArray.GetLowerBound(0); if (destinationIndex < lowerBound2 || destinationIndex - lowerBound2 < 0) { throw new ArgumentOutOfRangeException("destinationIndex", SR.ArgumentOutOfRange_ArrayLB); } destinationIndex -= lowerBound2; if ((uint)(sourceIndex + length) > sourceArray.NativeLength) { throw new ArgumentException(SR.Arg_LongerThanSrcArray, "sourceArray"); } if ((uint)(destinationIndex + length) > destinationArray.NativeLength) { throw new ArgumentException(SR.Arg_LongerThanDestArray, "destinationArray"); } if (sourceArray.GetType() == destinationArray.GetType() || IsSimpleCopy(sourceArray, destinationArray)) { MethodTable* methodTable = RuntimeHelpers.GetMethodTable(sourceArray); nuint num = methodTable->ComponentSize; nuint num2 = (uint)length * num; ref byte reference = ref Unsafe.AddByteOffset(ref MemoryMarshal.GetArrayDataReference(sourceArray), (uint)sourceIndex * num); ref byte reference2 = ref Unsafe.AddByteOffset(ref MemoryMarshal.GetArrayDataReference(destinationArray), (uint)destinationIndex * num); if (methodTable->ContainsGCPointers) { Buffer.BulkMoveWithWriteBarrier(ref reference2, ref reference, num2); } else { Buffer.Memmove(ref reference2, ref reference, num2); } } else { if (reliable) { throw new ArrayTypeMismatchException(SR.ArrayTypeMismatch_ConstrainedCopy); } CopySlow(sourceArray, sourceIndex, destinationArray, destinationIndex, length); } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsSimpleCopy(Array sourceArray, Array destinationArray); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void CopySlow(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length); public static void ConstrainedCopy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) { Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length, reliable: true); } public unsafe static void Clear(Array array) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } MethodTable* methodTable = RuntimeHelpers.GetMethodTable(array); nuint num = methodTable->ComponentSize * array.NativeLength; ref byte arrayDataReference = ref MemoryMarshal.GetArrayDataReference(array); if (!methodTable->ContainsGCPointers) { SpanHelpers.ClearWithoutReferences(ref arrayDataReference, num); } else { SpanHelpers.ClearWithReferences(ref Unsafe.As(ref arrayDataReference), num / (nuint)sizeof(IntPtr)); } } public unsafe static void Clear(Array array, int index, int length) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } ref byte source = ref Unsafe.As(array).Data; int num = 0; MethodTable* methodTable = RuntimeHelpers.GetMethodTable(array); if (methodTable->IsMultiDimensionalArray) { int multiDimensionalArrayRank = methodTable->MultiDimensionalArrayRank; num = Unsafe.Add(ref Unsafe.As(ref source), multiDimensionalArrayRank); source = ref Unsafe.Add(ref source, 8 * multiDimensionalArrayRank); } int num2 = index - num; if (index < num || num2 < 0 || length < 0 || (uint)(num2 + length) > array.NativeLength) { ThrowHelper.ThrowIndexOutOfRangeException(); } nuint num3 = methodTable->ComponentSize; ref byte reference = ref Unsafe.AddByteOffset(ref source, (uint)num2 * num3); nuint num4 = (uint)length * num3; if (methodTable->ContainsGCPointers) { SpanHelpers.ClearWithReferences(ref Unsafe.As(ref reference), num4 / (uint)sizeof(IntPtr)); } else { SpanHelpers.ClearWithoutReferences(ref reference, num4); } } private unsafe nint GetFlattenedIndex(ReadOnlySpan indices) { if (RuntimeHelpers.GetMethodTable(this)->IsMultiDimensionalArray) { ref int multiDimensionalArrayBounds = ref RuntimeHelpers.GetMultiDimensionalArrayBounds(this); nint num = 0; for (int i = 0; i < indices.Length; i++) { int num2 = indices[i] - Unsafe.Add(ref multiDimensionalArrayBounds, indices.Length + i); int num3 = Unsafe.Add(ref multiDimensionalArrayBounds, i); if ((uint)num2 >= (uint)num3) { ThrowHelper.ThrowIndexOutOfRangeException(); } num = num3 * num + num2; } return num; } int num4 = indices[0]; if ((uint)num4 >= (uint)LongLength) { ThrowHelper.ThrowIndexOutOfRangeException(); } return num4; } [MethodImpl(MethodImplOptions.InternalCall)] internal extern object InternalGetValue(nint flattenedIndex); [MethodImpl(MethodImplOptions.InternalCall)] private extern void InternalSetValue(object value, nint flattenedIndex); public int GetLength(int dimension) { int multiDimensionalArrayRank = RuntimeHelpers.GetMultiDimensionalArrayRank(this); if (multiDimensionalArrayRank == 0 && dimension == 0) { return Length; } if ((uint)dimension >= (uint)multiDimensionalArrayRank) { throw new IndexOutOfRangeException(SR.IndexOutOfRange_ArrayRankIndex); } return Unsafe.Add(ref RuntimeHelpers.GetMultiDimensionalArrayBounds(this), dimension); } public int GetUpperBound(int dimension) { int multiDimensionalArrayRank = RuntimeHelpers.GetMultiDimensionalArrayRank(this); if (multiDimensionalArrayRank == 0 && dimension == 0) { return Length - 1; } if ((uint)dimension >= (uint)multiDimensionalArrayRank) { throw new IndexOutOfRangeException(SR.IndexOutOfRange_ArrayRankIndex); } ref int multiDimensionalArrayBounds = ref RuntimeHelpers.GetMultiDimensionalArrayBounds(this); return Unsafe.Add(ref multiDimensionalArrayBounds, dimension) + Unsafe.Add(ref multiDimensionalArrayBounds, multiDimensionalArrayRank + dimension) - 1; } public int GetLowerBound(int dimension) { int multiDimensionalArrayRank = RuntimeHelpers.GetMultiDimensionalArrayRank(this); if (multiDimensionalArrayRank == 0 && dimension == 0) { return 0; } if ((uint)dimension >= (uint)multiDimensionalArrayRank) { throw new IndexOutOfRangeException(SR.IndexOutOfRange_ArrayRankIndex); } return Unsafe.Add(ref RuntimeHelpers.GetMultiDimensionalArrayBounds(this), multiDimensionalArrayRank + dimension); } [MethodImpl(MethodImplOptions.InternalCall)] internal extern CorElementType GetCorElementTypeOfElementType(); private unsafe bool IsValueOfElementType(object value) { MethodTable* methodTable = RuntimeHelpers.GetMethodTable(this); return (IntPtr)methodTable->ElementType == (IntPtr)RuntimeHelpers.GetMethodTable(value); } [MethodImpl(MethodImplOptions.InternalCall)] public extern void Initialize(); private protected Array() { } public static ReadOnlyCollection AsReadOnly(T[] array) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return new ReadOnlyCollection(array); } public static void Resize([NotNull] ref T[]? array, int newSize) { if (newSize < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.newSize, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } T[] array2 = array; if (array2 == null) { array = new T[newSize]; } else if (array2.Length != newSize) { T[] array3 = new T[newSize]; Buffer.Memmove(ref MemoryMarshal.GetArrayDataReference(array3), ref MemoryMarshal.GetArrayDataReference(array2), (uint)Math.Min(newSize, array2.Length)); array = array3; } } public static Array CreateInstance(Type elementType, params long[] lengths) { if (lengths == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.lengths); } if (lengths.Length == 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NeedAtLeast1Rank); } int[] array = new int[lengths.Length]; for (int i = 0; i < lengths.Length; i++) { long num = lengths[i]; int num2 = (int)num; if (num != num2) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.len, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } array[i] = num2; } return CreateInstance(elementType, array); } public static void Copy(Array sourceArray, Array destinationArray, long length) { int num = (int)length; if (length != num) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } Copy(sourceArray, destinationArray, num); } public static void Copy(Array sourceArray, long sourceIndex, Array destinationArray, long destinationIndex, long length) { int num = (int)sourceIndex; int num2 = (int)destinationIndex; int num3 = (int)length; if (sourceIndex != num) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceIndex, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } if (destinationIndex != num2) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.destinationIndex, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } if (length != num3) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } Copy(sourceArray, num, destinationArray, num2, num3); } public object? GetValue(params int[] indices) { if (indices == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); } if (Rank != indices.Length) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); } return InternalGetValue(GetFlattenedIndex(new ReadOnlySpan(indices))); } public unsafe object? GetValue(int index) { if (Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need1DArray); } return InternalGetValue(GetFlattenedIndex(new ReadOnlySpan(&index, 1))); } public object? GetValue(int index1, int index2) { if (Rank != 2) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need2DArray); } Span span = stackalloc int[2] { index1, index2 }; return InternalGetValue(GetFlattenedIndex(span)); } public object? GetValue(int index1, int index2, int index3) { if (Rank != 3) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need3DArray); } Span span = stackalloc int[3] { index1, index2, index3 }; return InternalGetValue(GetFlattenedIndex(span)); } public unsafe void SetValue(object? value, int index) { if (Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need1DArray); } InternalSetValue(value, GetFlattenedIndex(new ReadOnlySpan(&index, 1))); } public void SetValue(object? value, int index1, int index2) { if (Rank != 2) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need2DArray); } Span span = stackalloc int[2] { index1, index2 }; InternalSetValue(value, GetFlattenedIndex(span)); } public void SetValue(object? value, int index1, int index2, int index3) { if (Rank != 3) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_Need3DArray); } Span span = stackalloc int[3] { index1, index2, index3 }; InternalSetValue(value, GetFlattenedIndex(span)); } public void SetValue(object? value, params int[] indices) { if (indices == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); } if (Rank != indices.Length) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); } InternalSetValue(value, GetFlattenedIndex(new ReadOnlySpan(indices))); } public object? GetValue(long index) { int num = (int)index; if (index != num) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } return GetValue(num); } public object? GetValue(long index1, long index2) { int num = (int)index1; int num2 = (int)index2; if (index1 != num) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } if (index2 != num2) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } return GetValue(num, num2); } public object? GetValue(long index1, long index2, long index3) { int num = (int)index1; int num2 = (int)index2; int num3 = (int)index3; if (index1 != num) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } if (index2 != num2) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } if (index3 != num3) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index3, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } return GetValue(num, num2, num3); } public object? GetValue(params long[] indices) { if (indices == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); } if (Rank != indices.Length) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); } int[] array = new int[indices.Length]; for (int i = 0; i < indices.Length; i++) { long num = indices[i]; int num2 = (int)num; if (num != num2) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } array[i] = num2; } return GetValue(array); } public void SetValue(object? value, long index) { int num = (int)index; if (index != num) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } SetValue(value, num); } public void SetValue(object? value, long index1, long index2) { int num = (int)index1; int num2 = (int)index2; if (index1 != num) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } if (index2 != num2) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } SetValue(value, num, num2); } public void SetValue(object? value, long index1, long index2, long index3) { int num = (int)index1; int num2 = (int)index2; int num3 = (int)index3; if (index1 != num) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index1, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } if (index2 != num2) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index2, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } if (index3 != num3) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index3, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } SetValue(value, num, num2, num3); } public void SetValue(object? value, params long[] indices) { if (indices == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.indices); } if (Rank != indices.Length) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankIndices); } int[] array = new int[indices.Length]; for (int i = 0; i < indices.Length; i++) { long num = indices[i]; int num2 = (int)num; if (num != num2) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } array[i] = num2; } SetValue(value, array); } private static int GetMedian(int low, int hi) { return low + (hi - low >> 1); } public long GetLongLength(int dimension) { return GetLength(dimension); } int IList.Add(object value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); return 0; } bool IList.Contains(object value) { return IndexOf(this, value) >= GetLowerBound(0); } void IList.Clear() { Clear(this); } int IList.IndexOf(object value) { return IndexOf(this, value); } void IList.Insert(int index, object value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } void IList.Remove(object value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } void IList.RemoveAt(int index) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } [Intrinsic] public object Clone() { return MemberwiseClone(); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) { return 1; } Array array = other as Array; if (array == null || Length != array.Length) { ThrowHelper.ThrowArgumentException(ExceptionResource.ArgumentException_OtherNotArrayOfCorrectLength, ExceptionArgument.other); } int i = 0; int num = 0; for (; i < array.Length; i++) { if (num != 0) { break; } object value = GetValue(i); object value2 = array.GetValue(i); num = comparer.Compare(value, value2); } return num; } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other == null) { return false; } if (this == other) { return true; } if (!(other is Array array) || array.Length != Length) { return false; } for (int i = 0; i < array.Length; i++) { object value = GetValue(i); object value2 = array.GetValue(i); if (!comparer.Equals(value, value2)) { return false; } } return true; } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { if (comparer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer); } HashCode hashCode = default(HashCode); for (int i = ((Length >= 8) ? (Length - 8) : 0); i < Length; i++) { hashCode.Add(comparer.GetHashCode(GetValue(i))); } return hashCode.ToHashCode(); } public static int BinarySearch(Array array, object? value) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return BinarySearch(array, array.GetLowerBound(0), array.Length, value, null); } public static int BinarySearch(Array array, int index, int length, object? value) { return BinarySearch(array, index, length, value, null); } public static int BinarySearch(Array array, object? value, IComparer? comparer) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return BinarySearch(array, array.GetLowerBound(0), array.Length, value, comparer); } public static int BinarySearch(Array array, int index, int length, object? value, IComparer? comparer) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } int lowerBound = array.GetLowerBound(0); if (index < lowerBound) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (length < 0) { ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); } if (array.Length - (index - lowerBound) < length) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } if (array.Rank != 1) { ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); } if (comparer == null) { comparer = Comparer.Default; } int num = index; int num2 = index + length - 1; if (array is object[] array2) { while (num <= num2) { int median = GetMedian(num, num2); int num3; try { num3 = comparer.Compare(array2[median], value); } catch (Exception e) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e); return 0; } if (num3 == 0) { return median; } if (num3 < 0) { num = median + 1; } else { num2 = median - 1; } } return ~num; } if (comparer == Comparer.Default) { CorElementType corElementTypeOfElementType = array.GetCorElementTypeOfElementType(); if (corElementTypeOfElementType.IsPrimitiveType()) { if (value == null) { return ~index; } if (array.IsValueOfElementType(value)) { int adjustedIndex2 = index - lowerBound; int num4 = -1; switch (corElementTypeOfElementType) { case CorElementType.ELEMENT_TYPE_I1: num4 = GenericBinarySearch(array, adjustedIndex2, length, value); break; case CorElementType.ELEMENT_TYPE_BOOLEAN: case CorElementType.ELEMENT_TYPE_U1: num4 = GenericBinarySearch(array, adjustedIndex2, length, value); break; case CorElementType.ELEMENT_TYPE_I2: num4 = GenericBinarySearch(array, adjustedIndex2, length, value); break; case CorElementType.ELEMENT_TYPE_CHAR: case CorElementType.ELEMENT_TYPE_U2: num4 = GenericBinarySearch(array, adjustedIndex2, length, value); break; case CorElementType.ELEMENT_TYPE_I4: case CorElementType.ELEMENT_TYPE_I: num4 = GenericBinarySearch(array, adjustedIndex2, length, value); break; case CorElementType.ELEMENT_TYPE_U4: case CorElementType.ELEMENT_TYPE_U: num4 = GenericBinarySearch(array, adjustedIndex2, length, value); break; case CorElementType.ELEMENT_TYPE_I8: num4 = GenericBinarySearch(array, adjustedIndex2, length, value); break; case CorElementType.ELEMENT_TYPE_U8: num4 = GenericBinarySearch(array, adjustedIndex2, length, value); break; case CorElementType.ELEMENT_TYPE_R4: num4 = GenericBinarySearch(array, adjustedIndex2, length, value); break; case CorElementType.ELEMENT_TYPE_R8: num4 = GenericBinarySearch(array, adjustedIndex2, length, value); break; } if (num4 < 0) { return ~(index + ~num4); } return index + num4; } } } while (num <= num2) { int median2 = GetMedian(num, num2); int num5; try { num5 = comparer.Compare(array.GetValue(median2), value); } catch (Exception e2) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_IComparerFailed, e2); return 0; } if (num5 == 0) { return median2; } if (num5 < 0) { num = median2 + 1; } else { num2 = median2 - 1; } } return ~num; static int GenericBinarySearch(Array array, int adjustedIndex, int length, object value) where T : struct, IComparable { return UnsafeArrayAsSpan(array, adjustedIndex, length).BinarySearch(Unsafe.As(ref value.GetRawData())); } } public static int BinarySearch(T[] array, T value) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return BinarySearch(array, 0, array.Length, value, null); } public static int BinarySearch(T[] array, T value, IComparer? comparer) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return BinarySearch(array, 0, array.Length, value, comparer); } public static int BinarySearch(T[] array, int index, int length, T value) { return BinarySearch(array, index, length, value, null); } public static int BinarySearch(T[] array, int index, int length, T value, IComparer? comparer) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (length < 0) { ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); } if (array.Length - index < length) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } return ArraySortHelper.Default.BinarySearch(array, index, length, value, comparer); } public static TOutput[] ConvertAll(TInput[] array, Converter converter) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (converter == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter); } TOutput[] array2 = new TOutput[array.Length]; for (int i = 0; i < array.Length; i++) { array2[i] = converter(array[i]); } return array2; } public void CopyTo(Array array, int index) { if (array != null && array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } Copy(this, GetLowerBound(0), array, index, Length); } public void CopyTo(Array array, long index) { int num = (int)index; if (index != num) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported); } CopyTo(array, num); } public static T[] Empty() { return EmptyArray.Value; } public static bool Exists(T[] array, Predicate match) { return FindIndex(array, match) != -1; } public static void Fill(T[] array, T value) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (!typeof(T).IsValueType && array.GetType() != typeof(T[])) { for (int i = 0; i < array.Length; i++) { array[i] = value; } } else { new Span(array).Fill(value); } } public static void Fill(T[] array, T value, int startIndex, int count) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if ((uint)startIndex > (uint)array.Length) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if ((uint)count > (uint)(array.Length - startIndex)) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } if (!typeof(T).IsValueType && array.GetType() != typeof(T[])) { for (int i = startIndex; i < startIndex + count; i++) { array[i] = value; } } else { new Span(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), (nint)(uint)startIndex), count).Fill(value); } } public static T? Find(T[] array, Predicate match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } for (int i = 0; i < array.Length; i++) { if (match(array[i])) { return array[i]; } } return default(T); } public static T[] FindAll(T[] array, Predicate match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } List list = new List(); for (int i = 0; i < array.Length; i++) { if (match(array[i])) { list.Add(array[i]); } } return list.ToArray(); } public static int FindIndex(T[] array, Predicate match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return FindIndex(array, 0, array.Length, match); } public static int FindIndex(T[] array, int startIndex, Predicate match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return FindIndex(array, startIndex, array.Length - startIndex, match); } public static int FindIndex(T[] array, int startIndex, int count, Predicate match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (startIndex < 0 || startIndex > array.Length) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if (count < 0 || startIndex > array.Length - count) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } int num = startIndex + count; for (int i = startIndex; i < num; i++) { if (match(array[i])) { return i; } } return -1; } public static T? FindLast(T[] array, Predicate match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } for (int num = array.Length - 1; num >= 0; num--) { if (match(array[num])) { return array[num]; } } return default(T); } public static int FindLastIndex(T[] array, Predicate match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return FindLastIndex(array, array.Length - 1, array.Length, match); } public static int FindLastIndex(T[] array, int startIndex, Predicate match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return FindLastIndex(array, startIndex, startIndex + 1, match); } public static int FindLastIndex(T[] array, int startIndex, int count, Predicate match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } if (array.Length == 0) { if (startIndex != -1) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } } else if (startIndex < 0 || startIndex >= array.Length) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if (count < 0 || startIndex - count + 1 < 0) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } int num = startIndex - count; for (int num2 = startIndex; num2 > num; num2--) { if (match(array[num2])) { return num2; } } return -1; } public static void ForEach(T[] array, Action action) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (action == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } for (int i = 0; i < array.Length; i++) { action(array[i]); } } public static int IndexOf(Array array, object? value) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return IndexOf(array, value, array.GetLowerBound(0), array.Length); } public static int IndexOf(Array array, object? value, int startIndex) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } int lowerBound = array.GetLowerBound(0); return IndexOf(array, value, startIndex, array.Length - startIndex + lowerBound); } public static int IndexOf(Array array, object? value, int startIndex, int count) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); } int lowerBound = array.GetLowerBound(0); if (startIndex < lowerBound || startIndex > array.Length + lowerBound) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if (count < 0 || count > array.Length - startIndex + lowerBound) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } int num = startIndex + count; if (array is object[] array2) { if (value == null) { for (int i = startIndex; i < num; i++) { if (array2[i] == null) { return i; } } } else { for (int j = startIndex; j < num; j++) { object obj = array2[j]; if (obj != null && obj.Equals(value)) { return j; } } } return -1; } CorElementType corElementTypeOfElementType = array.GetCorElementTypeOfElementType(); if (corElementTypeOfElementType.IsPrimitiveType()) { if (value == null) { return lowerBound - 1; } if (array.IsValueOfElementType(value)) { int adjustedIndex2 = startIndex - lowerBound; int num2 = -1; switch (corElementTypeOfElementType) { case CorElementType.ELEMENT_TYPE_BOOLEAN: case CorElementType.ELEMENT_TYPE_I1: case CorElementType.ELEMENT_TYPE_U1: num2 = GenericIndexOf(array, value, adjustedIndex2, count); break; case CorElementType.ELEMENT_TYPE_CHAR: case CorElementType.ELEMENT_TYPE_I2: case CorElementType.ELEMENT_TYPE_U2: num2 = GenericIndexOf(array, value, adjustedIndex2, count); break; case CorElementType.ELEMENT_TYPE_I4: case CorElementType.ELEMENT_TYPE_U4: case CorElementType.ELEMENT_TYPE_I: case CorElementType.ELEMENT_TYPE_U: num2 = GenericIndexOf(array, value, adjustedIndex2, count); break; case CorElementType.ELEMENT_TYPE_I8: case CorElementType.ELEMENT_TYPE_U8: num2 = GenericIndexOf(array, value, adjustedIndex2, count); break; case CorElementType.ELEMENT_TYPE_R4: num2 = GenericIndexOf(array, value, adjustedIndex2, count); break; case CorElementType.ELEMENT_TYPE_R8: num2 = GenericIndexOf(array, value, adjustedIndex2, count); break; } return ((num2 >= 0) ? startIndex : lowerBound) + num2; } } for (int k = startIndex; k < num; k++) { object value2 = array.GetValue(k); if (value2 == null) { if (value == null) { return k; } } else if (value2.Equals(value)) { return k; } } return lowerBound - 1; static int GenericIndexOf(Array array, object value, int adjustedIndex, int length) where T : struct, IEquatable { return UnsafeArrayAsSpan(array, adjustedIndex, length).IndexOf(Unsafe.As(ref value.GetRawData())); } } public static int IndexOf(T[] array, T value) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return IndexOf(array, value, 0, array.Length); } public static int IndexOf(T[] array, T value, int startIndex) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return IndexOf(array, value, startIndex, array.Length - startIndex); } public static int IndexOf(T[] array, T value, int startIndex, int count) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if ((uint)startIndex > (uint)array.Length) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if ((uint)count > (uint)(array.Length - startIndex)) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { int num = SpanHelpers.IndexOf(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(array)), startIndex), Unsafe.As(ref value), count); return ((num >= 0) ? startIndex : 0) + num; } if (Unsafe.SizeOf() == 2) { int num2 = SpanHelpers.IndexOf(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(array)), startIndex), Unsafe.As(ref value), count); return ((num2 >= 0) ? startIndex : 0) + num2; } if (Unsafe.SizeOf() == 4) { int num3 = SpanHelpers.IndexOf(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(array)), startIndex), Unsafe.As(ref value), count); return ((num3 >= 0) ? startIndex : 0) + num3; } if (Unsafe.SizeOf() == 8) { int num4 = SpanHelpers.IndexOf(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(array)), startIndex), Unsafe.As(ref value), count); return ((num4 >= 0) ? startIndex : 0) + num4; } } return EqualityComparer.Default.IndexOf(array, value, startIndex, count); } public static int LastIndexOf(Array array, object? value) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } int lowerBound = array.GetLowerBound(0); return LastIndexOf(array, value, array.Length - 1 + lowerBound, array.Length); } public static int LastIndexOf(Array array, object? value, int startIndex) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } int lowerBound = array.GetLowerBound(0); return LastIndexOf(array, value, startIndex, startIndex + 1 - lowerBound); } public static int LastIndexOf(Array array, object? value, int startIndex, int count) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } int lowerBound = array.GetLowerBound(0); if (array.Length == 0) { return lowerBound - 1; } if (startIndex < lowerBound || startIndex >= array.Length + lowerBound) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if (count < 0) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } if (count > startIndex - lowerBound + 1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.endIndex, ExceptionResource.ArgumentOutOfRange_EndIndexStartIndex); } if (array.Rank != 1) { ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); } int num = startIndex - count + 1; if (array is object[] array2) { if (value == null) { for (int num2 = startIndex; num2 >= num; num2--) { if (array2[num2] == null) { return num2; } } } else { for (int num3 = startIndex; num3 >= num; num3--) { object obj = array2[num3]; if (obj != null && obj.Equals(value)) { return num3; } } } return -1; } CorElementType corElementTypeOfElementType = array.GetCorElementTypeOfElementType(); if (corElementTypeOfElementType.IsPrimitiveType()) { if (value == null) { return lowerBound - 1; } if (array.IsValueOfElementType(value)) { int adjustedIndex2 = num - lowerBound; int num4 = -1; switch (corElementTypeOfElementType) { case CorElementType.ELEMENT_TYPE_BOOLEAN: case CorElementType.ELEMENT_TYPE_I1: case CorElementType.ELEMENT_TYPE_U1: num4 = GenericLastIndexOf(array, value, adjustedIndex2, count); break; case CorElementType.ELEMENT_TYPE_CHAR: case CorElementType.ELEMENT_TYPE_I2: case CorElementType.ELEMENT_TYPE_U2: num4 = GenericLastIndexOf(array, value, adjustedIndex2, count); break; case CorElementType.ELEMENT_TYPE_I4: case CorElementType.ELEMENT_TYPE_U4: case CorElementType.ELEMENT_TYPE_I: case CorElementType.ELEMENT_TYPE_U: num4 = GenericLastIndexOf(array, value, adjustedIndex2, count); break; case CorElementType.ELEMENT_TYPE_I8: case CorElementType.ELEMENT_TYPE_U8: num4 = GenericLastIndexOf(array, value, adjustedIndex2, count); break; case CorElementType.ELEMENT_TYPE_R4: num4 = GenericLastIndexOf(array, value, adjustedIndex2, count); break; case CorElementType.ELEMENT_TYPE_R8: num4 = GenericLastIndexOf(array, value, adjustedIndex2, count); break; } return ((num4 >= 0) ? num : lowerBound) + num4; } } for (int num5 = startIndex; num5 >= num; num5--) { object value2 = array.GetValue(num5); if (value2 == null) { if (value == null) { return num5; } } else if (value2.Equals(value)) { return num5; } } return lowerBound - 1; static int GenericLastIndexOf(Array array, object value, int adjustedIndex, int length) where T : struct, IEquatable { return UnsafeArrayAsSpan(array, adjustedIndex, length).LastIndexOf(Unsafe.As(ref value.GetRawData())); } } public static int LastIndexOf(T[] array, T value) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return LastIndexOf(array, value, array.Length - 1, array.Length); } public static int LastIndexOf(T[] array, T value, int startIndex) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return LastIndexOf(array, value, startIndex, (array.Length != 0) ? (startIndex + 1) : 0); } public static int LastIndexOf(T[] array, T value, int startIndex, int count) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Length == 0) { if (startIndex != -1 && startIndex != 0) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if (count != 0) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } return -1; } if ((uint)startIndex >= (uint)array.Length) { ThrowHelper.ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index(); } if (count < 0 || startIndex - count + 1 < 0) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { int num = startIndex - count + 1; int num2 = SpanHelpers.LastIndexOf(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(array)), num), Unsafe.As(ref value), count); return ((num2 >= 0) ? num : 0) + num2; } if (Unsafe.SizeOf() == 2) { int num3 = startIndex - count + 1; int num4 = SpanHelpers.LastIndexOf(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(array)), num3), Unsafe.As(ref value), count); return ((num4 >= 0) ? num3 : 0) + num4; } if (Unsafe.SizeOf() == 4) { int num5 = startIndex - count + 1; int num6 = SpanHelpers.LastIndexOf(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(array)), num5), Unsafe.As(ref value), count); return ((num6 >= 0) ? num5 : 0) + num6; } if (Unsafe.SizeOf() == 8) { int num7 = startIndex - count + 1; int num8 = SpanHelpers.LastIndexOf(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(array)), num7), Unsafe.As(ref value), count); return ((num8 >= 0) ? num7 : 0) + num8; } } return EqualityComparer.Default.LastIndexOf(array, value, startIndex, count); } public static void Reverse(Array array) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Reverse(array, array.GetLowerBound(0), array.Length); } public static void Reverse(Array array, int index, int length) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } int lowerBound = array.GetLowerBound(0); if (index < lowerBound) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (length < 0) { ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); } if (array.Length - (index - lowerBound) < length) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } if (array.Rank != 1) { ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); } if (length <= 1) { return; } int adjustedIndex = index - lowerBound; switch (array.GetCorElementTypeOfElementType()) { case CorElementType.ELEMENT_TYPE_BOOLEAN: case CorElementType.ELEMENT_TYPE_I1: case CorElementType.ELEMENT_TYPE_U1: UnsafeArrayAsSpan(array, adjustedIndex, length).Reverse(); return; case CorElementType.ELEMENT_TYPE_CHAR: case CorElementType.ELEMENT_TYPE_I2: case CorElementType.ELEMENT_TYPE_U2: UnsafeArrayAsSpan(array, adjustedIndex, length).Reverse(); return; case CorElementType.ELEMENT_TYPE_I4: case CorElementType.ELEMENT_TYPE_U4: case CorElementType.ELEMENT_TYPE_R4: case CorElementType.ELEMENT_TYPE_I: case CorElementType.ELEMENT_TYPE_U: UnsafeArrayAsSpan(array, adjustedIndex, length).Reverse(); return; case CorElementType.ELEMENT_TYPE_I8: case CorElementType.ELEMENT_TYPE_U8: case CorElementType.ELEMENT_TYPE_R8: UnsafeArrayAsSpan(array, adjustedIndex, length).Reverse(); return; case CorElementType.ELEMENT_TYPE_ARRAY: case CorElementType.ELEMENT_TYPE_OBJECT: case CorElementType.ELEMENT_TYPE_SZARRAY: UnsafeArrayAsSpan(array, adjustedIndex, length).Reverse(); return; } int num = index; int num2 = index + length - 1; while (num < num2) { object value = array.GetValue(num); array.SetValue(array.GetValue(num2), num); array.SetValue(value, num2); num++; num2--; } } public static void Reverse(T[] array) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Reverse(array, 0, array.Length); } public static void Reverse(T[] array, int index, int length) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (length < 0) { ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); } if (array.Length - index < length) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } if (length > 1) { ref T reference = ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), index); ref T reference2 = ref Unsafe.Add(ref Unsafe.Add(ref reference, length), -1); do { T val = reference; reference = reference2; reference2 = val; reference = ref Unsafe.Add(ref reference, 1); reference2 = ref Unsafe.Add(ref reference2, -1); } while (Unsafe.IsAddressLessThan(ref reference, ref reference2)); } } public static void Sort(Array array) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Sort(array, null, array.GetLowerBound(0), array.Length, null); } public static void Sort(Array keys, Array? items) { if (keys == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); } Sort(keys, items, keys.GetLowerBound(0), keys.Length, null); } public static void Sort(Array array, int index, int length) { Sort(array, null, index, length, null); } public static void Sort(Array keys, Array? items, int index, int length) { Sort(keys, items, index, length, null); } public static void Sort(Array array, IComparer? comparer) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Sort(array, null, array.GetLowerBound(0), array.Length, comparer); } public static void Sort(Array keys, Array? items, IComparer? comparer) { if (keys == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); } Sort(keys, items, keys.GetLowerBound(0), keys.Length, comparer); } public static void Sort(Array array, int index, int length, IComparer? comparer) { Sort(array, null, index, length, comparer); } public static void Sort(Array keys, Array? items, int index, int length, IComparer? comparer) { if (keys == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); } if (keys.Rank != 1 || (items != null && items.Rank != 1)) { ThrowHelper.ThrowRankException(ExceptionResource.Rank_MultiDimNotSupported); } int lowerBound = keys.GetLowerBound(0); if (items != null && lowerBound != items.GetLowerBound(0)) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_LowerBoundsMustMatch); } if (index < lowerBound) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (length < 0) { ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); } if (keys.Length - (index - lowerBound) < length || (items != null && index - lowerBound > items.Length - length)) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } if (length <= 1) { return; } if (comparer == null) { comparer = Comparer.Default; } if (keys is object[] keys2) { object[] array = items as object[]; if (items == null || array != null) { new SorterObjectArray(keys2, array, comparer).Sort(index, length); return; } } if (comparer == Comparer.Default) { CorElementType corElementTypeOfElementType = keys.GetCorElementTypeOfElementType(); if (items == null || items.GetCorElementTypeOfElementType() == corElementTypeOfElementType) { int adjustedIndex2 = index - lowerBound; switch (corElementTypeOfElementType) { case CorElementType.ELEMENT_TYPE_I1: GenericSort(keys, items, adjustedIndex2, length); return; case CorElementType.ELEMENT_TYPE_BOOLEAN: case CorElementType.ELEMENT_TYPE_U1: GenericSort(keys, items, adjustedIndex2, length); return; case CorElementType.ELEMENT_TYPE_I2: GenericSort(keys, items, adjustedIndex2, length); return; case CorElementType.ELEMENT_TYPE_CHAR: case CorElementType.ELEMENT_TYPE_U2: GenericSort(keys, items, adjustedIndex2, length); return; case CorElementType.ELEMENT_TYPE_I4: case CorElementType.ELEMENT_TYPE_I: GenericSort(keys, items, adjustedIndex2, length); return; case CorElementType.ELEMENT_TYPE_U4: case CorElementType.ELEMENT_TYPE_U: GenericSort(keys, items, adjustedIndex2, length); return; case CorElementType.ELEMENT_TYPE_I8: GenericSort(keys, items, adjustedIndex2, length); return; case CorElementType.ELEMENT_TYPE_U8: GenericSort(keys, items, adjustedIndex2, length); return; case CorElementType.ELEMENT_TYPE_R4: GenericSort(keys, items, adjustedIndex2, length); return; case CorElementType.ELEMENT_TYPE_R8: GenericSort(keys, items, adjustedIndex2, length); return; } } } new SorterGenericArray(keys, items, comparer).Sort(index, length); static void GenericSort(Array keys, Array items, int adjustedIndex, int length) where T : struct { Span span = UnsafeArrayAsSpan(keys, adjustedIndex, length); if (items != null) { span.Sort(UnsafeArrayAsSpan(items, adjustedIndex, length)); } else { span.Sort(); } } } public static void Sort(T[] array) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Length > 1) { Span keys = new Span(ref MemoryMarshal.GetArrayDataReference(array), array.Length); ArraySortHelper.Default.Sort(keys, null); } } public static void Sort(TKey[] keys, TValue[]? items) { if (keys == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); } Sort(keys, items, 0, keys.Length, null); } public static void Sort(T[] array, int index, int length) { Sort(array, index, length, null); } public static void Sort(TKey[] keys, TValue[]? items, int index, int length) { Sort(keys, items, index, length, null); } public static void Sort(T[] array, IComparer? comparer) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } Sort(array, 0, array.Length, comparer); } public static void Sort(TKey[] keys, TValue[]? items, IComparer? comparer) { if (keys == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); } Sort(keys, items, 0, keys.Length, comparer); } public static void Sort(T[] array, int index, int length, IComparer? comparer) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (length < 0) { ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); } if (array.Length - index < length) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } if (length > 1) { Span keys = new Span(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), index), length); ArraySortHelper.Default.Sort(keys, comparer); } } public static void Sort(TKey[] keys, TValue[]? items, int index, int length, IComparer? comparer) { if (keys == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keys); } if (index < 0) { ThrowHelper.ThrowIndexArgumentOutOfRange_NeedNonNegNumException(); } if (length < 0) { ThrowHelper.ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum(); } if (keys.Length - index < length || (items != null && index > items.Length - length)) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } if (length > 1) { if (items == null) { Sort(keys, index, length, comparer); return; } Span keys2 = new Span(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(keys), index), length); Span values = new Span(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(items), index), length); ArraySortHelper.Default.Sort(keys2, values, comparer); } } public static void Sort(T[] array, Comparison comparison) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (comparison == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } Span keys = new Span(ref MemoryMarshal.GetArrayDataReference(array), array.Length); ArraySortHelper.Sort(keys, comparison); } public static bool TrueForAll(T[] array, Predicate match) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } for (int i = 0; i < array.Length; i++) { if (!match(array[i])) { return false; } } return true; } private static Span UnsafeArrayAsSpan(Array array, int adjustedIndex, int length) { return new Span(ref Unsafe.As(ref MemoryMarshal.GetArrayDataReference(array)), array.Length).Slice(adjustedIndex, length); } public System.Collections.IEnumerator GetEnumerator() { return new ArrayEnumerator(this); } } internal sealed class SZArrayHelper { private SZArrayHelper() { } internal IEnumerator GetEnumerator() { T[] array = Unsafe.As(this); if (array.Length != 0) { return new SZGenericArrayEnumerator(array); } return SZGenericArrayEnumerator.Empty; } private void CopyTo(T[] array, int index) { T[] array2 = Unsafe.As(this); Array.Copy(array2, 0, array, index, array2.Length); } internal int get_Count() { T[] array = Unsafe.As(this); return array.Length; } internal T get_Item(int index) { T[] array = Unsafe.As(this); if ((uint)index >= (uint)array.Length) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return array[index]; } internal void set_Item(int index, T value) { T[] array = Unsafe.As(this); if ((uint)index >= (uint)array.Length) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } array[index] = value; } private void Add(T value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } private bool Contains(T value) { T[] array = Unsafe.As(this); return Array.IndexOf(array, value, 0, array.Length) >= 0; } private bool get_IsReadOnly() { return true; } private void Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ReadOnlyCollection); } private int IndexOf(T value) { T[] array = Unsafe.As(this); return Array.IndexOf(array, value, 0, array.Length); } private void Insert(int index, T value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } private bool Remove(T value) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); return false; } private void RemoveAt(int index) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_FixedSizeCollection); } } [Serializable] [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class Attribute { public virtual object TypeId => GetType(); private static Attribute[] InternalGetCustomAttributes(PropertyInfo element, Type type, bool inherit) { Attribute[] array = (Attribute[])element.GetCustomAttributes(type, inherit); if (!inherit) { return array; } Type[] indexParameterTypes = GetIndexParameterTypes(element); PropertyInfo parentDefinition = GetParentDefinition(element, indexParameterTypes); if (parentDefinition == null) { return array; } Dictionary types = new Dictionary(11); List list = new List(); CopyToAttributeList(list, array, types); do { array = GetCustomAttributes(parentDefinition, type, inherit: false); AddAttributesToList(list, array, types); parentDefinition = GetParentDefinition(parentDefinition, indexParameterTypes); } while (parentDefinition != null); Attribute[] array2 = CreateAttributeArrayHelper(type, list.Count); list.CopyTo(array2, 0); return array2; } private static bool InternalIsDefined(PropertyInfo element, Type attributeType, bool inherit) { if (element.IsDefined(attributeType, inherit)) { return true; } if (inherit) { AttributeUsageAttribute attributeUsageAttribute = InternalGetAttributeUsage(attributeType); if (!attributeUsageAttribute.Inherited) { return false; } Type[] indexParameterTypes = GetIndexParameterTypes(element); PropertyInfo parentDefinition = GetParentDefinition(element, indexParameterTypes); while (parentDefinition != null) { if (parentDefinition.IsDefined(attributeType, inherit: false)) { return true; } parentDefinition = GetParentDefinition(parentDefinition, indexParameterTypes); } } return false; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", Justification = "rtPropAccessor.DeclaringType is guaranteed to have the specified property because rtPropAccessor.GetParentDefinition() returned a non-null MethodInfo.")] private static PropertyInfo GetParentDefinition(PropertyInfo property, Type[] propertyParameters) { MethodInfo methodInfo = property.GetGetMethod(nonPublic: true) ?? property.GetSetMethod(nonPublic: true); RuntimeMethodInfo runtimeMethodInfo = methodInfo as RuntimeMethodInfo; if (runtimeMethodInfo != null) { runtimeMethodInfo = runtimeMethodInfo.GetParentDefinition(); if (runtimeMethodInfo != null) { return runtimeMethodInfo.DeclaringType.GetProperty(property.Name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, property.PropertyType, propertyParameters, null); } } return null; } private static Attribute[] InternalGetCustomAttributes(EventInfo element, Type type, bool inherit) { Attribute[] array = (Attribute[])element.GetCustomAttributes(type, inherit); if (!inherit) { return array; } EventInfo parentDefinition = GetParentDefinition(element); if (parentDefinition == null) { return array; } Dictionary types = new Dictionary(11); List list = new List(); CopyToAttributeList(list, array, types); do { array = GetCustomAttributes(parentDefinition, type, inherit: false); AddAttributesToList(list, array, types); parentDefinition = GetParentDefinition(parentDefinition); } while (parentDefinition != null); Attribute[] array2 = CreateAttributeArrayHelper(type, list.Count); list.CopyTo(array2, 0); return array2; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", Justification = "rtAdd.DeclaringType is guaranteed to have the specified event because rtAdd.GetParentDefinition() returned a non-null MethodInfo.")] private static EventInfo GetParentDefinition(EventInfo ev) { MethodInfo addMethod = ev.GetAddMethod(nonPublic: true); RuntimeMethodInfo runtimeMethodInfo = addMethod as RuntimeMethodInfo; if (runtimeMethodInfo != null) { runtimeMethodInfo = runtimeMethodInfo.GetParentDefinition(); if (runtimeMethodInfo != null) { return runtimeMethodInfo.DeclaringType.GetEvent(ev.Name); } } return null; } private static bool InternalIsDefined(EventInfo element, Type attributeType, bool inherit) { if (element.IsDefined(attributeType, inherit)) { return true; } if (inherit) { AttributeUsageAttribute attributeUsageAttribute = InternalGetAttributeUsage(attributeType); if (!attributeUsageAttribute.Inherited) { return false; } EventInfo parentDefinition = GetParentDefinition(element); while (parentDefinition != null) { if (parentDefinition.IsDefined(attributeType, inherit: false)) { return true; } parentDefinition = GetParentDefinition(parentDefinition); } } return false; } private static ParameterInfo GetParentDefinition(ParameterInfo param) { RuntimeMethodInfo runtimeMethodInfo = param.Member as RuntimeMethodInfo; if (runtimeMethodInfo != null) { runtimeMethodInfo = runtimeMethodInfo.GetParentDefinition(); if (runtimeMethodInfo != null) { int position = param.Position; if (position == -1) { return runtimeMethodInfo.ReturnParameter; } ParameterInfo[] parameters = runtimeMethodInfo.GetParameters(); return parameters[position]; } } return null; } private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type type, bool inherit) { List list = new List(); if ((object)type == null) { type = typeof(Attribute); } object[] customAttributes = param.GetCustomAttributes(type, inherit: false); for (int i = 0; i < customAttributes.Length; i++) { Type type2 = customAttributes[i].GetType(); AttributeUsageAttribute attributeUsageAttribute = InternalGetAttributeUsage(type2); if (!attributeUsageAttribute.AllowMultiple) { list.Add(type2); } } Attribute[] array = ((customAttributes.Length != 0) ? ((Attribute[])customAttributes) : CreateAttributeArrayHelper(type, 0)); if ((object)param.Member.DeclaringType == null) { return array; } if (!inherit) { return array; } for (ParameterInfo parentDefinition = GetParentDefinition(param); parentDefinition != null; parentDefinition = GetParentDefinition(parentDefinition)) { customAttributes = parentDefinition.GetCustomAttributes(type, inherit: false); int num = 0; for (int j = 0; j < customAttributes.Length; j++) { Type type3 = customAttributes[j].GetType(); AttributeUsageAttribute attributeUsageAttribute2 = InternalGetAttributeUsage(type3); if (attributeUsageAttribute2.Inherited && !list.Contains(type3)) { if (!attributeUsageAttribute2.AllowMultiple) { list.Add(type3); } num++; } else { customAttributes[j] = null; } } Attribute[] array2 = CreateAttributeArrayHelper(type, num); num = 0; foreach (object obj in customAttributes) { if (obj != null) { array2[num] = (Attribute)obj; num++; } } Attribute[] array3 = array; array = CreateAttributeArrayHelper(type, array3.Length + num); Array.Copy(array3, array, array3.Length); int num2 = array3.Length; for (int l = 0; l < array2.Length; l++) { array[num2 + l] = array2[l]; } } return array; } private static bool InternalParamIsDefined(ParameterInfo param, Type type, bool inherit) { if (param.IsDefined(type, inherit: false)) { return true; } if ((object)param.Member.DeclaringType == null || !inherit) { return false; } for (ParameterInfo parentDefinition = GetParentDefinition(param); parentDefinition != null; parentDefinition = GetParentDefinition(parentDefinition)) { object[] customAttributes = parentDefinition.GetCustomAttributes(type, inherit: false); for (int i = 0; i < customAttributes.Length; i++) { Type type2 = customAttributes[i].GetType(); AttributeUsageAttribute attributeUsageAttribute = InternalGetAttributeUsage(type2); if (customAttributes[i] is Attribute && attributeUsageAttribute.Inherited) { return true; } } } return false; } private static void CopyToAttributeList(List attributeList, Attribute[] attributes, Dictionary types) { for (int i = 0; i < attributes.Length; i++) { attributeList.Add(attributes[i]); Type type = attributes[i].GetType(); if (!types.ContainsKey(type)) { types[type] = InternalGetAttributeUsage(type); } } } private static Type[] GetIndexParameterTypes(PropertyInfo element) { ParameterInfo[] indexParameters = element.GetIndexParameters(); if (indexParameters.Length != 0) { Type[] array = new Type[indexParameters.Length]; for (int i = 0; i < indexParameters.Length; i++) { array[i] = indexParameters[i].ParameterType; } return array; } return Type.EmptyTypes; } private static void AddAttributesToList(List attributeList, Attribute[] attributes, Dictionary types) { for (int i = 0; i < attributes.Length; i++) { Type type = attributes[i].GetType(); types.TryGetValue(type, out var value); if (value == null) { value = (types[type] = InternalGetAttributeUsage(type)); if (value.Inherited) { attributeList.Add(attributes[i]); } } else if (value.Inherited && value.AllowMultiple) { attributeList.Add(attributes[i]); } } } private static AttributeUsageAttribute InternalGetAttributeUsage(Type type) { object[] customAttributes = type.GetCustomAttributes(typeof(AttributeUsageAttribute), inherit: false); if (customAttributes.Length == 1) { return (AttributeUsageAttribute)customAttributes[0]; } if (customAttributes.Length == 0) { return AttributeUsageAttribute.Default; } throw new FormatException(SR.Format(SR.Format_AttributeUsage, type)); } private static Attribute[] CreateAttributeArrayHelper(Type elementType, int elementCount) { return (Attribute[])Array.CreateInstance(elementType, elementCount); } public static Attribute[] GetCustomAttributes(MemberInfo element, Type attributeType) { return GetCustomAttributes(element, attributeType, inherit: true); } public static Attribute[] GetCustomAttributes(MemberInfo element, Type attributeType, bool inherit) { if (element == null) { throw new ArgumentNullException("element"); } if (attributeType == null) { throw new ArgumentNullException("attributeType"); } if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) { throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); } return element.MemberType switch { MemberTypes.Property => InternalGetCustomAttributes((PropertyInfo)element, attributeType, inherit), MemberTypes.Event => InternalGetCustomAttributes((EventInfo)element, attributeType, inherit), _ => element.GetCustomAttributes(attributeType, inherit) as Attribute[], }; } public static Attribute[] GetCustomAttributes(MemberInfo element) { return GetCustomAttributes(element, inherit: true); } public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit) { if (element == null) { throw new ArgumentNullException("element"); } return element.MemberType switch { MemberTypes.Property => InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit), MemberTypes.Event => InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit), _ => element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[], }; } public static bool IsDefined(MemberInfo element, Type attributeType) { return IsDefined(element, attributeType, inherit: true); } public static bool IsDefined(MemberInfo element, Type attributeType, bool inherit) { if (element == null) { throw new ArgumentNullException("element"); } if (attributeType == null) { throw new ArgumentNullException("attributeType"); } if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) { throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); } return element.MemberType switch { MemberTypes.Property => InternalIsDefined((PropertyInfo)element, attributeType, inherit), MemberTypes.Event => InternalIsDefined((EventInfo)element, attributeType, inherit), _ => element.IsDefined(attributeType, inherit), }; } public static Attribute? GetCustomAttribute(MemberInfo element, Type attributeType) { return GetCustomAttribute(element, attributeType, inherit: true); } public static Attribute? GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit) { Attribute[] customAttributes = GetCustomAttributes(element, attributeType, inherit); if (customAttributes == null || customAttributes.Length == 0) { return null; } if (customAttributes.Length == 1) { return customAttributes[0]; } throw new AmbiguousMatchException(SR.RFLCT_AmbigCust); } public static Attribute[] GetCustomAttributes(ParameterInfo element) { return GetCustomAttributes(element, inherit: true); } public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType) { return GetCustomAttributes(element, attributeType, inherit: true); } public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType, bool inherit) { if (element == null) { throw new ArgumentNullException("element"); } if (attributeType == null) { throw new ArgumentNullException("attributeType"); } if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) { throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); } if (element.Member == null) { throw new ArgumentException(SR.Argument_InvalidParameterInfo, "element"); } MemberInfo member = element.Member; if (member.MemberType == MemberTypes.Method && inherit) { return InternalParamGetCustomAttributes(element, attributeType, inherit); } return element.GetCustomAttributes(attributeType, inherit) as Attribute[]; } public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit) { if (element == null) { throw new ArgumentNullException("element"); } if (element.Member == null) { throw new ArgumentException(SR.Argument_InvalidParameterInfo, "element"); } MemberInfo member = element.Member; if (member.MemberType == MemberTypes.Method && inherit) { return InternalParamGetCustomAttributes(element, null, inherit); } return element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[]; } public static bool IsDefined(ParameterInfo element, Type attributeType) { return IsDefined(element, attributeType, inherit: true); } public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit) { if (element == null) { throw new ArgumentNullException("element"); } if (attributeType == null) { throw new ArgumentNullException("attributeType"); } if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) { throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); } MemberInfo member = element.Member; return member.MemberType switch { MemberTypes.Method => InternalParamIsDefined(element, attributeType, inherit), MemberTypes.Constructor => element.IsDefined(attributeType, inherit: false), MemberTypes.Property => element.IsDefined(attributeType, inherit: false), _ => throw new ArgumentException(SR.Argument_InvalidParamInfo), }; } public static Attribute? GetCustomAttribute(ParameterInfo element, Type attributeType) { return GetCustomAttribute(element, attributeType, inherit: true); } public static Attribute? GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit) { Attribute[] customAttributes = GetCustomAttributes(element, attributeType, inherit); if (customAttributes == null || customAttributes.Length == 0) { return null; } if (customAttributes.Length == 0) { return null; } if (customAttributes.Length == 1) { return customAttributes[0]; } throw new AmbiguousMatchException(SR.RFLCT_AmbigCust); } public static Attribute[] GetCustomAttributes(Module element, Type attributeType) { return GetCustomAttributes(element, attributeType, inherit: true); } public static Attribute[] GetCustomAttributes(Module element) { return GetCustomAttributes(element, inherit: true); } public static Attribute[] GetCustomAttributes(Module element, bool inherit) { if (element == null) { throw new ArgumentNullException("element"); } return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit); } public static Attribute[] GetCustomAttributes(Module element, Type attributeType, bool inherit) { if (element == null) { throw new ArgumentNullException("element"); } if (attributeType == null) { throw new ArgumentNullException("attributeType"); } if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) { throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); } return (Attribute[])element.GetCustomAttributes(attributeType, inherit); } public static bool IsDefined(Module element, Type attributeType) { return IsDefined(element, attributeType, inherit: false); } public static bool IsDefined(Module element, Type attributeType, bool inherit) { if (element == null) { throw new ArgumentNullException("element"); } if (attributeType == null) { throw new ArgumentNullException("attributeType"); } if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) { throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); } return element.IsDefined(attributeType, inherit: false); } public static Attribute? GetCustomAttribute(Module element, Type attributeType) { return GetCustomAttribute(element, attributeType, inherit: true); } public static Attribute? GetCustomAttribute(Module element, Type attributeType, bool inherit) { Attribute[] customAttributes = GetCustomAttributes(element, attributeType, inherit); if (customAttributes == null || customAttributes.Length == 0) { return null; } if (customAttributes.Length == 1) { return customAttributes[0]; } throw new AmbiguousMatchException(SR.RFLCT_AmbigCust); } public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType) { return GetCustomAttributes(element, attributeType, inherit: true); } public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType, bool inherit) { if (element == null) { throw new ArgumentNullException("element"); } if (attributeType == null) { throw new ArgumentNullException("attributeType"); } if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) { throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); } return (Attribute[])element.GetCustomAttributes(attributeType, inherit); } public static Attribute[] GetCustomAttributes(Assembly element) { return GetCustomAttributes(element, inherit: true); } public static Attribute[] GetCustomAttributes(Assembly element, bool inherit) { if (element == null) { throw new ArgumentNullException("element"); } return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit); } public static bool IsDefined(Assembly element, Type attributeType) { return IsDefined(element, attributeType, inherit: true); } public static bool IsDefined(Assembly element, Type attributeType, bool inherit) { if (element == null) { throw new ArgumentNullException("element"); } if (attributeType == null) { throw new ArgumentNullException("attributeType"); } if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute)) { throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass); } return element.IsDefined(attributeType, inherit: false); } public static Attribute? GetCustomAttribute(Assembly element, Type attributeType) { return GetCustomAttribute(element, attributeType, inherit: true); } public static Attribute? GetCustomAttribute(Assembly element, Type attributeType, bool inherit) { Attribute[] customAttributes = GetCustomAttributes(element, attributeType, inherit); if (customAttributes == null || customAttributes.Length == 0) { return null; } if (customAttributes.Length == 1) { return customAttributes[0]; } throw new AmbiguousMatchException(SR.RFLCT_AmbigCust); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", Justification = "Unused fields don't make a difference for equality")] public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == null) { return false; } if (GetType() != obj.GetType()) { return false; } Type type = GetType(); while (type != typeof(Attribute)) { FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < fields.Length; i++) { object value = fields[i].GetValue(this); object value2 = fields[i].GetValue(obj); if (!AreFieldValuesEqual(value, value2)) { return false; } } type = type.BaseType; } return true; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", Justification = "Unused fields don't make a difference for hashcode quality")] public override int GetHashCode() { Type type = GetType(); while (type != typeof(Attribute)) { FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); object obj = null; for (int i = 0; i < fields.Length; i++) { object value = fields[i].GetValue(this); if (value != null && !value.GetType().IsArray) { obj = value; } if (obj != null) { break; } } if (obj != null) { return obj.GetHashCode(); } type = type.BaseType; } return type.GetHashCode(); } private static bool AreFieldValuesEqual(object thisValue, object thatValue) { if (thisValue == null && thatValue == null) { return true; } if (thisValue == null || thatValue == null) { return false; } Type type = thisValue.GetType(); if (type.IsArray) { if (!type.Equals(thatValue.GetType())) { return false; } Array array = (Array)thisValue; Array array2 = (Array)thatValue; if (array.Length != array2.Length) { return false; } for (int i = 0; i < array.Length; i++) { if (!AreFieldValuesEqual(array.GetValue(i), array2.GetValue(i))) { return false; } } } else if (!thisValue.Equals(thatValue)) { return false; } return true; } public virtual bool Match(object? obj) { return Equals(obj); } public virtual bool IsDefaultAttribute() { return false; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class BadImageFormatException : SystemException { private readonly string _fileName; private readonly string _fusionLog; public override string Message { get { SetMessageField(); return _message; } } public string? FileName => _fileName; public string? FusionLog => _fusionLog; private BadImageFormatException(string fileName, int hResult) : base(null) { base.HResult = hResult; _fileName = fileName; SetMessageField(); } public BadImageFormatException() : base(SR.Arg_BadImageFormatException) { base.HResult = -2147024885; } public BadImageFormatException(string? message) : base(message) { base.HResult = -2147024885; } public BadImageFormatException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2147024885; } public BadImageFormatException(string? message, string? fileName) : base(message) { base.HResult = -2147024885; _fileName = fileName; } public BadImageFormatException(string? message, string? fileName, Exception? inner) : base(message, inner) { base.HResult = -2147024885; _fileName = fileName; } protected BadImageFormatException(SerializationInfo info, StreamingContext context) : base(info, context) { _fileName = info.GetString("BadImageFormat_FileName"); _fusionLog = info.GetString("BadImageFormat_FusionLog"); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("BadImageFormat_FileName", _fileName, typeof(string)); info.AddValue("BadImageFormat_FusionLog", _fusionLog, typeof(string)); } private void SetMessageField() { if (_message == null) { if (_fileName == null && base.HResult == -2146233088) { _message = SR.Arg_BadImageFormatException; } else { _message = FileLoadException.FormatFileLoadExceptionMessage(_fileName, base.HResult); } } } public override string ToString() { string text = GetType().ToString() + ": " + Message; if (!string.IsNullOrEmpty(_fileName)) { text = text + "\r\n" + SR.Format(SR.IO_FileName_Name, _fileName); } if (base.InnerException != null) { text = text + " ---> " + base.InnerException.ToString(); } if (StackTrace != null) { text = text + "\r\n" + StackTrace; } if (_fusionLog != null) { if (text == null) { text = " "; } text = text + "\r\n\r\n" + _fusionLog; } return text; } } public static class Buffer { [StructLayout(LayoutKind.Sequential, Size = 16)] private struct Block16 { } [StructLayout(LayoutKind.Sequential, Size = 64)] private struct Block64 { } [MethodImpl(MethodImplOptions.NoInlining)] internal unsafe static void _ZeroMemory(ref byte b, nuint byteLength) { fixed (byte* b2 = &b) { __ZeroMemory(b2, byteLength); } } [DllImport("QCall", CharSet = CharSet.Unicode)] private unsafe static extern void __ZeroMemory(void* b, nuint byteLength); internal static void BulkMoveWithWriteBarrier(ref byte destination, ref byte source, nuint byteCount) { if (byteCount <= 16384) { __BulkMoveWithWriteBarrier(ref destination, ref source, byteCount); } else { _BulkMoveWithWriteBarrier(ref destination, ref source, byteCount); } } [MethodImpl(MethodImplOptions.NoInlining)] private static void _BulkMoveWithWriteBarrier(ref byte destination, ref byte source, nuint byteCount) { if (Unsafe.AreSame(ref source, ref destination)) { return; } if ((nuint)(nint)Unsafe.ByteOffset(ref source, ref destination) >= byteCount) { do { byteCount -= 16384; __BulkMoveWithWriteBarrier(ref destination, ref source, 16384u); destination = ref Unsafe.AddByteOffset(ref destination, 16384u); source = ref Unsafe.AddByteOffset(ref source, 16384u); } while (byteCount > 16384); } else { do { byteCount -= 16384; __BulkMoveWithWriteBarrier(ref Unsafe.AddByteOffset(ref destination, byteCount), ref Unsafe.AddByteOffset(ref source, byteCount), 16384u); } while (byteCount > 16384); } __BulkMoveWithWriteBarrier(ref destination, ref source, byteCount); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void __BulkMoveWithWriteBarrier(ref byte destination, ref byte source, nuint byteCount); [DllImport("QCall", CharSet = CharSet.Unicode)] private unsafe static extern void __Memmove(byte* dest, byte* src, nuint len); internal unsafe static void Memcpy(byte* dest, byte* src, int len) { Memmove(ref *dest, ref *src, (uint)len); } internal unsafe static void Memcpy(byte* pDest, int destIndex, byte[] src, int srcIndex, int len) { Memmove(ref pDest[(uint)destIndex], ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(src), (nint)(uint)srcIndex), (uint)len); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void Memmove(ref T destination, ref T source, nuint elementCount) { if (!RuntimeHelpers.IsReferenceOrContainsReferences()) { Memmove(ref Unsafe.As(ref destination), ref Unsafe.As(ref source), elementCount * (nuint)Unsafe.SizeOf()); } else { BulkMoveWithWriteBarrier(ref Unsafe.As(ref destination), ref Unsafe.As(ref source), elementCount * (nuint)Unsafe.SizeOf()); } } public static void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count) { if (src == null) { throw new ArgumentNullException("src"); } if (dst == null) { throw new ArgumentNullException("dst"); } nuint num = src.NativeLength; if (src.GetType() != typeof(byte[])) { if (!src.GetCorElementTypeOfElementType().IsPrimitiveType()) { throw new ArgumentException(SR.Arg_MustBePrimArray, "src"); } num *= src.GetElementSize(); } nuint num2 = num; if (src != dst) { num2 = dst.NativeLength; if (dst.GetType() != typeof(byte[])) { if (!dst.GetCorElementTypeOfElementType().IsPrimitiveType()) { throw new ArgumentException(SR.Arg_MustBePrimArray, "dst"); } num2 *= dst.GetElementSize(); } } if (srcOffset < 0) { throw new ArgumentOutOfRangeException("srcOffset", SR.ArgumentOutOfRange_MustBeNonNegInt32); } if (dstOffset < 0) { throw new ArgumentOutOfRangeException("dstOffset", SR.ArgumentOutOfRange_MustBeNonNegInt32); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_MustBeNonNegInt32); } nuint num3 = (nuint)count; nuint num4 = (nuint)srcOffset; nuint num5 = (nuint)dstOffset; if (num < num4 + num3 || num2 < num5 + num3) { throw new ArgumentException(SR.Argument_InvalidOffLen); } Memmove(ref Unsafe.AddByteOffset(ref MemoryMarshal.GetArrayDataReference(dst), num5), ref Unsafe.AddByteOffset(ref MemoryMarshal.GetArrayDataReference(src), num4), num3); } public static int ByteLength(Array array) { if (array == null) { throw new ArgumentNullException("array"); } if (!array.GetCorElementTypeOfElementType().IsPrimitiveType()) { throw new ArgumentException(SR.Arg_MustBePrimArray, "array"); } nuint num = array.NativeLength * array.GetElementSize(); return checked((int)num); } public static byte GetByte(Array array, int index) { if ((uint)index >= (uint)ByteLength(array)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), index); } public static void SetByte(Array array, int index, byte value) { if ((uint)index >= (uint)ByteLength(array)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), index) = value; } internal unsafe static void ZeroMemory(byte* dest, nuint len) { SpanHelpers.ClearWithoutReferences(ref *dest, len); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe static void MemoryCopy(void* source, void* destination, long destinationSizeInBytes, long sourceBytesToCopy) { if (sourceBytesToCopy > destinationSizeInBytes) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceBytesToCopy); } Memmove(ref *(byte*)destination, ref *(byte*)source, checked((nuint)sourceBytesToCopy)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe static void MemoryCopy(void* source, void* destination, ulong destinationSizeInBytes, ulong sourceBytesToCopy) { if (sourceBytesToCopy > destinationSizeInBytes) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sourceBytesToCopy); } Memmove(ref *(byte*)destination, ref *(byte*)source, checked((nuint)sourceBytesToCopy)); } internal static void Memmove(ref byte dest, ref byte src, nuint len) { if ((nuint)(nint)Unsafe.ByteOffset(ref src, ref dest) >= len && (nuint)(nint)Unsafe.ByteOffset(ref dest, ref src) >= len) { ref byte source = ref Unsafe.Add(ref src, (nint)len); ref byte source2 = ref Unsafe.Add(ref dest, (nint)len); if (len > 16) { if (len > 64) { if (len > 2048) { goto IL_0211; } nuint num = len >> 6; do { Unsafe.As(ref dest) = Unsafe.As(ref src); dest = ref Unsafe.Add(ref dest, 64); src = ref Unsafe.Add(ref src, 64); num--; } while (num != 0); len %= 64; if (len <= 16) { Unsafe.As(ref Unsafe.Add(ref source2, -16)) = Unsafe.As(ref Unsafe.Add(ref source, -16)); return; } } Unsafe.As(ref dest) = Unsafe.As(ref src); if (len > 32) { Unsafe.As(ref Unsafe.Add(ref dest, 16)) = Unsafe.As(ref Unsafe.Add(ref src, 16)); if (len > 48) { Unsafe.As(ref Unsafe.Add(ref dest, 32)) = Unsafe.As(ref Unsafe.Add(ref src, 32)); } } Unsafe.As(ref Unsafe.Add(ref source2, -16)) = Unsafe.As(ref Unsafe.Add(ref source, -16)); } else if ((len & 0x18) != 0) { Unsafe.As(ref dest) = Unsafe.As(ref src); Unsafe.As(ref Unsafe.Add(ref dest, 4)) = Unsafe.As(ref Unsafe.Add(ref src, 4)); Unsafe.As(ref Unsafe.Add(ref source2, -8)) = Unsafe.As(ref Unsafe.Add(ref source, -8)); Unsafe.As(ref Unsafe.Add(ref source2, -4)) = Unsafe.As(ref Unsafe.Add(ref source, -4)); } else if ((len & 4) != 0) { Unsafe.As(ref dest) = Unsafe.As(ref src); Unsafe.As(ref Unsafe.Add(ref source2, -4)) = Unsafe.As(ref Unsafe.Add(ref source, -4)); } else if (len != 0) { dest = src; if ((len & 2) != 0) { Unsafe.As(ref Unsafe.Add(ref source2, -2)) = Unsafe.As(ref Unsafe.Add(ref source, -2)); } } return; } if (Unsafe.AreSame(ref dest, ref src)) { return; } goto IL_0211; IL_0211: _Memmove(ref dest, ref src, len); } [MethodImpl(MethodImplOptions.NoInlining)] private unsafe static void _Memmove(ref byte dest, ref byte src, nuint len) { fixed (byte* dest2 = &dest) { fixed (byte* src2 = &src) { __Memmove(dest2, src2, len); } } } } internal struct Currency { internal long m_value; public Currency(decimal value) { m_value = decimal.ToOACurrency(value); } } [Serializable] [NonVersionable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Decimal : ISpanFormattable, IFormattable, IComparable, IConvertible, IComparable, IEquatable, ISerializable, IDeserializationCallback, IMinMaxValue, ISignedNumber, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators { [StructLayout(LayoutKind.Explicit)] private struct DecCalc { private struct PowerOvfl { public readonly uint Hi; public readonly ulong MidLo; public PowerOvfl(uint hi, uint mid, uint lo) { Hi = hi; MidLo = ((ulong)mid << 32) + lo; } } [StructLayout(LayoutKind.Explicit)] private struct Buf12 { [FieldOffset(0)] public uint U0; [FieldOffset(4)] public uint U1; [FieldOffset(8)] public uint U2; [FieldOffset(0)] private ulong ulo64LE; [FieldOffset(4)] private ulong uhigh64LE; public ulong Low64 { get { return ulo64LE; } set { ulo64LE = value; } } public ulong High64 { get { return uhigh64LE; } set { uhigh64LE = value; } } } [StructLayout(LayoutKind.Explicit)] private struct Buf16 { [FieldOffset(0)] public uint U0; [FieldOffset(4)] public uint U1; [FieldOffset(8)] public uint U2; [FieldOffset(12)] public uint U3; [FieldOffset(0)] private ulong ulo64LE; [FieldOffset(8)] private ulong uhigh64LE; public ulong Low64 { get { return ulo64LE; } set { ulo64LE = value; } } public ulong High64 { get { return uhigh64LE; } set { uhigh64LE = value; } } } [StructLayout(LayoutKind.Explicit)] private struct Buf24 { [FieldOffset(0)] public uint U0; [FieldOffset(4)] public uint U1; [FieldOffset(8)] public uint U2; [FieldOffset(12)] public uint U3; [FieldOffset(16)] public uint U4; [FieldOffset(20)] public uint U5; [FieldOffset(0)] private ulong ulo64LE; [FieldOffset(8)] private ulong umid64LE; [FieldOffset(16)] private ulong uhigh64LE; public ulong Low64 { get { return ulo64LE; } set { ulo64LE = value; } } public ulong Mid64 { set { umid64LE = value; } } public ulong High64 { set { uhigh64LE = value; } } } private struct Buf28 { public Buf24 Buf24; public uint U6; } [FieldOffset(0)] private uint uflags; [FieldOffset(4)] private uint uhi; [FieldOffset(8)] private uint ulo; [FieldOffset(12)] private uint umid; [FieldOffset(8)] private ulong ulomid; private static readonly uint[] s_powers10 = new uint[10] { 1u, 10u, 100u, 1000u, 10000u, 100000u, 1000000u, 10000000u, 100000000u, 1000000000u }; private static readonly ulong[] s_ulongPowers10 = new ulong[19] { 10uL, 100uL, 1000uL, 10000uL, 100000uL, 1000000uL, 10000000uL, 100000000uL, 1000000000uL, 10000000000uL, 100000000000uL, 1000000000000uL, 10000000000000uL, 100000000000000uL, 1000000000000000uL, 10000000000000000uL, 100000000000000000uL, 1000000000000000000uL, 10000000000000000000uL }; private static readonly double[] s_doublePowers10 = new double[81] { 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0, 100000000000.0, 1000000000000.0, 10000000000000.0, 100000000000000.0, 1000000000000000.0, 10000000000000000.0, 1E+17, 1E+18, 1E+19, 1E+20, 1E+21, 1E+22, 1E+23, 1E+24, 1E+25, 1E+26, 1E+27, 1E+28, 1E+29, 1E+30, 1E+31, 1E+32, 1E+33, 1E+34, 1E+35, 1E+36, 1E+37, 1E+38, 1E+39, 1E+40, 1E+41, 1E+42, 1E+43, 1E+44, 1E+45, 1E+46, 1E+47, 1E+48, 1E+49, 1E+50, 1E+51, 1E+52, 1E+53, 1E+54, 1E+55, 1E+56, 1E+57, 1E+58, 1E+59, 1E+60, 1E+61, 1E+62, 1E+63, 1E+64, 1E+65, 1E+66, 1E+67, 1E+68, 1E+69, 1E+70, 1E+71, 1E+72, 1E+73, 1E+74, 1E+75, 1E+76, 1E+77, 1E+78, 1E+79, 1E+80 }; private static readonly PowerOvfl[] PowerOvflValues = new PowerOvfl[8] { new PowerOvfl(429496729u, 2576980377u, 2576980377u), new PowerOvfl(42949672u, 4123168604u, 687194767u), new PowerOvfl(4294967u, 1271310319u, 2645699854u), new PowerOvfl(429496u, 3133608139u, 694066715u), new PowerOvfl(42949u, 2890341191u, 2216890319u), new PowerOvfl(4294u, 4154504685u, 2369172679u), new PowerOvfl(429u, 2133437386u, 4102387834u), new PowerOvfl(42u, 4078814305u, 410238783u) }; private uint High { get { return uhi; } set { uhi = value; } } private uint Low { get { return ulo; } set { ulo = value; } } private uint Mid { get { return umid; } set { umid = value; } } private bool IsNegative => (int)uflags < 0; private int Scale => (byte)(uflags >> 16); private ulong Low64 { get { return ulomid; } set { ulomid = value; } } private unsafe static uint GetExponent(float f) { return (byte)(*(uint*)(&f) >> 23); } private unsafe static uint GetExponent(double d) { return (uint)(int)((ulong)(*(long*)(&d)) >> 52) & 0x7FFu; } private static ulong UInt32x32To64(uint a, uint b) { return (ulong)a * (ulong)b; } private static void UInt64x64To128(ulong a, ulong b, ref DecCalc result) { ulong num = UInt32x32To64((uint)a, (uint)b); ulong num2 = UInt32x32To64((uint)a, (uint)(b >> 32)); ulong num3 = UInt32x32To64((uint)(a >> 32), (uint)(b >> 32)); num3 += num2 >> 32; num += (num2 <<= 32); if (num < num2) { num3++; } num2 = UInt32x32To64((uint)(a >> 32), (uint)b); num3 += num2 >> 32; num += (num2 <<= 32); if (num < num2) { num3++; } if (num3 > uint.MaxValue) { Number.ThrowOverflowException(TypeCode.Decimal); } result.Low64 = num; result.High = (uint)num3; } private static uint Div96By32(ref Buf12 bufNum, uint den) { ulong high; ulong num2; if (bufNum.U2 != 0) { high = bufNum.High64; num2 = (bufNum.High64 = high / den); high = (high - (uint)((int)num2 * (int)den) << 32) | bufNum.U0; if (high == 0L) { return 0u; } return (uint)(int)high - (bufNum.U0 = (uint)(high / den)) * den; } high = bufNum.Low64; if (high == 0L) { return 0u; } num2 = (bufNum.Low64 = high / den); return (uint)(high - num2 * den); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool Div96ByConst(ref ulong high64, ref uint low, uint pow) { if (high64 <= uint.MaxValue) { uint num = (uint)high64; uint num2 = num / pow; num = num - num2 * pow << 16; num += low >> 16; uint num3 = num / pow; num = num - num3 * pow << 16; num += (ushort)low; uint num4 = num / pow; if (num == num4 * pow) { high64 = num2; low = (num3 << 16) + num4; return true; } } else { uint num = (uint)(high64 >> 32); uint num5 = num / pow; num = num - num5 * pow << 16; num += (uint)high64 >> 16; uint num2 = num / pow; num = num - num2 * pow << 16; num += (ushort)high64; uint num4 = num / pow; num = num - num4 * pow << 16; num2 = num4 + (num2 << 16); num += low >> 16; uint num3 = num / pow; num = num - num3 * pow << 16; num += (ushort)low; num4 = num / pow; if (num == num4 * pow) { high64 = ((ulong)num5 << 32) | num2; low = (num3 << 16) + num4; return true; } } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Unscale(ref uint low, ref ulong high64, ref int scale) { while ((low & 0xF) == 0 && scale >= 4 && Div96ByConst(ref high64, ref low, 10000u)) { scale -= 4; } if ((low & 3) == 0 && scale >= 2 && Div96ByConst(ref high64, ref low, 100u)) { scale -= 2; } if ((low & 1) == 0 && scale >= 1 && Div96ByConst(ref high64, ref low, 10u)) { scale--; } } private static uint Div96By64(ref Buf12 bufNum, ulong den) { uint u = bufNum.U2; uint num; ulong low; if (u == 0) { low = bufNum.Low64; if (low < den) { return 0u; } num = (uint)(low / den); low -= num * den; bufNum.Low64 = low; return num; } uint num2 = (uint)(den >> 32); if (u >= num2) { low = bufNum.Low64; low -= den << 32; num = 0u; do { num--; low += den; } while (low >= den); bufNum.Low64 = low; return num; } ulong high = bufNum.High64; if (high < num2) { return 0u; } num = (uint)(high / num2); low = bufNum.U0 | (high - num * num2 << 32); ulong num3 = UInt32x32To64(num, (uint)den); low -= num3; if (low > ~num3) { do { num--; low += den; } while (low >= den); } bufNum.Low64 = low; return num; } private static uint Div128By96(ref Buf16 bufNum, ref Buf12 bufDen) { ulong high = bufNum.High64; uint u = bufDen.U2; if (high < u) { return 0u; } uint num = (uint)(high / u); uint num2 = (uint)(int)high - num * u; ulong num3 = UInt32x32To64(num, bufDen.U0); ulong num4 = UInt32x32To64(num, bufDen.U1); num4 += num3 >> 32; num3 = (uint)num3 | (num4 << 32); num4 >>= 32; ulong low = bufNum.Low64; low -= num3; num2 -= (uint)(int)num4; if (low > ~num3) { num2--; if (num2 >= (uint)(~num4)) { goto IL_008b; } } else if (num2 > (uint)(~num4)) { goto IL_008b; } goto IL_00b4; IL_008b: num3 = bufDen.Low64; do { num--; low += num3; num2 += u; } while ((low >= num3 || num2++ >= u) && num2 >= u); goto IL_00b4; IL_00b4: bufNum.Low64 = low; bufNum.U2 = num2; return num; } private static uint IncreaseScale(ref Buf12 bufNum, uint power) { ulong num = UInt32x32To64(bufNum.U0, power); bufNum.U0 = (uint)num; num >>= 32; num += UInt32x32To64(bufNum.U1, power); bufNum.U1 = (uint)num; num >>= 32; num += UInt32x32To64(bufNum.U2, power); bufNum.U2 = (uint)num; return (uint)(num >> 32); } private static void IncreaseScale64(ref Buf12 bufNum, uint power) { ulong num = UInt32x32To64(bufNum.U0, power); bufNum.U0 = (uint)num; num >>= 32; num += UInt32x32To64(bufNum.U1, power); bufNum.High64 = num; } private unsafe static int ScaleResult(Buf24* bufRes, uint hiRes, int scale) { int num = 0; if (hiRes > 2) { num = (int)(hiRes * 32 - 64 - 1); num -= BitOperations.LeadingZeroCount(*(uint*)((byte*)bufRes + (long)hiRes * 4L)); num = (num * 77 >> 8) + 1; if (num > scale) { goto IL_014e; } } if (num < scale - 28) { num = scale - 28; } if (num == 0) { goto IL_014c; } scale -= num; uint num2 = 0u; uint remainder = 0u; while (true) { num2 |= remainder; uint num3 = num switch { 1 => DivByConst((uint*)bufRes, hiRes, out var quotient, out remainder, 10u), 2 => DivByConst((uint*)bufRes, hiRes, out quotient, out remainder, 100u), 3 => DivByConst((uint*)bufRes, hiRes, out quotient, out remainder, 1000u), _ => DivByConst((uint*)bufRes, hiRes, out quotient, out remainder, 10000u), }; *(uint*)((byte*)bufRes + (long)hiRes * 4L) = quotient; if (quotient == 0 && hiRes != 0) { hiRes--; } num -= 4; if (num > 0) { continue; } if (hiRes > 2) { if (scale == 0) { break; } num = 1; scale--; continue; } num3 >>= 1; if (num3 <= remainder && (num3 < remainder || ((*(uint*)bufRes & (true ? 1u : 0u)) | num2) != 0) && ++(*(int*)bufRes) == 0) { uint num4 = 0u; while (++(*(int*)((byte*)bufRes + (long)(++num4) * 4L)) == 0) { } if (num4 > 2) { if (scale == 0) { break; } hiRes = num4; num2 = 0u; remainder = 0u; num = 1; scale--; continue; } } goto IL_014c; } goto IL_014e; IL_014c: return scale; IL_014e: Number.ThrowOverflowException(TypeCode.Decimal); return 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static uint DivByConst(uint* result, uint hiRes, out uint quotient, out uint remainder, uint power) { uint num = result[hiRes]; remainder = num - (quotient = num / power) * power; uint num2 = hiRes - 1; while ((int)num2 >= 0) { uint num3 = *(ushort*)((byte*)result + num2 * 4 + 2) + (remainder << 16); uint num4 = num3 / power; remainder = num3 - num4 * power; *(ushort*)((byte*)result + num2 * 4 + 2) = (ushort)num4; num3 = *(ushort*)((byte*)result + num2 * 4) + (remainder << 16); num4 = num3 / power; remainder = num3 - num4 * power; *(ushort*)((byte*)result + num2 * 4) = (ushort)num4; num2--; } return power; } private static int OverflowUnscale(ref Buf12 bufQuo, int scale, bool sticky) { if (--scale < 0) { Number.ThrowOverflowException(TypeCode.Decimal); } bufQuo.U2 = 429496729u; ulong num = 25769803776uL + (ulong)bufQuo.U1; num = (num - (bufQuo.U1 = (uint)(num / 10)) * 10 << 32) + bufQuo.U0; uint num2 = (uint)(num - (bufQuo.U0 = (uint)(num / 10)) * 10); if (num2 > 5 || (num2 == 5 && (sticky || (bufQuo.U0 & (true ? 1u : 0u)) != 0))) { Add32To96(ref bufQuo, 1u); } return scale; } private static int SearchScale(ref Buf12 bufQuo, int scale) { uint u = bufQuo.U2; ulong low = bufQuo.Low64; int num = 0; if (u <= 429496729) { PowerOvfl[] powerOvflValues = PowerOvflValues; if (scale > 19) { num = 28 - scale; if (u < powerOvflValues[num - 1].Hi) { goto IL_00d1; } } else if (u < 4 || (u == 4 && low <= 5441186219426131129L)) { return 9; } if (u > 42949) { if (u > 4294967) { num = 2; if (u > 42949672) { num--; } } else { num = 4; if (u > 429496) { num--; } } } else if (u > 429) { num = 6; if (u > 4294) { num--; } } else { num = 8; if (u > 42) { num--; } } if (u == powerOvflValues[num - 1].Hi && low > powerOvflValues[num - 1].MidLo) { num--; } } goto IL_00d1; IL_00d1: if (num + scale < 0) { Number.ThrowOverflowException(TypeCode.Decimal); } return num; } private static bool Add32To96(ref Buf12 bufNum, uint value) { if ((bufNum.Low64 += value) < value && ++bufNum.U2 == 0) { return false; } return true; } internal unsafe static void DecAddSub(ref DecCalc d1, ref DecCalc d2, bool sign) { ulong num = d1.Low64; uint num2 = d1.High; uint num3 = d1.uflags; uint num4 = d2.uflags; uint num5 = num4 ^ num3; sign ^= (num5 & 0x80000000u) != 0; int num7; if ((num5 & 0xFF0000u) != 0) { uint num6 = num3; num3 = (num4 & 0xFF0000u) | (num3 & 0x80000000u); num7 = (int)(num3 - num6) >> 16; if (num7 < 0) { num7 = -num7; num3 = num6; if (sign) { num3 ^= 0x80000000u; } num = d2.Low64; num2 = d2.High; d2 = d1; } if (num2 != 0) { goto IL_015f; } if (num > uint.MaxValue) { goto IL_0106; } if ((int)num == 0) { uint num8 = num3 & 0x80000000u; if (sign) { num8 ^= 0x80000000u; } d1 = d2; d1.uflags = (d2.uflags & 0xFF0000u) | num8; return; } while (num7 > 9) { num7 -= 9; num = UInt32x32To64((uint)num, 1000000000u); if (num <= uint.MaxValue) { continue; } goto IL_0106; } num = UInt32x32To64((uint)num, s_powers10[num7]); } goto IL_0450; IL_03b1: if ((num3 & 0xFF0000) == 0) { Number.ThrowOverflowException(TypeCode.Decimal); } num3 -= 65536; ulong num9 = (ulong)num2 + 4294967296uL; num2 = (uint)(num9 / 10); num9 = (num9 - num2 * 10 << 32) + (num >> 32); uint num10 = (uint)(num9 / 10); num9 = (num9 - num10 * 10 << 32) + (uint)num; num = num10; num <<= 32; num10 = (uint)(num9 / 10); num += num10; num10 = (uint)(int)num9 - num10 * 10; if (num10 >= 5 && (num10 > 5 || (num & 1) != 0L) && ++num == 0L) { num2++; } goto IL_04b9; IL_0350: Buf24 value; value.Low64 = num; value.U2 = num2; uint num11; num7 = ScaleResult(&value, num11, (byte)(num3 >> 16)); num3 = (num3 & 0xFF00FFFFu) | (uint)(num7 << 16); num = value.Low64; num2 = value.U2; goto IL_04b9; IL_0106: ulong num13; while (true) { uint b = 1000000000u; if (num7 < 9) { b = s_powers10[num7]; } ulong num12 = UInt32x32To64((uint)num, b); num13 = UInt32x32To64((uint)(num >> 32), b) + (num12 >> 32); num = (uint)num12 + (num13 << 32); num2 = (uint)(num13 >> 32); if ((num7 -= 9) <= 0) { break; } if (num2 == 0) { continue; } goto IL_015f; } goto IL_0450; IL_0312: uint* ptr = (uint*)(&value); uint num14 = 3u; while (++ptr[num14++] == 0) { if (num11 < num14) { ptr[num14] = 1u; num11 = num14; break; } } goto IL_0350; IL_015f: while (true) { uint b = 1000000000u; if (num7 < 9) { b = s_powers10[num7]; } ulong num12 = UInt32x32To64((uint)num, b); num13 = UInt32x32To64((uint)(num >> 32), b) + (num12 >> 32); num = (uint)num12 + (num13 << 32); num13 >>= 32; num13 += UInt32x32To64(num2, b); num7 -= 9; if (num13 > uint.MaxValue) { break; } num2 = (uint)num13; if (num7 > 0) { continue; } goto IL_0450; } Unsafe.SkipInit(out value); value.Low64 = num; value.Mid64 = num13; num11 = 3u; while (num7 > 0) { uint b = 1000000000u; if (num7 < 9) { b = s_powers10[num7]; } num13 = 0uL; uint* ptr2 = (uint*)(&value); uint num15 = 0u; do { num13 += UInt32x32To64(ptr2[num15], b); ptr2[num15] = (uint)num13; num15++; num13 >>= 32; } while (num15 <= num11); if ((uint)num13 != 0) { ptr2[++num11] = (uint)num13; } num7 -= 9; } num13 = value.Low64; num = d2.Low64; uint u = value.U2; num2 = d2.High; if (sign) { num = num13 - num; num2 = u - num2; if (num > num13) { num2--; if (num2 >= u) { goto IL_02b3; } } else if (num2 > u) { goto IL_02b3; } } else { num += num13; num2 += u; if (num < num13) { num2++; if (num2 <= u) { goto IL_0312; } } else if (num2 < u) { goto IL_0312; } } goto IL_0350; IL_0394: num3 ^= 0x80000000u; num2 = ~num2; num = 0L - num; if (num == 0L) { num2++; } goto IL_04b9; IL_0450: ulong num16 = num; uint num17 = num2; if (sign) { num = num16 - d2.Low64; num2 = num17 - d2.High; if (num > num16) { num2--; if (num2 >= num17) { goto IL_0394; } } else if (num2 > num17) { goto IL_0394; } } else { num = num16 + d2.Low64; num2 = num17 + d2.High; if (num < num16) { num2++; if (num2 <= num17) { goto IL_03b1; } } else if (num2 < num17) { goto IL_03b1; } } goto IL_04b9; IL_04b9: d1.uflags = num3; d1.High = num2; d1.Low64 = num; return; IL_02b3: uint* ptr3 = (uint*)(&value); uint num18 = 3u; while (ptr3[num18++]-- == 0) { } if (ptr3[num11] != 0 || --num11 > 2) { goto IL_0350; } goto IL_04b9; } internal static long VarCyFromDec(ref DecCalc pdecIn) { int num = pdecIn.Scale - 4; long num4; if (num < 0) { if (pdecIn.High == 0) { uint a = s_powers10[-num]; ulong num2 = UInt32x32To64(a, pdecIn.Mid); if (num2 <= uint.MaxValue) { ulong num3 = UInt32x32To64(a, pdecIn.Low); num3 += (num2 <<= 32); if (num3 >= num2) { num4 = (long)num3; goto IL_006d; } } } } else { if (num != 0) { InternalRound(ref pdecIn, (uint)num, MidpointRounding.ToEven); } if (pdecIn.High == 0) { num4 = (long)pdecIn.Low64; goto IL_006d; } } goto IL_0093; IL_006d: if (num4 >= 0 || (num4 == long.MinValue && pdecIn.IsNegative)) { if (pdecIn.IsNegative) { num4 = -num4; } return num4; } goto IL_0093; IL_0093: throw new OverflowException(SR.Overflow_Currency); } internal static int VarDecCmp(in decimal d1, in decimal d2) { if ((d2.Low64 | d2.High) == 0L) { if ((d1.Low64 | d1.High) == 0L) { return 0; } return (d1._flags >> 31) | 1; } if ((d1.Low64 | d1.High) == 0L) { return -((d2._flags >> 31) | 1); } int num = (d1._flags >> 31) - (d2._flags >> 31); if (num != 0) { return num; } return VarDecCmpSub(in d1, in d2); } private static int VarDecCmpSub(in decimal d1, in decimal d2) { int flags = d2._flags; int num = (flags >> 31) | 1; int num2 = flags - d1._flags; ulong num3 = d1.Low64; uint num4 = d1.High; ulong num5 = d2.Low64; uint num6 = d2.High; if (num2 != 0) { num2 >>= 16; if (num2 < 0) { num2 = -num2; num = -num; ulong num7 = num3; num3 = num5; num5 = num7; uint num8 = num4; num4 = num6; num6 = num8; } do { uint b = ((num2 >= 9) ? 1000000000u : s_powers10[num2]); ulong num9 = UInt32x32To64((uint)num3, b); ulong num10 = UInt32x32To64((uint)(num3 >> 32), b) + (num9 >> 32); num3 = (uint)num9 + (num10 << 32); num10 >>= 32; num10 += UInt32x32To64(num4, b); if (num10 > uint.MaxValue) { return num; } num4 = (uint)num10; } while ((num2 -= 9) > 0); } uint num11 = num4 - num6; if (num11 != 0) { if (num11 > num4) { num = -num; } return num; } ulong num12 = num3 - num5; if (num12 == 0L) { num = 0; } else if (num12 > num3) { num = -num; } return num; } internal unsafe static void VarDecMul(ref DecCalc d1, ref DecCalc d2) { int num = (byte)(d1.uflags + d2.uflags >> 16); Unsafe.SkipInit(out var value); uint num6; if ((d1.High | d1.Mid) == 0) { ulong num4; if ((d2.High | d2.Mid) == 0) { ulong num2 = UInt32x32To64(d1.Low, d2.Low); if (num > 28) { if (num > 47) { goto IL_03b4; } num -= 29; ulong num3 = s_ulongPowers10[num]; num4 = num2 / num3; ulong num5 = num2 - num4 * num3; num2 = num4; num3 >>= 1; if (num5 >= num3 && (num5 > num3 || ((uint)(int)num2 & (true ? 1u : 0u)) != 0)) { num2++; } num = 28; } d1.Low64 = num2; d1.uflags = ((d2.uflags ^ d1.uflags) & 0x80000000u) | (uint)(num << 16); return; } num4 = UInt32x32To64(d1.Low, d2.Low); value.U0 = (uint)num4; num4 = UInt32x32To64(d1.Low, d2.Mid) + (num4 >> 32); value.U1 = (uint)num4; num4 >>= 32; if (d2.High != 0) { num4 += UInt32x32To64(d1.Low, d2.High); if (num4 > uint.MaxValue) { value.Mid64 = num4; num6 = 3u; goto IL_0368; } } value.U2 = (uint)num4; num6 = 2u; } else if ((d2.High | d2.Mid) == 0) { ulong num4 = UInt32x32To64(d2.Low, d1.Low); value.U0 = (uint)num4; num4 = UInt32x32To64(d2.Low, d1.Mid) + (num4 >> 32); value.U1 = (uint)num4; num4 >>= 32; if (d1.High != 0) { num4 += UInt32x32To64(d2.Low, d1.High); if (num4 > uint.MaxValue) { value.Mid64 = num4; num6 = 3u; goto IL_0368; } } value.U2 = (uint)num4; num6 = 2u; } else { ulong num4 = UInt32x32To64(d1.Low, d2.Low); value.U0 = (uint)num4; ulong num7 = UInt32x32To64(d1.Low, d2.Mid) + (num4 >> 32); num4 = UInt32x32To64(d1.Mid, d2.Low); num4 += num7; value.U1 = (uint)num4; num7 = ((num4 >= num7) ? (num4 >> 32) : ((num4 >> 32) | 0x100000000uL)); num4 = UInt32x32To64(d1.Mid, d2.Mid) + num7; if ((d1.High | d2.High) != 0) { num7 = UInt32x32To64(d1.Low, d2.High); num4 += num7; uint num8 = 0u; if (num4 < num7) { num8 = 1u; } num7 = UInt32x32To64(d1.High, d2.Low); num4 += num7; value.U2 = (uint)num4; if (num4 < num7) { num8++; } num7 = ((ulong)num8 << 32) | (num4 >> 32); num4 = UInt32x32To64(d1.Mid, d2.High); num4 += num7; num8 = 0u; if (num4 < num7) { num8 = 1u; } num7 = UInt32x32To64(d1.High, d2.Mid); num4 += num7; value.U3 = (uint)num4; if (num4 < num7) { num8++; } num4 = ((ulong)num8 << 32) | (num4 >> 32); value.High64 = UInt32x32To64(d1.High, d2.High) + num4; num6 = 5u; } else { value.Mid64 = num4; num6 = 3u; } } uint* ptr = (uint*)(&value); while (ptr[(int)num6] == 0) { if (num6 != 0) { num6--; continue; } goto IL_03b4; } goto IL_0368; IL_0368: if (num6 > 2 || num > 28) { num = ScaleResult(&value, num6, num); } d1.Low64 = value.Low64; d1.High = value.U2; d1.uflags = ((d2.uflags ^ d1.uflags) & 0x80000000u) | (uint)(num << 16); return; IL_03b4: d1 = default(DecCalc); } internal static void VarDecFromR4(float input, out DecCalc result) { result = default(DecCalc); int num = (int)(GetExponent(input) - 126); if (num < -94) { return; } if (num > 96) { Number.ThrowOverflowException(TypeCode.Decimal); } uint num2 = 0u; if (input < 0f) { input = 0f - input; num2 = 2147483648u; } double num3 = input; int num4 = 6 - (num * 19728 >> 16); if (num4 >= 0) { if (num4 > 28) { num4 = 28; } num3 *= s_doublePowers10[num4]; } else if (num4 != -1 || num3 >= 10000000.0) { num3 /= s_doublePowers10[-num4]; } else { num4 = 0; } if (num3 < 1000000.0 && num4 < 28) { num3 *= 10.0; num4++; } uint num5; if (Sse41.IsSupported) { num5 = (uint)(int)Math.Round(num3); } else { num5 = (uint)(int)num3; num3 -= (double)(int)num5; if (num3 > 0.5 || (num3 == 0.5 && (num5 & (true ? 1u : 0u)) != 0)) { num5++; } } if (num5 == 0) { return; } if (num4 < 0) { num4 = -num4; if (num4 < 10) { result.Low64 = UInt32x32To64(num5, s_powers10[num4]); } else if (num4 > 18) { ulong a = UInt32x32To64(num5, s_powers10[num4 - 18]); UInt64x64To128(a, 1000000000000000000uL, ref result); } else { ulong num6 = UInt32x32To64(num5, s_powers10[num4 - 9]); ulong num7 = UInt32x32To64(1000000000u, (uint)(num6 >> 32)); num6 = UInt32x32To64(1000000000u, (uint)num6); result.Low = (uint)num6; num7 += num6 >> 32; result.Mid = (uint)num7; num7 >>= 32; result.High = (uint)num7; } } else { int num8 = num4; if (num8 > 6) { num8 = 6; } if ((num5 & 0xF) == 0 && num8 >= 4) { uint num9 = num5 / 10000; if (num5 == num9 * 10000) { num5 = num9; num4 -= 4; num8 -= 4; } } if ((num5 & 3) == 0 && num8 >= 2) { uint num10 = num5 / 100; if (num5 == num10 * 100) { num5 = num10; num4 -= 2; num8 -= 2; } } if ((num5 & 1) == 0 && num8 >= 1) { uint num11 = num5 / 10; if (num5 == num11 * 10) { num5 = num11; num4--; } } num2 |= (uint)(num4 << 16); result.Low = num5; } result.uflags = num2; } internal static void VarDecFromR8(double input, out DecCalc result) { result = default(DecCalc); int num = (int)(GetExponent(input) - 1022); if (num < -94) { return; } if (num > 96) { Number.ThrowOverflowException(TypeCode.Decimal); } uint num2 = 0u; if (input < 0.0) { input = 0.0 - input; num2 = 2147483648u; } double num3 = input; int num4 = 14 - (num * 19728 >> 16); if (num4 >= 0) { if (num4 > 28) { num4 = 28; } num3 *= s_doublePowers10[num4]; } else if (num4 != -1 || num3 >= 1000000000000000.0) { num3 /= s_doublePowers10[-num4]; } else { num4 = 0; } if (num3 < 100000000000000.0 && num4 < 28) { num3 *= 10.0; num4++; } ulong num5; if (Sse41.IsSupported) { num5 = (ulong)(long)Math.Round(num3); } else { num5 = (ulong)(long)num3; num3 -= (double)(long)num5; if (num3 > 0.5 || (num3 == 0.5 && (num5 & 1) != 0L)) { num5++; } } if (num5 == 0L) { return; } if (num4 < 0) { num4 = -num4; if (num4 < 10) { uint b = s_powers10[num4]; ulong num6 = UInt32x32To64((uint)num5, b); ulong num7 = UInt32x32To64((uint)(num5 >> 32), b); result.Low = (uint)num6; num7 += num6 >> 32; result.Mid = (uint)num7; num7 >>= 32; result.High = (uint)num7; } else { UInt64x64To128(num5, s_ulongPowers10[num4 - 1], ref result); } } else { int num8 = num4; if (num8 > 14) { num8 = 14; } if ((byte)num5 == 0 && num8 >= 8) { ulong num9 = num5 / 100000000; if ((uint)num5 == (uint)(num9 * 100000000)) { num5 = num9; num4 -= 8; num8 -= 8; } } if (((int)num5 & 0xF) == 0 && num8 >= 4) { ulong num10 = num5 / 10000; if ((uint)num5 == (uint)(num10 * 10000)) { num5 = num10; num4 -= 4; num8 -= 4; } } if (((int)num5 & 3) == 0 && num8 >= 2) { ulong num11 = num5 / 100; if ((uint)num5 == (uint)(num11 * 100)) { num5 = num11; num4 -= 2; num8 -= 2; } } if (((int)num5 & 1) == 0 && num8 >= 1) { ulong num12 = num5 / 10; if ((uint)num5 == (uint)(num12 * 10)) { num5 = num12; num4--; } } num2 |= (uint)(num4 << 16); result.Low64 = num5; } result.uflags = num2; } internal static float VarR4FromDec(in decimal value) { return (float)VarR8FromDec(in value); } internal static double VarR8FromDec(in decimal value) { double num = ((double)value.Low64 + (double)value.High * 1.8446744073709552E+19) / s_doublePowers10[value.Scale]; if (value.IsNegative) { num = 0.0 - num; } return num; } internal static int GetHashCode(in decimal d) { if ((d.Low64 | d.High) == 0L) { return 0; } uint flags = (uint)d._flags; if ((flags & 0xFF0000) == 0 || (d.Low & (true ? 1u : 0u)) != 0) { return (int)(flags ^ d.High ^ d.Mid ^ d.Low); } int scale = (byte)(flags >> 16); uint low = d.Low; ulong high = ((ulong)d.High << 32) | d.Mid; Unscale(ref low, ref high, ref scale); flags = (flags & 0xFF00FFFFu) | (uint)(scale << 16); return (int)flags ^ (int)(high >> 32) ^ (int)high ^ (int)low; } internal unsafe static void VarDecDiv(ref DecCalc d1, ref DecCalc d2) { Unsafe.SkipInit(out var value); int scale = (sbyte)(d1.uflags - d2.uflags >> 16); bool flag = false; uint low; uint num; Buf16 value2; ulong num7; Buf12 value3; uint num6; if ((d2.High | d2.Mid) == 0) { low = d2.Low; if (low == 0) { throw new DivideByZeroException(); } value.Low64 = d1.Low64; value.U2 = d1.High; num = Div96By32(ref value, low); while (true) { int num2; if (num == 0) { if (scale >= 0) { break; } num2 = Math.Min(9, -scale); } else { flag = true; if (scale == 28 || (num2 = SearchScale(ref value, scale)) == 0) { goto IL_0090; } } uint num3 = s_powers10[num2]; scale += num2; if (IncreaseScale(ref value, num3) == 0) { ulong num4 = UInt32x32To64(num, num3); uint num5 = (uint)(num4 / low); num = (uint)(int)num4 - num5 * low; if (!Add32To96(ref value, num5)) { scale = OverflowUnscale(ref value, scale, num != 0); break; } continue; } goto IL_04ab; } } else { num6 = d2.High; if (num6 == 0) { num6 = d2.Mid; } int num2 = BitOperations.LeadingZeroCount(num6); Unsafe.SkipInit(out value2); value2.Low64 = d1.Low64 << num2; value2.High64 = d1.Mid + ((ulong)d1.High << 32) >> 32 - num2; num7 = d2.Low64 << num2; if (d2.High == 0) { value.U2 = 0u; value.U1 = Div96By64(ref *(Buf12*)(&value2.U1), num7); value.U0 = Div96By64(ref *(Buf12*)(&value2), num7); while (true) { if (value2.Low64 == 0L) { if (scale >= 0) { break; } num2 = Math.Min(9, -scale); } else { flag = true; if (scale == 28 || (num2 = SearchScale(ref value, scale)) == 0) { goto IL_01e8; } } uint num3 = s_powers10[num2]; scale += num2; if (IncreaseScale(ref value, num3) == 0) { IncreaseScale64(ref *(Buf12*)(&value2), num3); num6 = Div96By64(ref *(Buf12*)(&value2), num7); if (!Add32To96(ref value, num6)) { scale = OverflowUnscale(ref value, scale, value2.Low64 != 0); break; } continue; } goto IL_04ab; } } else { Unsafe.SkipInit(out value3); value3.Low64 = num7; value3.U2 = (uint)(d2.Mid + ((ulong)d2.High << 32) >> 32 - num2); value.Low64 = Div128By96(ref value2, ref value3); value.U2 = 0u; while (true) { if ((value2.Low64 | value2.U2) == 0L) { if (scale >= 0) { break; } num2 = Math.Min(9, -scale); } else { flag = true; if (scale == 28 || (num2 = SearchScale(ref value, scale)) == 0) { goto IL_0302; } } uint num3 = s_powers10[num2]; scale += num2; if (IncreaseScale(ref value, num3) == 0) { value2.U3 = IncreaseScale(ref *(Buf12*)(&value2), num3); num6 = Div128By96(ref value2, ref value3); if (!Add32To96(ref value, num6)) { scale = OverflowUnscale(ref value, scale, (value2.Low64 | value2.High64) != 0); break; } continue; } goto IL_04ab; } } } goto IL_03f3; IL_01e8: ulong low2 = value2.Low64; if ((long)low2 >= 0L && (low2 <<= 1) <= num7 && (low2 != num7 || (value.U0 & 1) == 0)) { goto IL_03f3; } goto IL_046a; IL_0090: num6 = num << 1; if (num6 >= num && (num6 < low || (num6 <= low && (value.U0 & 1) == 0))) { goto IL_03f3; } goto IL_046a; IL_0302: if ((int)value2.U2 >= 0) { num6 = value2.U1 >> 31; value2.Low64 <<= 1; value2.U2 = (value2.U2 << 1) + num6; if (value2.U2 <= value3.U2 && (value2.U2 != value3.U2 || (value2.Low64 <= value3.Low64 && (value2.Low64 != value3.Low64 || (value.U0 & 1) == 0)))) { goto IL_03f3; } } goto IL_046a; IL_04ab: Number.ThrowOverflowException(TypeCode.Decimal); return; IL_046a: if (++value.Low64 == 0L && ++value.U2 == 0) { scale = OverflowUnscale(ref value, scale, sticky: true); } goto IL_03f3; IL_03f3: if (flag) { uint low3 = value.U0; ulong high = value.High64; Unscale(ref low3, ref high, ref scale); d1.Low = low3; d1.Mid = (uint)high; d1.High = (uint)(high >> 32); } else { d1.Low64 = value.Low64; d1.High = value.U2; } d1.uflags = ((d1.uflags ^ d2.uflags) & 0x80000000u) | (uint)(scale << 16); } internal static void VarDecMod(ref DecCalc d1, ref DecCalc d2) { if ((d2.ulo | d2.umid | d2.uhi) == 0) { throw new DivideByZeroException(); } if ((d1.ulo | d1.umid | d1.uhi) == 0) { return; } d2.uflags = (d2.uflags & 0x7FFFFFFFu) | (d1.uflags & 0x80000000u); int num = VarDecCmpSub(in Unsafe.As(ref d1), in Unsafe.As(ref d2)); if (num == 0) { d1.ulo = 0u; d1.umid = 0u; d1.uhi = 0u; if (d2.uflags > d1.uflags) { d1.uflags = d2.uflags; } } else { if ((int)((uint)num ^ (d1.uflags & 0x80000000u)) < 0) { return; } int num2 = (sbyte)(d1.uflags - d2.uflags >> 16); if (num2 > 0) { do { uint num3 = ((num2 >= 9) ? 1000000000u : s_powers10[num2]); ulong num4 = UInt32x32To64(d2.Low, num3); d2.Low = (uint)num4; num4 >>= 32; num4 += (d2.Mid + ((ulong)d2.High << 32)) * num3; d2.Mid = (uint)num4; d2.High = (uint)(num4 >> 32); } while ((num2 -= 9) > 0); num2 = 0; } do { if (num2 < 0) { d1.uflags = d2.uflags; Unsafe.SkipInit(out var value); value.Low64 = d1.Low64; value.U2 = d1.High; uint num6; do { int num5 = SearchScale(ref value, 28 + num2); if (num5 == 0) { break; } num6 = ((num5 >= 9) ? 1000000000u : s_powers10[num5]); num2 += num5; ulong num7 = UInt32x32To64(value.U0, num6); value.U0 = (uint)num7; num7 >>= 32; value.High64 = num7 + value.High64 * num6; } while (num6 == 1000000000 && num2 < 0); d1.Low64 = value.Low64; d1.High = value.U2; } if (d1.High == 0) { d1.Low64 %= d2.Low64; break; } if ((d2.High | d2.Mid) == 0) { uint low = d2.Low; ulong num8 = ((ulong)d1.High << 32) | d1.Mid; num8 = (num8 % low << 32) | d1.Low; d1.Low64 = num8 % low; d1.High = 0u; continue; } VarDecModFull(ref d1, ref d2, num2); break; } while (num2 < 0); } } private unsafe static void VarDecModFull(ref DecCalc d1, ref DecCalc d2, int scale) { uint num = d2.High; if (num == 0) { num = d2.Mid; } int num2 = BitOperations.LeadingZeroCount(num); Unsafe.SkipInit(out var value); value.Buf24.Low64 = d1.Low64 << num2; value.Buf24.Mid64 = d1.Mid + ((ulong)d1.High << 32) >> 32 - num2; uint num3 = 3u; while (scale < 0) { uint b = ((scale <= -9) ? 1000000000u : s_powers10[-scale]); uint* ptr = (uint*)(&value); ulong num4 = UInt32x32To64(value.Buf24.U0, b); value.Buf24.U0 = (uint)num4; for (int i = 1; i <= num3; i++) { num4 >>= 32; num4 += UInt32x32To64(ptr[i], b); ptr[i] = (uint)num4; } if (num4 > int.MaxValue) { ptr[++num3] = (uint)(num4 >> 32); } scale += 9; } if (d2.High == 0) { ulong den = d2.Low64 << num2; switch (num3) { case 6u: Div96By64(ref *(Buf12*)(&value.Buf24.U4), den); goto case 5u; case 5u: Div96By64(ref *(Buf12*)(&value.Buf24.U3), den); goto case 4u; case 4u: Div96By64(ref *(Buf12*)(&value.Buf24.U2), den); break; } Div96By64(ref *(Buf12*)(&value.Buf24.U1), den); Div96By64(ref *(Buf12*)(&value), den); d1.Low64 = value.Buf24.Low64 >> num2; d1.High = 0u; return; } Unsafe.SkipInit(out var value2); value2.Low64 = d2.Low64 << num2; value2.U2 = (uint)(d2.Mid + ((ulong)d2.High << 32) >> 32 - num2); switch (num3) { case 6u: Div128By96(ref *(Buf16*)(&value.Buf24.U3), ref value2); goto case 5u; case 5u: Div128By96(ref *(Buf16*)(&value.Buf24.U2), ref value2); goto case 4u; case 4u: Div128By96(ref *(Buf16*)(&value.Buf24.U1), ref value2); break; } Div128By96(ref *(Buf16*)(&value), ref value2); d1.Low64 = (value.Buf24.Low64 >> num2) + ((ulong)value.Buf24.U2 << 32 - num2 << 32); d1.High = value.Buf24.U2 >> num2; } internal static void InternalRound(ref DecCalc d, uint scale, MidpointRounding mode) { d.uflags -= scale << 16; uint num = 0u; while (true) { uint num6; uint num5; if (scale >= 9) { scale -= 9; uint num2 = d.uhi; if (num2 == 0) { ulong low = d.Low64; ulong num4 = (d.Low64 = low / 1000000000); num5 = (uint)(low - num4 * 1000000000); } else { num5 = num2 - (d.uhi = num2 / 1000000000) * 1000000000; num2 = d.umid; if ((num2 | num5) != 0) { num5 = num2 - (d.umid = (uint)((((ulong)num5 << 32) | num2) / 1000000000)) * 1000000000; } num2 = d.ulo; if ((num2 | num5) != 0) { num5 = num2 - (d.ulo = (uint)((((ulong)num5 << 32) | num2) / 1000000000)) * 1000000000; } } num6 = 1000000000u; if (scale != 0) { num |= num5; continue; } } else { num6 = s_powers10[scale]; uint num7 = d.uhi; if (num7 == 0) { ulong low2 = d.Low64; if (low2 == 0L) { if (mode <= MidpointRounding.ToZero) { break; } num5 = 0u; } else { ulong num9 = (d.Low64 = low2 / num6); num5 = (uint)(low2 - num9 * num6); } } else { num5 = num7 - (d.uhi = num7 / num6) * num6; num7 = d.umid; if ((num7 | num5) != 0) { num5 = num7 - (d.umid = (uint)((((ulong)num5 << 32) | num7) / num6)) * num6; } num7 = d.ulo; if ((num7 | num5) != 0) { num5 = num7 - (d.ulo = (uint)((((ulong)num5 << 32) | num7) / num6)) * num6; } } } switch (mode) { case MidpointRounding.ToEven: num5 <<= 1; if ((num | (d.ulo & (true ? 1u : 0u))) != 0) { num5++; } if (num6 >= num5) { break; } goto IL_01e5; case MidpointRounding.AwayFromZero: num5 <<= 1; if (num6 > num5) { break; } goto IL_01e5; case MidpointRounding.ToNegativeInfinity: if ((num5 | num) == 0 || !d.IsNegative) { break; } goto IL_01e5; default: if ((num5 | num) == 0 || d.IsNegative) { break; } goto IL_01e5; case MidpointRounding.ToZero: break; IL_01e5: if (++d.Low64 == 0L) { d.uhi++; } break; } break; } } internal static uint DecDivMod1E9(ref DecCalc value) { ulong num = ((ulong)value.uhi << 32) + value.umid; ulong num2 = num / 1000000000; value.uhi = (uint)(num2 >> 32); value.umid = (uint)num2; ulong num3 = (num - (uint)((int)num2 * 1000000000) << 32) + value.ulo; return (uint)(int)num3 - (value.ulo = (uint)(num3 / 1000000000)) * 1000000000; } } public const decimal Zero = 0m; public const decimal One = 1m; public const decimal MinusOne = -1m; public const decimal MaxValue = 79228162514264337593543950335m; public const decimal MinValue = -79228162514264337593543950335m; private readonly int _flags; private readonly uint _hi32; private readonly ulong _lo64; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal IAdditiveIdentity.AdditiveIdentity => 0.0m; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal IMinMaxValue.MinValue => decimal.MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal IMinMaxValue.MaxValue => decimal.MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal IMultiplicativeIdentity.MultiplicativeIdentity => 1.0m; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal INumber.One => 1.0m; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal INumber.Zero => 0.0m; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal ISignedNumber.NegativeOne => -1m; internal uint High => _hi32; internal uint Low => (uint)_lo64; internal uint Mid => (uint)(_lo64 >> 32); internal bool IsNegative => _flags < 0; internal int Scale => (byte)(_flags >> 16); private ulong Low64 => _lo64; internal Decimal(Currency value) { this = FromOACurrency(value.m_value); } public Decimal(int value) { if (value >= 0) { _flags = 0; } else { _flags = int.MinValue; value = -value; } _lo64 = (uint)value; _hi32 = 0u; } [CLSCompliant(false)] public Decimal(uint value) { _flags = 0; _lo64 = value; _hi32 = 0u; } public Decimal(long value) { if (value >= 0) { _flags = 0; } else { _flags = int.MinValue; value = -value; } _lo64 = (ulong)value; _hi32 = 0u; } [CLSCompliant(false)] public Decimal(ulong value) { _flags = 0; _lo64 = value; _hi32 = 0u; } public Decimal(float value) { DecCalc.VarDecFromR4(value, out AsMutable(ref this)); } public Decimal(double value) { DecCalc.VarDecFromR8(value, out AsMutable(ref this)); } private Decimal(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } _flags = info.GetInt32("flags"); _hi32 = (uint)info.GetInt32("hi"); _lo64 = (ulong)((uint)info.GetInt32("lo") + ((long)info.GetInt32("mid") << 32)); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("flags", _flags); info.AddValue("hi", (int)High); info.AddValue("lo", (int)Low); info.AddValue("mid", (int)Mid); } public static decimal FromOACurrency(long cy) { bool isNegative = false; ulong num; if (cy < 0) { isNegative = true; num = (ulong)(-cy); } else { num = (ulong)cy; } int num2 = 4; if (num != 0L) { while (num2 != 0 && num % 10 == 0L) { num2--; num /= 10; } } return new decimal((int)num, (int)(num >> 32), 0, isNegative, (byte)num2); } public static long ToOACurrency(decimal value) { return DecCalc.VarCyFromDec(ref AsMutable(ref value)); } private static bool IsValid(int flags) { if ((flags & 0x7F00FFFF) == 0) { return (uint)(flags & 0xFF0000) <= 1835008u; } return false; } public Decimal(int[] bits) : this((ReadOnlySpan)(bits ?? throw new ArgumentNullException("bits"))) { } public Decimal(ReadOnlySpan bits) { if (bits.Length == 4) { int flags = bits[3]; if (IsValid(flags)) { _lo64 = (uint)bits[0] + ((ulong)(uint)bits[1] << 32); _hi32 = (uint)bits[2]; _flags = flags; return; } } throw new ArgumentException(SR.Arg_DecBitCtor); } public Decimal(int lo, int mid, int hi, bool isNegative, byte scale) { if (scale > 28) { throw new ArgumentOutOfRangeException("scale", SR.ArgumentOutOfRange_DecimalScale); } _lo64 = (uint)lo + ((ulong)(uint)mid << 32); _hi32 = (uint)hi; _flags = scale << 16; if (isNegative) { _flags |= int.MinValue; } } void IDeserializationCallback.OnDeserialization(object sender) { if (!IsValid(_flags)) { throw new SerializationException(SR.Overflow_Decimal); } } private Decimal(int lo, int mid, int hi, int flags) { if (IsValid(flags)) { _lo64 = (uint)lo + ((ulong)(uint)mid << 32); _hi32 = (uint)hi; _flags = flags; return; } throw new ArgumentException(SR.Arg_DecBitCtor); } private Decimal(in decimal d, int flags) { this = d; _flags = flags; } internal static decimal Abs(in decimal d) { return new decimal(in d, d._flags & 0x7FFFFFFF); } public static decimal Add(decimal d1, decimal d2) { DecCalc.DecAddSub(ref AsMutable(ref d1), ref AsMutable(ref d2), sign: false); return d1; } public static decimal Ceiling(decimal d) { int flags = d._flags; if (((uint)flags & 0xFF0000u) != 0) { DecCalc.InternalRound(ref AsMutable(ref d), (byte)(flags >> 16), MidpointRounding.ToPositiveInfinity); } return d; } public static int Compare(decimal d1, decimal d2) { return DecCalc.VarDecCmp(in d1, in d2); } public int CompareTo(object? value) { if (value == null) { return 1; } if (!(value is decimal d)) { throw new ArgumentException(SR.Arg_MustBeDecimal); } return DecCalc.VarDecCmp(in this, in d); } public int CompareTo(decimal value) { return DecCalc.VarDecCmp(in this, in value); } public static decimal Divide(decimal d1, decimal d2) { DecCalc.VarDecDiv(ref AsMutable(ref d1), ref AsMutable(ref d2)); return d1; } public override bool Equals([NotNullWhen(true)] object? value) { if (value is decimal d) { return DecCalc.VarDecCmp(in this, in d) == 0; } return false; } public bool Equals(decimal value) { return DecCalc.VarDecCmp(in this, in value) == 0; } public override int GetHashCode() { return DecCalc.GetHashCode(in this); } public static bool Equals(decimal d1, decimal d2) { return DecCalc.VarDecCmp(in d1, in d2) == 0; } public static decimal Floor(decimal d) { int flags = d._flags; if (((uint)flags & 0xFF0000u) != 0) { DecCalc.InternalRound(ref AsMutable(ref d), (byte)(flags >> 16), MidpointRounding.ToNegativeInfinity); } return d; } public override string ToString() { return Number.FormatDecimal(this, null, NumberFormatInfo.CurrentInfo); } public string ToString(string? format) { return Number.FormatDecimal(this, format, NumberFormatInfo.CurrentInfo); } public string ToString(IFormatProvider? provider) { return Number.FormatDecimal(this, null, NumberFormatInfo.GetInstance(provider)); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatDecimal(this, format, NumberFormatInfo.GetInstance(provider)); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return Number.TryFormatDecimal(this, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten); } public static decimal Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo); } public static decimal Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseDecimal(s, style, NumberFormatInfo.CurrentInfo); } public static decimal Parse(string s, IFormatProvider? provider) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.GetInstance(provider)); } public static decimal Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseDecimal(s, style, NumberFormatInfo.GetInstance(provider)); } public static decimal Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Number, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.ParseDecimal(s, style, NumberFormatInfo.GetInstance(provider)); } public static bool TryParse([NotNullWhen(true)] string? s, out decimal result) { if (s == null) { result = default(decimal); return false; } return Number.TryParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } public static bool TryParse(ReadOnlySpan s, out decimal result) { return Number.TryParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out decimal result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { result = default(decimal); return false; } return Number.TryParseDecimal(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out decimal result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.TryParseDecimal(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } public static int[] GetBits(decimal d) { return new int[4] { (int)d.Low, (int)d.Mid, (int)d.High, d._flags }; } public static int GetBits(decimal d, Span destination) { if ((uint)destination.Length <= 3u) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } destination[0] = (int)d.Low; destination[1] = (int)d.Mid; destination[2] = (int)d.High; destination[3] = d._flags; return 4; } public static bool TryGetBits(decimal d, Span destination, out int valuesWritten) { if ((uint)destination.Length <= 3u) { valuesWritten = 0; return false; } destination[0] = (int)d.Low; destination[1] = (int)d.Mid; destination[2] = (int)d.High; destination[3] = d._flags; valuesWritten = 4; return true; } internal static void GetBytes(in decimal d, Span buffer) { BinaryPrimitives.WriteInt32LittleEndian(buffer, (int)d.Low); BinaryPrimitives.WriteInt32LittleEndian(buffer.Slice(4), (int)d.Mid); BinaryPrimitives.WriteInt32LittleEndian(buffer.Slice(8), (int)d.High); BinaryPrimitives.WriteInt32LittleEndian(buffer.Slice(12), d._flags); } internal static decimal ToDecimal(ReadOnlySpan span) { int lo = BinaryPrimitives.ReadInt32LittleEndian(span); int mid = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(4)); int hi = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(8)); int flags = BinaryPrimitives.ReadInt32LittleEndian(span.Slice(12)); return new decimal(lo, mid, hi, flags); } internal static ref readonly decimal Max(in decimal d1, in decimal d2) { if (DecCalc.VarDecCmp(in d1, in d2) < 0) { return ref d2; } return ref d1; } internal static ref readonly decimal Min(in decimal d1, in decimal d2) { if (DecCalc.VarDecCmp(in d1, in d2) >= 0) { return ref d2; } return ref d1; } public static decimal Remainder(decimal d1, decimal d2) { DecCalc.VarDecMod(ref AsMutable(ref d1), ref AsMutable(ref d2)); return d1; } public static decimal Multiply(decimal d1, decimal d2) { DecCalc.VarDecMul(ref AsMutable(ref d1), ref AsMutable(ref d2)); return d1; } public static decimal Negate(decimal d) { return new decimal(in d, d._flags ^ int.MinValue); } public static decimal Round(decimal d) { return Round(ref d, 0, MidpointRounding.ToEven); } public static decimal Round(decimal d, int decimals) { return Round(ref d, decimals, MidpointRounding.ToEven); } public static decimal Round(decimal d, MidpointRounding mode) { return Round(ref d, 0, mode); } public static decimal Round(decimal d, int decimals, MidpointRounding mode) { return Round(ref d, decimals, mode); } private static decimal Round(ref decimal d, int decimals, MidpointRounding mode) { if ((uint)decimals > 28u) { throw new ArgumentOutOfRangeException("decimals", SR.ArgumentOutOfRange_DecimalRound); } if ((uint)mode > 4u) { throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, "MidpointRounding"), "mode"); } int num = d.Scale - decimals; if (num > 0) { DecCalc.InternalRound(ref AsMutable(ref d), (uint)num, mode); } return d; } internal static int Sign(in decimal d) { if ((d.Low64 | d.High) != 0L) { return (d._flags >> 31) | 1; } return 0; } public static decimal Subtract(decimal d1, decimal d2) { DecCalc.DecAddSub(ref AsMutable(ref d1), ref AsMutable(ref d2), sign: true); return d1; } public static byte ToByte(decimal value) { uint num; try { num = ToUInt32(value); } catch (OverflowException) { Number.ThrowOverflowException(TypeCode.Byte); throw; } if (num != (byte)num) { Number.ThrowOverflowException(TypeCode.Byte); } return (byte)num; } [CLSCompliant(false)] public static sbyte ToSByte(decimal value) { int num; try { num = ToInt32(value); } catch (OverflowException) { Number.ThrowOverflowException(TypeCode.SByte); throw; } if (num != (sbyte)num) { Number.ThrowOverflowException(TypeCode.SByte); } return (sbyte)num; } public static short ToInt16(decimal value) { int num; try { num = ToInt32(value); } catch (OverflowException) { Number.ThrowOverflowException(TypeCode.Int16); throw; } if (num != (short)num) { Number.ThrowOverflowException(TypeCode.Int16); } return (short)num; } public static double ToDouble(decimal d) { return DecCalc.VarR8FromDec(in d); } public static int ToInt32(decimal d) { Truncate(ref d); if ((d.High | d.Mid) == 0) { int low = (int)d.Low; if (!d.IsNegative) { if (low >= 0) { return low; } } else { low = -low; if (low <= 0) { return low; } } } throw new OverflowException(SR.Overflow_Int32); } public static long ToInt64(decimal d) { Truncate(ref d); if (d.High == 0) { long low = (long)d.Low64; if (!d.IsNegative) { if (low >= 0) { return low; } } else { low = -low; if (low <= 0) { return low; } } } throw new OverflowException(SR.Overflow_Int64); } [CLSCompliant(false)] public static ushort ToUInt16(decimal value) { uint num; try { num = ToUInt32(value); } catch (OverflowException) { Number.ThrowOverflowException(TypeCode.UInt16); throw; } if (num != (ushort)num) { Number.ThrowOverflowException(TypeCode.UInt16); } return (ushort)num; } [CLSCompliant(false)] public static uint ToUInt32(decimal d) { Truncate(ref d); if ((d.High | d.Mid) == 0) { uint low = d.Low; if (!d.IsNegative || low == 0) { return low; } } throw new OverflowException(SR.Overflow_UInt32); } [CLSCompliant(false)] public static ulong ToUInt64(decimal d) { Truncate(ref d); if (d.High == 0) { ulong low = d.Low64; if (!d.IsNegative || low == 0L) { return low; } } throw new OverflowException(SR.Overflow_UInt64); } public static float ToSingle(decimal d) { return DecCalc.VarR4FromDec(in d); } public static decimal Truncate(decimal d) { Truncate(ref d); return d; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Truncate(ref decimal d) { int flags = d._flags; if (((uint)flags & 0xFF0000u) != 0) { DecCalc.InternalRound(ref AsMutable(ref d), (byte)(flags >> 16), MidpointRounding.ToZero); } } public static implicit operator decimal(byte value) { return new decimal((uint)value); } [CLSCompliant(false)] public static implicit operator decimal(sbyte value) { return new decimal(value); } public static implicit operator decimal(short value) { return new decimal(value); } [CLSCompliant(false)] public static implicit operator decimal(ushort value) { return new decimal((uint)value); } public static implicit operator decimal(char value) { return new decimal((uint)value); } public static implicit operator decimal(int value) { return new decimal(value); } [CLSCompliant(false)] public static implicit operator decimal(uint value) { return new decimal(value); } public static implicit operator decimal(long value) { return new decimal(value); } [CLSCompliant(false)] public static implicit operator decimal(ulong value) { return new decimal(value); } public static explicit operator decimal(float value) { return new decimal(value); } public static explicit operator decimal(double value) { return new decimal(value); } public static explicit operator byte(decimal value) { return ToByte(value); } [CLSCompliant(false)] public static explicit operator sbyte(decimal value) { return ToSByte(value); } public static explicit operator char(decimal value) { try { return (char)ToUInt16(value); } catch (OverflowException innerException) { throw new OverflowException(SR.Overflow_Char, innerException); } } public static explicit operator short(decimal value) { return ToInt16(value); } [CLSCompliant(false)] public static explicit operator ushort(decimal value) { return ToUInt16(value); } public static explicit operator int(decimal value) { return ToInt32(value); } [CLSCompliant(false)] public static explicit operator uint(decimal value) { return ToUInt32(value); } public static explicit operator long(decimal value) { return ToInt64(value); } [CLSCompliant(false)] public static explicit operator ulong(decimal value) { return ToUInt64(value); } public static explicit operator float(decimal value) { return DecCalc.VarR4FromDec(in value); } public static explicit operator double(decimal value) { return DecCalc.VarR8FromDec(in value); } public static decimal operator +(decimal d) { return d; } public static decimal operator -(decimal d) { return new decimal(in d, d._flags ^ int.MinValue); } public static decimal operator ++(decimal d) { return Add(d, 1m); } public static decimal operator --(decimal d) { return Subtract(d, 1m); } public static decimal operator +(decimal d1, decimal d2) { DecCalc.DecAddSub(ref AsMutable(ref d1), ref AsMutable(ref d2), sign: false); return d1; } public static decimal operator -(decimal d1, decimal d2) { DecCalc.DecAddSub(ref AsMutable(ref d1), ref AsMutable(ref d2), sign: true); return d1; } public static decimal operator *(decimal d1, decimal d2) { DecCalc.VarDecMul(ref AsMutable(ref d1), ref AsMutable(ref d2)); return d1; } public static decimal operator /(decimal d1, decimal d2) { DecCalc.VarDecDiv(ref AsMutable(ref d1), ref AsMutable(ref d2)); return d1; } public static decimal operator %(decimal d1, decimal d2) { DecCalc.VarDecMod(ref AsMutable(ref d1), ref AsMutable(ref d2)); return d1; } public static bool operator ==(decimal d1, decimal d2) { return DecCalc.VarDecCmp(in d1, in d2) == 0; } public static bool operator !=(decimal d1, decimal d2) { return DecCalc.VarDecCmp(in d1, in d2) != 0; } public static bool operator <(decimal d1, decimal d2) { return DecCalc.VarDecCmp(in d1, in d2) < 0; } public static bool operator <=(decimal d1, decimal d2) { return DecCalc.VarDecCmp(in d1, in d2) <= 0; } public static bool operator >(decimal d1, decimal d2) { return DecCalc.VarDecCmp(in d1, in d2) > 0; } public static bool operator >=(decimal d1, decimal d2) { return DecCalc.VarDecCmp(in d1, in d2) >= 0; } public TypeCode GetTypeCode() { return TypeCode.Decimal; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(this); } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Decimal", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { return DecCalc.VarR4FromDec(in this); } double IConvertible.ToDouble(IFormatProvider provider) { return DecCalc.VarR8FromDec(in this); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return this; } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Decimal", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal IAdditionOperators.op_Addition(decimal left, decimal right) { return left + right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(decimal left, decimal right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(decimal left, decimal right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(decimal left, decimal right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(decimal left, decimal right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal IDecrementOperators.op_Decrement(decimal value) { return --value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal IDivisionOperators.op_Division(decimal left, decimal right) { return left / right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(decimal left, decimal right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(decimal left, decimal right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal IIncrementOperators.op_Increment(decimal value) { return ++value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal IModulusOperators.op_Modulus(decimal left, decimal right) { return left % right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal IMultiplyOperators.op_Multiply(decimal left, decimal right) { return left * right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal INumber.Abs(decimal value) { return Math.Abs(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal INumber.Create(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (decimal)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (long)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (decimal)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (ulong)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0m; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (decimal)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (long)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (decimal)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (ulong)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0m; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (decimal)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (long)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (decimal)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (ulong)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0m; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal INumber.Clamp(decimal value, decimal min, decimal max) { return Math.Clamp(value, min, max); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (decimal Quotient, decimal Remainder) INumber.DivRem(decimal left, decimal right) { return (left / right, left % right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal INumber.Max(decimal x, decimal y) { return Math.Max(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal INumber.Min(decimal x, decimal y) { return Math.Min(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal INumber.Sign(decimal value) { return Math.Sign(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out decimal result) { if (typeof(TOther) == typeof(byte)) { result = (byte)(object)value; return true; } if (typeof(TOther) == typeof(char)) { result = (char)(object)value; return true; } if (typeof(TOther) == typeof(decimal)) { result = (decimal)(object)value; return true; } if (typeof(TOther) == typeof(double)) { result = (decimal)(double)(object)value; return true; } if (typeof(TOther) == typeof(short)) { result = (short)(object)value; return true; } if (typeof(TOther) == typeof(int)) { result = (int)(object)value; return true; } if (typeof(TOther) == typeof(long)) { result = (long)(object)value; return true; } if (typeof(TOther) == typeof(IntPtr)) { result = (long)(IntPtr)(object)value; return true; } if (typeof(TOther) == typeof(sbyte)) { result = (sbyte)(object)value; return true; } if (typeof(TOther) == typeof(float)) { result = (decimal)(float)(object)value; return true; } if (typeof(TOther) == typeof(ushort)) { result = (ushort)(object)value; return true; } if (typeof(TOther) == typeof(uint)) { result = (uint)(object)value; return true; } if (typeof(TOther) == typeof(ulong)) { result = (ulong)(object)value; return true; } if (typeof(TOther) == typeof(UIntPtr)) { result = (ulong)(UIntPtr)(object)value; return true; } ThrowHelper.ThrowNotSupportedException(); result = default(decimal); return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out decimal result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out decimal result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out decimal result) { return TryParse(s, NumberStyles.Number, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, NumberStyles.Number, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out decimal result) { return TryParse(s, NumberStyles.Number, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal ISubtractionOperators.op_Subtraction(decimal left, decimal right) { return left - right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal IUnaryNegationOperators.op_UnaryNegation(decimal value) { return -value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static decimal IUnaryPlusOperators.op_UnaryPlus(decimal value) { return value; } private static ref DecCalc AsMutable(ref decimal d) { return ref Unsafe.As(ref d); } internal static uint DecDivMod1E9(ref decimal value) { return DecCalc.DecDivMod1E9(ref AsMutable(ref value)); } } [ClassInterface(ClassInterfaceType.None)] [ComVisible(true)] public abstract class Delegate : ICloneable, ISerializable { internal object _target; internal object _methodBase; internal IntPtr _methodPtr; internal IntPtr _methodPtrAux; public object? Target => GetTarget(); public MethodInfo Method => GetMethodImpl(); [RequiresUnreferencedCode("The target method might be removed")] protected Delegate(object target, string method) { if (target == null) { throw new ArgumentNullException("target"); } if (method == null) { throw new ArgumentNullException("method"); } if (!BindToMethodName(target, (RuntimeType)target.GetType(), method, (DelegateBindingFlags)10)) { throw new ArgumentException(SR.Arg_DlgtTargMeth); } } protected Delegate([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type target, string method) { if (target == null) { throw new ArgumentNullException("target"); } if (target.ContainsGenericParameters) { throw new ArgumentException(SR.Arg_UnboundGenParam, "target"); } if (method == null) { throw new ArgumentNullException("method"); } if (!(target is RuntimeType methodType)) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, "target"); } BindToMethodName(null, methodType, method, (DelegateBindingFlags)37); } protected virtual object? DynamicInvokeImpl(object?[]? args) { RuntimeMethodInfo runtimeMethodInfo = (RuntimeMethodInfo)RuntimeType.GetMethodBase(methodHandle: new RuntimeMethodHandleInternal(GetInvokeMethod()), reflectedType: (RuntimeType)GetType()); return runtimeMethodInfo.Invoke(this, BindingFlags.Default, null, args, null); } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == null || !InternalEqualTypes(this, obj)) { return false; } Delegate @delegate = (Delegate)obj; if (_target == @delegate._target && _methodPtr == @delegate._methodPtr && _methodPtrAux == @delegate._methodPtrAux) { return true; } if (_methodPtrAux == IntPtr.Zero) { if (@delegate._methodPtrAux != IntPtr.Zero) { return false; } if (_target != @delegate._target) { return false; } } else { if (@delegate._methodPtrAux == IntPtr.Zero) { return false; } if (_methodPtrAux == @delegate._methodPtrAux) { return true; } } if (_methodBase == null || @delegate._methodBase == null || !(_methodBase is MethodInfo) || !(@delegate._methodBase is MethodInfo)) { return InternalEqualMethodHandles(this, @delegate); } return _methodBase.Equals(@delegate._methodBase); } public override int GetHashCode() { if (_methodPtrAux == IntPtr.Zero) { return ((_target != null) ? (RuntimeHelpers.GetHashCode(_target) * 33) : 0) + GetType().GetHashCode(); } return GetType().GetHashCode(); } protected virtual MethodInfo GetMethodImpl() { if (_methodBase == null || !(_methodBase is MethodInfo)) { IRuntimeMethodInfo runtimeMethodInfo = FindMethodHandle(); RuntimeType runtimeType = RuntimeMethodHandle.GetDeclaringType(runtimeMethodInfo); if ((RuntimeTypeHandle.IsGenericTypeDefinition(runtimeType) || RuntimeTypeHandle.HasInstantiation(runtimeType)) && (RuntimeMethodHandle.GetAttributes(runtimeMethodInfo) & MethodAttributes.Static) == 0) { if (_methodPtrAux == IntPtr.Zero) { Type type = _target.GetType(); Type genericTypeDefinition = runtimeType.GetGenericTypeDefinition(); while (type != null) { if (type.IsGenericType && type.GetGenericTypeDefinition() == genericTypeDefinition) { runtimeType = type as RuntimeType; break; } type = type.BaseType; } } else { MethodInfo method = GetType().GetMethod("Invoke"); runtimeType = (RuntimeType)method.GetParameters()[0].ParameterType; } } _methodBase = (MethodInfo)RuntimeType.GetMethodBase(runtimeType, runtimeMethodInfo); } return (MethodInfo)_methodBase; } [RequiresUnreferencedCode("The target method might be removed")] public static Delegate? CreateDelegate(Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure) { if (type == null) { throw new ArgumentNullException("type"); } if (target == null) { throw new ArgumentNullException("target"); } if (method == null) { throw new ArgumentNullException("method"); } if (!(type is RuntimeType runtimeType)) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, "type"); } if (!runtimeType.IsDelegate()) { throw new ArgumentException(SR.Arg_MustBeDelegate, "type"); } Delegate @delegate = InternalAlloc(runtimeType); if (!@delegate.BindToMethodName(target, (RuntimeType)target.GetType(), method, (DelegateBindingFlags)26 | (ignoreCase ? DelegateBindingFlags.CaselessMatching : ((DelegateBindingFlags)0)))) { if (throwOnBindFailure) { throw new ArgumentException(SR.Arg_DlgtTargMeth); } return null; } return @delegate; } public static Delegate? CreateDelegate(Type type, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type target, string method, bool ignoreCase, bool throwOnBindFailure) { if (type == null) { throw new ArgumentNullException("type"); } if (target == null) { throw new ArgumentNullException("target"); } if (target.ContainsGenericParameters) { throw new ArgumentException(SR.Arg_UnboundGenParam, "target"); } if (method == null) { throw new ArgumentNullException("method"); } if (!(type is RuntimeType runtimeType)) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, "type"); } if (!(target is RuntimeType methodType)) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, "target"); } if (!runtimeType.IsDelegate()) { throw new ArgumentException(SR.Arg_MustBeDelegate, "type"); } Delegate @delegate = InternalAlloc(runtimeType); if (!@delegate.BindToMethodName(null, methodType, method, (DelegateBindingFlags)5 | (ignoreCase ? DelegateBindingFlags.CaselessMatching : ((DelegateBindingFlags)0)))) { if (throwOnBindFailure) { throw new ArgumentException(SR.Arg_DlgtTargMeth); } return null; } return @delegate; } public static Delegate? CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure) { if (type == null) { throw new ArgumentNullException("type"); } if (method == null) { throw new ArgumentNullException("method"); } if (!(type is RuntimeType runtimeType)) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, "type"); } if (!(method is RuntimeMethodInfo rtMethod)) { throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, "method"); } if (!runtimeType.IsDelegate()) { throw new ArgumentException(SR.Arg_MustBeDelegate, "type"); } Delegate @delegate = CreateDelegateInternal(runtimeType, rtMethod, null, (DelegateBindingFlags)68); if ((object)@delegate == null && throwOnBindFailure) { throw new ArgumentException(SR.Arg_DlgtTargMeth); } return @delegate; } public static Delegate? CreateDelegate(Type type, object? firstArgument, MethodInfo method, bool throwOnBindFailure) { if (type == null) { throw new ArgumentNullException("type"); } if (method == null) { throw new ArgumentNullException("method"); } if (!(type is RuntimeType runtimeType)) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, "type"); } if (!(method is RuntimeMethodInfo rtMethod)) { throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, "method"); } if (!runtimeType.IsDelegate()) { throw new ArgumentException(SR.Arg_MustBeDelegate, "type"); } Delegate @delegate = CreateDelegateInternal(runtimeType, rtMethod, firstArgument, DelegateBindingFlags.RelaxedSignature); if ((object)@delegate == null && throwOnBindFailure) { throw new ArgumentException(SR.Arg_DlgtTargMeth); } return @delegate; } internal static Delegate CreateDelegateNoSecurityCheck(Type type, object target, RuntimeMethodHandle method) { if (type == null) { throw new ArgumentNullException("type"); } if (method.IsNullHandle()) { throw new ArgumentNullException("method"); } if (!(type is RuntimeType runtimeType)) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, "type"); } if (!runtimeType.IsDelegate()) { throw new ArgumentException(SR.Arg_MustBeDelegate, "type"); } Delegate @delegate = InternalAlloc(runtimeType); if (!@delegate.BindToMethodInfo(target, method.GetMethodInfo(), RuntimeMethodHandle.GetDeclaringType(method.GetMethodInfo()), DelegateBindingFlags.RelaxedSignature)) { throw new ArgumentException(SR.Arg_DlgtTargMeth); } return @delegate; } internal static Delegate CreateDelegateInternal(RuntimeType rtType, RuntimeMethodInfo rtMethod, object firstArgument, DelegateBindingFlags flags) { Delegate @delegate = InternalAlloc(rtType); if (@delegate.BindToMethodInfo(firstArgument, rtMethod, rtMethod.GetDeclaringTypeInternal(), flags)) { return @delegate; } return null; } [MethodImpl(MethodImplOptions.InternalCall)] private extern bool BindToMethodName(object target, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] RuntimeType methodType, string method, DelegateBindingFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] private extern bool BindToMethodInfo(object target, IRuntimeMethodInfo method, RuntimeType methodType, DelegateBindingFlags flags); [MethodImpl(MethodImplOptions.InternalCall)] private static extern MulticastDelegate InternalAlloc(RuntimeType type); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern MulticastDelegate InternalAllocLike(Delegate d); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool InternalEqualTypes(object a, object b); [MethodImpl(MethodImplOptions.InternalCall)] private extern void DelegateConstruct(object target, IntPtr slot); [MethodImpl(MethodImplOptions.InternalCall)] internal extern IntPtr GetMulticastInvoke(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern IntPtr GetInvokeMethod(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern IRuntimeMethodInfo FindMethodHandle(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool InternalEqualMethodHandles(Delegate left, Delegate right); [MethodImpl(MethodImplOptions.InternalCall)] internal extern IntPtr AdjustTarget(object target, IntPtr methodPtr); [MethodImpl(MethodImplOptions.InternalCall)] internal extern IntPtr GetCallStub(IntPtr methodPtr); internal virtual object GetTarget() { if (!(_methodPtrAux == IntPtr.Zero)) { return null; } return _target; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool CompareUnmanagedFunctionPtrs(Delegate d1, Delegate d2); public virtual object Clone() { return MemberwiseClone(); } [return: NotNullIfNotNull("a")] [return: NotNullIfNotNull("b")] public static Delegate? Combine(Delegate? a, Delegate? b) { if ((object)a == null) { return b; } return a.CombineImpl(b); } public static Delegate? Combine(params Delegate?[]? delegates) { if (delegates == null || delegates.Length == 0) { return null; } Delegate @delegate = delegates[0]; for (int i = 1; i < delegates.Length; i++) { @delegate = Combine(@delegate, delegates[i]); } return @delegate; } public static Delegate CreateDelegate(Type type, object? firstArgument, MethodInfo method) { return CreateDelegate(type, firstArgument, method, throwOnBindFailure: true); } public static Delegate CreateDelegate(Type type, MethodInfo method) { return CreateDelegate(type, method, throwOnBindFailure: true); } [RequiresUnreferencedCode("The target method might be removed")] public static Delegate CreateDelegate(Type type, object target, string method) { return CreateDelegate(type, target, method, ignoreCase: false, throwOnBindFailure: true); } [RequiresUnreferencedCode("The target method might be removed")] public static Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase) { return CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure: true); } public static Delegate CreateDelegate(Type type, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type target, string method) { return CreateDelegate(type, target, method, ignoreCase: false, throwOnBindFailure: true); } public static Delegate CreateDelegate(Type type, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type target, string method, bool ignoreCase) { return CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure: true); } protected virtual Delegate CombineImpl(Delegate? d) { throw new MulticastNotSupportedException(SR.Multicast_Combine); } protected virtual Delegate? RemoveImpl(Delegate d) { if (!d.Equals(this)) { return this; } return null; } public virtual Delegate[] GetInvocationList() { return new Delegate[1] { this }; } public object? DynamicInvoke(params object?[]? args) { return DynamicInvokeImpl(args); } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public static Delegate? Remove(Delegate? source, Delegate? value) { if ((object)source == null) { return null; } if ((object)value == null) { return source; } if (!InternalEqualTypes(source, value)) { throw new ArgumentException(SR.Arg_DlgtTypeMis); } return source.RemoveImpl(value); } public static Delegate? RemoveAll(Delegate? source, Delegate? value) { Delegate @delegate; do { @delegate = source; source = Remove(source, value); } while (@delegate != source); return @delegate; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Delegate? d1, Delegate? d2) { if ((object)d2 == null) { if ((object)d1 != null) { return false; } return true; } if ((object)d2 != d1) { return d2.Equals(d1); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Delegate? d1, Delegate? d2) { if ((object)d2 == null) { if ((object)d1 != null) { return true; } return false; } if ((object)d2 != d1) { return !d2.Equals(d1); } return false; } } internal enum DelegateBindingFlags { StaticMethodOnly = 1, InstanceMethodOnly = 2, OpenDelegateOnly = 4, ClosedDelegateOnly = 8, NeverCloseOverNull = 0x10, CaselessMatching = 0x20, RelaxedSignature = 0x40 } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible { internal sealed class EnumInfo { public readonly bool HasFlagsAttribute; public readonly ulong[] Values; public readonly string[] Names; public EnumInfo(bool hasFlagsAttribute, ulong[] values, string[] names) { HasFlagsAttribute = hasFlagsAttribute; Values = values; Names = names; } } private const char EnumSeparatorChar = ','; [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetEnumValuesAndNames(QCallTypeHandle enumType, ObjectHandleOnStack values, ObjectHandleOnStack names, Interop.BOOL getNames); [MethodImpl(MethodImplOptions.InternalCall)] public override extern bool Equals([NotNullWhen(true)] object? obj); [MethodImpl(MethodImplOptions.InternalCall)] private static extern object InternalBoxEnum(RuntimeType enumType, long value); [MethodImpl(MethodImplOptions.InternalCall)] private extern CorElementType InternalGetCorElementType(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeType InternalGetUnderlyingType(RuntimeType enumType); [MethodImpl(MethodImplOptions.InternalCall)] private extern bool InternalHasFlag(Enum flags); private static EnumInfo GetEnumInfo(RuntimeType enumType, bool getNames = true) { EnumInfo enumInfo = enumType.GenericCache as EnumInfo; if (enumInfo == null || (getNames && enumInfo.Names == null)) { ulong[] o = null; string[] o2 = null; RuntimeTypeHandle rth = enumType.GetTypeHandleInternal(); GetEnumValuesAndNames(new QCallTypeHandle(ref rth), ObjectHandleOnStack.Create(ref o), ObjectHandleOnStack.Create(ref o2), getNames ? Interop.BOOL.TRUE : Interop.BOOL.FALSE); bool hasFlagsAttribute = enumType.IsDefined(typeof(FlagsAttribute), inherit: false); enumInfo = (EnumInfo)(enumType.GenericCache = new EnumInfo(hasFlagsAttribute, o, o2)); } return enumInfo; } private string ValueToString() { ref byte rawData = ref this.GetRawData(); return InternalGetCorElementType() switch { CorElementType.ELEMENT_TYPE_I1 => Unsafe.As(ref rawData).ToString(), CorElementType.ELEMENT_TYPE_U1 => rawData.ToString(), CorElementType.ELEMENT_TYPE_BOOLEAN => Unsafe.As(ref rawData).ToString(), CorElementType.ELEMENT_TYPE_I2 => Unsafe.As(ref rawData).ToString(), CorElementType.ELEMENT_TYPE_U2 => Unsafe.As(ref rawData).ToString(), CorElementType.ELEMENT_TYPE_CHAR => Unsafe.As(ref rawData).ToString(), CorElementType.ELEMENT_TYPE_I4 => Unsafe.As(ref rawData).ToString(), CorElementType.ELEMENT_TYPE_U4 => Unsafe.As(ref rawData).ToString(), CorElementType.ELEMENT_TYPE_R4 => Unsafe.As(ref rawData).ToString(), CorElementType.ELEMENT_TYPE_I8 => Unsafe.As(ref rawData).ToString(), CorElementType.ELEMENT_TYPE_U8 => Unsafe.As(ref rawData).ToString(), CorElementType.ELEMENT_TYPE_R8 => Unsafe.As(ref rawData).ToString(), CorElementType.ELEMENT_TYPE_I => Unsafe.As(ref rawData).ToString(), CorElementType.ELEMENT_TYPE_U => Unsafe.As(ref rawData).ToString(), _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType), }; } private string ValueToHexString() { ref byte rawData = ref this.GetRawData(); Span destination = stackalloc byte[8]; int length; switch (InternalGetCorElementType()) { case CorElementType.ELEMENT_TYPE_I1: case CorElementType.ELEMENT_TYPE_U1: destination[0] = rawData; length = 1; break; case CorElementType.ELEMENT_TYPE_BOOLEAN: if (rawData == 0) { return "00"; } return "01"; case CorElementType.ELEMENT_TYPE_CHAR: case CorElementType.ELEMENT_TYPE_I2: case CorElementType.ELEMENT_TYPE_U2: BinaryPrimitives.WriteUInt16BigEndian(destination, Unsafe.As(ref rawData)); length = 2; break; case CorElementType.ELEMENT_TYPE_I4: case CorElementType.ELEMENT_TYPE_U4: BinaryPrimitives.WriteUInt32BigEndian(destination, Unsafe.As(ref rawData)); length = 4; break; case CorElementType.ELEMENT_TYPE_I8: case CorElementType.ELEMENT_TYPE_U8: BinaryPrimitives.WriteUInt64BigEndian(destination, Unsafe.As(ref rawData)); length = 8; break; default: throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } return HexConverter.ToString(destination.Slice(0, length)); } private static string ValueToHexString(object value) { return Convert.GetTypeCode(value) switch { TypeCode.SByte => ((byte)(sbyte)value).ToString("X2", null), TypeCode.Byte => ((byte)value).ToString("X2", null), TypeCode.Boolean => ((bool)value) ? "01" : "00", TypeCode.Int16 => ((ushort)(short)value).ToString("X4", null), TypeCode.UInt16 => ((ushort)value).ToString("X4", null), TypeCode.Char => ((ushort)(char)value).ToString("X4", null), TypeCode.UInt32 => ((uint)value).ToString("X8", null), TypeCode.Int32 => ((uint)(int)value).ToString("X8", null), TypeCode.UInt64 => ((ulong)value).ToString("X16", null), TypeCode.Int64 => ((ulong)(long)value).ToString("X16", null), _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType), }; } internal static string GetEnumName(RuntimeType enumType, ulong ulValue) { return GetEnumName(GetEnumInfo(enumType), ulValue); } private static string GetEnumName(EnumInfo enumInfo, ulong ulValue) { int num = Array.BinarySearch(enumInfo.Values, ulValue); if (num >= 0) { return enumInfo.Names[num]; } return null; } private static string InternalFormat(RuntimeType enumType, ulong value) { EnumInfo enumInfo = GetEnumInfo(enumType); if (!enumInfo.HasFlagsAttribute) { return GetEnumName(enumInfo, value); } return InternalFlagsFormat(enumInfo, value); } private static string InternalFlagsFormat(RuntimeType enumType, ulong result) { return InternalFlagsFormat(GetEnumInfo(enumType), result); } private static string InternalFlagsFormat(EnumInfo enumInfo, ulong resultValue) { string[] names = enumInfo.Names; ulong[] values = enumInfo.Values; if (resultValue == 0L) { if (values.Length == 0 || values[0] != 0L) { return "0"; } return names[0]; } Span span = stackalloc int[64]; int num; for (num = values.Length - 1; num >= 0; num--) { if (values[num] == resultValue) { return names[num]; } if (values[num] < resultValue) { break; } } int num2 = 0; int num3 = 0; while (num >= 0) { ulong num4 = values[num]; if (num == 0 && num4 == 0L) { break; } if ((resultValue & num4) == num4) { resultValue -= num4; span[num3++] = num; num2 = checked(num2 + names[num].Length); } num--; } if (resultValue != 0L) { return null; } string text = string.FastAllocateString(checked(num2 + 2 * (num3 - 1))); Span destination = new Span(ref text.GetRawStringData(), text.Length); string text2 = names[span[--num3]]; text2.CopyTo(destination); destination = destination.Slice(text2.Length); while (--num3 >= 0) { destination[0] = ','; destination[1] = ' '; destination = destination.Slice(2); text2 = names[span[num3]]; text2.CopyTo(destination); destination = destination.Slice(text2.Length); } return text; } internal static ulong ToUInt64(object value) { return Convert.GetTypeCode(value) switch { TypeCode.SByte => (ulong)(sbyte)value, TypeCode.Byte => (byte)value, TypeCode.Boolean => (ulong)(((bool)value) ? 1 : 0), TypeCode.Int16 => (ulong)(short)value, TypeCode.UInt16 => (ushort)value, TypeCode.Char => (char)value, TypeCode.UInt32 => (uint)value, TypeCode.Int32 => (ulong)(int)value, TypeCode.UInt64 => (ulong)value, TypeCode.Int64 => (ulong)(long)value, _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType), }; } private static ulong ToUInt64(TEnum value) where TEnum : struct, Enum { return Type.GetTypeCode(typeof(TEnum)) switch { TypeCode.SByte => (ulong)Unsafe.As(ref value), TypeCode.Byte => Unsafe.As(ref value), TypeCode.Boolean => (ulong)(Unsafe.As(ref value) ? 1 : 0), TypeCode.Int16 => (ulong)Unsafe.As(ref value), TypeCode.UInt16 => Unsafe.As(ref value), TypeCode.Char => Unsafe.As(ref value), TypeCode.UInt32 => Unsafe.As(ref value), TypeCode.Int32 => (ulong)Unsafe.As(ref value), TypeCode.UInt64 => Unsafe.As(ref value), TypeCode.Int64 => (ulong)Unsafe.As(ref value), _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType), }; } public static string? GetName(TEnum value) where TEnum : struct, Enum { return GetEnumName((RuntimeType)typeof(TEnum), ToUInt64(value)); } public static string? GetName(Type enumType, object value) { if ((object)enumType == null) { throw new ArgumentNullException("enumType"); } return enumType.GetEnumName(value); } public static string[] GetNames() where TEnum : struct, Enum { return new ReadOnlySpan(InternalGetNames((RuntimeType)typeof(TEnum))).ToArray(); } public static string[] GetNames(Type enumType) { if ((object)enumType == null) { throw new ArgumentNullException("enumType"); } return enumType.GetEnumNames(); } internal static string[] InternalGetNames(RuntimeType enumType) { return GetEnumInfo(enumType).Names; } public static Type GetUnderlyingType(Type enumType) { if (enumType == null) { throw new ArgumentNullException("enumType"); } return enumType.GetEnumUnderlyingType(); } public static TEnum[] GetValues() where TEnum : struct, Enum { return (TEnum[])GetValues(typeof(TEnum)); } public static Array GetValues(Type enumType) { if ((object)enumType == null) { throw new ArgumentNullException("enumType"); } return enumType.GetEnumValues(); } [Intrinsic] public bool HasFlag(Enum flag) { if (flag == null) { throw new ArgumentNullException("flag"); } if (!GetType().IsEquivalentTo(flag.GetType())) { throw new ArgumentException(SR.Format(SR.Argument_EnumTypeDoesNotMatch, flag.GetType(), GetType())); } return InternalHasFlag(flag); } internal static ulong[] InternalGetValues(RuntimeType enumType) { return GetEnumInfo(enumType, getNames: false).Values; } public static bool IsDefined(TEnum value) where TEnum : struct, Enum { RuntimeType enumType = (RuntimeType)typeof(TEnum); ulong[] array = InternalGetValues(enumType); ulong value2 = ToUInt64(value); return Array.BinarySearch(array, value2) >= 0; } public static bool IsDefined(Type enumType, object value) { if ((object)enumType == null) { throw new ArgumentNullException("enumType"); } return enumType.IsEnumDefined(value); } public static object Parse(Type enumType, string value) { return Parse(enumType, value, ignoreCase: false); } public static object Parse(Type enumType, ReadOnlySpan value) { return Parse(enumType, value, ignoreCase: false); } public static object Parse(Type enumType, string value, bool ignoreCase) { object result; bool flag = TryParse(enumType, value, ignoreCase, throwOnFailure: true, out result); return result; } public static object Parse(Type enumType, ReadOnlySpan value, bool ignoreCase) { object result; bool flag = TryParse(enumType, value, ignoreCase, throwOnFailure: true, out result); return result; } public static TEnum Parse(string value) where TEnum : struct { return Parse(value, ignoreCase: false); } public static TEnum Parse(ReadOnlySpan value) where TEnum : struct { return Parse(value, ignoreCase: false); } public static TEnum Parse(string value, bool ignoreCase) where TEnum : struct { TEnum result; bool flag = TryParse(value, ignoreCase, throwOnFailure: true, out result); return result; } public static TEnum Parse(ReadOnlySpan value, bool ignoreCase) where TEnum : struct { TEnum result; bool flag = TryParse(value, ignoreCase, throwOnFailure: true, out result); return result; } public static bool TryParse(Type enumType, string? value, out object? result) { return TryParse(enumType, value, ignoreCase: false, out result); } public static bool TryParse(Type enumType, ReadOnlySpan value, out object? result) { return TryParse(enumType, value, ignoreCase: false, out result); } public static bool TryParse(Type enumType, string? value, bool ignoreCase, out object? result) { return TryParse(enumType, value, ignoreCase, throwOnFailure: false, out result); } public static bool TryParse(Type enumType, ReadOnlySpan value, bool ignoreCase, out object? result) { return TryParse(enumType, value, ignoreCase, throwOnFailure: false, out result); } private static bool TryParse(Type enumType, string value, bool ignoreCase, bool throwOnFailure, out object result) { if (value == null) { if (throwOnFailure) { throw new ArgumentNullException("value"); } result = null; return false; } return TryParse(enumType, value.AsSpan(), ignoreCase, throwOnFailure, out result); } private static bool TryParse(Type enumType, ReadOnlySpan value, bool ignoreCase, bool throwOnFailure, out object result) { RuntimeType runtimeType = ValidateRuntimeType(enumType); value = value.TrimStart(); if (value.Length == 0) { if (throwOnFailure) { throw new ArgumentException(SR.Arg_MustContainEnumInfo, "value"); } result = null; return false; } int result3; uint result4; switch (Type.GetTypeCode(runtimeType)) { case TypeCode.SByte: { bool flag = TryParseInt32Enum(runtimeType, value, -128, 127, ignoreCase, throwOnFailure, TypeCode.SByte, out result3); result = (flag ? InternalBoxEnum(runtimeType, result3) : null); return flag; } case TypeCode.Int16: { bool flag = TryParseInt32Enum(runtimeType, value, -32768, 32767, ignoreCase, throwOnFailure, TypeCode.Int16, out result3); result = (flag ? InternalBoxEnum(runtimeType, result3) : null); return flag; } case TypeCode.Int32: { bool flag = TryParseInt32Enum(runtimeType, value, int.MinValue, int.MaxValue, ignoreCase, throwOnFailure, TypeCode.Int32, out result3); result = (flag ? InternalBoxEnum(runtimeType, result3) : null); return flag; } case TypeCode.Byte: { bool flag = TryParseUInt32Enum(runtimeType, value, 255u, ignoreCase, throwOnFailure, TypeCode.Byte, out result4); result = (flag ? InternalBoxEnum(runtimeType, result4) : null); return flag; } case TypeCode.UInt16: { bool flag = TryParseUInt32Enum(runtimeType, value, 65535u, ignoreCase, throwOnFailure, TypeCode.UInt16, out result4); result = (flag ? InternalBoxEnum(runtimeType, result4) : null); return flag; } case TypeCode.UInt32: { bool flag = TryParseUInt32Enum(runtimeType, value, uint.MaxValue, ignoreCase, throwOnFailure, TypeCode.UInt32, out result4); result = (flag ? InternalBoxEnum(runtimeType, result4) : null); return flag; } case TypeCode.Int64: { long result5; bool flag = TryParseInt64Enum(runtimeType, value, ignoreCase, throwOnFailure, out result5); result = (flag ? InternalBoxEnum(runtimeType, result5) : null); return flag; } case TypeCode.UInt64: { ulong result2; bool flag = TryParseUInt64Enum(runtimeType, value, ignoreCase, throwOnFailure, out result2); result = (flag ? InternalBoxEnum(runtimeType, (long)result2) : null); return flag; } default: return TryParseRareEnum(runtimeType, value, ignoreCase, throwOnFailure, out result); } } public static bool TryParse([NotNullWhen(true)] string? value, out TEnum result) where TEnum : struct { return TryParse(value, ignoreCase: false, out result); } public static bool TryParse(ReadOnlySpan value, out TEnum result) where TEnum : struct { return TryParse(value, ignoreCase: false, out result); } public static bool TryParse([NotNullWhen(true)] string? value, bool ignoreCase, out TEnum result) where TEnum : struct { return TryParse(value, ignoreCase, throwOnFailure: false, out result); } public static bool TryParse(ReadOnlySpan value, bool ignoreCase, out TEnum result) where TEnum : struct { return TryParse(value, ignoreCase, throwOnFailure: false, out result); } private static bool TryParse(string value, bool ignoreCase, bool throwOnFailure, out TEnum result) where TEnum : struct { if (value == null) { if (throwOnFailure) { throw new ArgumentNullException("value"); } result = default(TEnum); return false; } return TryParse(value.AsSpan(), ignoreCase, throwOnFailure, out result); } private static bool TryParse(ReadOnlySpan value, bool ignoreCase, bool throwOnFailure, out TEnum result) where TEnum : struct { if (!typeof(TEnum).IsEnum) { throw new ArgumentException(SR.Arg_MustBeEnum, "TEnum"); } value = value.TrimStart(); if (value.Length == 0) { if (throwOnFailure) { throw new ArgumentException(SR.Arg_MustContainEnumInfo, "value"); } result = default(TEnum); return false; } RuntimeType enumType = (RuntimeType)typeof(TEnum); int result3; uint result6; switch (Type.GetTypeCode(typeof(TEnum))) { case TypeCode.SByte: { bool flag = TryParseInt32Enum(enumType, value, -128, 127, ignoreCase, throwOnFailure, TypeCode.SByte, out result3); sbyte source2 = (sbyte)result3; result = Unsafe.As(ref source2); return flag; } case TypeCode.Int16: { bool flag = TryParseInt32Enum(enumType, value, -32768, 32767, ignoreCase, throwOnFailure, TypeCode.Int16, out result3); short source = (short)result3; result = Unsafe.As(ref source); return flag; } case TypeCode.Int32: { bool flag = TryParseInt32Enum(enumType, value, int.MinValue, int.MaxValue, ignoreCase, throwOnFailure, TypeCode.Int32, out result3); result = Unsafe.As(ref result3); return flag; } case TypeCode.Byte: { bool flag = TryParseUInt32Enum(enumType, value, 255u, ignoreCase, throwOnFailure, TypeCode.Byte, out result6); byte source4 = (byte)result6; result = Unsafe.As(ref source4); return flag; } case TypeCode.UInt16: { bool flag = TryParseUInt32Enum(enumType, value, 65535u, ignoreCase, throwOnFailure, TypeCode.UInt16, out result6); ushort source3 = (ushort)result6; result = Unsafe.As(ref source3); return flag; } case TypeCode.UInt32: { bool flag = TryParseUInt32Enum(enumType, value, uint.MaxValue, ignoreCase, throwOnFailure, TypeCode.UInt32, out result6); result = Unsafe.As(ref result6); return flag; } case TypeCode.Int64: { long result5; bool flag = TryParseInt64Enum(enumType, value, ignoreCase, throwOnFailure, out result5); result = Unsafe.As(ref result5); return flag; } case TypeCode.UInt64: { ulong result4; bool flag = TryParseUInt64Enum(enumType, value, ignoreCase, throwOnFailure, out result4); result = Unsafe.As(ref result4); return flag; } default: { object result2; bool flag = TryParseRareEnum(enumType, value, ignoreCase, throwOnFailure, out result2); result = (flag ? ((TEnum)result2) : default(TEnum)); return flag; } } } private static bool TryParseInt32Enum(RuntimeType enumType, ReadOnlySpan value, int minInclusive, int maxInclusive, bool ignoreCase, bool throwOnFailure, TypeCode type, out int result) { Number.ParsingStatus parsingStatus = Number.ParsingStatus.OK; if (StartsNumber(value[0])) { parsingStatus = Number.TryParseInt32IntegerStyle(value, NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture.NumberFormat, out result); if (parsingStatus == Number.ParsingStatus.OK) { if ((uint)(result - minInclusive) <= (uint)(maxInclusive - minInclusive)) { return true; } parsingStatus = Number.ParsingStatus.Overflow; } } ulong result2; if (parsingStatus == Number.ParsingStatus.Overflow) { if (throwOnFailure) { Number.ThrowOverflowException(type); } } else if (TryParseByName(enumType, value, ignoreCase, throwOnFailure, out result2)) { result = (int)result2; return true; } result = 0; return false; } private static bool TryParseUInt32Enum(RuntimeType enumType, ReadOnlySpan value, uint maxInclusive, bool ignoreCase, bool throwOnFailure, TypeCode type, out uint result) { Number.ParsingStatus parsingStatus = Number.ParsingStatus.OK; if (StartsNumber(value[0])) { parsingStatus = Number.TryParseUInt32IntegerStyle(value, NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture.NumberFormat, out result); if (parsingStatus == Number.ParsingStatus.OK) { if (result <= maxInclusive) { return true; } parsingStatus = Number.ParsingStatus.Overflow; } } ulong result2; if (parsingStatus == Number.ParsingStatus.Overflow) { if (throwOnFailure) { Number.ThrowOverflowException(type); } } else if (TryParseByName(enumType, value, ignoreCase, throwOnFailure, out result2)) { result = (uint)result2; return true; } result = 0u; return false; } private static bool TryParseInt64Enum(RuntimeType enumType, ReadOnlySpan value, bool ignoreCase, bool throwOnFailure, out long result) { Number.ParsingStatus parsingStatus = Number.ParsingStatus.OK; if (StartsNumber(value[0])) { parsingStatus = Number.TryParseInt64IntegerStyle(value, NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture.NumberFormat, out result); if (parsingStatus == Number.ParsingStatus.OK) { return true; } } ulong result2; if (parsingStatus == Number.ParsingStatus.Overflow) { if (throwOnFailure) { Number.ThrowOverflowException(TypeCode.Int64); } } else if (TryParseByName(enumType, value, ignoreCase, throwOnFailure, out result2)) { result = (long)result2; return true; } result = 0L; return false; } private static bool TryParseUInt64Enum(RuntimeType enumType, ReadOnlySpan value, bool ignoreCase, bool throwOnFailure, out ulong result) { Number.ParsingStatus parsingStatus = Number.ParsingStatus.OK; if (StartsNumber(value[0])) { parsingStatus = Number.TryParseUInt64IntegerStyle(value, NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture.NumberFormat, out result); if (parsingStatus == Number.ParsingStatus.OK) { return true; } } if (parsingStatus == Number.ParsingStatus.Overflow) { if (throwOnFailure) { Number.ThrowOverflowException(TypeCode.UInt64); } } else if (TryParseByName(enumType, value, ignoreCase, throwOnFailure, out result)) { return true; } result = 0uL; return false; } private static bool TryParseRareEnum(RuntimeType enumType, ReadOnlySpan value, bool ignoreCase, bool throwOnFailure, [NotNullWhen(true)] out object result) { if (StartsNumber(value[0])) { Type underlyingType = GetUnderlyingType(enumType); try { result = ToObject(enumType, Convert.ChangeType(value.ToString(), underlyingType, CultureInfo.InvariantCulture)); return true; } catch (FormatException) { } catch when (!throwOnFailure) { result = null; return false; } } if (TryParseByName(enumType, value, ignoreCase, throwOnFailure, out var result2)) { try { result = ToObject(enumType, result2); return true; } catch when (!throwOnFailure) { } } result = null; return false; } private static bool TryParseByName(RuntimeType enumType, ReadOnlySpan value, bool ignoreCase, bool throwOnFailure, out ulong result) { ReadOnlySpan readOnlySpan = value; EnumInfo enumInfo = GetEnumInfo(enumType); string[] names = enumInfo.Names; ulong[] values = enumInfo.Values; bool flag = true; ulong num = 0uL; while (value.Length > 0) { int num2 = value.IndexOf(','); ReadOnlySpan span; if (num2 == -1) { span = value.Trim(); value = default(ReadOnlySpan); } else { if (num2 == value.Length - 1) { flag = false; break; } span = value.Slice(0, num2).Trim(); value = value.Slice(num2 + 1); } bool flag2 = false; if (ignoreCase) { for (int i = 0; i < names.Length; i++) { if (span.EqualsOrdinalIgnoreCase(names[i])) { num |= values[i]; flag2 = true; break; } } } else { for (int j = 0; j < names.Length; j++) { if (span.EqualsOrdinal(names[j])) { num |= values[j]; flag2 = true; break; } } } if (!flag2) { flag = false; break; } } if (flag) { result = num; return true; } if (throwOnFailure) { throw new ArgumentException(SR.Format(SR.Arg_EnumValueNotFound, readOnlySpan.ToString())); } result = 0uL; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool StartsNumber(char c) { if (!char.IsInRange(c, '0', '9') && c != '-') { return c == '+'; } return true; } public static object ToObject(Type enumType, object value) { if (value == null) { throw new ArgumentNullException("value"); } return Convert.GetTypeCode(value) switch { TypeCode.Int32 => ToObject(enumType, (int)value), TypeCode.SByte => ToObject(enumType, (sbyte)value), TypeCode.Int16 => ToObject(enumType, (short)value), TypeCode.Int64 => ToObject(enumType, (long)value), TypeCode.UInt32 => ToObject(enumType, (uint)value), TypeCode.Byte => ToObject(enumType, (byte)value), TypeCode.UInt16 => ToObject(enumType, (ushort)value), TypeCode.UInt64 => ToObject(enumType, (ulong)value), TypeCode.Char => ToObject(enumType, (char)value), TypeCode.Boolean => ToObject(enumType, (bool)value), _ => throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, "value"), }; } public static string Format(Type enumType, object value, string format) { RuntimeType enumType2 = ValidateRuntimeType(enumType); if (value == null) { throw new ArgumentNullException("value"); } if (format == null) { throw new ArgumentNullException("format"); } Type type = value.GetType(); if (type.IsEnum) { if (!type.IsEquivalentTo(enumType)) { throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, type, enumType)); } if (format.Length != 1) { throw new FormatException(SR.Format_InvalidEnumFormatSpecification); } return ((Enum)value).ToString(format); } Type underlyingType = GetUnderlyingType(enumType); if (type != underlyingType) { throw new ArgumentException(SR.Format(SR.Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType, type, underlyingType)); } if (format.Length == 1) { switch (format[0]) { case 'G': case 'g': return InternalFormat(enumType2, ToUInt64(value)) ?? value.ToString(); case 'D': case 'd': return value.ToString(); case 'X': case 'x': return ValueToHexString(value); case 'F': case 'f': return InternalFlagsFormat(enumType2, ToUInt64(value)) ?? value.ToString(); } } throw new FormatException(SR.Format_InvalidEnumFormatSpecification); } internal object GetValue() { ref byte rawData = ref this.GetRawData(); return InternalGetCorElementType() switch { CorElementType.ELEMENT_TYPE_I1 => Unsafe.As(ref rawData), CorElementType.ELEMENT_TYPE_U1 => rawData, CorElementType.ELEMENT_TYPE_BOOLEAN => Unsafe.As(ref rawData), CorElementType.ELEMENT_TYPE_I2 => Unsafe.As(ref rawData), CorElementType.ELEMENT_TYPE_U2 => Unsafe.As(ref rawData), CorElementType.ELEMENT_TYPE_CHAR => Unsafe.As(ref rawData), CorElementType.ELEMENT_TYPE_I4 => Unsafe.As(ref rawData), CorElementType.ELEMENT_TYPE_U4 => Unsafe.As(ref rawData), CorElementType.ELEMENT_TYPE_R4 => Unsafe.As(ref rawData), CorElementType.ELEMENT_TYPE_I8 => Unsafe.As(ref rawData), CorElementType.ELEMENT_TYPE_U8 => Unsafe.As(ref rawData), CorElementType.ELEMENT_TYPE_R8 => Unsafe.As(ref rawData), CorElementType.ELEMENT_TYPE_I => Unsafe.As(ref rawData), CorElementType.ELEMENT_TYPE_U => Unsafe.As(ref rawData), _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType), }; } private ulong ToUInt64() { ref byte rawData = ref this.GetRawData(); switch (InternalGetCorElementType()) { case CorElementType.ELEMENT_TYPE_I1: return (ulong)Unsafe.As(ref rawData); case CorElementType.ELEMENT_TYPE_U1: return rawData; case CorElementType.ELEMENT_TYPE_BOOLEAN: if (rawData == 0) { return 0uL; } return 1uL; case CorElementType.ELEMENT_TYPE_I2: return (ulong)Unsafe.As(ref rawData); case CorElementType.ELEMENT_TYPE_CHAR: case CorElementType.ELEMENT_TYPE_U2: return Unsafe.As(ref rawData); case CorElementType.ELEMENT_TYPE_I4: return (ulong)Unsafe.As(ref rawData); case CorElementType.ELEMENT_TYPE_U4: case CorElementType.ELEMENT_TYPE_R4: return Unsafe.As(ref rawData); case CorElementType.ELEMENT_TYPE_I8: return (ulong)Unsafe.As(ref rawData); case CorElementType.ELEMENT_TYPE_U8: case CorElementType.ELEMENT_TYPE_R8: return Unsafe.As(ref rawData); case CorElementType.ELEMENT_TYPE_I: return (ulong)(long)Unsafe.As(ref rawData); case CorElementType.ELEMENT_TYPE_U: return (ulong)Unsafe.As(ref rawData); default: throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } } public override int GetHashCode() { ref byte rawData = ref this.GetRawData(); return InternalGetCorElementType() switch { CorElementType.ELEMENT_TYPE_I1 => Unsafe.As(ref rawData).GetHashCode(), CorElementType.ELEMENT_TYPE_U1 => rawData.GetHashCode(), CorElementType.ELEMENT_TYPE_BOOLEAN => Unsafe.As(ref rawData).GetHashCode(), CorElementType.ELEMENT_TYPE_I2 => Unsafe.As(ref rawData).GetHashCode(), CorElementType.ELEMENT_TYPE_U2 => Unsafe.As(ref rawData).GetHashCode(), CorElementType.ELEMENT_TYPE_CHAR => Unsafe.As(ref rawData).GetHashCode(), CorElementType.ELEMENT_TYPE_I4 => Unsafe.As(ref rawData).GetHashCode(), CorElementType.ELEMENT_TYPE_U4 => Unsafe.As(ref rawData).GetHashCode(), CorElementType.ELEMENT_TYPE_R4 => Unsafe.As(ref rawData).GetHashCode(), CorElementType.ELEMENT_TYPE_I8 => Unsafe.As(ref rawData).GetHashCode(), CorElementType.ELEMENT_TYPE_U8 => Unsafe.As(ref rawData).GetHashCode(), CorElementType.ELEMENT_TYPE_R8 => Unsafe.As(ref rawData).GetHashCode(), CorElementType.ELEMENT_TYPE_I => Unsafe.As(ref rawData).GetHashCode(), CorElementType.ELEMENT_TYPE_U => Unsafe.As(ref rawData).GetHashCode(), _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType), }; } public override string ToString() { return InternalFormat((RuntimeType)GetType(), ToUInt64()) ?? ValueToString(); } public int CompareTo(object? target) { if (target == this) { return 0; } if (target == null) { return 1; } if (GetType() != target.GetType()) { throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, target.GetType(), GetType())); } ref byte rawData = ref this.GetRawData(); ref byte rawData2 = ref target.GetRawData(); switch (InternalGetCorElementType()) { case CorElementType.ELEMENT_TYPE_I1: return Unsafe.As(ref rawData).CompareTo(Unsafe.As(ref rawData2)); case CorElementType.ELEMENT_TYPE_BOOLEAN: case CorElementType.ELEMENT_TYPE_U1: return rawData.CompareTo(rawData2); case CorElementType.ELEMENT_TYPE_I2: return Unsafe.As(ref rawData).CompareTo(Unsafe.As(ref rawData2)); case CorElementType.ELEMENT_TYPE_CHAR: case CorElementType.ELEMENT_TYPE_U2: return Unsafe.As(ref rawData).CompareTo(Unsafe.As(ref rawData2)); case CorElementType.ELEMENT_TYPE_I4: case CorElementType.ELEMENT_TYPE_I: return Unsafe.As(ref rawData).CompareTo(Unsafe.As(ref rawData2)); case CorElementType.ELEMENT_TYPE_U4: case CorElementType.ELEMENT_TYPE_U: return Unsafe.As(ref rawData).CompareTo(Unsafe.As(ref rawData2)); case CorElementType.ELEMENT_TYPE_I8: return Unsafe.As(ref rawData).CompareTo(Unsafe.As(ref rawData2)); case CorElementType.ELEMENT_TYPE_U8: return Unsafe.As(ref rawData).CompareTo(Unsafe.As(ref rawData2)); case CorElementType.ELEMENT_TYPE_R4: return Unsafe.As(ref rawData).CompareTo(Unsafe.As(ref rawData2)); case CorElementType.ELEMENT_TYPE_R8: return Unsafe.As(ref rawData).CompareTo(Unsafe.As(ref rawData2)); default: throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } } [Obsolete("The provider argument is not used. Use ToString(String) instead.")] public string ToString(string? format, IFormatProvider? provider) { return ToString(format); } public string ToString(string? format) { if (string.IsNullOrEmpty(format)) { return ToString(); } if (format.Length == 1) { switch (format[0]) { case 'G': case 'g': return ToString(); case 'D': case 'd': return ValueToString(); case 'X': case 'x': return ValueToHexString(); case 'F': case 'f': return InternalFlagsFormat((RuntimeType)GetType(), ToUInt64()) ?? ValueToString(); } } throw new FormatException(SR.Format_InvalidEnumFormatSpecification); } [Obsolete("The provider argument is not used. Use ToString() instead.")] public string ToString(IFormatProvider? provider) { return ToString(); } public TypeCode GetTypeCode() { return InternalGetCorElementType() switch { CorElementType.ELEMENT_TYPE_I1 => TypeCode.SByte, CorElementType.ELEMENT_TYPE_U1 => TypeCode.Byte, CorElementType.ELEMENT_TYPE_BOOLEAN => TypeCode.Boolean, CorElementType.ELEMENT_TYPE_I2 => TypeCode.Int16, CorElementType.ELEMENT_TYPE_U2 => TypeCode.UInt16, CorElementType.ELEMENT_TYPE_CHAR => TypeCode.Char, CorElementType.ELEMENT_TYPE_I4 => TypeCode.Int32, CorElementType.ELEMENT_TYPE_U4 => TypeCode.UInt32, CorElementType.ELEMENT_TYPE_I8 => TypeCode.Int64, CorElementType.ELEMENT_TYPE_U8 => TypeCode.UInt64, _ => throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType), }; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(GetValue()); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(GetValue()); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(GetValue()); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(GetValue()); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(GetValue()); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(GetValue()); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(GetValue()); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(GetValue()); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(GetValue()); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(GetValue()); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(GetValue()); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(GetValue()); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(GetValue()); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Enum", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } [CLSCompliant(false)] public static object ToObject(Type enumType, sbyte value) { return InternalBoxEnum(ValidateRuntimeType(enumType), value); } public static object ToObject(Type enumType, short value) { return InternalBoxEnum(ValidateRuntimeType(enumType), value); } public static object ToObject(Type enumType, int value) { return InternalBoxEnum(ValidateRuntimeType(enumType), value); } public static object ToObject(Type enumType, byte value) { return InternalBoxEnum(ValidateRuntimeType(enumType), value); } [CLSCompliant(false)] public static object ToObject(Type enumType, ushort value) { return InternalBoxEnum(ValidateRuntimeType(enumType), value); } [CLSCompliant(false)] public static object ToObject(Type enumType, uint value) { return InternalBoxEnum(ValidateRuntimeType(enumType), value); } public static object ToObject(Type enumType, long value) { return InternalBoxEnum(ValidateRuntimeType(enumType), value); } [CLSCompliant(false)] public static object ToObject(Type enumType, ulong value) { return InternalBoxEnum(ValidateRuntimeType(enumType), (long)value); } private static object ToObject(Type enumType, char value) { return InternalBoxEnum(ValidateRuntimeType(enumType), value); } private static object ToObject(Type enumType, bool value) { return InternalBoxEnum(ValidateRuntimeType(enumType), value ? 1 : 0); } private static RuntimeType ValidateRuntimeType(Type enumType) { if (enumType == null) { throw new ArgumentNullException("enumType"); } if (!enumType.IsEnum) { throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); } if (!(enumType is RuntimeType result)) { throw new ArgumentException(SR.Arg_MustBeType, "enumType"); } return result; } } public static class Environment { public enum SpecialFolder { ApplicationData = 26, CommonApplicationData = 35, LocalApplicationData = 28, Cookies = 33, Desktop = 0, Favorites = 6, History = 34, InternetCache = 32, Programs = 2, MyComputer = 17, MyMusic = 13, MyPictures = 39, MyVideos = 14, Recent = 8, SendTo = 9, StartMenu = 11, Startup = 7, System = 37, Templates = 21, DesktopDirectory = 16, Personal = 5, MyDocuments = 5, ProgramFiles = 38, CommonProgramFiles = 43, AdminTools = 48, CDBurning = 59, CommonAdminTools = 47, CommonDocuments = 46, CommonMusic = 53, CommonOemLinks = 58, CommonPictures = 54, CommonStartMenu = 22, CommonPrograms = 23, CommonStartup = 24, CommonDesktopDirectory = 25, CommonTemplates = 45, CommonVideos = 55, Fonts = 20, NetworkShortcuts = 19, PrinterShortcuts = 27, UserProfile = 40, CommonProgramFilesX86 = 44, ProgramFilesX86 = 42, Resources = 56, LocalizedResources = 57, SystemX86 = 41, Windows = 36 } public enum SpecialFolderOption { None = 0, Create = 32768, DoNotVerify = 16384 } private static class WindowsVersion { internal static readonly bool IsWindows8OrAbove = GetIsWindows8OrAbove(); private unsafe static bool GetIsWindows8OrAbove() { ulong conditionMask = Interop.Kernel32.VerSetConditionMask(0uL, 2u, 3); conditionMask = Interop.Kernel32.VerSetConditionMask(conditionMask, 1u, 3); conditionMask = Interop.Kernel32.VerSetConditionMask(conditionMask, 32u, 3); conditionMask = Interop.Kernel32.VerSetConditionMask(conditionMask, 16u, 3); Interop.Kernel32.OSVERSIONINFOEX lpVersionInfo = default(Interop.Kernel32.OSVERSIONINFOEX); lpVersionInfo.dwOSVersionInfoSize = sizeof(Interop.Kernel32.OSVERSIONINFOEX); lpVersionInfo.dwMajorVersion = 6; lpVersionInfo.dwMinorVersion = 2; lpVersionInfo.wServicePackMajor = 0; lpVersionInfo.wServicePackMinor = 0; return Interop.Kernel32.VerifyVersionInfoW(ref lpVersionInfo, 51u, conditionMask); } } private static string[] s_commandLineArgs; private static volatile int s_processId; private static volatile string s_processPath; private static volatile OperatingSystem s_osVersion; public static extern int CurrentManagedThreadId { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static extern int ExitCode { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public static extern int TickCount { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static extern long TickCount64 { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static int ProcessorCount { get; } = GetProcessorCount(); internal static bool IsSingleProcessor => ProcessorCount == 1; public static bool HasShutdownStarted => false; public static string CommandLine => PasteArguments.Paste(GetCommandLineArgs(), pasteFirstArgumentUsingArgV0Rules: true); public static string CurrentDirectory { get { return CurrentDirectoryCore; } set { if (value == null) { throw new ArgumentNullException("value"); } if (value.Length == 0) { throw new ArgumentException(SR.Argument_PathEmpty, "value"); } CurrentDirectoryCore = value; } } public static int ProcessId { get { int num = s_processId; if (num == 0) { Interlocked.CompareExchange(ref s_processId, GetProcessId(), 0); num = s_processId; } return num; } } public static string? ProcessPath { get { string text = s_processPath; if (text == null) { Interlocked.CompareExchange(ref s_processPath, GetProcessPath() ?? "", null); text = s_processPath; } if (text.Length == 0) { return null; } return text; } } public static bool Is64BitProcess => IntPtr.Size == 8; public static bool Is64BitOperatingSystem { get { _ = Is64BitProcess; return Is64BitOperatingSystemWhen32BitProcess; } } public static string NewLine => "\r\n"; public static OperatingSystem OSVersion { get { OperatingSystem operatingSystem = s_osVersion; if (operatingSystem == null) { Interlocked.CompareExchange(ref s_osVersion, GetOSVersion(), null); operatingSystem = s_osVersion; } return operatingSystem; } } public static Version Version { get { string text = typeof(object).Assembly.GetCustomAttribute()?.InformationalVersion; ReadOnlySpan readOnlySpan = text.AsSpan(); int num = readOnlySpan.IndexOfAny('-', '+', ' '); if (num != -1) { readOnlySpan = readOnlySpan.Slice(0, num); } if (!System.Version.TryParse(readOnlySpan, out Version result)) { return new Version(); } return result; } } public static string StackTrace { [MethodImpl(MethodImplOptions.NoInlining)] get { return new StackTrace(fNeedFileInfo: true).ToString(System.Diagnostics.StackTrace.TraceFormat.Normal); } } internal static bool IsWindows8OrAbove => WindowsVersion.IsWindows8OrAbove; public static string UserName { get { Span initialBuffer = stackalloc char[40]; ValueStringBuilder builder = new ValueStringBuilder(initialBuffer); GetUserName(ref builder); ReadOnlySpan span = builder.AsSpan(); int num = span.IndexOf('\\'); if (num != -1) { span = span.Slice(num + 1); } string result = span.ToString(); builder.Dispose(); return result; } } public static string UserDomainName { get { Span initialBuffer = stackalloc char[40]; ValueStringBuilder builder = new ValueStringBuilder(initialBuffer); GetUserName(ref builder); ReadOnlySpan span = builder.AsSpan(); int num = span.IndexOf('\\'); if (num != -1) { builder.Length = num; return builder.ToString(); } initialBuffer = stackalloc char[64]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); uint cchReferencedDomainName = (uint)valueStringBuilder.Capacity; Span span2 = stackalloc byte[68]; uint cbSid = 68u; uint peUse; while (!Interop.Advapi32.LookupAccountNameW(null, ref builder.GetPinnableReference(), ref MemoryMarshal.GetReference(span2), ref cbSid, ref valueStringBuilder.GetPinnableReference(), ref cchReferencedDomainName, out peUse)) { int lastPInvokeError = Marshal.GetLastPInvokeError(); if (lastPInvokeError != 122) { throw new InvalidOperationException(Win32Marshal.GetMessage(lastPInvokeError)); } valueStringBuilder.EnsureCapacity((int)cchReferencedDomainName); } builder.Dispose(); valueStringBuilder.Length = (int)cchReferencedDomainName; return valueStringBuilder.ToString(); } } private static string CurrentDirectoryCore { get { Span initialBuffer = stackalloc char[260]; ValueStringBuilder outputBuilder = new ValueStringBuilder(initialBuffer); uint currentDirectory; while ((currentDirectory = Interop.Kernel32.GetCurrentDirectory((uint)outputBuilder.Capacity, ref outputBuilder.GetPinnableReference())) > outputBuilder.Capacity) { outputBuilder.EnsureCapacity((int)currentDirectory); } if (currentDirectory == 0) { throw Win32Marshal.GetExceptionForLastWin32Error(); } outputBuilder.Length = (int)currentDirectory; if (outputBuilder.AsSpan().Contains('~')) { string result = PathHelper.TryExpandShortFileName(ref outputBuilder, null); outputBuilder.Dispose(); return result; } return outputBuilder.ToString(); } set { if (!Interop.Kernel32.SetCurrentDirectory(value)) { int lastPInvokeError = Marshal.GetLastPInvokeError(); throw Win32Marshal.GetExceptionForWin32Error((lastPInvokeError == 2) ? 3 : lastPInvokeError, value); } } } public static int SystemPageSize { get { Interop.Kernel32.GetSystemInfo(out var lpSystemInfo); return lpSystemInfo.dwPageSize; } } private static bool Is64BitOperatingSystemWhen32BitProcess { get { bool Wow64Process; return Interop.Kernel32.IsWow64Process(Interop.Kernel32.GetCurrentProcess(), out Wow64Process) && Wow64Process; } } public static string MachineName => Interop.Kernel32.GetComputerName() ?? throw new InvalidOperationException(SR.InvalidOperation_ComputerName); public static string SystemDirectory { get { Span initialBuffer = stackalloc char[32]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); uint systemDirectoryW; while ((systemDirectoryW = Interop.Kernel32.GetSystemDirectoryW(ref valueStringBuilder.GetPinnableReference(), (uint)valueStringBuilder.Capacity)) > valueStringBuilder.Capacity) { valueStringBuilder.EnsureCapacity((int)systemDirectoryW); } if (systemDirectoryW == 0) { throw Win32Marshal.GetExceptionForLastWin32Error(); } valueStringBuilder.Length = (int)systemDirectoryW; return valueStringBuilder.ToString(); } } public unsafe static bool UserInteractive { get { IntPtr processWindowStation = Interop.User32.GetProcessWindowStation(); if (processWindowStation != IntPtr.Zero) { Interop.User32.USEROBJECTFLAGS uSEROBJECTFLAGS = default(Interop.User32.USEROBJECTFLAGS); uint lpnLengthNeeded = 0u; if (Interop.User32.GetUserObjectInformationW(processWindowStation, 1, &uSEROBJECTFLAGS, (uint)sizeof(Interop.User32.USEROBJECTFLAGS), ref lpnLengthNeeded)) { return (uSEROBJECTFLAGS.dwFlags & 1) != 0; } } return true; } } public unsafe static long WorkingSet { get { Interop.Kernel32.PROCESS_MEMORY_COUNTERS ppsmemCounters = default(Interop.Kernel32.PROCESS_MEMORY_COUNTERS); ppsmemCounters.cb = (uint)sizeof(Interop.Kernel32.PROCESS_MEMORY_COUNTERS); if (!Interop.Kernel32.GetProcessMemoryInfo(Interop.Kernel32.GetCurrentProcess(), ref ppsmemCounters, ppsmemCounters.cb)) { return 0L; } return (long)(ulong)ppsmemCounters.WorkingSetSize; } } [DllImport("QCall", CharSet = CharSet.Unicode)] [DoesNotReturn] private static extern void _Exit(int exitCode); [DoesNotReturn] public static void Exit(int exitCode) { _Exit(exitCode); } [MethodImpl(MethodImplOptions.InternalCall)] [DoesNotReturn] public static extern void FailFast(string? message); [MethodImpl(MethodImplOptions.InternalCall)] [DoesNotReturn] public static extern void FailFast(string? message, Exception? exception); [MethodImpl(MethodImplOptions.InternalCall)] [DoesNotReturn] public static extern void FailFast(string? message, Exception? exception, string? errorMessage); [MethodImpl(MethodImplOptions.InternalCall)] private static extern string[] GetCommandLineArgsNative(); public static string[] GetCommandLineArgs() { if (s_commandLineArgs == null) { return GetCommandLineArgsNative(); } return (string[])s_commandLineArgs.Clone(); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern int GetProcessorCount(); internal static string GetResourceStringLocal(string key) { return SR.GetResourceString(key); } public static string? GetEnvironmentVariable(string variable) { if (variable == null) { throw new ArgumentNullException("variable"); } return GetEnvironmentVariableCore(variable); } public static string? GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) { return GetEnvironmentVariable(variable); } if (variable == null) { throw new ArgumentNullException("variable"); } bool fromMachine = ValidateAndConvertRegistryTarget(target); return GetEnvironmentVariableFromRegistry(variable, fromMachine); } public static IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) { return GetEnvironmentVariables(); } bool fromMachine = ValidateAndConvertRegistryTarget(target); return GetEnvironmentVariablesFromRegistry(fromMachine); } public static void SetEnvironmentVariable(string variable, string? value) { ValidateVariableAndValue(variable, ref value); SetEnvironmentVariableCore(variable, value); } public static void SetEnvironmentVariable(string variable, string? value, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) { SetEnvironmentVariable(variable, value); return; } ValidateVariableAndValue(variable, ref value); bool fromMachine = ValidateAndConvertRegistryTarget(target); SetEnvironmentVariableFromRegistry(variable, value, fromMachine); } public static string ExpandEnvironmentVariables(string name) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { return name; } return ExpandEnvironmentVariablesCore(name); } internal static void SetCommandLineArgs(string[] cmdLineArgs) { s_commandLineArgs = cmdLineArgs; } public static string GetFolderPath(SpecialFolder folder) { return GetFolderPath(folder, SpecialFolderOption.None); } public static string GetFolderPath(SpecialFolder folder, SpecialFolderOption option) { if (!Enum.IsDefined(typeof(SpecialFolder), folder)) { throw new ArgumentOutOfRangeException("folder", folder, SR.Format(SR.Arg_EnumIllegalVal, folder)); } if (option != 0 && !Enum.IsDefined(typeof(SpecialFolderOption), option)) { throw new ArgumentOutOfRangeException("option", option, SR.Format(SR.Arg_EnumIllegalVal, option)); } return GetFolderPathCore(folder, option); } private static bool ValidateAndConvertRegistryTarget(EnvironmentVariableTarget target) { return target switch { EnvironmentVariableTarget.Machine => true, EnvironmentVariableTarget.User => false, _ => throw new ArgumentOutOfRangeException("target", target, SR.Format(SR.Arg_EnumIllegalVal, target)), }; } private static void ValidateVariableAndValue(string variable, ref string value) { if (variable == null) { throw new ArgumentNullException("variable"); } if (variable.Length == 0) { throw new ArgumentException(SR.Argument_StringZeroLength, "variable"); } if (variable[0] == '\0') { throw new ArgumentException(SR.Argument_StringFirstCharIsZero, "variable"); } if (variable.Contains('=')) { throw new ArgumentException(SR.Argument_IllegalEnvVarName, "variable"); } if (string.IsNullOrEmpty(value) || value[0] == '\0') { value = null; } } private static string GetEnvironmentVariableFromRegistry(string variable, bool fromMachine) { using RegistryKey registryKey = OpenEnvironmentKeyIfExists(fromMachine, writable: false); return registryKey?.GetValue(variable) as string; } private unsafe static void SetEnvironmentVariableFromRegistry(string variable, string value, bool fromMachine) { if (!fromMachine && variable.Length >= 255) { throw new ArgumentException(SR.Argument_LongEnvVarValue, "variable"); } using (RegistryKey registryKey = OpenEnvironmentKeyIfExists(fromMachine, writable: true)) { if (registryKey != null) { if (value == null) { registryKey.DeleteValue(variable, throwOnMissingValue: false); } else { registryKey.SetValue(variable, value); } } } fixed (char* ptr = &"Environment".GetPinnableReference()) { IntPtr pdwResult; IntPtr intPtr = Interop.User32.SendMessageTimeout(new IntPtr(65535), 26, IntPtr.Zero, (IntPtr)ptr, 0, 1000, out pdwResult); } } private static IDictionary GetEnvironmentVariablesFromRegistry(bool fromMachine) { Hashtable hashtable = new Hashtable(); using (RegistryKey registryKey = OpenEnvironmentKeyIfExists(fromMachine, writable: false)) { if (registryKey != null) { string[] valueNames = registryKey.GetValueNames(); foreach (string text in valueNames) { string value = registryKey.GetValue(text, "").ToString(); try { hashtable.Add(text, value); } catch (ArgumentException) { } } } } return hashtable; } private static RegistryKey OpenEnvironmentKeyIfExists(bool fromMachine, bool writable) { RegistryKey registryKey; string name; if (fromMachine) { registryKey = Registry.LocalMachine; name = "System\\CurrentControlSet\\Control\\Session Manager\\Environment"; } else { registryKey = Registry.CurrentUser; name = "Environment"; } return registryKey.OpenSubKey(name, writable); } private static void GetUserName(ref ValueStringBuilder builder) { uint lpnSize = 0u; while (Interop.Secur32.GetUserNameExW(2, ref builder.GetPinnableReference(), ref lpnSize) == Interop.BOOLEAN.FALSE) { if (Marshal.GetLastPInvokeError() == 234) { builder.EnsureCapacity(checked((int)lpnSize)); continue; } builder.Length = 0; return; } builder.Length = (int)lpnSize; } private static string GetFolderPathCore(SpecialFolder folder, SpecialFolderOption option) { string folderGuid; switch (folder) { case SpecialFolder.ApplicationData: folderGuid = "{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}"; break; case SpecialFolder.CommonApplicationData: folderGuid = "{62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}"; break; case SpecialFolder.LocalApplicationData: folderGuid = "{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}"; break; case SpecialFolder.Cookies: folderGuid = "{2B0F765D-C0E9-4171-908E-08A611B84FF6}"; break; case SpecialFolder.Desktop: folderGuid = "{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}"; break; case SpecialFolder.Favorites: folderGuid = "{1777F761-68AD-4D8A-87BD-30B759FA33DD}"; break; case SpecialFolder.History: folderGuid = "{D9DC8A3B-B784-432E-A781-5A1130A75963}"; break; case SpecialFolder.InternetCache: folderGuid = "{352481E8-33BE-4251-BA85-6007CAEDCF9D}"; break; case SpecialFolder.Programs: folderGuid = "{A77F5D77-2E2B-44C3-A6A2-ABA601054A51}"; break; case SpecialFolder.MyComputer: folderGuid = "{0AC0837C-BBF8-452A-850D-79D08E667CA7}"; break; case SpecialFolder.MyMusic: folderGuid = "{4BD8D571-6D19-48D3-BE97-422220080E43}"; break; case SpecialFolder.MyPictures: folderGuid = "{33E28130-4E1E-4676-835A-98395C3BC3BB}"; break; case SpecialFolder.MyVideos: folderGuid = "{18989B1D-99B5-455B-841C-AB7C74E4DDFC}"; break; case SpecialFolder.Recent: folderGuid = "{AE50C081-EBD2-438A-8655-8A092E34987A}"; break; case SpecialFolder.SendTo: folderGuid = "{8983036C-27C0-404B-8F08-102D10DCFD74}"; break; case SpecialFolder.StartMenu: folderGuid = "{625B53C3-AB48-4EC1-BA1F-A1EF4146FC19}"; break; case SpecialFolder.Startup: folderGuid = "{B97D20BB-F46A-4C97-BA10-5E3608430854}"; break; case SpecialFolder.System: folderGuid = "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}"; break; case SpecialFolder.Templates: folderGuid = "{A63293E8-664E-48DB-A079-DF759E0509F7}"; break; case SpecialFolder.DesktopDirectory: folderGuid = "{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}"; break; case SpecialFolder.Personal: folderGuid = "{FDD39AD0-238F-46AF-ADB4-6C85480369C7}"; break; case SpecialFolder.ProgramFiles: folderGuid = "{905e63b6-c1bf-494e-b29c-65b732d3d21a}"; break; case SpecialFolder.CommonProgramFiles: folderGuid = "{F7F1ED05-9F6D-47A2-AAAE-29D317C6F066}"; break; case SpecialFolder.AdminTools: folderGuid = "{724EF170-A42D-4FEF-9F26-B60E846FBA4F}"; break; case SpecialFolder.CDBurning: folderGuid = "{9E52AB10-F80D-49DF-ACB8-4330F5687855}"; break; case SpecialFolder.CommonAdminTools: folderGuid = "{D0384E7D-BAC3-4797-8F14-CBA229B392B5}"; break; case SpecialFolder.CommonDocuments: folderGuid = "{ED4824AF-DCE4-45A8-81E2-FC7965083634}"; break; case SpecialFolder.CommonMusic: folderGuid = "{3214FAB5-9757-4298-BB61-92A9DEAA44FF}"; break; case SpecialFolder.CommonOemLinks: folderGuid = "{C1BAE2D0-10DF-4334-BEDD-7AA20B227A9D}"; break; case SpecialFolder.CommonPictures: folderGuid = "{B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5}"; break; case SpecialFolder.CommonStartMenu: folderGuid = "{A4115719-D62E-491D-AA7C-E74B8BE3B067}"; break; case SpecialFolder.CommonPrograms: folderGuid = "{0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8}"; break; case SpecialFolder.CommonStartup: folderGuid = "{82A5EA35-D9CD-47C5-9629-E15D2F714E6E}"; break; case SpecialFolder.CommonDesktopDirectory: folderGuid = "{C4AA340D-F20F-4863-AFEF-F87EF2E6BA25}"; break; case SpecialFolder.CommonTemplates: folderGuid = "{B94237E7-57AC-4347-9151-B08C6C32D1F7}"; break; case SpecialFolder.CommonVideos: folderGuid = "{2400183A-6185-49FB-A2D8-4A392A602BA3}"; break; case SpecialFolder.Fonts: folderGuid = "{FD228CB7-AE11-4AE3-864C-16F3910AB8FE}"; break; case SpecialFolder.NetworkShortcuts: folderGuid = "{C5ABBF53-E17F-4121-8900-86626FC2C973}"; break; case SpecialFolder.PrinterShortcuts: folderGuid = "{76FC4E2D-D6AD-4519-A663-37BD56068185}"; break; case SpecialFolder.UserProfile: folderGuid = "{5E6C858F-0E22-4760-9AFE-EA3317B67173}"; break; case SpecialFolder.CommonProgramFilesX86: folderGuid = "{DE974D24-D9C6-4D3E-BF91-F4455120B917}"; break; case SpecialFolder.ProgramFilesX86: folderGuid = "{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}"; break; case SpecialFolder.Resources: folderGuid = "{8AD10C31-2ADB-4296-A8F7-E4701232C972}"; break; case SpecialFolder.LocalizedResources: folderGuid = "{2A00375E-224C-49DE-B8D1-440DF7EF3DDC}"; break; case SpecialFolder.SystemX86: folderGuid = "{D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27}"; break; case SpecialFolder.Windows: folderGuid = "{F38BF404-1D43-42F2-9305-67DE0B28FC23}"; break; default: return string.Empty; } return GetKnownFolderPath(folderGuid, option); } private static string GetKnownFolderPath(string folderGuid, SpecialFolderOption option) { Guid rfid = new Guid(folderGuid); if (Interop.Shell32.SHGetKnownFolderPath(rfid, (uint)option, IntPtr.Zero, out var ppszPath) != 0) { return string.Empty; } return ppszPath; } public static string[] GetLogicalDrives() { return DriveInfoInternal.GetLogicalDrives(); } private static string ExpandEnvironmentVariablesCore(string name) { Span initialBuffer = stackalloc char[128]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); uint num; while ((num = Interop.Kernel32.ExpandEnvironmentStrings(name, ref valueStringBuilder.GetPinnableReference(), (uint)valueStringBuilder.Capacity)) > valueStringBuilder.Capacity) { valueStringBuilder.EnsureCapacity((int)num); } if (num == 0) { throw Win32Marshal.GetExceptionForLastWin32Error(); } valueStringBuilder.Length = (int)(num - 1); return valueStringBuilder.ToString(); } [MethodImpl(MethodImplOptions.NoInlining)] private static int GetProcessId() { return (int)Interop.Kernel32.GetCurrentProcessId(); } private static string GetProcessPath() { Span initialBuffer = stackalloc char[260]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); uint moduleFileName; while ((moduleFileName = Interop.Kernel32.GetModuleFileName(IntPtr.Zero, ref valueStringBuilder.GetPinnableReference(), (uint)valueStringBuilder.Capacity)) >= valueStringBuilder.Capacity) { valueStringBuilder.EnsureCapacity((int)moduleFileName); } if (moduleFileName == 0) { throw Win32Marshal.GetExceptionForLastWin32Error(); } valueStringBuilder.Length = (int)moduleFileName; return valueStringBuilder.ToString(); } private unsafe static OperatingSystem GetOSVersion() { if (Interop.NtDll.RtlGetVersionEx(out var osvi) != 0) { throw new InvalidOperationException(SR.InvalidOperation_GetVersion); } Version version = new Version((int)osvi.dwMajorVersion, (int)osvi.dwMinorVersion, (int)osvi.dwBuildNumber, 0); if (osvi.szCSDVersion[0] == '\0') { return new OperatingSystem(PlatformID.Win32NT, version); } return new OperatingSystem(PlatformID.Win32NT, version, new string(osvi.szCSDVersion)); } private static string GetEnvironmentVariableCore(string variable) { Span initialBuffer = stackalloc char[128]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); uint environmentVariable; while ((environmentVariable = Interop.Kernel32.GetEnvironmentVariable(variable, ref valueStringBuilder.GetPinnableReference(), (uint)valueStringBuilder.Capacity)) > valueStringBuilder.Capacity) { valueStringBuilder.EnsureCapacity((int)environmentVariable); } if (environmentVariable == 0 && Marshal.GetLastPInvokeError() == 203) { valueStringBuilder.Dispose(); return null; } valueStringBuilder.Length = (int)environmentVariable; return valueStringBuilder.ToString(); } private static void SetEnvironmentVariableCore(string variable, string value) { if (!Interop.Kernel32.SetEnvironmentVariable(variable, value)) { int lastPInvokeError = Marshal.GetLastPInvokeError(); switch (lastPInvokeError) { case 203: break; case 206: throw new ArgumentException(SR.Argument_LongEnvVarValue); case 8: case 1450: throw new OutOfMemoryException(Interop.Kernel32.GetMessage(lastPInvokeError)); default: throw new ArgumentException(Interop.Kernel32.GetMessage(lastPInvokeError)); } } } public unsafe static IDictionary GetEnvironmentVariables() { char* environmentStringsW = Interop.Kernel32.GetEnvironmentStringsW(); if (environmentStringsW == null) { throw new OutOfMemoryException(); } try { Hashtable hashtable = new Hashtable(); char* ptr = environmentStringsW; while (true) { ReadOnlySpan span = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(ptr); if (span.IsEmpty) { break; } int num = span.IndexOf('='); if (num > 0) { string key = new string(span.Slice(0, num)); string value = new string(span.Slice(num + 1)); try { hashtable.Add(key, value); } catch (ArgumentException) { } } ptr += span.Length + 1; } return hashtable; } finally { Interop.BOOL bOOL = Interop.Kernel32.FreeEnvironmentStringsW(environmentStringsW); } } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Exception : ISerializable { internal enum ExceptionMessageKind { ThreadAbort = 1, ThreadInterrupted, OutOfMemory } internal readonly struct DispatchState { public readonly byte[] StackTrace; public readonly object[] DynamicMethods; public readonly string RemoteStackTrace; public readonly UIntPtr IpForWatsonBuckets; public readonly byte[] WatsonBuckets; public DispatchState(byte[] stackTrace, object[] dynamicMethods, string remoteStackTrace, UIntPtr ipForWatsonBuckets, byte[] watsonBuckets) { StackTrace = stackTrace; DynamicMethods = dynamicMethods; RemoteStackTrace = remoteStackTrace; IpForWatsonBuckets = ipForWatsonBuckets; WatsonBuckets = watsonBuckets; } } private MethodBase _exceptionMethod; internal string _message; private IDictionary _data; private readonly Exception _innerException; private string _helpURL; private byte[] _stackTrace; private byte[] _watsonBuckets; private string _stackTraceString; private string _remoteStackTraceString; private readonly object[] _dynamicMethods; private string _source; private UIntPtr _ipForWatsonBuckets; private readonly IntPtr _xptrs; private readonly int _xcode = -532462766; private int _HResult; private const int _COMPlusExceptionCode = -532462766; private protected const string InnerExceptionPrefix = " ---> "; public MethodBase? TargetSite { get { if (_exceptionMethod != null) { return _exceptionMethod; } if (_stackTrace == null) { return null; } _exceptionMethod = GetExceptionMethodFromStackTrace(); return _exceptionMethod; } } private bool HasBeenThrown => _stackTrace != null; private object? SerializationWatsonBuckets => _watsonBuckets; public virtual string Message => _message ?? SR.Format(SR.Exception_WasThrown, GetClassName()); public virtual IDictionary Data => _data ?? (_data = CreateDataContainer()); public Exception? InnerException => _innerException; public virtual string? HelpLink { get { return _helpURL; } set { _helpURL = value; } } public virtual string? Source { get { return _source ?? (_source = CreateSourceName()); } set { _source = value; } } public int HResult { get { return _HResult; } set { _HResult = value; } } public virtual string? StackTrace { get { string stackTraceString = _stackTraceString; string remoteStackTraceString = _remoteStackTraceString; if (stackTraceString != null) { return remoteStackTraceString + stackTraceString; } if (!HasBeenThrown) { return remoteStackTraceString; } return remoteStackTraceString + GetStackTrace(); } } private string? SerializationStackTraceString { get { string text = _stackTraceString; if (text == null && HasBeenThrown) { text = GetStackTrace(); } return text; } } [Obsolete("BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.", DiagnosticId = "SYSLIB0011", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] protected event EventHandler? SerializeObjectState { add { throw new PlatformNotSupportedException(SR.PlatformNotSupported_SecureBinarySerialization); } remove { throw new PlatformNotSupportedException(SR.PlatformNotSupported_SecureBinarySerialization); } } private IDictionary CreateDataContainer() { if (IsImmutableAgileException(this)) { return new EmptyReadOnlyDictionaryInternal(); } return new ListDictionaryInternal(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsImmutableAgileException(Exception e); [MethodImpl(MethodImplOptions.InternalCall)] private static extern IRuntimeMethodInfo GetMethodFromStackTrace(object stackTrace); private MethodBase GetExceptionMethodFromStackTrace() { IRuntimeMethodInfo methodFromStackTrace = GetMethodFromStackTrace(_stackTrace); if (methodFromStackTrace == null) { return null; } return RuntimeType.GetMethodBase(methodFromStackTrace); } private string CreateSourceName() { StackTrace stackTrace = new StackTrace(this, fNeedFileInfo: false); if (stackTrace.FrameCount > 0) { StackFrame frame = stackTrace.GetFrame(0); MethodBase method = frame.GetMethod(); Module module = method.Module; RuntimeModule runtimeModule = module as RuntimeModule; if ((object)runtimeModule == null) { if (!(module is ModuleBuilder moduleBuilder)) { throw new ArgumentException(SR.Argument_MustBeRuntimeReflectionObject); } runtimeModule = moduleBuilder.InternalModule; } return runtimeModule.GetRuntimeAssembly().GetSimpleName(); } return null; } [OnDeserialized] private void OnDeserialized(StreamingContext context) { _stackTrace = null; _ipForWatsonBuckets = UIntPtr.Zero; } internal void InternalPreserveStackTrace() { _ = Source; string stackTrace = StackTrace; if (!string.IsNullOrEmpty(stackTrace)) { _remoteStackTraceString = stackTrace + "\r\n"; } _stackTrace = null; _stackTraceString = null; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void PrepareForForeignExceptionRaise(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetStackTracesDeepCopy(Exception exception, out byte[] currentStackTrace, out object[] dynamicMethodArray); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void SaveStackTracesFromDeepCopy(Exception exception, byte[] currentStackTrace, object[] dynamicMethodArray); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern uint GetExceptionCount(); internal void RestoreDispatchState(in DispatchState dispatchState) { if (!IsImmutableAgileException(this)) { byte[] currentStackTrace = (byte[])dispatchState.StackTrace?.Clone(); object[] dynamicMethodArray = (object[])dispatchState.DynamicMethods?.Clone(); _watsonBuckets = dispatchState.WatsonBuckets; _ipForWatsonBuckets = dispatchState.IpForWatsonBuckets; _remoteStackTraceString = dispatchState.RemoteStackTrace; SaveStackTracesFromDeepCopy(this, currentStackTrace, dynamicMethodArray); _stackTraceString = null; PrepareForForeignExceptionRaise(); } } internal static string GetMessageFromNativeResources(ExceptionMessageKind kind) { string s = null; GetMessageFromNativeResources(kind, new StringHandleOnStack(ref s)); return s; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetMessageFromNativeResources(ExceptionMessageKind kind, StringHandleOnStack retMesg); internal DispatchState CaptureDispatchState() { GetStackTracesDeepCopy(this, out var currentStackTrace, out var dynamicMethodArray); return new DispatchState(currentStackTrace, dynamicMethodArray, _remoteStackTraceString, _ipForWatsonBuckets, _watsonBuckets); } private bool CanSetRemoteStackTrace() { if (IsImmutableAgileException(this)) { return false; } if (_stackTrace != null || _stackTraceString != null || _remoteStackTraceString != null) { ThrowHelper.ThrowInvalidOperationException(); } return true; } public Exception() { _HResult = -2146233088; } public Exception(string? message) : this() { _message = message; } public Exception(string? message, Exception? innerException) : this() { _message = message; _innerException = innerException; } protected Exception(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } _message = info.GetString("Message"); _data = (IDictionary)info.GetValueNoThrow("Data", typeof(IDictionary)); _innerException = (Exception)info.GetValue("InnerException", typeof(Exception)); _helpURL = info.GetString("HelpURL"); _stackTraceString = info.GetString("StackTraceString"); _remoteStackTraceString = info.GetString("RemoteStackTraceString"); _HResult = info.GetInt32("HResult"); _source = info.GetString("Source"); RestoreRemoteStackTrace(info, context); } private string GetClassName() { return GetType().ToString(); } public virtual Exception GetBaseException() { Exception innerException = InnerException; Exception result = this; while (innerException != null) { result = innerException; innerException = innerException.InnerException; } return result; } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } if (_source == null) { _source = Source; } info.AddValue("ClassName", GetClassName(), typeof(string)); info.AddValue("Message", _message, typeof(string)); info.AddValue("Data", _data, typeof(IDictionary)); info.AddValue("InnerException", _innerException, typeof(Exception)); info.AddValue("HelpURL", _helpURL, typeof(string)); info.AddValue("StackTraceString", SerializationStackTraceString, typeof(string)); info.AddValue("RemoteStackTraceString", _remoteStackTraceString, typeof(string)); info.AddValue("RemoteStackIndex", 0, typeof(int)); info.AddValue("ExceptionMethod", null, typeof(string)); info.AddValue("HResult", _HResult); info.AddValue("Source", _source, typeof(string)); info.AddValue("WatsonBuckets", SerializationWatsonBuckets, typeof(byte[])); } public override string ToString() { string className = GetClassName(); string message = Message; string text = _innerException?.ToString() ?? ""; string exception_EndOfInnerExceptionStack = SR.Exception_EndOfInnerExceptionStack; string stackTrace = StackTrace; int num = className.Length; checked { if (!string.IsNullOrEmpty(message)) { num += 2 + message.Length; } if (_innerException != null) { num += "\r\n".Length + " ---> ".Length + text.Length + "\r\n".Length + 3 + exception_EndOfInnerExceptionStack.Length; } if (stackTrace != null) { num += "\r\n".Length + stackTrace.Length; } string text2 = string.FastAllocateString(num); Span dest2 = new Span(ref text2.GetRawStringData(), text2.Length); Write(className, ref dest2); if (!string.IsNullOrEmpty(message)) { Write(": ", ref dest2); Write(message, ref dest2); } if (_innerException != null) { Write("\r\n", ref dest2); Write(" ---> ", ref dest2); Write(text, ref dest2); Write("\r\n", ref dest2); Write(" ", ref dest2); Write(exception_EndOfInnerExceptionStack, ref dest2); } if (stackTrace != null) { Write("\r\n", ref dest2); Write(stackTrace, ref dest2); } return text2; } static void Write(string source, ref Span dest) { source.CopyTo(dest); dest = dest.Slice(source.Length); } } public new Type GetType() { return base.GetType(); } private void RestoreRemoteStackTrace(SerializationInfo info, StreamingContext context) { _watsonBuckets = (byte[])info.GetValueNoThrow("WatsonBuckets", typeof(byte[])); if (context.State == StreamingContextStates.CrossAppDomain) { _remoteStackTraceString += _stackTraceString; _stackTraceString = null; } } private string GetStackTrace() { return new StackTrace(this, fNeedFileInfo: true).ToString(System.Diagnostics.StackTrace.TraceFormat.Normal); } [StackTraceHidden] internal void SetCurrentStackTrace() { if (CanSetRemoteStackTrace()) { StringBuilder stringBuilder = new StringBuilder(256); new StackTrace(fNeedFileInfo: true).ToString(System.Diagnostics.StackTrace.TraceFormat.TrailingNewLine, stringBuilder); stringBuilder.AppendLine(SR.Exception_EndStackTraceFromPreviousThrow); _remoteStackTraceString = stringBuilder.ToString(); } } internal void SetRemoteStackTrace(string stackTrace) { if (CanSetRemoteStackTrace()) { _remoteStackTraceString = stackTrace + "\r\n" + SR.Exception_EndStackTraceFromPreviousThrow + "\r\n"; } } } public enum GCCollectionMode { Default, Forced, Optimized } public enum GCNotificationStatus { Succeeded, Failed, Canceled, Timeout, NotApplicable } public static class GC { internal enum GC_ALLOC_FLAGS { GC_ALLOC_NO_FLAGS = 0, GC_ALLOC_ZEROING_OPTIONAL = 0x10, GC_ALLOC_PINNED_OBJECT_HEAP = 0x40 } private enum StartNoGCRegionStatus { Succeeded, NotEnoughMemory, AmountTooLarge, AlreadyInProgress } private enum EndNoGCRegionStatus { Succeeded, NotInProgress, GCInduced, AllocationExceeded } public static int MaxGeneration => GetMaxGeneration(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetMemoryInfo(GCMemoryInfoData data, int kind); public static GCMemoryInfo GetGCMemoryInfo() { return GetGCMemoryInfo(GCKind.Any); } public static GCMemoryInfo GetGCMemoryInfo(GCKind kind) { if (kind < GCKind.Any || kind > GCKind.Background) { throw new ArgumentOutOfRangeException("kind", SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, GCKind.Any, GCKind.Background)); } GCMemoryInfoData data = new GCMemoryInfoData(); GetMemoryInfo(data, (int)kind); return new GCMemoryInfo(data); } [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern int _StartNoGCRegion(long totalSize, bool lohSizeKnown, long lohSize, bool disallowFullBlockingGC); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern int _EndNoGCRegion(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Array AllocateNewArray(IntPtr typeHandle, int length, GC_ALLOC_FLAGS flags); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetGenerationWR(IntPtr handle); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern long GetTotalMemory(); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void _Collect(int generation, int mode); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetMaxGeneration(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int _CollectionCount(int generation, int getSpecialGCCount); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern ulong GetSegmentSize(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetLastGCPercentTimeInGC(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern ulong GetGenerationSize(int gen); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void _AddMemoryPressure(ulong bytesAllocated); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void _RemoveMemoryPressure(ulong bytesAllocated); public static void AddMemoryPressure(long bytesAllocated) { if (bytesAllocated <= 0) { throw new ArgumentOutOfRangeException("bytesAllocated", SR.ArgumentOutOfRange_NeedPosNum); } _ = 4; _ = IntPtr.Size; if (bytesAllocated > int.MaxValue) { throw new ArgumentOutOfRangeException("bytesAllocated", SR.ArgumentOutOfRange_MustBeNonNegInt32); } _AddMemoryPressure((ulong)bytesAllocated); } public static void RemoveMemoryPressure(long bytesAllocated) { if (bytesAllocated <= 0) { throw new ArgumentOutOfRangeException("bytesAllocated", SR.ArgumentOutOfRange_NeedPosNum); } _ = 4; _ = IntPtr.Size; if (bytesAllocated > int.MaxValue) { throw new ArgumentOutOfRangeException("bytesAllocated", SR.ArgumentOutOfRange_MustBeNonNegInt32); } _RemoveMemoryPressure((ulong)bytesAllocated); } [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetGeneration(object obj); public static void Collect(int generation) { Collect(generation, GCCollectionMode.Default); } public static void Collect() { _Collect(-1, 2); } public static void Collect(int generation, GCCollectionMode mode) { Collect(generation, mode, blocking: true); } public static void Collect(int generation, GCCollectionMode mode, bool blocking) { Collect(generation, mode, blocking, compacting: false); } public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting) { if (generation < 0) { throw new ArgumentOutOfRangeException("generation", SR.ArgumentOutOfRange_GenericPositive); } if (mode < GCCollectionMode.Default || mode > GCCollectionMode.Optimized) { throw new ArgumentOutOfRangeException("mode", SR.ArgumentOutOfRange_Enum); } int num = 0; if (mode == GCCollectionMode.Optimized) { num |= 4; } if (compacting) { num |= 8; } if (blocking) { num |= 2; } else if (!compacting) { num |= 1; } _Collect(generation, num); } public static int CollectionCount(int generation) { if (generation < 0) { throw new ArgumentOutOfRangeException("generation", SR.ArgumentOutOfRange_GenericPositive); } return _CollectionCount(generation, 0); } [MethodImpl(MethodImplOptions.NoInlining)] [Intrinsic] public static void KeepAlive(object? obj) { } public static int GetGeneration(WeakReference wo) { int generationWR = GetGenerationWR(wo.m_handle); KeepAlive(wo); return generationWR; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void _WaitForPendingFinalizers(); public static void WaitForPendingFinalizers() { _WaitForPendingFinalizers(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _SuppressFinalize(object o); public static void SuppressFinalize(object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } _SuppressFinalize(obj); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _ReRegisterForFinalize(object o); public static void ReRegisterForFinalize(object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } _ReRegisterForFinalize(obj); } public static long GetTotalMemory(bool forceFullCollection) { long totalMemory = GetTotalMemory(); if (!forceFullCollection) { return totalMemory; } int num = 20; long num2 = totalMemory; float num3; do { WaitForPendingFinalizers(); Collect(); totalMemory = num2; num2 = GetTotalMemory(); num3 = (float)(num2 - totalMemory) / (float)totalMemory; } while (num-- > 0 && (!(-0.05 < (double)num3) || !((double)num3 < 0.05))); return num2; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern IntPtr _RegisterFrozenSegment(IntPtr sectionAddress, nint sectionSize); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void _UnregisterFrozenSegment(IntPtr segmentHandle); [MethodImpl(MethodImplOptions.InternalCall)] public static extern long GetAllocatedBytesForCurrentThread(); [MethodImpl(MethodImplOptions.InternalCall)] public static extern long GetTotalAllocatedBytes(bool precise = false); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool _RegisterForFullGCNotification(int maxGenerationPercentage, int largeObjectHeapPercentage); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool _CancelFullGCNotification(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int _WaitForFullGCApproach(int millisecondsTimeout); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int _WaitForFullGCComplete(int millisecondsTimeout); public static void RegisterForFullGCNotification(int maxGenerationThreshold, int largeObjectHeapThreshold) { if (maxGenerationThreshold <= 0 || maxGenerationThreshold >= 100) { throw new ArgumentOutOfRangeException("maxGenerationThreshold", SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); } if (largeObjectHeapThreshold <= 0 || largeObjectHeapThreshold >= 100) { throw new ArgumentOutOfRangeException("largeObjectHeapThreshold", SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99)); } if (!_RegisterForFullGCNotification(maxGenerationThreshold, largeObjectHeapThreshold)) { throw new InvalidOperationException(SR.InvalidOperation_NotWithConcurrentGC); } } public static void CancelFullGCNotification() { if (!_CancelFullGCNotification()) { throw new InvalidOperationException(SR.InvalidOperation_NotWithConcurrentGC); } } public static GCNotificationStatus WaitForFullGCApproach() { return (GCNotificationStatus)_WaitForFullGCApproach(-1); } public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return (GCNotificationStatus)_WaitForFullGCApproach(millisecondsTimeout); } public static GCNotificationStatus WaitForFullGCComplete() { return (GCNotificationStatus)_WaitForFullGCComplete(-1); } public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return (GCNotificationStatus)_WaitForFullGCComplete(millisecondsTimeout); } private static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC) { if (totalSize <= 0) { throw new ArgumentOutOfRangeException("totalSize", "totalSize can't be zero or negative"); } if (hasLohSize) { if (lohSize <= 0) { throw new ArgumentOutOfRangeException("lohSize", "lohSize can't be zero or negative"); } if (lohSize > totalSize) { throw new ArgumentOutOfRangeException("lohSize", "lohSize can't be greater than totalSize"); } } return (StartNoGCRegionStatus)_StartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC) switch { StartNoGCRegionStatus.NotEnoughMemory => false, StartNoGCRegionStatus.AlreadyInProgress => throw new InvalidOperationException("The NoGCRegion mode was already in progress"), StartNoGCRegionStatus.AmountTooLarge => throw new ArgumentOutOfRangeException("totalSize", "totalSize is too large. For more information about setting the maximum size, see \"Latency Modes\" in https://go.microsoft.com/fwlink/?LinkId=522706"), _ => true, }; } public static bool TryStartNoGCRegion(long totalSize) { return StartNoGCRegionWorker(totalSize, hasLohSize: false, 0L, disallowFullBlockingGC: false); } public static bool TryStartNoGCRegion(long totalSize, long lohSize) { return StartNoGCRegionWorker(totalSize, hasLohSize: true, lohSize, disallowFullBlockingGC: false); } public static bool TryStartNoGCRegion(long totalSize, bool disallowFullBlockingGC) { return StartNoGCRegionWorker(totalSize, hasLohSize: false, 0L, disallowFullBlockingGC); } public static bool TryStartNoGCRegion(long totalSize, long lohSize, bool disallowFullBlockingGC) { return StartNoGCRegionWorker(totalSize, hasLohSize: true, lohSize, disallowFullBlockingGC); } public static void EndNoGCRegion() { switch ((EndNoGCRegionStatus)_EndNoGCRegion()) { case EndNoGCRegionStatus.NotInProgress: throw new InvalidOperationException("NoGCRegion mode must be set"); case EndNoGCRegionStatus.GCInduced: throw new InvalidOperationException("Garbage collection was induced in NoGCRegion mode"); case EndNoGCRegionStatus.AllocationExceeded: throw new InvalidOperationException("Allocated memory exceeds specified memory for NoGCRegion mode"); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T[] AllocateUninitializedArray(int length, bool pinned = false) { if (!pinned) { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { return new T[length]; } if (length < 2048 / Unsafe.SizeOf()) { return new T[length]; } } else if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); } return AllocateNewUninitializedArray(length, pinned); static T[] AllocateNewUninitializedArray(int length, bool pinned) { GC_ALLOC_FLAGS gC_ALLOC_FLAGS = GC_ALLOC_FLAGS.GC_ALLOC_ZEROING_OPTIONAL; if (pinned) { gC_ALLOC_FLAGS |= GC_ALLOC_FLAGS.GC_ALLOC_PINNED_OBJECT_HEAP; } return Unsafe.As(AllocateNewArray(typeof(T[]).TypeHandle.Value, length, gC_ALLOC_FLAGS)); } } public static T[] AllocateArray(int length, bool pinned = false) { GC_ALLOC_FLAGS flags = GC_ALLOC_FLAGS.GC_ALLOC_NO_FLAGS; if (pinned) { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); } flags = GC_ALLOC_FLAGS.GC_ALLOC_PINNED_OBJECT_HEAP; } return Unsafe.As(AllocateNewArray(typeof(T[]).TypeHandle.Value, length, flags)); } } public static class Math { public const double E = 2.718281828459045; public const double PI = 3.141592653589793; public const double Tau = Math.PI * 2.0; private static readonly double[] roundPower10Double = new double[16] { 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0, 100000000000.0, 1000000000000.0, 10000000000000.0, 100000000000000.0, 1000000000000000.0 }; [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Abs(double value); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Abs(float value); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Acos(double d); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Acosh(double d); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Asin(double d); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Asinh(double d); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Atan(double d); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Atanh(double d); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Atan2(double y, double x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Cbrt(double d); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Ceiling(double a); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Cos(double d); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Cosh(double value); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Exp(double d); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Floor(double d); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double FusedMultiplyAdd(double x, double y, double z); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern int ILogB(double x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Log(double d); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Log2(double x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Log10(double d); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Pow(double x, double y); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Sin(double a); public unsafe static (double Sin, double Cos) SinCos(double x) { System.Runtime.CompilerServices.Unsafe.SkipInit(out double item); System.Runtime.CompilerServices.Unsafe.SkipInit(out double item2); SinCos(x, &item, &item2); return (item, item2); } [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Sinh(double value); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Sqrt(double d); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Tan(double a); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern double Tanh(double value); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern double ModF(double x, double* intptr); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void SinCos(double x, double* sin, double* cos); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short Abs(short value) { if (value < 0) { value = (short)(-value); if (value < 0) { ThrowAbsOverflow(); } } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Abs(int value) { if (value < 0) { value = -value; if (value < 0) { ThrowAbsOverflow(); } } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long Abs(long value) { if (value < 0) { value = -value; if (value < 0) { ThrowAbsOverflow(); } } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static nint Abs(nint value) { if (value < 0) { value = -value; if (value < 0) { ThrowAbsOverflow(); } } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static sbyte Abs(sbyte value) { if (value < 0) { value = (sbyte)(-value); if (value < 0) { ThrowAbsOverflow(); } } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Abs(decimal value) { return decimal.Abs(in value); } [DoesNotReturn] [StackTraceHidden] private static void ThrowAbsOverflow() { throw new OverflowException(SR.Overflow_NegateTwosCompNum); } public static long BigMul(int a, int b) { return (long)a * (long)b; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe static ulong BigMul(ulong a, ulong b, out ulong low) { if (Bmi2.X64.IsSupported) { System.Runtime.CompilerServices.Unsafe.SkipInit(out ulong num); ulong result = Bmi2.X64.MultiplyNoFlags(a, b, &num); low = num; return result; } if (ArmBase.Arm64.IsSupported) { } return SoftwareFallback(a, b, out low); static ulong SoftwareFallback(ulong a, ulong b, out ulong low) { uint num2 = (uint)a; uint num3 = (uint)(a >> 32); uint num4 = (uint)b; uint num5 = (uint)(b >> 32); ulong num6 = (ulong)num2 * (ulong)num4; ulong num7 = (ulong)((long)num3 * (long)num4) + (num6 >> 32); ulong num8 = (ulong)((long)num2 * (long)num5 + (uint)num7); low = (num8 << 32) | (uint)num6; return (ulong)((long)num3 * (long)num5 + (long)(num7 >> 32)) + (num8 >> 32); } } public static long BigMul(long a, long b, out long low) { if (ArmBase.Arm64.IsSupported) { } ulong low2; ulong num = BigMul((ulong)a, (ulong)b, out low2); low = (long)low2; return (long)num - ((a >> 63) & b) - ((b >> 63) & a); } public static double BitDecrement(double x) { long num = BitConverter.DoubleToInt64Bits(x); if (((num >> 32) & 0x7FF00000) >= 2146435072) { if (num != 9218868437227405312L) { return x; } return double.MaxValue; } if (num == 0L) { return -5E-324; } num += ((num < 0) ? 1 : (-1)); return BitConverter.Int64BitsToDouble(num); } public static double BitIncrement(double x) { long num = BitConverter.DoubleToInt64Bits(x); if (((num >> 32) & 0x7FF00000) >= 2146435072) { if (num != -4503599627370496L) { return x; } return double.MinValue; } if (num == long.MinValue) { return double.Epsilon; } num += ((num >= 0) ? 1 : (-1)); return BitConverter.Int64BitsToDouble(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double CopySign(double x, double y) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return VectorMath.ConditionalSelectBitwise(Vector128.CreateScalarUnsafe(-0.0), Vector128.CreateScalarUnsafe(y), Vector128.CreateScalarUnsafe(x)).ToScalar(); } return SoftwareFallback(x, y); static double SoftwareFallback(double x, double y) { long num = BitConverter.DoubleToInt64Bits(x); long num2 = BitConverter.DoubleToInt64Bits(y); num &= 0x7FFFFFFFFFFFFFFFL; num2 &= long.MinValue; return BitConverter.Int64BitsToDouble(num | num2); } } public static int DivRem(int a, int b, out int result) { int num = a / b; result = a - num * b; return num; } public static long DivRem(long a, long b, out long result) { long num = a / b; result = a - num * b; return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] [CLSCompliant(false)] public static (sbyte Quotient, sbyte Remainder) DivRem(sbyte left, sbyte right) { sbyte b = (sbyte)(left / right); return (b, (sbyte)(left - b * right)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static (byte Quotient, byte Remainder) DivRem(byte left, byte right) { byte b = (byte)(left / right); return (b, (byte)(left - b * right)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static (short Quotient, short Remainder) DivRem(short left, short right) { short num = (short)(left / right); return (num, (short)(left - num * right)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] [CLSCompliant(false)] public static (ushort Quotient, ushort Remainder) DivRem(ushort left, ushort right) { ushort num = (ushort)(left / right); return (num, (ushort)(left - num * right)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static (int Quotient, int Remainder) DivRem(int left, int right) { int num = left / right; return (num, left - num * right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] [CLSCompliant(false)] public static (uint Quotient, uint Remainder) DivRem(uint left, uint right) { uint num = left / right; return (num, left - num * right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static (long Quotient, long Remainder) DivRem(long left, long right) { long num = left / right; return (num, left - num * right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] [CLSCompliant(false)] public static (ulong Quotient, ulong Remainder) DivRem(ulong left, ulong right) { ulong num = left / right; return (num, left - num * right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static (nint Quotient, nint Remainder) DivRem(nint left, nint right) { nint num = left / right; return (num, left - num * right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] [CLSCompliant(false)] public static (nuint Quotient, nuint Remainder) DivRem(nuint left, nuint right) { nuint num = left / right; return (num, left - num * right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Ceiling(decimal d) { return decimal.Ceiling(d); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte Clamp(byte value, byte min, byte max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Clamp(decimal value, decimal min, decimal max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Clamp(double value, double min, double max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short Clamp(short value, short min, short max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Clamp(int value, int min, int max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long Clamp(long value, long min, long max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static nint Clamp(nint value, nint min, nint max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static sbyte Clamp(sbyte value, sbyte min, sbyte max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Clamp(float value, float min, float max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ushort Clamp(ushort value, ushort min, ushort max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint Clamp(uint value, uint min, uint max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong Clamp(ulong value, ulong min, ulong max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static nuint Clamp(nuint value, nuint min, nuint max) { if (min > max) { ThrowMinMaxException(min, max); } if (value < min) { return min; } if (value > max) { return max; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Floor(decimal d) { return decimal.Floor(d); } public static double IEEERemainder(double x, double y) { if (double.IsNaN(x)) { return x; } if (double.IsNaN(y)) { return y; } double num = x % y; if (double.IsNaN(num)) { return double.NaN; } if (num == 0.0 && double.IsNegative(x)) { return -0.0; } double num2 = num - Abs(y) * (double)Sign(x); if (Abs(num2) == Abs(num)) { double num3 = x / y; double value = Round(num3); if (Abs(value) > Abs(num3)) { return num2; } return num; } if (Abs(num2) < Abs(num)) { return num2; } return num; } public static double Log(double a, double newBase) { if (double.IsNaN(a)) { return a; } if (double.IsNaN(newBase)) { return newBase; } if (newBase == 1.0) { return double.NaN; } if (a != 1.0 && (newBase == 0.0 || double.IsPositiveInfinity(newBase))) { return double.NaN; } return Log(a) / Log(newBase); } [NonVersionable] public static byte Max(byte val1, byte val2) { if (val1 < val2) { return val2; } return val1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Max(decimal val1, decimal val2) { return decimal.Max(in val1, in val2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Max(double val1, double val2) { if (val1 != val2) { if (!double.IsNaN(val1)) { if (!(val2 < val1)) { return val2; } return val1; } return val1; } if (!double.IsNegative(val2)) { return val2; } return val1; } [NonVersionable] public static short Max(short val1, short val2) { if (val1 < val2) { return val2; } return val1; } [NonVersionable] public static int Max(int val1, int val2) { if (val1 < val2) { return val2; } return val1; } [NonVersionable] public static long Max(long val1, long val2) { if (val1 < val2) { return val2; } return val1; } [NonVersionable] public static nint Max(nint val1, nint val2) { if (val1 < val2) { return val2; } return val1; } [CLSCompliant(false)] [NonVersionable] public static sbyte Max(sbyte val1, sbyte val2) { if (val1 < val2) { return val2; } return val1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Max(float val1, float val2) { if (val1 != val2) { if (!float.IsNaN(val1)) { if (!(val2 < val1)) { return val2; } return val1; } return val1; } if (!float.IsNegative(val2)) { return val2; } return val1; } [CLSCompliant(false)] [NonVersionable] public static ushort Max(ushort val1, ushort val2) { if (val1 < val2) { return val2; } return val1; } [CLSCompliant(false)] [NonVersionable] public static uint Max(uint val1, uint val2) { if (val1 < val2) { return val2; } return val1; } [CLSCompliant(false)] [NonVersionable] public static ulong Max(ulong val1, ulong val2) { if (val1 < val2) { return val2; } return val1; } [CLSCompliant(false)] [NonVersionable] public static nuint Max(nuint val1, nuint val2) { if (val1 < val2) { return val2; } return val1; } public static double MaxMagnitude(double x, double y) { double num = Abs(x); double num2 = Abs(y); if (num > num2 || double.IsNaN(num)) { return x; } if (num == num2) { if (!double.IsNegative(x)) { return x; } return y; } return y; } [NonVersionable] public static byte Min(byte val1, byte val2) { if (val1 > val2) { return val2; } return val1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Min(decimal val1, decimal val2) { return decimal.Min(in val1, in val2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Min(double val1, double val2) { if (val1 != val2 && !double.IsNaN(val1)) { if (!(val1 < val2)) { return val2; } return val1; } if (!double.IsNegative(val1)) { return val2; } return val1; } [NonVersionable] public static short Min(short val1, short val2) { if (val1 > val2) { return val2; } return val1; } [NonVersionable] public static int Min(int val1, int val2) { if (val1 > val2) { return val2; } return val1; } [NonVersionable] public static long Min(long val1, long val2) { if (val1 > val2) { return val2; } return val1; } [NonVersionable] public static nint Min(nint val1, nint val2) { if (val1 > val2) { return val2; } return val1; } [CLSCompliant(false)] [NonVersionable] public static sbyte Min(sbyte val1, sbyte val2) { if (val1 > val2) { return val2; } return val1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Min(float val1, float val2) { if (val1 != val2 && !float.IsNaN(val1)) { if (!(val1 < val2)) { return val2; } return val1; } if (!float.IsNegative(val1)) { return val2; } return val1; } [CLSCompliant(false)] [NonVersionable] public static ushort Min(ushort val1, ushort val2) { if (val1 > val2) { return val2; } return val1; } [CLSCompliant(false)] [NonVersionable] public static uint Min(uint val1, uint val2) { if (val1 > val2) { return val2; } return val1; } [CLSCompliant(false)] [NonVersionable] public static ulong Min(ulong val1, ulong val2) { if (val1 > val2) { return val2; } return val1; } [CLSCompliant(false)] [NonVersionable] public static nuint Min(nuint val1, nuint val2) { if (val1 > val2) { return val2; } return val1; } public static double MinMagnitude(double x, double y) { double num = Abs(x); double num2 = Abs(y); if (num < num2 || double.IsNaN(num)) { return x; } if (num == num2) { if (!double.IsNegative(x)) { return y; } return x; } return y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double ReciprocalEstimate(double d) { if (AdvSimd.Arm64.IsSupported) { } return 1.0 / d; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double ReciprocalSqrtEstimate(double d) { if (AdvSimd.Arm64.IsSupported) { } return 1.0 / Sqrt(d); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Round(decimal d) { return decimal.Round(d, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Round(decimal d, int decimals) { return decimal.Round(d, decimals); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Round(decimal d, MidpointRounding mode) { return decimal.Round(d, 0, mode); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Round(decimal d, int decimals, MidpointRounding mode) { return decimal.Round(d, decimals, mode); } [Intrinsic] public static double Round(double a) { ulong num = BitConverter.DoubleToUInt64Bits(a); int num2 = double.ExtractExponentFromBits(num); if (num2 <= 1022) { if (num << 1 == 0L) { return a; } double x = ((num2 == 1022 && double.ExtractSignificandFromBits(num) != 0L) ? 1.0 : 0.0); return CopySign(x, a); } if (num2 >= 1075) { return a; } ulong num3 = (ulong)(1L << 1075 - num2); ulong num4 = num3 - 1; num += num3 >> 1; num = (((num & num4) != 0L) ? (num & ~num4) : (num & ~num3)); return BitConverter.UInt64BitsToDouble(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Round(double value, int digits) { return Round(value, digits, MidpointRounding.ToEven); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double Round(double value, MidpointRounding mode) { return Round(value, 0, mode); } public unsafe static double Round(double value, int digits, MidpointRounding mode) { if (digits < 0 || digits > 15) { throw new ArgumentOutOfRangeException("digits", SR.ArgumentOutOfRange_RoundingDigits); } if (mode < MidpointRounding.ToEven || mode > MidpointRounding.ToPositiveInfinity) { throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, "MidpointRounding"), "mode"); } if (Abs(value) < 10000000000000000.0) { double num = roundPower10Double[digits]; value *= num; switch (mode) { case MidpointRounding.ToEven: value = Round(value); break; case MidpointRounding.AwayFromZero: { double value2 = ModF(value, &value); if (Abs(value2) >= 0.5) { value += (double)Sign(value2); } break; } case MidpointRounding.ToZero: value = Truncate(value); break; case MidpointRounding.ToNegativeInfinity: value = Floor(value); break; case MidpointRounding.ToPositiveInfinity: value = Ceiling(value); break; default: throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, "MidpointRounding"), "mode"); } value /= num; } return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Sign(decimal value) { return decimal.Sign(in value); } public static int Sign(double value) { if (value < 0.0) { return -1; } if (value > 0.0) { return 1; } if (value == 0.0) { return 0; } throw new ArithmeticException(SR.Arithmetic_NaN); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Sign(short value) { return Sign((int)value); } public static int Sign(int value) { return (value >> 31) | (-value >>> 31); } public static int Sign(long value) { return (int)((value >> 63) | (-value >>> 63)); } public static int Sign(nint value) { return (int)(value >> 31) | (int)((uint)(-value) >> 31); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int Sign(sbyte value) { return Sign((int)value); } public static int Sign(float value) { if (value < 0f) { return -1; } if (value > 0f) { return 1; } if (value == 0f) { return 0; } throw new ArithmeticException(SR.Arithmetic_NaN); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal Truncate(decimal d) { return decimal.Truncate(d); } public unsafe static double Truncate(double d) { ModF(d, &d); return d; } [DoesNotReturn] private static void ThrowMinMaxException(T min, T max) { throw new ArgumentException(SR.Format(SR.Argument_MinMaxValue, min, max)); } public static double ScaleB(double x, int n) { double num = x; if (n > 1023) { num *= 8.98846567431158E+307; n -= 1023; if (n > 1023) { num *= 8.98846567431158E+307; n -= 1023; if (n > 1023) { n = 1023; } } } else if (n < -1022) { num *= 2.004168360008973E-292; n += 969; if (n < -1022) { num *= 2.004168360008973E-292; n += 969; if (n < -1022) { n = -1022; } } } double num2 = BitConverter.Int64BitsToDouble((long)(1023 + n) << 52); return num * num2; } } public static class MathF { public const float E = 2.7182817f; public const float PI = 3.1415927f; public const float Tau = (float)Math.PI * 2f; private static readonly float[] roundPower10Single = new float[7] { 1f, 10f, 100f, 1000f, 10000f, 100000f, 1000000f }; [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Acos(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Acosh(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Asin(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Asinh(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Atan(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Atanh(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Atan2(float y, float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Cbrt(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Ceiling(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Cos(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Cosh(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Exp(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Floor(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float FusedMultiplyAdd(float x, float y, float z); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern int ILogB(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Log(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Log2(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Log10(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Pow(float x, float y); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Sin(float x); public unsafe static (float Sin, float Cos) SinCos(float x) { System.Runtime.CompilerServices.Unsafe.SkipInit(out float item); System.Runtime.CompilerServices.Unsafe.SkipInit(out float item2); SinCos(x, &item, &item2); return (item, item2); } [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Sinh(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Sqrt(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Tan(float x); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern float Tanh(float x); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern float ModF(float x, float* intptr); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void SinCos(float x, float* sin, float* cos); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Abs(float x) { return Math.Abs(x); } public static float BitDecrement(float x) { int num = BitConverter.SingleToInt32Bits(x); if ((num & 0x7F800000) >= 2139095040) { if (num != 2139095040) { return x; } return float.MaxValue; } if (num == 0) { return -1E-45f; } num += ((num < 0) ? 1 : (-1)); return BitConverter.Int32BitsToSingle(num); } public static float BitIncrement(float x) { int num = BitConverter.SingleToInt32Bits(x); if ((num & 0x7F800000) >= 2139095040) { if (num != -8388608) { return x; } return float.MinValue; } if (num == int.MinValue) { return float.Epsilon; } num += ((num >= 0) ? 1 : (-1)); return BitConverter.Int32BitsToSingle(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float CopySign(float x, float y) { if (Sse.IsSupported || AdvSimd.IsSupported) { return VectorMath.ConditionalSelectBitwise(Vector128.CreateScalarUnsafe(-0f), Vector128.CreateScalarUnsafe(y), Vector128.CreateScalarUnsafe(x)).ToScalar(); } return SoftwareFallback(x, y); static float SoftwareFallback(float x, float y) { int num = BitConverter.SingleToInt32Bits(x); int num2 = BitConverter.SingleToInt32Bits(y); num &= 0x7FFFFFFF; num2 &= int.MinValue; return BitConverter.Int32BitsToSingle(num | num2); } } public static float IEEERemainder(float x, float y) { if (float.IsNaN(x)) { return x; } if (float.IsNaN(y)) { return y; } float num = x % y; if (float.IsNaN(num)) { return float.NaN; } if (num == 0f && float.IsNegative(x)) { return -0f; } float num2 = num - Abs(y) * (float)Sign(x); if (Abs(num2) == Abs(num)) { float x2 = x / y; float x3 = Round(x2); if (Abs(x3) > Abs(x2)) { return num2; } return num; } if (Abs(num2) < Abs(num)) { return num2; } return num; } public static float Log(float x, float y) { if (float.IsNaN(x)) { return x; } if (float.IsNaN(y)) { return y; } if (y == 1f) { return float.NaN; } if (x != 1f && (y == 0f || float.IsPositiveInfinity(y))) { return float.NaN; } return Log(x) / Log(y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Max(float x, float y) { return Math.Max(x, y); } public static float MaxMagnitude(float x, float y) { float num = Abs(x); float num2 = Abs(y); if (num > num2 || float.IsNaN(num)) { return x; } if (num == num2) { if (!float.IsNegative(x)) { return x; } return y; } return y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Min(float x, float y) { return Math.Min(x, y); } public static float MinMagnitude(float x, float y) { float num = Abs(x); float num2 = Abs(y); if (num < num2 || float.IsNaN(num)) { return x; } if (num == num2) { if (!float.IsNegative(x)) { return y; } return x; } return y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float ReciprocalEstimate(float x) { if (Sse.IsSupported) { return Sse.ReciprocalScalar(Vector128.CreateScalarUnsafe(x)).ToScalar(); } if (AdvSimd.Arm64.IsSupported) { } return 1f / x; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float ReciprocalSqrtEstimate(float x) { if (Sse.IsSupported) { return Sse.ReciprocalSqrtScalar(Vector128.CreateScalarUnsafe(x)).ToScalar(); } if (AdvSimd.Arm64.IsSupported) { } return 1f / Sqrt(x); } [Intrinsic] public static float Round(float x) { uint num = BitConverter.SingleToUInt32Bits(x); int num2 = float.ExtractExponentFromBits(num); if (num2 <= 126) { if (num << 1 == 0) { return x; } float x2 = ((num2 == 126 && float.ExtractSignificandFromBits(num) != 0) ? 1f : 0f); return CopySign(x2, x); } if (num2 >= 150) { return x; } uint num3 = (uint)(1 << 150 - num2); uint num4 = num3 - 1; num += num3 >> 1; num = (((num & num4) != 0) ? (num & ~num4) : (num & ~num3)); return BitConverter.UInt32BitsToSingle(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Round(float x, int digits) { return Round(x, digits, MidpointRounding.ToEven); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Round(float x, MidpointRounding mode) { return Round(x, 0, mode); } public unsafe static float Round(float x, int digits, MidpointRounding mode) { if (digits < 0 || digits > 6) { throw new ArgumentOutOfRangeException("digits", SR.ArgumentOutOfRange_RoundingDigits_MathF); } if (mode < MidpointRounding.ToEven || mode > MidpointRounding.ToPositiveInfinity) { throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, "MidpointRounding"), "mode"); } if (Abs(x) < 100000000f) { float num = roundPower10Single[digits]; x *= num; switch (mode) { case MidpointRounding.ToEven: x = Round(x); break; case MidpointRounding.AwayFromZero: { float x2 = ModF(x, &x); if (Abs(x2) >= 0.5f) { x += (float)Sign(x2); } break; } case MidpointRounding.ToZero: x = Truncate(x); break; case MidpointRounding.ToNegativeInfinity: x = Floor(x); break; case MidpointRounding.ToPositiveInfinity: x = Ceiling(x); break; default: throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, "MidpointRounding"), "mode"); } x /= num; } return x; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int Sign(float x) { return Math.Sign(x); } public unsafe static float Truncate(float x) { ModF(x, &x); return x; } public static float ScaleB(float x, int n) { float num = x; if (n > 127) { num *= 1.7014118E+38f; n -= 127; if (n > 127) { num *= 1.7014118E+38f; n -= 127; if (n > 127) { n = 127; } } } else if (n < -126) { num *= 1.9721523E-31f; n += 102; if (n < -126) { num *= 1.9721523E-31f; n += 102; if (n < -126) { n = -126; } } } float num2 = BitConverter.Int32BitsToSingle(127 + n << 23); return num * num2; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class MissingMemberException : MemberAccessException, ISerializable { protected string? ClassName; protected string? MemberName; protected byte[]? Signature; public override string Message { get { if (ClassName == null) { return base.Message; } return SR.Format(SR.MissingMember_Name, ClassName + "." + MemberName + ((Signature != null) ? (" " + FormatSignature(Signature)) : string.Empty)); } } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern string FormatSignature(byte[] signature); public MissingMemberException() : base(SR.Arg_MissingMemberException) { base.HResult = -2146233070; } public MissingMemberException(string? message) : base(message) { base.HResult = -2146233070; } public MissingMemberException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233070; } public MissingMemberException(string? className, string? memberName) { ClassName = className; MemberName = memberName; } protected MissingMemberException(SerializationInfo info, StreamingContext context) : base(info, context) { ClassName = info.GetString("MMClassName"); MemberName = info.GetString("MMMemberName"); Signature = (byte[])info.GetValue("MMSignature", typeof(byte[])); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("MMClassName", ClassName, typeof(string)); info.AddValue("MMMemberName", MemberName, typeof(string)); info.AddValue("MMSignature", Signature, typeof(byte[])); } } [ClassInterface(ClassInterfaceType.None)] [ComVisible(true)] public abstract class MulticastDelegate : Delegate { private object _invocationList; private IntPtr _invocationCount; [RequiresUnreferencedCode("The target method might be removed")] protected MulticastDelegate(object target, string method) : base(target, method) { } protected MulticastDelegate([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type target, string method) : base(target, method) { } internal bool IsUnmanagedFunctionPtr() { return _invocationCount == (IntPtr)(-1); } internal bool InvocationListLogicallyNull() { if (_invocationList != null && !(_invocationList is LoaderAllocator)) { return _invocationList is DynamicResolver; } return true; } public override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new SerializationException(SR.Serialization_DelegatesNotSupported); } public sealed override bool Equals([NotNullWhen(true)] object? obj) { if (obj == null) { return false; } if (this == obj) { return true; } if (!Delegate.InternalEqualTypes(this, obj)) { return false; } MulticastDelegate multicastDelegate = Unsafe.As(obj); if (_invocationCount != (IntPtr)0) { if (InvocationListLogicallyNull()) { if (IsUnmanagedFunctionPtr()) { if (!multicastDelegate.IsUnmanagedFunctionPtr()) { return false; } return Delegate.CompareUnmanagedFunctionPtrs(this, multicastDelegate); } if (multicastDelegate._invocationList is Delegate) { return Equals(multicastDelegate._invocationList); } return base.Equals(obj); } if (_invocationList is Delegate @delegate) { return @delegate.Equals(obj); } return InvocationListEquals(multicastDelegate); } if (!InvocationListLogicallyNull()) { if (!_invocationList.Equals(multicastDelegate._invocationList)) { return false; } return base.Equals((object?)multicastDelegate); } if (multicastDelegate._invocationList is Delegate) { return Equals(multicastDelegate._invocationList); } return base.Equals((object?)multicastDelegate); } private bool InvocationListEquals(MulticastDelegate d) { object[] array = (object[])_invocationList; if (d._invocationCount != _invocationCount) { return false; } int num = (int)_invocationCount; for (int i = 0; i < num; i++) { Delegate @delegate = (Delegate)array[i]; object[] array2 = d._invocationList as object[]; if (!@delegate.Equals(array2[i])) { return false; } } return true; } private static bool TrySetSlot(object[] a, int index, object o) { if (a[index] == null && Interlocked.CompareExchange(ref a[index], o, (object)null) == null) { return true; } object obj = a[index]; if (obj != null) { MulticastDelegate multicastDelegate = (MulticastDelegate)o; MulticastDelegate multicastDelegate2 = (MulticastDelegate)obj; if (multicastDelegate2._methodPtr == multicastDelegate._methodPtr && multicastDelegate2._target == multicastDelegate._target && multicastDelegate2._methodPtrAux == multicastDelegate._methodPtrAux) { return true; } } return false; } private MulticastDelegate NewMulticastDelegate(object[] invocationList, int invocationCount, bool thisIsMultiCastAlready) { MulticastDelegate multicastDelegate = Delegate.InternalAllocLike(this); if (thisIsMultiCastAlready) { multicastDelegate._methodPtr = _methodPtr; multicastDelegate._methodPtrAux = _methodPtrAux; } else { multicastDelegate._methodPtr = GetMulticastInvoke(); multicastDelegate._methodPtrAux = GetInvokeMethod(); } multicastDelegate._target = multicastDelegate; multicastDelegate._invocationList = invocationList; multicastDelegate._invocationCount = (IntPtr)invocationCount; return multicastDelegate; } internal MulticastDelegate NewMulticastDelegate(object[] invocationList, int invocationCount) { return NewMulticastDelegate(invocationList, invocationCount, thisIsMultiCastAlready: false); } internal void StoreDynamicMethod(MethodInfo dynamicMethod) { if (_invocationCount != (IntPtr)0) { MulticastDelegate multicastDelegate = (MulticastDelegate)_invocationList; multicastDelegate._methodBase = dynamicMethod; } else { _methodBase = dynamicMethod; } } protected sealed override Delegate CombineImpl(Delegate? follow) { if ((object)follow == null) { return this; } if (!Delegate.InternalEqualTypes(this, follow)) { throw new ArgumentException(SR.Arg_DlgtTypeMis); } MulticastDelegate multicastDelegate = (MulticastDelegate)follow; int num = 1; object[] array = multicastDelegate._invocationList as object[]; if (array != null) { num = (int)multicastDelegate._invocationCount; } int num2; object[] array3; if (!(_invocationList is object[] array2)) { num2 = 1 + num; array3 = new object[num2]; array3[0] = this; if (array == null) { array3[1] = multicastDelegate; } else { for (int i = 0; i < num; i++) { array3[1 + i] = array[i]; } } return NewMulticastDelegate(array3, num2); } int num3 = (int)_invocationCount; num2 = num3 + num; array3 = null; if (num2 <= array2.Length) { array3 = array2; if (array == null) { if (!TrySetSlot(array3, num3, multicastDelegate)) { array3 = null; } } else { for (int j = 0; j < num; j++) { if (!TrySetSlot(array3, num3 + j, array[j])) { array3 = null; break; } } } } if (array3 == null) { int num4; for (num4 = array2.Length; num4 < num2; num4 *= 2) { } array3 = new object[num4]; for (int k = 0; k < num3; k++) { array3[k] = array2[k]; } if (array == null) { array3[num3] = multicastDelegate; } else { for (int l = 0; l < num; l++) { array3[num3 + l] = array[l]; } } } return NewMulticastDelegate(array3, num2, thisIsMultiCastAlready: true); } private object[] DeleteFromInvocationList(object[] invocationList, int invocationCount, int deleteIndex, int deleteCount) { object[] array = (object[])_invocationList; int num = array.Length; while (num / 2 >= invocationCount - deleteCount) { num /= 2; } object[] array2 = new object[num]; for (int i = 0; i < deleteIndex; i++) { array2[i] = invocationList[i]; } for (int j = deleteIndex + deleteCount; j < invocationCount; j++) { array2[j - deleteCount] = invocationList[j]; } return array2; } private static bool EqualInvocationLists(object[] a, object[] b, int start, int count) { for (int i = 0; i < count; i++) { if (!a[start + i].Equals(b[i])) { return false; } } return true; } protected sealed override Delegate? RemoveImpl(Delegate value) { if (!(value is MulticastDelegate multicastDelegate)) { return this; } if (!(multicastDelegate._invocationList is object[])) { if (!(_invocationList is object[] array)) { if (Equals(value)) { return null; } } else { int num = (int)_invocationCount; int num2 = num; while (--num2 >= 0) { if (value.Equals(array[num2])) { if (num == 2) { return (Delegate)array[1 - num2]; } object[] invocationList = DeleteFromInvocationList(array, num, num2, 1); return NewMulticastDelegate(invocationList, num - 1, thisIsMultiCastAlready: true); } } } } else if (_invocationList is object[] array2) { int num3 = (int)_invocationCount; int num4 = (int)multicastDelegate._invocationCount; for (int num5 = num3 - num4; num5 >= 0; num5--) { if (EqualInvocationLists(array2, multicastDelegate._invocationList as object[], num5, num4)) { if (num3 - num4 == 0) { return null; } if (num3 - num4 == 1) { return (Delegate)array2[(num5 == 0) ? (num3 - 1) : 0]; } object[] invocationList2 = DeleteFromInvocationList(array2, num3, num5, num4); return NewMulticastDelegate(invocationList2, num3 - num4, thisIsMultiCastAlready: true); } } } return this; } public sealed override Delegate[] GetInvocationList() { Delegate[] array2; if (!(_invocationList is object[] array)) { array2 = new Delegate[1] { this }; } else { array2 = new Delegate[(int)_invocationCount]; for (int i = 0; i < array2.Length; i++) { array2[i] = (Delegate)array[i]; } } return array2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(MulticastDelegate? d1, MulticastDelegate? d2) { if ((object)d2 == null) { if ((object)d1 != null) { return false; } return true; } if ((object)d2 != d1) { return d2.Equals(d1); } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(MulticastDelegate? d1, MulticastDelegate? d2) { if ((object)d2 == null) { if ((object)d1 != null) { return true; } return false; } if ((object)d2 != d1) { return !d2.Equals(d1); } return false; } public sealed override int GetHashCode() { if (IsUnmanagedFunctionPtr()) { return ValueType.GetHashCodeOfPtr(_methodPtr) ^ ValueType.GetHashCodeOfPtr(_methodPtrAux); } if (_invocationCount != (IntPtr)0 && _invocationList is Delegate @delegate) { return @delegate.GetHashCode(); } if (!(_invocationList is object[] array)) { return base.GetHashCode(); } int num = 0; for (int i = 0; i < (int)_invocationCount; i++) { num = num * 33 + array[i].GetHashCode(); } return num; } internal override object GetTarget() { if (_invocationCount != (IntPtr)0) { if (InvocationListLogicallyNull()) { return null; } if (_invocationList is object[] array) { int num = (int)_invocationCount; return ((Delegate)array[num - 1]).GetTarget(); } if (_invocationList is Delegate @delegate) { return @delegate.GetTarget(); } } return base.GetTarget(); } protected override MethodInfo GetMethodImpl() { if (_invocationCount != (IntPtr)0 && _invocationList != null) { if (_invocationList is object[] array) { int num = (int)_invocationCount - 1; return ((Delegate)array[num]).Method; } if (_invocationList is MulticastDelegate multicastDelegate) { return multicastDelegate.GetMethodImpl(); } } else if (IsUnmanagedFunctionPtr()) { if (_methodBase == null || !(_methodBase is MethodInfo)) { IRuntimeMethodInfo runtimeMethodInfo = FindMethodHandle(); RuntimeType runtimeType = RuntimeMethodHandle.GetDeclaringType(runtimeMethodInfo); if (RuntimeTypeHandle.IsGenericTypeDefinition(runtimeType) || RuntimeTypeHandle.HasInstantiation(runtimeType)) { RuntimeType runtimeType2 = (RuntimeType)GetType(); runtimeType = runtimeType2; } _methodBase = (MethodInfo)RuntimeType.GetMethodBase(runtimeType, runtimeMethodInfo); } return (MethodInfo)_methodBase; } return base.GetMethodImpl(); } [DoesNotReturn] [DebuggerNonUserCode] private static void ThrowNullThisInDelegateToInstance() { throw new ArgumentException(SR.Arg_DlgtNullInst); } [DebuggerNonUserCode] private void CtorClosed(object target, IntPtr methodPtr) { if (target == null) { ThrowNullThisInDelegateToInstance(); } _target = target; _methodPtr = methodPtr; } [DebuggerNonUserCode] private void CtorClosedStatic(object target, IntPtr methodPtr) { _target = target; _methodPtr = methodPtr; } [DebuggerNonUserCode] private void CtorRTClosed(object target, IntPtr methodPtr) { _target = target; _methodPtr = AdjustTarget(target, methodPtr); } [DebuggerNonUserCode] private void CtorOpened(object target, IntPtr methodPtr, IntPtr shuffleThunk) { _target = this; _methodPtr = shuffleThunk; _methodPtrAux = methodPtr; } [DebuggerNonUserCode] private void CtorVirtualDispatch(object target, IntPtr methodPtr, IntPtr shuffleThunk) { _target = this; _methodPtr = shuffleThunk; _methodPtrAux = GetCallStub(methodPtr); } [DebuggerNonUserCode] private void CtorCollectibleClosedStatic(object target, IntPtr methodPtr, IntPtr gchandle) { _target = target; _methodPtr = methodPtr; _methodBase = GCHandle.InternalGet(gchandle); } [DebuggerNonUserCode] private void CtorCollectibleOpened(object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr gchandle) { _target = this; _methodPtr = shuffleThunk; _methodPtrAux = methodPtr; _methodBase = GCHandle.InternalGet(gchandle); } [DebuggerNonUserCode] private void CtorCollectibleVirtualDispatch(object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr gchandle) { _target = this; _methodPtr = shuffleThunk; _methodPtrAux = GetCallStub(methodPtr); _methodBase = GCHandle.InternalGet(gchandle); } } [Serializable] [ClassInterface(ClassInterfaceType.AutoDispatch)] [ComVisible(true)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Object { [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public extern Type GetType(); [Intrinsic] protected unsafe object MemberwiseClone() { object obj = RuntimeHelpers.AllocateUninitializedClone(this); nuint rawObjectDataSize = RuntimeHelpers.GetRawObjectDataSize(obj); ref byte rawData = ref this.GetRawData(); ref byte rawData2 = ref obj.GetRawData(); if (RuntimeHelpers.GetMethodTable(obj)->ContainsGCPointers) { Buffer.BulkMoveWithWriteBarrier(ref rawData2, ref rawData, rawObjectDataSize); } else { Buffer.Memmove(ref rawData2, ref rawData, rawObjectDataSize); } return obj; } [NonVersionable] public Object() { } [NonVersionable] ~Object() { } public virtual string? ToString() { return GetType().ToString(); } public virtual bool Equals(object? obj) { return RuntimeHelpers.Equals(this, obj); } public static bool Equals(object? objA, object? objB) { if (objA == objB) { return true; } if (objA == null || objB == null) { return false; } return objA.Equals(objB); } [NonVersionable] public static bool ReferenceEquals(object? objA, object? objB) { return objA == objB; } public virtual int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } } public ref struct RuntimeArgumentHandle { private IntPtr m_ptr; internal IntPtr Value => m_ptr; } [NonVersionable] public struct RuntimeTypeHandle : ISerializable { internal struct IntroducedMethodEnumerator { private bool _firstCall; private RuntimeMethodHandleInternal _handle; public RuntimeMethodHandleInternal Current => _handle; internal IntroducedMethodEnumerator(RuntimeType type) { _handle = GetFirstIntroducedMethod(type); _firstCall = true; } public bool MoveNext() { if (_firstCall) { _firstCall = false; } else if (_handle.Value != IntPtr.Zero) { GetNextIntroducedMethod(ref _handle); } return !(_handle.Value == IntPtr.Zero); } public IntroducedMethodEnumerator GetEnumerator() { return this; } } internal RuntimeType m_type; public IntPtr Value { get { if (!(m_type != null)) { return IntPtr.Zero; } return m_type.m_handle; } } internal RuntimeTypeHandle GetNativeHandle() { RuntimeType type = m_type; if (type == null) { throw new ArgumentNullException(null, SR.Arg_InvalidHandle); } return new RuntimeTypeHandle(type); } internal RuntimeType GetTypeChecked() { RuntimeType type = m_type; if (type == null) { throw new ArgumentNullException(null, SR.Arg_InvalidHandle); } return type; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsInstanceOfType(RuntimeType type, [NotNullWhen(true)] object o); [RequiresUnreferencedCode("MakeGenericType cannot be statically analyzed. It's not possible to guarantee the availability of requirements of the generic type.")] internal unsafe static Type GetTypeHelper(Type typeStart, Type[] genericArgs, IntPtr pModifiers, int cModifiers) { Type type = typeStart; if (genericArgs != null) { type = type.MakeGenericType(genericArgs); } if (cModifiers > 0) { int* ptr = (int*)pModifiers.ToPointer(); for (int i = 0; i < cModifiers; i++) { type = (((byte)Marshal.ReadInt32((IntPtr)ptr, i * 4) != 15) ? (((byte)Marshal.ReadInt32((IntPtr)ptr, i * 4) != 16) ? (((byte)Marshal.ReadInt32((IntPtr)ptr, i * 4) != 29) ? type.MakeArrayType(Marshal.ReadInt32((IntPtr)ptr, ++i * 4)) : type.MakeArrayType()) : type.MakeByRefType()) : type.MakePointerType()); } } return type; } public static bool operator ==(RuntimeTypeHandle left, object? right) { return left.Equals(right); } public static bool operator ==(object? left, RuntimeTypeHandle right) { return right.Equals(left); } public static bool operator !=(RuntimeTypeHandle left, object? right) { return !left.Equals(right); } public static bool operator !=(object? left, RuntimeTypeHandle right) { return !right.Equals(left); } public override int GetHashCode() { if (!(m_type != null)) { return 0; } return m_type.GetHashCode(); } public override bool Equals(object? obj) { if (!(obj is RuntimeTypeHandle runtimeTypeHandle)) { return false; } return runtimeTypeHandle.m_type == m_type; } public bool Equals(RuntimeTypeHandle handle) { return handle.m_type == m_type; } [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] internal static extern IntPtr GetValueInternal(RuntimeTypeHandle handle); internal RuntimeTypeHandle(RuntimeType type) { m_type = type; } internal static bool IsTypeDefinition(RuntimeType type) { CorElementType corElementType = GetCorElementType(type); if (((int)corElementType < 1 || (int)corElementType >= 15) && corElementType != CorElementType.ELEMENT_TYPE_VALUETYPE && corElementType != CorElementType.ELEMENT_TYPE_CLASS && corElementType != CorElementType.ELEMENT_TYPE_TYPEDBYREF && corElementType != CorElementType.ELEMENT_TYPE_I && corElementType != CorElementType.ELEMENT_TYPE_U && corElementType != CorElementType.ELEMENT_TYPE_OBJECT) { return false; } if (HasInstantiation(type) && !IsGenericTypeDefinition(type)) { return false; } return true; } internal static bool IsPrimitive(RuntimeType type) { return GetCorElementType(type).IsPrimitiveType(); } internal static bool IsByRef(RuntimeType type) { CorElementType corElementType = GetCorElementType(type); return corElementType == CorElementType.ELEMENT_TYPE_BYREF; } internal static bool IsPointer(RuntimeType type) { CorElementType corElementType = GetCorElementType(type); return corElementType == CorElementType.ELEMENT_TYPE_PTR; } internal static bool IsArray(RuntimeType type) { CorElementType corElementType = GetCorElementType(type); if (corElementType != CorElementType.ELEMENT_TYPE_ARRAY) { return corElementType == CorElementType.ELEMENT_TYPE_SZARRAY; } return true; } internal static bool IsSZArray(RuntimeType type) { CorElementType corElementType = GetCorElementType(type); return corElementType == CorElementType.ELEMENT_TYPE_SZARRAY; } internal static bool HasElementType(RuntimeType type) { CorElementType corElementType = GetCorElementType(type); if (corElementType != CorElementType.ELEMENT_TYPE_ARRAY && corElementType != CorElementType.ELEMENT_TYPE_SZARRAY && corElementType != CorElementType.ELEMENT_TYPE_PTR) { return corElementType == CorElementType.ELEMENT_TYPE_BYREF; } return true; } internal static IntPtr[] CopyRuntimeTypeHandles(RuntimeTypeHandle[] inHandles, out int length) { if (inHandles == null || inHandles.Length == 0) { length = 0; return null; } IntPtr[] array = new IntPtr[inHandles.Length]; for (int i = 0; i < inHandles.Length; i++) { array[i] = inHandles[i].Value; } length = array.Length; return array; } internal static IntPtr[] CopyRuntimeTypeHandles(Type[] inHandles, out int length) { if (inHandles == null || inHandles.Length == 0) { length = 0; return null; } IntPtr[] array = new IntPtr[inHandles.Length]; for (int i = 0; i < inHandles.Length; i++) { array[i] = inHandles[i].GetTypeHandleInternal().Value; } length = array.Length; return array; } internal unsafe static object CreateInstanceForAnotherGenericParameter([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] RuntimeType type, RuntimeType genericParameter) { object o = null; IntPtr value = genericParameter.GetTypeHandleInternal().Value; CreateInstanceForAnotherGenericParameter(new QCallTypeHandle(ref type), &value, 1, ObjectHandleOnStack.Create(ref o)); GC.KeepAlive(genericParameter); return o; } internal unsafe static object CreateInstanceForAnotherGenericParameter([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] RuntimeType type, RuntimeType genericParameter1, RuntimeType genericParameter2) { object o = null; IntPtr* pTypeHandles = stackalloc IntPtr[2] { genericParameter1.GetTypeHandleInternal().Value, genericParameter2.GetTypeHandleInternal().Value }; CreateInstanceForAnotherGenericParameter(new QCallTypeHandle(ref type), pTypeHandles, 2, ObjectHandleOnStack.Create(ref o)); GC.KeepAlive(genericParameter1); GC.KeepAlive(genericParameter2); return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] private unsafe static extern void CreateInstanceForAnotherGenericParameter(QCallTypeHandle baseType, IntPtr* pTypeHandles, int cTypeHandles, ObjectHandleOnStack instantiatedObject); internal unsafe static void GetActivationInfo(RuntimeType rt, out delegate* pfnAllocator, out void* vAllocatorFirstArg, out delegate* pfnCtor, out bool ctorIsPublic) { delegate* delegate* = default(delegate*); void* ptr = default(void*); delegate* delegate*2 = default(delegate*); Interop.BOOL bOOL = Interop.BOOL.FALSE; GetActivationInfo(ObjectHandleOnStack.Create(ref rt), &delegate*, &ptr, &delegate*2, &bOOL); System.Runtime.CompilerServices.Unsafe.As, IntPtr>(ref pfnAllocator) = (nint)delegate*; vAllocatorFirstArg = ptr; System.Runtime.CompilerServices.Unsafe.As, IntPtr>(ref pfnCtor) = (nint)delegate*2; ctorIsPublic = bOOL != Interop.BOOL.FALSE; } [DllImport("QCall", CharSet = CharSet.Unicode)] private unsafe static extern void GetActivationInfo(ObjectHandleOnStack pRuntimeType, delegate** ppfnAllocator, void** pvAllocatorFirstArg, delegate** ppfnCtor, Interop.BOOL* pfCtorIsPublic); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern object AllocateComObject(void* pClassFactory); internal RuntimeType GetRuntimeType() { return m_type; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern CorElementType GetCorElementType(RuntimeType type); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeAssembly GetAssembly(RuntimeType type); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeModule GetModule(RuntimeType type); public ModuleHandle GetModuleHandle() { return new ModuleHandle(GetModule(m_type)); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeType GetBaseType(RuntimeType type); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern TypeAttributes GetAttributes(RuntimeType type); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeType GetElementType(RuntimeType type); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool CompareCanonicalHandles(RuntimeType left, RuntimeType right); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetArrayRank(RuntimeType type); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetToken(RuntimeType type); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeMethodHandleInternal GetMethodAt(RuntimeType type, int slot); internal static IntroducedMethodEnumerator GetIntroducedMethods(RuntimeType type) { return new IntroducedMethodEnumerator(type); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern RuntimeMethodHandleInternal GetFirstIntroducedMethod(RuntimeType type); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetNextIntroducedMethod(ref RuntimeMethodHandleInternal method); [MethodImpl(MethodImplOptions.InternalCall)] internal unsafe static extern bool GetFields(RuntimeType type, IntPtr* result, int* count); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Type[] GetInterfaces(RuntimeType type); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetConstraints(QCallTypeHandle handle, ObjectHandleOnStack types); internal Type[] GetConstraints() { Type[] o = null; RuntimeTypeHandle rth = GetNativeHandle(); GetConstraints(new QCallTypeHandle(ref rth), ObjectHandleOnStack.Create(ref o)); return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern IntPtr GetGCHandle(QCallTypeHandle handle, GCHandleType type); internal IntPtr GetGCHandle(GCHandleType type) { RuntimeTypeHandle rth = GetNativeHandle(); return GetGCHandle(new QCallTypeHandle(ref rth), type); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern IntPtr FreeGCHandle(QCallTypeHandle typeHandle, IntPtr objHandle); internal IntPtr FreeGCHandle(IntPtr objHandle) { RuntimeTypeHandle rth = GetNativeHandle(); return FreeGCHandle(new QCallTypeHandle(ref rth), objHandle); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetNumVirtuals(RuntimeType type); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetNumVirtualsAndStaticVirtuals(RuntimeType type); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void VerifyInterfaceIsImplemented(QCallTypeHandle handle, QCallTypeHandle interfaceHandle); internal void VerifyInterfaceIsImplemented(RuntimeTypeHandle interfaceHandle) { RuntimeTypeHandle rth = GetNativeHandle(); RuntimeTypeHandle rth2 = interfaceHandle.GetNativeHandle(); VerifyInterfaceIsImplemented(new QCallTypeHandle(ref rth), new QCallTypeHandle(ref rth2)); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern RuntimeMethodHandleInternal GetInterfaceMethodImplementation(QCallTypeHandle handle, QCallTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle); internal RuntimeMethodHandleInternal GetInterfaceMethodImplementation(RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle) { RuntimeTypeHandle rth = GetNativeHandle(); RuntimeTypeHandle rth2 = interfaceHandle.GetNativeHandle(); return GetInterfaceMethodImplementation(new QCallTypeHandle(ref rth), new QCallTypeHandle(ref rth2), interfaceMethodHandle); } internal static bool IsComObject(RuntimeType type, bool isGenericCOM) { if (isGenericCOM) { return type.TypeHandle.Value == typeof(__ComObject).TypeHandle.Value; } return CanCastTo(type, (RuntimeType)typeof(__ComObject)); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsInterface(RuntimeType type); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsByRefLike(RuntimeType type); [DllImport("QCall", CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool _IsVisible(QCallTypeHandle typeHandle); internal static bool IsVisible(RuntimeType type) { return _IsVisible(new QCallTypeHandle(ref type)); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsValueType(RuntimeType type); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void ConstructName(QCallTypeHandle handle, TypeNameFormatFlags formatFlags, StringHandleOnStack retString); internal string ConstructName(TypeNameFormatFlags formatFlags) { string s = null; RuntimeTypeHandle rth = GetNativeHandle(); ConstructName(new QCallTypeHandle(ref rth), formatFlags, new StringHandleOnStack(ref s)); return s; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void* _GetUtf8Name(RuntimeType type); internal unsafe static MdUtf8String GetUtf8Name(RuntimeType type) { return new MdUtf8String(_GetUtf8Name(type)); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool CanCastTo(RuntimeType type, RuntimeType target); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeType GetDeclaringType(RuntimeType type); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IRuntimeMethodInfo GetDeclaringMethod(RuntimeType type); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetTypeByName(string name, bool throwOnError, bool ignoreCase, StackCrawlMarkHandle stackMark, ObjectHandleOnStack assemblyLoadContext, ObjectHandleOnStack type, ObjectHandleOnStack keepalive); internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { return GetTypeByName(name, throwOnError, ignoreCase, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext); } internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark, AssemblyLoadContext assemblyLoadContext) { if (string.IsNullOrEmpty(name)) { if (throwOnError) { throw new TypeLoadException(SR.Arg_TypeLoadNullStr); } return null; } RuntimeType o = null; object o2 = null; AssemblyLoadContext o3 = assemblyLoadContext; GetTypeByName(name, throwOnError, ignoreCase, new StackCrawlMarkHandle(ref stackMark), ObjectHandleOnStack.Create(ref o3), ObjectHandleOnStack.Create(ref o), ObjectHandleOnStack.Create(ref o2)); GC.KeepAlive(o2); return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetTypeByNameUsingCARules(string name, QCallModule scope, ObjectHandleOnStack type); internal static RuntimeType GetTypeByNameUsingCARules(string name, RuntimeModule scope) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException(null, "name"); } RuntimeType o = null; GetTypeByNameUsingCARules(name, new QCallModule(ref scope), ObjectHandleOnStack.Create(ref o)); return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern void GetInstantiation(QCallTypeHandle type, ObjectHandleOnStack types, Interop.BOOL fAsRuntimeTypeArray); internal RuntimeType[] GetInstantiationInternal() { RuntimeType[] o = null; RuntimeTypeHandle rth = GetNativeHandle(); GetInstantiation(new QCallTypeHandle(ref rth), ObjectHandleOnStack.Create(ref o), Interop.BOOL.TRUE); return o; } internal Type[] GetInstantiationPublic() { Type[] o = null; RuntimeTypeHandle rth = GetNativeHandle(); GetInstantiation(new QCallTypeHandle(ref rth), ObjectHandleOnStack.Create(ref o), Interop.BOOL.FALSE); return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] private unsafe static extern void Instantiate(QCallTypeHandle handle, IntPtr* pInst, int numGenericArgs, ObjectHandleOnStack type); internal unsafe RuntimeType Instantiate(RuntimeType inst) { IntPtr value = inst.TypeHandle.Value; RuntimeType o = null; RuntimeTypeHandle rth = GetNativeHandle(); Instantiate(new QCallTypeHandle(ref rth), &value, 1, ObjectHandleOnStack.Create(ref o)); GC.KeepAlive(inst); return o; } internal unsafe RuntimeType Instantiate(Type[] inst) { int length; fixed (IntPtr* pInst = CopyRuntimeTypeHandles(inst, out length)) { RuntimeType o = null; RuntimeTypeHandle rth = GetNativeHandle(); Instantiate(new QCallTypeHandle(ref rth), pInst, length, ObjectHandleOnStack.Create(ref o)); GC.KeepAlive(inst); return o; } } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void MakeArray(QCallTypeHandle handle, int rank, ObjectHandleOnStack type); internal RuntimeType MakeArray(int rank) { RuntimeType o = null; RuntimeTypeHandle rth = GetNativeHandle(); MakeArray(new QCallTypeHandle(ref rth), rank, ObjectHandleOnStack.Create(ref o)); return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void MakeSZArray(QCallTypeHandle handle, ObjectHandleOnStack type); internal RuntimeType MakeSZArray() { RuntimeType o = null; RuntimeTypeHandle rth = GetNativeHandle(); MakeSZArray(new QCallTypeHandle(ref rth), ObjectHandleOnStack.Create(ref o)); return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void MakeByRef(QCallTypeHandle handle, ObjectHandleOnStack type); internal RuntimeType MakeByRef() { RuntimeType o = null; RuntimeTypeHandle rth = GetNativeHandle(); MakeByRef(new QCallTypeHandle(ref rth), ObjectHandleOnStack.Create(ref o)); return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void MakePointer(QCallTypeHandle handle, ObjectHandleOnStack type); internal RuntimeType MakePointer() { RuntimeType o = null; RuntimeTypeHandle rth = GetNativeHandle(); MakePointer(new QCallTypeHandle(ref rth), ObjectHandleOnStack.Create(ref o)); return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern Interop.BOOL IsCollectible(QCallTypeHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool HasInstantiation(RuntimeType type); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetGenericTypeDefinition(QCallTypeHandle type, ObjectHandleOnStack retType); internal static RuntimeType GetGenericTypeDefinition(RuntimeType type) { RuntimeType o = type; if (HasInstantiation(o) && !IsGenericTypeDefinition(o)) { RuntimeTypeHandle rth = o.GetTypeHandleInternal(); GetGenericTypeDefinition(new QCallTypeHandle(ref rth), ObjectHandleOnStack.Create(ref o)); } return o; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsGenericTypeDefinition(RuntimeType type); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsGenericVariable(RuntimeType type); [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetGenericVariableIndex(RuntimeType type); internal int GetGenericVariableIndex() { RuntimeType typeChecked = GetTypeChecked(); if (!IsGenericVariable(typeChecked)) { throw new InvalidOperationException(SR.Arg_NotGenericParameter); } return GetGenericVariableIndex(typeChecked); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool ContainsGenericVariables(RuntimeType handle); internal bool ContainsGenericVariables() { return ContainsGenericVariables(GetTypeChecked()); } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern bool SatisfiesConstraints(RuntimeType paramType, IntPtr* pTypeContext, int typeContextLength, IntPtr* pMethodContext, int methodContextLength, RuntimeType toType); internal unsafe static bool SatisfiesConstraints(RuntimeType paramType, RuntimeType[] typeContext, RuntimeType[] methodContext, RuntimeType toType) { Type[] inHandles = typeContext; int length; IntPtr[] array = CopyRuntimeTypeHandles(inHandles, out length); inHandles = methodContext; int length2; IntPtr[] array2 = CopyRuntimeTypeHandles(inHandles, out length2); fixed (IntPtr* pTypeContext = array) { fixed (IntPtr* pMethodContext = array2) { bool result = SatisfiesConstraints(paramType, pTypeContext, length, pMethodContext, length2, toType); GC.KeepAlive(typeContext); GC.KeepAlive(methodContext); return result; } } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr _GetMetadataImport(RuntimeType type); internal static MetadataImport GetMetadataImport(RuntimeType type) { return new MetadataImport(_GetMetadataImport(type), type); } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsEquivalentTo(RuntimeType rtType1, RuntimeType rtType2); } internal struct RuntimeMethodHandleInternal { internal IntPtr m_handle; internal static RuntimeMethodHandleInternal EmptyHandle => default(RuntimeMethodHandleInternal); internal IntPtr Value => m_handle; internal bool IsNullHandle() { return m_handle == IntPtr.Zero; } internal RuntimeMethodHandleInternal(IntPtr value) { m_handle = value; } } internal sealed class RuntimeMethodInfoStub : IRuntimeMethodInfo { private readonly object m_keepalive; private object m_a; private object m_b; private object m_c; private object m_d; private object m_e; private object m_f; private object m_g; public RuntimeMethodHandleInternal m_value; RuntimeMethodHandleInternal IRuntimeMethodInfo.Value => m_value; public RuntimeMethodInfoStub(RuntimeMethodHandleInternal methodHandleValue, object keepalive) { m_keepalive = keepalive; m_value = methodHandleValue; } public RuntimeMethodInfoStub(IntPtr methodHandleValue, object keepalive) { m_keepalive = keepalive; m_value = new RuntimeMethodHandleInternal(methodHandleValue); } } internal interface IRuntimeMethodInfo { RuntimeMethodHandleInternal Value { get; } } [NonVersionable] public struct RuntimeMethodHandle : ISerializable { private readonly IRuntimeMethodInfo m_value; public IntPtr Value { get { if (m_value == null) { return IntPtr.Zero; } return m_value.Value.Value; } } internal static IRuntimeMethodInfo EnsureNonNullMethodInfo(IRuntimeMethodInfo method) { if (method == null) { throw new ArgumentNullException(null, SR.Arg_InvalidHandle); } return method; } internal RuntimeMethodHandle(IRuntimeMethodInfo method) { m_value = method; } internal IRuntimeMethodInfo GetMethodInfo() { return m_value; } private static IntPtr GetValueInternal(RuntimeMethodHandle rmh) { return rmh.Value; } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public override int GetHashCode() { return ValueType.GetHashCodeOfPtr(Value); } public override bool Equals(object? obj) { if (!(obj is RuntimeMethodHandle runtimeMethodHandle)) { return false; } return runtimeMethodHandle.Value == Value; } public static bool operator ==(RuntimeMethodHandle left, RuntimeMethodHandle right) { return left.Equals(right); } public static bool operator !=(RuntimeMethodHandle left, RuntimeMethodHandle right) { return !left.Equals(right); } public bool Equals(RuntimeMethodHandle handle) { return handle.Value == Value; } internal bool IsNullHandle() { return m_value == null; } [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern IntPtr GetFunctionPointer(RuntimeMethodHandleInternal handle); public IntPtr GetFunctionPointer() { IntPtr functionPointer = GetFunctionPointer(EnsureNonNullMethodInfo(m_value).Value); GC.KeepAlive(m_value); return functionPointer; } [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern Interop.BOOL GetIsCollectible(RuntimeMethodHandleInternal handle); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern Interop.BOOL IsCAVisibleFromDecoratedType(QCallTypeHandle attrTypeHandle, RuntimeMethodHandleInternal attrCtor, QCallTypeHandle sourceTypeHandle, QCallModule sourceModule); [MethodImpl(MethodImplOptions.InternalCall)] private static extern IRuntimeMethodInfo _GetCurrentMethod(ref StackCrawlMark stackMark); internal static IRuntimeMethodInfo GetCurrentMethod(ref StackCrawlMark stackMark) { return _GetCurrentMethod(ref stackMark); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern MethodAttributes GetAttributes(RuntimeMethodHandleInternal method); internal static MethodAttributes GetAttributes(IRuntimeMethodInfo method) { MethodAttributes attributes = GetAttributes(method.Value); GC.KeepAlive(method); return attributes; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern MethodImplAttributes GetImplAttributes(IRuntimeMethodInfo method); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void ConstructInstantiation(RuntimeMethodHandleInternal method, TypeNameFormatFlags format, StringHandleOnStack retString); internal static string ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format) { string s = null; IRuntimeMethodInfo runtimeMethodInfo = EnsureNonNullMethodInfo(method); ConstructInstantiation(runtimeMethodInfo.Value, format, new StringHandleOnStack(ref s)); GC.KeepAlive(runtimeMethodInfo); return s; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeType GetDeclaringType(RuntimeMethodHandleInternal method); internal static RuntimeType GetDeclaringType(IRuntimeMethodInfo method) { RuntimeType declaringType = GetDeclaringType(method.Value); GC.KeepAlive(method); return declaringType; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetSlot(RuntimeMethodHandleInternal method); internal static int GetSlot(IRuntimeMethodInfo method) { int slot = GetSlot(method.Value); GC.KeepAlive(method); return slot; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetMethodDef(IRuntimeMethodInfo method); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern string GetName(RuntimeMethodHandleInternal method); internal static string GetName(IRuntimeMethodInfo method) { string name = GetName(method.Value); GC.KeepAlive(method); return name; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void* _GetUtf8Name(RuntimeMethodHandleInternal method); internal unsafe static MdUtf8String GetUtf8Name(RuntimeMethodHandleInternal method) { return new MdUtf8String(_GetUtf8Name(method)); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool MatchesNameHash(RuntimeMethodHandleInternal method, uint hash); [MethodImpl(MethodImplOptions.InternalCall)] [DebuggerStepThrough] [DebuggerHidden] internal static extern object InvokeMethod(object target, in Span arguments, Signature sig, bool constructor, bool wrapExceptions); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack types, Interop.BOOL fAsRuntimeTypeArray); internal static RuntimeType[] GetMethodInstantiationInternal(IRuntimeMethodInfo method) { RuntimeType[] o = null; GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, ObjectHandleOnStack.Create(ref o), Interop.BOOL.TRUE); GC.KeepAlive(method); return o; } internal static RuntimeType[] GetMethodInstantiationInternal(RuntimeMethodHandleInternal method) { RuntimeType[] o = null; GetMethodInstantiation(method, ObjectHandleOnStack.Create(ref o), Interop.BOOL.TRUE); return o; } internal static Type[] GetMethodInstantiationPublic(IRuntimeMethodInfo method) { RuntimeType[] o = null; GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, ObjectHandleOnStack.Create(ref o), Interop.BOOL.FALSE); GC.KeepAlive(method); return o; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool HasMethodInstantiation(RuntimeMethodHandleInternal method); internal static bool HasMethodInstantiation(IRuntimeMethodInfo method) { bool result = HasMethodInstantiation(method.Value); GC.KeepAlive(method); return result; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeMethodHandleInternal GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[] methodInstantiation); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeMethodHandleInternal GetMethodFromCanonical(RuntimeMethodHandleInternal method, RuntimeType declaringType); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsGenericMethodDefinition(RuntimeMethodHandleInternal method); internal static bool IsGenericMethodDefinition(IRuntimeMethodInfo method) { bool result = IsGenericMethodDefinition(method.Value); GC.KeepAlive(method); return result; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsTypicalMethodDefinition(IRuntimeMethodInfo method); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetTypicalMethodDefinition(RuntimeMethodHandleInternal method, ObjectHandleOnStack outMethod); internal static IRuntimeMethodInfo GetTypicalMethodDefinition(IRuntimeMethodInfo method) { if (!IsTypicalMethodDefinition(method)) { GetTypicalMethodDefinition(method.Value, ObjectHandleOnStack.Create(ref method)); GC.KeepAlive(method); } return method; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetGenericParameterCount(RuntimeMethodHandleInternal method); internal static int GetGenericParameterCount(IRuntimeMethodInfo method) { return GetGenericParameterCount(method.Value); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void StripMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack outMethod); internal static IRuntimeMethodInfo StripMethodInstantiation(IRuntimeMethodInfo method) { IRuntimeMethodInfo o = method; StripMethodInstantiation(method.Value, ObjectHandleOnStack.Create(ref o)); GC.KeepAlive(method); return o; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsDynamicMethod(RuntimeMethodHandleInternal method); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern void Destroy(RuntimeMethodHandleInternal method); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Resolver GetResolver(RuntimeMethodHandleInternal method); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeMethodBody GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsConstructor(RuntimeMethodHandleInternal method); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern LoaderAllocator GetLoaderAllocator(RuntimeMethodHandleInternal method); } internal struct RuntimeFieldHandleInternal { internal IntPtr m_handle; internal IntPtr Value => m_handle; internal RuntimeFieldHandleInternal(IntPtr value) { m_handle = value; } } internal interface IRuntimeFieldInfo { RuntimeFieldHandleInternal Value { get; } } [StructLayout(LayoutKind.Sequential)] internal sealed class RuntimeFieldInfoStub : IRuntimeFieldInfo { private object m_keepalive; private object m_c; private object m_d; private int m_b; private object m_e; private RuntimeFieldHandleInternal m_fieldHandle; RuntimeFieldHandleInternal IRuntimeFieldInfo.Value => m_fieldHandle; } [NonVersionable] public struct RuntimeFieldHandle : ISerializable { private readonly IRuntimeFieldInfo m_ptr; public IntPtr Value { get { if (m_ptr == null) { return IntPtr.Zero; } return m_ptr.Value.Value; } } internal RuntimeFieldHandle(IRuntimeFieldInfo fieldInfo) { m_ptr = fieldInfo; } internal IRuntimeFieldInfo GetRuntimeFieldInfo() { return m_ptr; } internal bool IsNullHandle() { return m_ptr == null; } public override int GetHashCode() { return ValueType.GetHashCodeOfPtr(Value); } public override bool Equals(object? obj) { if (!(obj is RuntimeFieldHandle runtimeFieldHandle)) { return false; } return runtimeFieldHandle.Value == Value; } public bool Equals(RuntimeFieldHandle handle) { return handle.Value == Value; } public static bool operator ==(RuntimeFieldHandle left, RuntimeFieldHandle right) { return left.Equals(right); } public static bool operator !=(RuntimeFieldHandle left, RuntimeFieldHandle right) { return !left.Equals(right); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern string GetName(RtFieldInfo field); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void* _GetUtf8Name(RuntimeFieldHandleInternal field); internal unsafe static MdUtf8String GetUtf8Name(RuntimeFieldHandleInternal field) { return new MdUtf8String(_GetUtf8Name(field)); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool MatchesNameHash(RuntimeFieldHandleInternal handle, uint hash); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern FieldAttributes GetAttributes(RuntimeFieldHandleInternal field); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeType GetApproxDeclaringType(RuntimeFieldHandleInternal field); internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field) { RuntimeType approxDeclaringType = GetApproxDeclaringType(field.Value); GC.KeepAlive(field); return approxDeclaringType; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetToken(RtFieldInfo field); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern object GetValue(RtFieldInfo field, object instance, RuntimeType fieldType, RuntimeType declaringType, ref bool domainInitialized); [MethodImpl(MethodImplOptions.InternalCall)] internal unsafe static extern object GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, RuntimeType contextType); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void SetValue(RtFieldInfo field, object obj, object value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType declaringType, ref bool domainInitialized); [MethodImpl(MethodImplOptions.InternalCall)] internal unsafe static extern void SetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, object value, RuntimeType contextType); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeFieldHandleInternal GetStaticFieldForGenericType(RuntimeFieldHandleInternal field, RuntimeType declaringType); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool AcquiresContextFromThis(RuntimeFieldHandleInternal field); public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } } public struct ModuleHandle { public static readonly ModuleHandle EmptyHandle; private readonly RuntimeModule m_ptr; public int MDStreamVersion => GetMDStreamVersion(GetRuntimeModule()); internal ModuleHandle(RuntimeModule module) { m_ptr = module; } internal RuntimeModule GetRuntimeModule() { return m_ptr; } public override int GetHashCode() { if (!(m_ptr != null)) { return 0; } return m_ptr.GetHashCode(); } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is ModuleHandle moduleHandle)) { return false; } return moduleHandle.m_ptr == m_ptr; } public bool Equals(ModuleHandle handle) { return handle.m_ptr == m_ptr; } public static bool operator ==(ModuleHandle left, ModuleHandle right) { return left.Equals(right); } public static bool operator !=(ModuleHandle left, ModuleHandle right) { return !left.Equals(right); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IRuntimeMethodInfo GetDynamicMethod(DynamicMethod method, RuntimeModule module, string name, byte[] sig, Resolver resolver); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetToken(RuntimeModule module); private static void ValidateModulePointer(RuntimeModule module) { if ((object)module == null) { ThrowInvalidOperationException(); } [StackTraceHidden] [DoesNotReturn] static void ThrowInvalidOperationException() { throw new InvalidOperationException(SR.InvalidOperation_NullModuleHandle); } } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public RuntimeTypeHandle GetRuntimeTypeHandleFromMetadataToken(int typeToken) { return ResolveTypeHandle(typeToken); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public RuntimeTypeHandle ResolveTypeHandle(int typeToken) { return ResolveTypeHandle(typeToken, null, null); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public unsafe RuntimeTypeHandle ResolveTypeHandle(int typeToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext) { RuntimeModule module = GetRuntimeModule(); ValidateModulePointer(module); IntPtr[] array = null; int length = 0; IntPtr[] array2 = null; int length2 = 0; if (typeInstantiationContext != null && typeInstantiationContext.Length != 0) { typeInstantiationContext = (RuntimeTypeHandle[])typeInstantiationContext.Clone(); array = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out length); } if (methodInstantiationContext != null && methodInstantiationContext.Length != 0) { methodInstantiationContext = (RuntimeTypeHandle[])methodInstantiationContext.Clone(); array2 = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out length2); } fixed (IntPtr* typeInstArgs = array) { fixed (IntPtr* methodInstArgs = array2) { try { RuntimeType o = null; ResolveType(new QCallModule(ref module), typeToken, typeInstArgs, length, methodInstArgs, length2, ObjectHandleOnStack.Create(ref o)); GC.KeepAlive(typeInstantiationContext); GC.KeepAlive(methodInstantiationContext); return new RuntimeTypeHandle(o); } catch (Exception) { if (!GetMetadataImport(module).IsValidToken(typeToken)) { throw new ArgumentOutOfRangeException("typeToken", SR.Format(SR.Argument_InvalidToken, typeToken, new ModuleHandle(module))); } throw; } } } } [DllImport("QCall", CharSet = CharSet.Unicode)] private unsafe static extern void ResolveType(QCallModule module, int typeToken, IntPtr* typeInstArgs, int typeInstCount, IntPtr* methodInstArgs, int methodInstCount, ObjectHandleOnStack type); [RequiresUnreferencedCode("Trimming changes metadata tokens")] public RuntimeMethodHandle GetRuntimeMethodHandleFromMetadataToken(int methodToken) { return ResolveMethodHandle(methodToken); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public RuntimeMethodHandle ResolveMethodHandle(int methodToken) { return ResolveMethodHandle(methodToken, null, null); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public RuntimeMethodHandle ResolveMethodHandle(int methodToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext) { RuntimeModule runtimeModule = GetRuntimeModule(); typeInstantiationContext = (RuntimeTypeHandle[])typeInstantiationContext?.Clone(); methodInstantiationContext = (RuntimeTypeHandle[])methodInstantiationContext?.Clone(); int length; IntPtr[] typeInstantiationContext2 = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out length); int length2; IntPtr[] methodInstantiationContext2 = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out length2); RuntimeMethodHandleInternal runtimeMethodHandleInternal = ResolveMethodHandleInternal(runtimeModule, methodToken, typeInstantiationContext2, length, methodInstantiationContext2, length2); IRuntimeMethodInfo method = new RuntimeMethodInfoStub(runtimeMethodHandleInternal, RuntimeMethodHandle.GetLoaderAllocator(runtimeMethodHandleInternal)); GC.KeepAlive(typeInstantiationContext); GC.KeepAlive(methodInstantiationContext); return new RuntimeMethodHandle(method); } internal unsafe static RuntimeMethodHandleInternal ResolveMethodHandleInternal(RuntimeModule module, int methodToken, IntPtr[] typeInstantiationContext, int typeInstCount, IntPtr[] methodInstantiationContext, int methodInstCount) { ValidateModulePointer(module); try { fixed (IntPtr* typeInstArgs = typeInstantiationContext) { fixed (IntPtr* methodInstArgs = methodInstantiationContext) { return ResolveMethod(new QCallModule(ref module), methodToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount); } } } catch (Exception) { if (!GetMetadataImport(module).IsValidToken(methodToken)) { throw new ArgumentOutOfRangeException("methodToken", SR.Format(SR.Argument_InvalidToken, methodToken, new ModuleHandle(module))); } throw; } } [DllImport("QCall", CharSet = CharSet.Unicode)] private unsafe static extern RuntimeMethodHandleInternal ResolveMethod(QCallModule module, int methodToken, IntPtr* typeInstArgs, int typeInstCount, IntPtr* methodInstArgs, int methodInstCount); [RequiresUnreferencedCode("Trimming changes metadata tokens")] public RuntimeFieldHandle GetRuntimeFieldHandleFromMetadataToken(int fieldToken) { return ResolveFieldHandle(fieldToken); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public RuntimeFieldHandle ResolveFieldHandle(int fieldToken) { return ResolveFieldHandle(fieldToken, null, null); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public unsafe RuntimeFieldHandle ResolveFieldHandle(int fieldToken, RuntimeTypeHandle[]? typeInstantiationContext, RuntimeTypeHandle[]? methodInstantiationContext) { RuntimeModule module = GetRuntimeModule(); ValidateModulePointer(module); IntPtr[] array = null; int length = 0; IntPtr[] array2 = null; int length2 = 0; if (typeInstantiationContext != null && typeInstantiationContext.Length != 0) { typeInstantiationContext = (RuntimeTypeHandle[])typeInstantiationContext.Clone(); array = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out length); } if (methodInstantiationContext != null && methodInstantiationContext.Length != 0) { methodInstantiationContext = (RuntimeTypeHandle[])methodInstantiationContext.Clone(); array2 = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out length2); } fixed (IntPtr* typeInstArgs = array) { fixed (IntPtr* methodInstArgs = array2) { try { IRuntimeFieldInfo o = null; ResolveField(new QCallModule(ref module), fieldToken, typeInstArgs, length, methodInstArgs, length2, ObjectHandleOnStack.Create(ref o)); GC.KeepAlive(typeInstantiationContext); GC.KeepAlive(methodInstantiationContext); return new RuntimeFieldHandle(o); } catch (Exception) { if (!GetMetadataImport(module).IsValidToken(fieldToken)) { throw new ArgumentOutOfRangeException("fieldToken", SR.Format(SR.Argument_InvalidToken, fieldToken, new ModuleHandle(module))); } throw; } } } } [DllImport("QCall", CharSet = CharSet.Unicode)] private unsafe static extern void ResolveField(QCallModule module, int fieldToken, IntPtr* typeInstArgs, int typeInstCount, IntPtr* methodInstArgs, int methodInstCount, ObjectHandleOnStack retField); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern Interop.BOOL _ContainsPropertyMatchingHash(QCallModule module, int propertyToken, uint hash); internal static bool ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash) { return _ContainsPropertyMatchingHash(new QCallModule(ref module), propertyToken, hash) != Interop.BOOL.FALSE; } [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern void GetModuleType(QCallModule handle, ObjectHandleOnStack type); internal static RuntimeType GetModuleType(RuntimeModule module) { RuntimeType o = null; GetModuleType(new QCallModule(ref module), ObjectHandleOnStack.Create(ref o)); return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] private unsafe static extern void GetPEKind(QCallModule handle, int* peKind, int* machine); internal unsafe static void GetPEKind(RuntimeModule module, out PortableExecutableKinds peKind, out ImageFileMachine machine) { System.Runtime.CompilerServices.Unsafe.SkipInit(out int num); System.Runtime.CompilerServices.Unsafe.SkipInit(out int num2); GetPEKind(new QCallModule(ref module), &num, &num2); peKind = (PortableExecutableKinds)num; machine = (ImageFileMachine)num2; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetMDStreamVersion(RuntimeModule module); [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr _GetMetadataImport(RuntimeModule module); internal static MetadataImport GetMetadataImport(RuntimeModule module) { return new MetadataImport(_GetMetadataImport(module), module); } } internal class Signature { internal RuntimeType[] m_arguments; internal RuntimeType m_declaringType; internal RuntimeType m_returnTypeORfieldType; internal object m_keepalive; internal unsafe void* m_sig; internal int m_managedCallingConventionAndArgIteratorFlags; internal int m_nSizeOfArgStack; internal int m_csig; internal RuntimeMethodHandleInternal m_pMethod; internal CallingConventions CallingConvention => (CallingConventions)(byte)m_managedCallingConventionAndArgIteratorFlags; internal RuntimeType[] Arguments => m_arguments; internal RuntimeType ReturnType => m_returnTypeORfieldType; internal RuntimeType FieldType => m_returnTypeORfieldType; [MethodImpl(MethodImplOptions.InternalCall)] [MemberNotNull("m_arguments")] [MemberNotNull("m_returnTypeORfieldType")] private unsafe extern void GetSignature(void* pCorSig, int cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType); public unsafe Signature(IRuntimeMethodInfo method, RuntimeType[] arguments, RuntimeType returnType, CallingConventions callingConvention) { m_pMethod = method.Value; m_arguments = arguments; m_returnTypeORfieldType = returnType; m_managedCallingConventionAndArgIteratorFlags = (byte)callingConvention; GetSignature(null, 0, default(RuntimeFieldHandleInternal), method, null); } public unsafe Signature(IRuntimeMethodInfo methodHandle, RuntimeType declaringType) { GetSignature(null, 0, default(RuntimeFieldHandleInternal), methodHandle, declaringType); } public unsafe Signature(IRuntimeFieldInfo fieldHandle, RuntimeType declaringType) { GetSignature(null, 0, fieldHandle.Value, null, declaringType); GC.KeepAlive(fieldHandle); } public unsafe Signature(void* pCorSig, int cCorSig, RuntimeType declaringType) { GetSignature(pCorSig, cCorSig, default(RuntimeFieldHandleInternal), null, declaringType); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool CompareSig(Signature sig1, Signature sig2); [MethodImpl(MethodImplOptions.InternalCall)] internal extern Type[] GetCustomModifiers(int position, bool required); } internal abstract class Resolver { internal struct CORINFO_EH_CLAUSE { internal int Flags; internal int TryOffset; internal int TryLength; internal int HandlerOffset; internal int HandlerLength; internal int ClassTokenOrFilterOffset; } internal abstract RuntimeType GetJitContext(out int securityControlFlags); internal abstract byte[] GetCodeInfo(out int stackSize, out int initLocals, out int EHCount); internal abstract byte[] GetLocalsSignature(); internal unsafe abstract void GetEHInfo(int EHNumber, void* exception); internal abstract byte[] GetRawEHInfo(); internal abstract string GetStringLiteral(int token); internal abstract void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle); internal abstract byte[] ResolveSignature(int token, int fromMethod); internal abstract MethodInfo GetDynamicMethod(); } internal sealed class RuntimeType : TypeInfo, ICloneable { private sealed class ActivatorCache { private unsafe readonly delegate* _pfnAllocator; private unsafe readonly void* _allocatorFirstArg; private unsafe readonly delegate* _pfnCtor; private readonly bool _ctorIsPublic; internal bool CtorIsPublic => _ctorIsPublic; internal unsafe ActivatorCache(RuntimeType rt) { rt.CreateInstanceCheckThis(); try { RuntimeTypeHandle.GetActivationInfo(rt, out _pfnAllocator, out _allocatorFirstArg, out _pfnCtor, out _ctorIsPublic); } catch (Exception ex) { string message = SR.Format(SR.Activator_CannotCreateInstance, rt, ex.Message); if (!(ex is ArgumentException)) { if (!(ex is PlatformNotSupportedException)) { if (!(ex is NotSupportedException)) { if (!(ex is MethodAccessException)) { if (!(ex is MissingMethodException)) { if (ex is MemberAccessException) { throw new MemberAccessException(message); } throw; } throw new MissingMethodException(message); } throw new MethodAccessException(message); } throw new NotSupportedException(message); } throw new PlatformNotSupportedException(message); } throw new ArgumentException(message); } if (_pfnAllocator == (delegate*)null) { _pfnAllocator = &ReturnNull; } if (_pfnCtor == (delegate*)null) { _pfnCtor = &CtorNoopStub; } static void CtorNoopStub(object uninitializedObject) { } unsafe static object ReturnNull(void* _) { return null; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe object CreateUninitializedObject(RuntimeType rt) { object result = _pfnAllocator(_allocatorFirstArg); GC.KeepAlive(rt); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe void CallConstructor(object uninitializedObject) { _pfnCtor(uninitializedObject); } } internal enum MemberListType { All, CaseSensitive, CaseInsensitive, HandleToInfo } internal struct ListBuilder where T : class { private T[] _items; private T _item; private int _count; private int _capacity; public T this[int index] { get { if (_items == null) { return _item; } return _items[index]; } } public int Count => _count; public ListBuilder(int capacity) { _items = null; _item = null; _count = 0; _capacity = capacity; } public T[] ToArray() { if (_count == 0) { return Array.Empty(); } if (_count == 1) { return new T[1] { _item }; } Array.Resize(ref _items, _count); _capacity = _count; return _items; } public void CopyTo(object[] array, int index) { if (_count != 0) { if (_count == 1) { array[index] = _item; } else { Array.Copy(_items, 0, array, index, _count); } } } public void Add(T item) { if (_count == 0) { _item = item; } else { if (_count == 1) { if (_capacity < 2) { _capacity = 4; } _items = new T[_capacity]; _items[0] = _item; } else if (_capacity == _count) { int num = 2 * _capacity; Array.Resize(ref _items, num); _capacity = num; } _items[_count] = item; } _count++; } } internal sealed class RuntimeTypeCache { internal enum CacheType { Method, Constructor, Field, Property, Event, Interface, NestedType } private readonly struct Filter { private readonly MdUtf8String m_name; private readonly MemberListType m_listType; private readonly uint m_nameHash; public unsafe Filter(byte* pUtf8Name, int cUtf8Name, MemberListType listType) { m_name = new MdUtf8String(pUtf8Name, cUtf8Name); m_listType = listType; m_nameHash = 0u; if (RequiresStringComparison()) { m_nameHash = m_name.HashCaseInsensitive(); } } public bool Match(MdUtf8String name) { bool result = true; if (m_listType == MemberListType.CaseSensitive) { result = m_name.Equals(name); } else if (m_listType == MemberListType.CaseInsensitive) { result = m_name.EqualsCaseInsensitive(name); } return result; } public bool RequiresStringComparison() { if (m_listType != MemberListType.CaseSensitive) { return m_listType == MemberListType.CaseInsensitive; } return true; } public bool CaseSensitive() { return m_listType == MemberListType.CaseSensitive; } public uint GetHashToMatch() { return m_nameHash; } } private sealed class MemberInfoCache where T : MemberInfo { private CerHashtable m_csMemberInfos; private CerHashtable m_cisMemberInfos; private T[] m_allMembers; private bool m_cacheComplete; private readonly RuntimeTypeCache m_runtimeTypeCache; internal RuntimeType ReflectedType => m_runtimeTypeCache.GetRuntimeType(); internal MemberInfoCache(RuntimeTypeCache runtimeTypeCache) { m_runtimeTypeCache = runtimeTypeCache; } internal MethodBase AddMethod(RuntimeType declaringType, RuntimeMethodHandleInternal method, CacheType cacheType) { T[] allMembers = m_allMembers; if (allMembers != null) { switch (cacheType) { case CacheType.Method: { T[] array2 = allMembers; foreach (T val2 in array2) { if (val2 == null) { break; } if (val2 is RuntimeMethodInfo runtimeMethodInfo && runtimeMethodInfo.MethodHandle.Value == method.Value) { return runtimeMethodInfo; } } break; } case CacheType.Constructor: { T[] array = allMembers; foreach (T val in array) { if (val == null) { break; } if (val is RuntimeConstructorInfo runtimeConstructorInfo && runtimeConstructorInfo.MethodHandle.Value == method.Value) { return runtimeConstructorInfo; } } break; } } } T[] list = null; MethodAttributes attributes = RuntimeMethodHandle.GetAttributes(method); bool isPublic = (attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; bool isStatic = (attributes & MethodAttributes.Static) != 0; bool isInherited = declaringType != ReflectedType; BindingFlags bindingFlags = FilterPreCalculate(isPublic, isInherited, isStatic); switch (cacheType) { case CacheType.Method: list = (T[])(object)new RuntimeMethodInfo[1] { new RuntimeMethodInfo(method, declaringType, m_runtimeTypeCache, attributes, bindingFlags, null) }; break; case CacheType.Constructor: list = (T[])(object)new RuntimeConstructorInfo[1] { new RuntimeConstructorInfo(method, declaringType, m_runtimeTypeCache, attributes, bindingFlags) }; break; } Insert(ref list, null, MemberListType.HandleToInfo); return (MethodBase)(object)list[0]; } internal FieldInfo AddField(RuntimeFieldHandleInternal field) { T[] allMembers = m_allMembers; if (allMembers != null) { T[] array = allMembers; foreach (T val in array) { if (val == null) { break; } if (val is RtFieldInfo rtFieldInfo && rtFieldInfo.GetFieldHandle() == field.Value) { return rtFieldInfo; } } } FieldAttributes attributes = RuntimeFieldHandle.GetAttributes(field); bool isPublic = (attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; bool isStatic = (attributes & FieldAttributes.Static) != 0; RuntimeType approxDeclaringType = RuntimeFieldHandle.GetApproxDeclaringType(field); bool isInherited = (RuntimeFieldHandle.AcquiresContextFromThis(field) ? (!RuntimeTypeHandle.CompareCanonicalHandles(approxDeclaringType, ReflectedType)) : (approxDeclaringType != ReflectedType)); BindingFlags bindingFlags = FilterPreCalculate(isPublic, isInherited, isStatic); T[] list = (T[])(object)new RuntimeFieldInfo[1] { new RtFieldInfo(field, ReflectedType, m_runtimeTypeCache, bindingFlags) }; Insert(ref list, null, MemberListType.HandleToInfo); return (FieldInfo)(object)list[0]; } private unsafe T[] Populate(string name, MemberListType listType, CacheType cacheType) { T[] list; if (string.IsNullOrEmpty(name) || (cacheType == CacheType.Constructor && name[0] != '.' && name[0] != '*')) { list = GetListByName(null, 0, null, 0, listType, cacheType); } else { int length = name.Length; fixed (char* ptr = name) { int byteCount = Encoding.UTF8.GetByteCount(ptr, length); if (byteCount > 1024) { byte[] array = new byte[byteCount]; fixed (byte* pUtf8Name = &array[0]) { list = GetListByName(ptr, length, pUtf8Name, byteCount, listType, cacheType); } } else { byte* pUtf8Name2 = stackalloc byte[(int)(uint)byteCount]; list = GetListByName(ptr, length, pUtf8Name2, byteCount, listType, cacheType); } } } Insert(ref list, name, listType); return list; } private unsafe T[] GetListByName(char* pName, int cNameLen, byte* pUtf8Name, int cUtf8Name, MemberListType listType, CacheType cacheType) { if (cNameLen != 0) { Encoding.UTF8.GetBytes(pName, cNameLen, pUtf8Name, cUtf8Name); } Filter filter = new Filter(pUtf8Name, cUtf8Name, listType); object obj = null; switch (cacheType) { case CacheType.Method: obj = PopulateMethods(filter); break; case CacheType.Field: obj = PopulateFields(filter); break; case CacheType.Constructor: obj = PopulateConstructors(filter); break; case CacheType.Property: obj = PopulateProperties(filter); break; case CacheType.Event: obj = PopulateEvents(filter); break; case CacheType.NestedType: obj = PopulateNestedClasses(filter); break; case CacheType.Interface: obj = PopulateInterfaces(filter); break; } return (T[])obj; } internal void Insert(ref T[] list, string name, MemberListType listType) { bool lockTaken = false; try { Monitor.Enter(this, ref lockTaken); switch (listType) { case MemberListType.CaseSensitive: { T[] array = m_csMemberInfos[name]; if (array == null) { MergeWithGlobalList(list); m_csMemberInfos[name] = list; } else { list = array; } break; } case MemberListType.CaseInsensitive: { T[] array2 = m_cisMemberInfos[name]; if (array2 == null) { MergeWithGlobalList(list); m_cisMemberInfos[name] = list; } else { list = array2; } break; } case MemberListType.All: if (!m_cacheComplete) { MergeWithGlobalList(list); int num = m_allMembers.Length; while (num > 0 && !((MemberInfo?)m_allMembers[num - 1] != (MemberInfo?)null)) { num--; } Array.Resize(ref m_allMembers, num); Volatile.Write(ref m_cacheComplete, value: true); } list = m_allMembers; break; default: MergeWithGlobalList(list); break; } } finally { if (lockTaken) { Monitor.Exit(this); } } } private void MergeWithGlobalList(T[] list) { T[] array = m_allMembers; if (array == null) { m_allMembers = list; return; } int num = array.Length; int num2 = 0; for (int i = 0; i < list.Length; i++) { T val = list[i]; bool flag = false; int j; for (j = 0; j < num; j++) { T val2 = array[j]; if ((MemberInfo?)val2 == (MemberInfo?)null) { break; } if (val.CacheEquals(val2)) { list[i] = val2; flag = true; break; } } if (!flag) { if (num2 == 0) { num2 = j; } if (num2 >= array.Length) { int newSize = ((!m_cacheComplete) ? Math.Max(Math.Max(4, 2 * array.Length), list.Length) : (array.Length + 1)); T[] array2 = array; Array.Resize(ref array2, newSize); array = array2; } Volatile.Write(ref array[num2], val); num2++; } } m_allMembers = array; } private unsafe RuntimeMethodInfo[] PopulateMethods(Filter filter) { ListBuilder listBuilder = default(ListBuilder); RuntimeType runtimeType = ReflectedType; if (RuntimeTypeHandle.IsInterface(runtimeType)) { RuntimeTypeHandle.IntroducedMethodEnumerator enumerator = RuntimeTypeHandle.GetIntroducedMethods(runtimeType).GetEnumerator(); while (enumerator.MoveNext()) { RuntimeMethodHandleInternal current = enumerator.Current; if (!filter.RequiresStringComparison() || (RuntimeMethodHandle.MatchesNameHash(current, filter.GetHashToMatch()) && filter.Match(RuntimeMethodHandle.GetUtf8Name(current)))) { MethodAttributes attributes = RuntimeMethodHandle.GetAttributes(current); if ((attributes & MethodAttributes.RTSpecialName) == 0) { bool isPublic = (attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; bool isStatic = (attributes & MethodAttributes.Static) != 0; BindingFlags bindingFlags = FilterPreCalculate(isPublic, isInherited: false, isStatic); RuntimeMethodHandleInternal stubIfNeeded = RuntimeMethodHandle.GetStubIfNeeded(current, runtimeType, null); RuntimeMethodInfo item = new RuntimeMethodInfo(stubIfNeeded, runtimeType, m_runtimeTypeCache, attributes, bindingFlags, null); listBuilder.Add(item); } } } } else { while (RuntimeTypeHandle.IsGenericVariable(runtimeType)) { runtimeType = runtimeType.GetBaseType(); } int numVirtuals = RuntimeTypeHandle.GetNumVirtuals(runtimeType); bool* ptr = stackalloc bool[(int)(uint)numVirtuals]; new Span(ptr, numVirtuals).Clear(); bool isValueType = runtimeType.IsValueType; do { int numVirtuals2 = RuntimeTypeHandle.GetNumVirtuals(runtimeType); RuntimeTypeHandle.IntroducedMethodEnumerator enumerator2 = RuntimeTypeHandle.GetIntroducedMethods(runtimeType).GetEnumerator(); while (enumerator2.MoveNext()) { RuntimeMethodHandleInternal current2 = enumerator2.Current; if (filter.RequiresStringComparison() && (!RuntimeMethodHandle.MatchesNameHash(current2, filter.GetHashToMatch()) || !filter.Match(RuntimeMethodHandle.GetUtf8Name(current2)))) { continue; } MethodAttributes attributes2 = RuntimeMethodHandle.GetAttributes(current2); MethodAttributes methodAttributes = attributes2 & MethodAttributes.MemberAccessMask; if ((attributes2 & MethodAttributes.RTSpecialName) != 0) { continue; } bool flag = false; int num = 0; if ((attributes2 & MethodAttributes.Virtual) != 0) { num = RuntimeMethodHandle.GetSlot(current2); flag = num < numVirtuals2; } bool flag2 = runtimeType != ReflectedType; bool flag3 = methodAttributes == MethodAttributes.Private; if (flag2 && flag3 && !flag) { continue; } if (flag) { if (ptr[num]) { continue; } ptr[num] = true; } else if (isValueType && (attributes2 & (MethodAttributes.Virtual | MethodAttributes.Abstract)) != 0) { continue; } bool isPublic2 = methodAttributes == MethodAttributes.Public; bool isStatic2 = (attributes2 & MethodAttributes.Static) != 0; BindingFlags bindingFlags2 = FilterPreCalculate(isPublic2, flag2, isStatic2); RuntimeMethodHandleInternal stubIfNeeded2 = RuntimeMethodHandle.GetStubIfNeeded(current2, runtimeType, null); RuntimeMethodInfo item2 = new RuntimeMethodInfo(stubIfNeeded2, runtimeType, m_runtimeTypeCache, attributes2, bindingFlags2, null); listBuilder.Add(item2); } runtimeType = RuntimeTypeHandle.GetBaseType(runtimeType); } while (runtimeType != null); } return listBuilder.ToArray(); } private RuntimeConstructorInfo[] PopulateConstructors(Filter filter) { if (ReflectedType.IsGenericParameter) { return Array.Empty(); } ListBuilder listBuilder = default(ListBuilder); RuntimeType reflectedType = ReflectedType; RuntimeTypeHandle.IntroducedMethodEnumerator enumerator = RuntimeTypeHandle.GetIntroducedMethods(reflectedType).GetEnumerator(); while (enumerator.MoveNext()) { RuntimeMethodHandleInternal current = enumerator.Current; if (!filter.RequiresStringComparison() || (RuntimeMethodHandle.MatchesNameHash(current, filter.GetHashToMatch()) && filter.Match(RuntimeMethodHandle.GetUtf8Name(current)))) { MethodAttributes attributes = RuntimeMethodHandle.GetAttributes(current); if ((attributes & MethodAttributes.RTSpecialName) != 0) { bool isPublic = (attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; bool isStatic = (attributes & MethodAttributes.Static) != 0; BindingFlags bindingFlags = FilterPreCalculate(isPublic, isInherited: false, isStatic); RuntimeMethodHandleInternal stubIfNeeded = RuntimeMethodHandle.GetStubIfNeeded(current, reflectedType, null); RuntimeConstructorInfo item = new RuntimeConstructorInfo(stubIfNeeded, ReflectedType, m_runtimeTypeCache, attributes, bindingFlags); listBuilder.Add(item); } } } return listBuilder.ToArray(); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", Justification = "Calls to GetInterfaces technically require all interfaces on ReflectedTypeBut this is not a public API to enumerate reflection items, all the public APIs which do thatshould be annotated accordingly.")] private RuntimeFieldInfo[] PopulateFields(Filter filter) { ListBuilder list = default(ListBuilder); RuntimeType runtimeType = ReflectedType; while (RuntimeTypeHandle.IsGenericVariable(runtimeType)) { runtimeType = runtimeType.GetBaseType(); } while (runtimeType != null) { PopulateRtFields(filter, runtimeType, ref list); PopulateLiteralFields(filter, runtimeType, ref list); runtimeType = RuntimeTypeHandle.GetBaseType(runtimeType); } if (ReflectedType.IsGenericParameter) { Type[] interfaces = ReflectedType.BaseType.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { PopulateLiteralFields(filter, (RuntimeType)interfaces[i], ref list); PopulateRtFields(filter, (RuntimeType)interfaces[i], ref list); } } else { Type[] interfaces2 = RuntimeTypeHandle.GetInterfaces(ReflectedType); if (interfaces2 != null) { for (int j = 0; j < interfaces2.Length; j++) { PopulateLiteralFields(filter, (RuntimeType)interfaces2[j], ref list); PopulateRtFields(filter, (RuntimeType)interfaces2[j], ref list); } } } return list.ToArray(); } private unsafe void PopulateRtFields(Filter filter, RuntimeType declaringType, ref ListBuilder list) { IntPtr* ptr = stackalloc IntPtr[64]; int num = 64; if (!RuntimeTypeHandle.GetFields(declaringType, ptr, &num)) { fixed (IntPtr* ptr2 = new IntPtr[num]) { RuntimeTypeHandle.GetFields(declaringType, ptr2, &num); PopulateRtFields(filter, ptr2, num, declaringType, ref list); } } else if (num > 0) { PopulateRtFields(filter, ptr, num, declaringType, ref list); } } private unsafe void PopulateRtFields(Filter filter, IntPtr* ppFieldHandles, int count, RuntimeType declaringType, ref ListBuilder list) { bool flag = RuntimeTypeHandle.HasInstantiation(declaringType) && !RuntimeTypeHandle.ContainsGenericVariables(declaringType); bool flag2 = declaringType != ReflectedType; for (int i = 0; i < count; i++) { RuntimeFieldHandleInternal runtimeFieldHandleInternal = new RuntimeFieldHandleInternal(ppFieldHandles[i]); if (filter.RequiresStringComparison() && (!RuntimeFieldHandle.MatchesNameHash(runtimeFieldHandleInternal, filter.GetHashToMatch()) || !filter.Match(RuntimeFieldHandle.GetUtf8Name(runtimeFieldHandleInternal)))) { continue; } FieldAttributes attributes = RuntimeFieldHandle.GetAttributes(runtimeFieldHandleInternal); FieldAttributes fieldAttributes = attributes & FieldAttributes.FieldAccessMask; if (!flag2 || fieldAttributes != FieldAttributes.Private) { bool isPublic = fieldAttributes == FieldAttributes.Public; bool flag3 = (attributes & FieldAttributes.Static) != 0; BindingFlags bindingFlags = FilterPreCalculate(isPublic, flag2, flag3); if (flag && flag3) { runtimeFieldHandleInternal = RuntimeFieldHandle.GetStaticFieldForGenericType(runtimeFieldHandleInternal, declaringType); } RuntimeFieldInfo item = new RtFieldInfo(runtimeFieldHandleInternal, declaringType, m_runtimeTypeCache, bindingFlags); list.Add(item); } } } private void PopulateLiteralFields(Filter filter, RuntimeType declaringType, ref ListBuilder list) { int token = RuntimeTypeHandle.GetToken(declaringType); if (System.Reflection.MetadataToken.IsNullToken(token)) { return; } MetadataImport metadataImport = RuntimeTypeHandle.GetMetadataImport(declaringType); metadataImport.EnumFields(token, out var result); for (int i = 0; i < result.Length; i++) { int num = result[i]; metadataImport.GetFieldDefProps(num, out var fieldAttributes); FieldAttributes fieldAttributes2 = fieldAttributes & FieldAttributes.FieldAccessMask; if ((fieldAttributes & FieldAttributes.Literal) == 0) { continue; } bool flag = declaringType != ReflectedType; if (flag && fieldAttributes2 == FieldAttributes.Private) { continue; } if (filter.RequiresStringComparison()) { MdUtf8String name = metadataImport.GetName(num); if (!filter.Match(name)) { continue; } } bool isPublic = fieldAttributes2 == FieldAttributes.Public; bool isStatic = (fieldAttributes & FieldAttributes.Static) != 0; BindingFlags bindingFlags = FilterPreCalculate(isPublic, flag, isStatic); RuntimeFieldInfo item = new MdFieldInfo(num, fieldAttributes, declaringType.GetTypeHandleInternal(), m_runtimeTypeCache, bindingFlags); list.Add(item); } } private void AddSpecialInterface(ref ListBuilder list, Filter filter, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] RuntimeType iList, bool addSubInterface) { if (!iList.IsAssignableFrom(ReflectedType)) { return; } if (filter.Match(RuntimeTypeHandle.GetUtf8Name(iList))) { list.Add(iList); } if (!addSubInterface) { return; } Type[] interfaces = iList.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { RuntimeType runtimeType = (RuntimeType)interfaces[i]; if (runtimeType.IsGenericType && filter.Match(RuntimeTypeHandle.GetUtf8Name(runtimeType))) { list.Add(runtimeType); } } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2065:UnrecognizedReflectionPattern", Justification = "Calls to GetInterfaces technically require all interfaces on ReflectedTypeBut this is not a public API to enumerate reflection items, all the public APIs which do thatshould be annotated accordingly.")] private RuntimeType[] PopulateInterfaces(Filter filter) { ListBuilder list = default(ListBuilder); RuntimeType reflectedType = ReflectedType; if (!RuntimeTypeHandle.IsGenericVariable(reflectedType)) { Type[] interfaces = RuntimeTypeHandle.GetInterfaces(reflectedType); if (interfaces != null) { for (int i = 0; i < interfaces.Length; i++) { RuntimeType runtimeType = (RuntimeType)interfaces[i]; if (!filter.RequiresStringComparison() || filter.Match(RuntimeTypeHandle.GetUtf8Name(runtimeType))) { list.Add(runtimeType); } } } if (ReflectedType.IsSZArray) { RuntimeType runtimeType2 = (RuntimeType)ReflectedType.GetElementType(); if (!runtimeType2.IsPointer) { AddSpecialInterface(ref list, filter, (RuntimeType)typeof(IList<>).MakeGenericType(runtimeType2), addSubInterface: true); AddSpecialInterface(ref list, filter, (RuntimeType)typeof(IReadOnlyList<>).MakeGenericType(runtimeType2), addSubInterface: false); AddSpecialInterface(ref list, filter, (RuntimeType)typeof(IReadOnlyCollection<>).MakeGenericType(runtimeType2), addSubInterface: false); } } } else { HashSet hashSet = new HashSet(); Type[] genericParameterConstraints = reflectedType.GetGenericParameterConstraints(); for (int j = 0; j < genericParameterConstraints.Length; j++) { RuntimeType runtimeType3 = (RuntimeType)genericParameterConstraints[j]; if (runtimeType3.IsInterface) { hashSet.Add(runtimeType3); } Type[] interfaces2 = runtimeType3.GetInterfaces(); for (int k = 0; k < interfaces2.Length; k++) { hashSet.Add((RuntimeType)interfaces2[k]); } } foreach (RuntimeType item in hashSet) { if (!filter.RequiresStringComparison() || filter.Match(RuntimeTypeHandle.GetUtf8Name(item))) { list.Add(item); } } } return list.ToArray(); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "Calls to ResolveTypeHandle technically require all types to be kept But this is not a public API to enumerate reflection items, all the public APIs which do that should be annotated accordingly.")] private RuntimeType[] PopulateNestedClasses(Filter filter) { RuntimeType runtimeType = ReflectedType; while (RuntimeTypeHandle.IsGenericVariable(runtimeType)) { runtimeType = runtimeType.GetBaseType(); } int token = RuntimeTypeHandle.GetToken(runtimeType); if (System.Reflection.MetadataToken.IsNullToken(token)) { return Array.Empty(); } ListBuilder listBuilder = default(ListBuilder); ModuleHandle moduleHandle = new ModuleHandle(RuntimeTypeHandle.GetModule(runtimeType)); ModuleHandle.GetMetadataImport(moduleHandle.GetRuntimeModule()).EnumNestedTypes(token, out var result); for (int i = 0; i < result.Length; i++) { RuntimeType runtimeType2; try { runtimeType2 = moduleHandle.ResolveTypeHandle(result[i]).GetRuntimeType(); } catch (TypeLoadException) { continue; } if (!filter.RequiresStringComparison() || filter.Match(RuntimeTypeHandle.GetUtf8Name(runtimeType2))) { listBuilder.Add(runtimeType2); } } return listBuilder.ToArray(); } private RuntimeEventInfo[] PopulateEvents(Filter filter) { Dictionary csEventInfos = (filter.CaseSensitive() ? null : new Dictionary()); RuntimeType runtimeType = ReflectedType; ListBuilder list = default(ListBuilder); if (!RuntimeTypeHandle.IsInterface(runtimeType)) { while (RuntimeTypeHandle.IsGenericVariable(runtimeType)) { runtimeType = runtimeType.GetBaseType(); } while (runtimeType != null) { PopulateEvents(filter, runtimeType, csEventInfos, ref list); runtimeType = RuntimeTypeHandle.GetBaseType(runtimeType); } } else { PopulateEvents(filter, runtimeType, csEventInfos, ref list); } return list.ToArray(); } private void PopulateEvents(Filter filter, RuntimeType declaringType, Dictionary csEventInfos, ref ListBuilder list) { int token = RuntimeTypeHandle.GetToken(declaringType); if (System.Reflection.MetadataToken.IsNullToken(token)) { return; } MetadataImport metadataImport = RuntimeTypeHandle.GetMetadataImport(declaringType); metadataImport.EnumEvents(token, out var result); for (int i = 0; i < result.Length; i++) { int num = result[i]; if (filter.RequiresStringComparison()) { MdUtf8String name = metadataImport.GetName(num); if (!filter.Match(name)) { continue; } } bool isPrivate; RuntimeEventInfo runtimeEventInfo = new RuntimeEventInfo(num, declaringType, m_runtimeTypeCache, out isPrivate); if (declaringType != m_runtimeTypeCache.GetRuntimeType() && isPrivate) { continue; } if (csEventInfos != null) { string name2 = runtimeEventInfo.Name; if (csEventInfos.ContainsKey(name2)) { continue; } csEventInfos[name2] = runtimeEventInfo; } else if (list.Count > 0) { break; } list.Add(runtimeEventInfo); } } private RuntimePropertyInfo[] PopulateProperties(Filter filter) { RuntimeType runtimeType = ReflectedType; ListBuilder list = default(ListBuilder); if (!RuntimeTypeHandle.IsInterface(runtimeType)) { while (RuntimeTypeHandle.IsGenericVariable(runtimeType)) { runtimeType = runtimeType.GetBaseType(); } Dictionary> csPropertyInfos = (filter.CaseSensitive() ? null : new Dictionary>()); bool[] usedSlots = new bool[RuntimeTypeHandle.GetNumVirtuals(runtimeType)]; do { PopulateProperties(filter, runtimeType, csPropertyInfos, usedSlots, ref list); runtimeType = RuntimeTypeHandle.GetBaseType(runtimeType); } while (runtimeType != null); } else { PopulateProperties(filter, runtimeType, null, null, ref list); } return list.ToArray(); } private void PopulateProperties(Filter filter, RuntimeType declaringType, Dictionary> csPropertyInfos, bool[] usedSlots, ref ListBuilder list) { int token = RuntimeTypeHandle.GetToken(declaringType); if (System.Reflection.MetadataToken.IsNullToken(token)) { return; } RuntimeTypeHandle.GetMetadataImport(declaringType).EnumProperties(token, out var result); RuntimeModule module = RuntimeTypeHandle.GetModule(declaringType); int numVirtuals = RuntimeTypeHandle.GetNumVirtuals(declaringType); for (int i = 0; i < result.Length; i++) { int num = result[i]; if (filter.RequiresStringComparison()) { if (!ModuleHandle.ContainsPropertyMatchingHash(module, num, filter.GetHashToMatch())) { continue; } MdUtf8String name = declaringType.GetRuntimeModule().MetadataImport.GetName(num); if (!filter.Match(name)) { continue; } } bool isPrivate; RuntimePropertyInfo runtimePropertyInfo = new RuntimePropertyInfo(num, declaringType, m_runtimeTypeCache, out isPrivate); if (usedSlots != null) { if (declaringType != ReflectedType && isPrivate) { continue; } MethodInfo methodInfo = runtimePropertyInfo.GetGetMethod() ?? runtimePropertyInfo.GetSetMethod(); if (methodInfo != null) { int slot = RuntimeMethodHandle.GetSlot((RuntimeMethodInfo)methodInfo); if (slot < numVirtuals) { if (usedSlots[slot]) { continue; } usedSlots[slot] = true; } } if (csPropertyInfos != null) { string name2 = runtimePropertyInfo.Name; if (!csPropertyInfos.TryGetValue(name2, out var value)) { value = (csPropertyInfos[name2] = new List(1)); } for (int j = 0; j < value.Count; j++) { if (runtimePropertyInfo.EqualsSig(value[j])) { value = null; break; } } if (value == null) { continue; } value.Add(runtimePropertyInfo); } else { bool flag = false; for (int k = 0; k < list.Count; k++) { if (runtimePropertyInfo.EqualsSig(list[k])) { flag = true; break; } } if (flag) { continue; } } } list.Add(runtimePropertyInfo); } } internal T[] GetMemberList(MemberListType listType, string name, CacheType cacheType) { switch (listType) { case MemberListType.CaseSensitive: return m_csMemberInfos[name] ?? Populate(name, listType, cacheType); case MemberListType.CaseInsensitive: return m_cisMemberInfos[name] ?? Populate(name, listType, cacheType); default: if (Volatile.Read(ref m_cacheComplete)) { return m_allMembers; } return Populate(null, listType, cacheType); } } } private readonly RuntimeType m_runtimeType; private RuntimeType m_enclosingType; private TypeCode m_typeCode; private string m_name; private string m_fullname; private string m_toString; private string m_namespace; private readonly bool m_isGlobal; private bool m_bIsDomainInitialized; private MemberInfoCache m_methodInfoCache; private MemberInfoCache m_constructorInfoCache; private MemberInfoCache m_fieldInfoCache; private MemberInfoCache m_interfaceCache; private MemberInfoCache m_nestedClassesCache; private MemberInfoCache m_propertyInfoCache; private MemberInfoCache m_eventInfoCache; private static CerHashtable s_methodInstantiations; private static object s_methodInstantiationsLock; private string m_defaultMemberName; private object m_genericCache; private object[] _emptyArray; internal object GenericCache { get { return m_genericCache; } set { m_genericCache = value; } } internal bool DomainInitialized { get { return m_bIsDomainInitialized; } set { m_bIsDomainInitialized = value; } } internal TypeCode TypeCode { get { return m_typeCode; } set { m_typeCode = value; } } internal bool IsGlobal => m_isGlobal; internal RuntimeTypeCache(RuntimeType runtimeType) { m_typeCode = TypeCode.Empty; m_runtimeType = runtimeType; m_isGlobal = RuntimeTypeHandle.GetModule(runtimeType).RuntimeType == runtimeType; } private string ConstructName([NotNull] ref string name, TypeNameFormatFlags formatFlags) { return name ?? (name = new RuntimeTypeHandle(m_runtimeType).ConstructName(formatFlags)); } private T[] GetMemberList(ref MemberInfoCache m_cache, MemberListType listType, string name, CacheType cacheType) where T : MemberInfo { MemberInfoCache memberCache = GetMemberCache(ref m_cache); return memberCache.GetMemberList(listType, name, cacheType); } private MemberInfoCache GetMemberCache(ref MemberInfoCache m_cache) where T : MemberInfo { MemberInfoCache memberInfoCache = m_cache; if (memberInfoCache == null) { MemberInfoCache memberInfoCache2 = new MemberInfoCache(this); memberInfoCache = Interlocked.CompareExchange(ref m_cache, memberInfoCache2, null); if (memberInfoCache == null) { memberInfoCache = memberInfoCache2; } } return memberInfoCache; } internal string GetName(TypeNameKind kind) { switch (kind) { case TypeNameKind.Name: return ConstructName(ref m_name, TypeNameFormatFlags.FormatBasic); case TypeNameKind.FullName: if (!m_runtimeType.GetRootElementType().IsGenericTypeDefinition && m_runtimeType.ContainsGenericParameters) { return null; } return ConstructName(ref m_fullname, (TypeNameFormatFlags)3); case TypeNameKind.ToString: return ConstructName(ref m_toString, TypeNameFormatFlags.FormatNamespace); default: throw new InvalidOperationException(); } } internal string GetNameSpace() { if (m_namespace == null) { Type runtimeType = m_runtimeType; runtimeType = runtimeType.GetRootElementType(); while (runtimeType.IsNested) { runtimeType = runtimeType.DeclaringType; } m_namespace = RuntimeTypeHandle.GetMetadataImport((RuntimeType)runtimeType).GetNamespace(runtimeType.MetadataToken).ToString(); } return m_namespace; } internal RuntimeType GetEnclosingType() { if (m_enclosingType == null) { RuntimeType declaringType = RuntimeTypeHandle.GetDeclaringType(GetRuntimeType()); m_enclosingType = declaringType ?? ((RuntimeType)typeof(void)); } if (!(m_enclosingType == typeof(void))) { return m_enclosingType; } return null; } internal RuntimeType GetRuntimeType() { return m_runtimeType; } internal void InvalidateCachedNestedType() { m_nestedClassesCache = null; } internal string GetDefaultMemberName() { if (m_defaultMemberName == null) { CustomAttributeData customAttributeData = null; Type typeFromHandle = typeof(DefaultMemberAttribute); RuntimeType runtimeType = m_runtimeType; while (runtimeType != null) { IList customAttributes = CustomAttributeData.GetCustomAttributes(runtimeType); for (int i = 0; i < customAttributes.Count; i++) { if ((object)customAttributes[i].Constructor.DeclaringType == typeFromHandle) { customAttributeData = customAttributes[i]; break; } } if (customAttributeData != null) { m_defaultMemberName = customAttributeData.ConstructorArguments[0].Value as string; break; } runtimeType = runtimeType.GetBaseType(); } } return m_defaultMemberName; } internal object[] GetEmptyArray() { return _emptyArray ?? (_emptyArray = (object[])Array.CreateInstance(m_runtimeType, 0)); } internal MethodInfo GetGenericMethodInfo(RuntimeMethodHandleInternal genericMethod) { LoaderAllocator loaderAllocator = RuntimeMethodHandle.GetLoaderAllocator(genericMethod); RuntimeMethodInfo runtimeMethodInfo = new RuntimeMethodInfo(genericMethod, RuntimeMethodHandle.GetDeclaringType(genericMethod), this, RuntimeMethodHandle.GetAttributes(genericMethod), (BindingFlags)(-1), loaderAllocator); RuntimeMethodInfo runtimeMethodInfo2 = ((loaderAllocator == null) ? s_methodInstantiations[runtimeMethodInfo] : loaderAllocator.m_methodInstantiations[runtimeMethodInfo]); if (runtimeMethodInfo2 != null) { return runtimeMethodInfo2; } if (s_methodInstantiationsLock == null) { Interlocked.CompareExchange(ref s_methodInstantiationsLock, new object(), null); } bool lockTaken = false; try { Monitor.Enter(s_methodInstantiationsLock, ref lockTaken); if (loaderAllocator != null) { runtimeMethodInfo2 = loaderAllocator.m_methodInstantiations[runtimeMethodInfo]; if (runtimeMethodInfo2 != null) { return runtimeMethodInfo2; } loaderAllocator.m_methodInstantiations[runtimeMethodInfo] = runtimeMethodInfo; } else { runtimeMethodInfo2 = s_methodInstantiations[runtimeMethodInfo]; if (runtimeMethodInfo2 != null) { return runtimeMethodInfo2; } s_methodInstantiations[runtimeMethodInfo] = runtimeMethodInfo; } } finally { if (lockTaken) { Monitor.Exit(s_methodInstantiationsLock); } } return runtimeMethodInfo; } internal RuntimeMethodInfo[] GetMethodList(MemberListType listType, string name) { return GetMemberList(ref m_methodInfoCache, listType, name, CacheType.Method); } internal RuntimeConstructorInfo[] GetConstructorList(MemberListType listType, string name) { return GetMemberList(ref m_constructorInfoCache, listType, name, CacheType.Constructor); } internal RuntimePropertyInfo[] GetPropertyList(MemberListType listType, string name) { return GetMemberList(ref m_propertyInfoCache, listType, name, CacheType.Property); } internal RuntimeEventInfo[] GetEventList(MemberListType listType, string name) { return GetMemberList(ref m_eventInfoCache, listType, name, CacheType.Event); } internal RuntimeFieldInfo[] GetFieldList(MemberListType listType, string name) { return GetMemberList(ref m_fieldInfoCache, listType, name, CacheType.Field); } internal RuntimeType[] GetInterfaceList(MemberListType listType, string name) { return GetMemberList(ref m_interfaceCache, listType, name, CacheType.Interface); } internal RuntimeType[] GetNestedTypeList(MemberListType listType, string name) { return GetMemberList(ref m_nestedClassesCache, listType, name, CacheType.NestedType); } internal MethodBase GetMethod(RuntimeType declaringType, RuntimeMethodHandleInternal method) { GetMemberCache(ref m_methodInfoCache); return m_methodInfoCache.AddMethod(declaringType, method, CacheType.Method); } internal MethodBase GetConstructor(RuntimeType declaringType, RuntimeMethodHandleInternal constructor) { GetMemberCache(ref m_constructorInfoCache); return m_constructorInfoCache.AddMethod(declaringType, constructor, CacheType.Constructor); } internal FieldInfo GetField(RuntimeFieldHandleInternal field) { GetMemberCache(ref m_fieldInfoCache); return m_fieldInfoCache.AddField(field); } } [Flags] private enum DispatchWrapperType { Unknown = 1, Dispatch = 2, Error = 8, Currency = 0x10, BStr = 0x20, SafeArray = 0x10000 } private readonly object m_keepalive; private IntPtr m_cache; internal IntPtr m_handle; internal static readonly RuntimeType ValueType = (RuntimeType)typeof(ValueType); private static readonly RuntimeType ObjectType = (RuntimeType)typeof(object); private static readonly RuntimeType StringType = (RuntimeType)typeof(string); private const int GenericParameterCountAny = -1; private static readonly RuntimeType s_typedRef = (RuntimeType)typeof(TypedReference); private static OleAutBinder s_ForwardCallBinder; internal object GenericCache { get { return CacheIfExists?.GenericCache; } set { Cache.GenericCache = value; } } internal bool DomainInitialized { get { return Cache.DomainInitialized; } set { Cache.DomainInitialized = value; } } private RuntimeTypeCache CacheIfExists { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (m_cache != IntPtr.Zero) { object value = GCHandle.InternalGet(m_cache); return Unsafe.As(value); } return null; } } private RuntimeTypeCache Cache { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (m_cache != IntPtr.Zero) { object obj = GCHandle.InternalGet(m_cache); if (obj != null) { return Unsafe.As(obj); } } return InitializeCache(); } } public sealed override bool IsCollectible { get { RuntimeType type = this; return RuntimeTypeHandle.IsCollectible(new QCallTypeHandle(ref type)) != Interop.BOOL.FALSE; } } public override MethodBase DeclaringMethod { get { if (!IsGenericParameter) { throw new InvalidOperationException(SR.Arg_NotGenericParameter); } IRuntimeMethodInfo declaringMethod = RuntimeTypeHandle.GetDeclaringMethod(this); if (declaringMethod == null) { return null; } return GetMethodBase(RuntimeMethodHandle.GetDeclaringType(declaringMethod), declaringMethod); } } public override string FullName => GetCachedName(TypeNameKind.FullName); public override string AssemblyQualifiedName { get { string fullName = FullName; if (fullName == null) { return null; } return Assembly.CreateQualifiedName(Assembly.FullName, fullName); } } public override string Namespace { get { string nameSpace = Cache.GetNameSpace(); if (string.IsNullOrEmpty(nameSpace)) { return null; } return nameSpace; } } public override Guid GUID { get { Guid result = default(Guid); GetGUID(ref result); return result; } } public override GenericParameterAttributes GenericParameterAttributes { get { if (!IsGenericParameter) { throw new InvalidOperationException(SR.Arg_NotGenericParameter); } RuntimeTypeHandle.GetMetadataImport(this).GetGenericParamProps(MetadataToken, out var attributes); return attributes; } } public sealed override bool IsSZArray => RuntimeTypeHandle.IsSZArray(this); public override int GenericParameterPosition { get { if (!IsGenericParameter) { throw new InvalidOperationException(SR.Arg_NotGenericParameter); } return new RuntimeTypeHandle(this).GetGenericVariableIndex(); } } public override bool ContainsGenericParameters => GetRootElementType().GetTypeHandleInternal().ContainsGenericVariables(); public override StructLayoutAttribute StructLayoutAttribute => PseudoCustomAttribute.GetStructLayoutCustomAttribute(this); public override string Name => GetCachedName(TypeNameKind.Name); public override Type DeclaringType => Cache.GetEnclosingType(); private static OleAutBinder ForwardCallBinder => s_ForwardCallBinder ?? (s_ForwardCallBinder = new OleAutBinder()); public override Assembly Assembly => RuntimeTypeHandle.GetAssembly(this); public override Type BaseType => GetBaseType(); public override bool IsByRefLike => RuntimeTypeHandle.IsByRefLike(this); public override bool IsConstructedGenericType { get { if (IsGenericType) { return !IsGenericTypeDefinition; } return false; } } public override bool IsGenericType => RuntimeTypeHandle.HasInstantiation(this); public override bool IsGenericTypeDefinition => RuntimeTypeHandle.IsGenericTypeDefinition(this); public override bool IsGenericParameter => RuntimeTypeHandle.IsGenericVariable(this); public override bool IsTypeDefinition => RuntimeTypeHandle.IsTypeDefinition(this); public override bool IsSecurityCritical => true; public override bool IsSecuritySafeCritical => false; public override bool IsSecurityTransparent => false; public override MemberTypes MemberType { get { if (!base.IsPublic && !base.IsNotPublic) { return MemberTypes.NestedType; } return MemberTypes.TypeInfo; } } public override int MetadataToken => RuntimeTypeHandle.GetToken(this); public override Module Module => GetRuntimeModule(); public override Type ReflectedType => DeclaringType; public override RuntimeTypeHandle TypeHandle => new RuntimeTypeHandle(this); public override Type UnderlyingSystemType => this; internal static RuntimeType GetType(string typeName, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { if (typeName == null) { throw new ArgumentNullException("typeName"); } return RuntimeTypeHandle.GetTypeByName(typeName, throwOnError, ignoreCase, ref stackMark); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] internal static MethodBase GetMethodBase(RuntimeModule scope, int typeMetadataToken) { return GetMethodBase(new ModuleHandle(scope).ResolveMethodHandle(typeMetadataToken).GetMethodInfo()); } internal static MethodBase GetMethodBase(IRuntimeMethodInfo methodHandle) { return GetMethodBase(null, methodHandle); } internal static MethodBase GetMethodBase(RuntimeType reflectedType, IRuntimeMethodInfo methodHandle) { MethodBase methodBase = GetMethodBase(reflectedType, methodHandle.Value); GC.KeepAlive(methodHandle); return methodBase; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "The code in this method looks up the method by name, but it always starts with a method handle.To get here something somwhere had to get the method handle and thus the method must exist.")] internal static MethodBase GetMethodBase(RuntimeType reflectedType, RuntimeMethodHandleInternal methodHandle) { if (RuntimeMethodHandle.IsDynamicMethod(methodHandle)) { return RuntimeMethodHandle.GetResolver(methodHandle)?.GetDynamicMethod(); } RuntimeType runtimeType = RuntimeMethodHandle.GetDeclaringType(methodHandle); RuntimeType[] array = null; if ((object)reflectedType == null) { reflectedType = runtimeType; } if (reflectedType != runtimeType && !reflectedType.IsSubclassOf(runtimeType)) { if (reflectedType.IsArray) { MethodBase[] array2 = reflectedType.GetMember(RuntimeMethodHandle.GetName(methodHandle), MemberTypes.Constructor | MemberTypes.Method, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) as MethodBase[]; bool flag = false; for (int i = 0; i < array2.Length; i++) { IRuntimeMethodInfo runtimeMethodInfo = (IRuntimeMethodInfo)array2[i]; if (runtimeMethodInfo.Value.Value == methodHandle.Value) { flag = true; } } if (!flag) { throw new ArgumentException(SR.Format(SR.Argument_ResolveMethodHandle, reflectedType, runtimeType)); } } else if (runtimeType.IsGenericType) { RuntimeType runtimeType2 = (RuntimeType)runtimeType.GetGenericTypeDefinition(); RuntimeType runtimeType3 = reflectedType; while (runtimeType3 != null) { RuntimeType runtimeType4 = runtimeType3; if (runtimeType4.IsGenericType && !runtimeType3.IsGenericTypeDefinition) { runtimeType4 = (RuntimeType)runtimeType4.GetGenericTypeDefinition(); } if (runtimeType4 == runtimeType2) { break; } runtimeType3 = runtimeType3.GetBaseType(); } if (runtimeType3 == null) { throw new ArgumentException(SR.Format(SR.Argument_ResolveMethodHandle, reflectedType, runtimeType)); } runtimeType = runtimeType3; if (!RuntimeMethodHandle.IsGenericMethodDefinition(methodHandle)) { array = RuntimeMethodHandle.GetMethodInstantiationInternal(methodHandle); } methodHandle = RuntimeMethodHandle.GetMethodFromCanonical(methodHandle, runtimeType); } else if (!runtimeType.IsAssignableFrom(reflectedType)) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.Argument_ResolveMethodHandle, reflectedType.ToString(), runtimeType.ToString())); } } methodHandle = RuntimeMethodHandle.GetStubIfNeeded(methodHandle, runtimeType, array); MethodBase result = (RuntimeMethodHandle.IsConstructor(methodHandle) ? reflectedType.Cache.GetConstructor(runtimeType, methodHandle) : ((!RuntimeMethodHandle.HasMethodInstantiation(methodHandle) || RuntimeMethodHandle.IsGenericMethodDefinition(methodHandle)) ? reflectedType.Cache.GetMethod(runtimeType, methodHandle) : reflectedType.Cache.GetGenericMethodInfo(methodHandle))); GC.KeepAlive(array); return result; } internal static FieldInfo GetFieldInfo(IRuntimeFieldInfo fieldHandle) { return GetFieldInfo(RuntimeFieldHandle.GetApproxDeclaringType(fieldHandle), fieldHandle); } internal static FieldInfo GetFieldInfo(RuntimeType reflectedType, IRuntimeFieldInfo field) { RuntimeFieldHandleInternal value = field.Value; if (reflectedType == null) { reflectedType = RuntimeFieldHandle.GetApproxDeclaringType(value); } else { RuntimeType approxDeclaringType = RuntimeFieldHandle.GetApproxDeclaringType(value); if (reflectedType != approxDeclaringType && (!RuntimeFieldHandle.AcquiresContextFromThis(value) || !RuntimeTypeHandle.CompareCanonicalHandles(approxDeclaringType, reflectedType))) { throw new ArgumentException(SR.Format(SR.Argument_ResolveFieldHandle, reflectedType, approxDeclaringType)); } } FieldInfo field2 = reflectedType.Cache.GetField(value); GC.KeepAlive(field); return field2; } private static PropertyInfo GetPropertyInfo(RuntimeType reflectedType, int tkProperty) { RuntimePropertyInfo[] propertyList = reflectedType.Cache.GetPropertyList(MemberListType.All, null); foreach (RuntimePropertyInfo runtimePropertyInfo in propertyList) { if (runtimePropertyInfo.MetadataToken == tkProperty) { return runtimePropertyInfo; } } throw new SystemException(); } internal static void ValidateGenericArguments(MemberInfo definition, RuntimeType[] genericArguments, Exception e) { RuntimeType[] typeContext = null; RuntimeType[] methodContext = null; RuntimeType[] genericArgumentsInternal; if (definition is Type) { RuntimeType runtimeType = (RuntimeType)definition; genericArgumentsInternal = runtimeType.GetGenericArgumentsInternal(); typeContext = genericArguments; } else { RuntimeMethodInfo runtimeMethodInfo = (RuntimeMethodInfo)definition; genericArgumentsInternal = runtimeMethodInfo.GetGenericArgumentsInternal(); methodContext = genericArguments; RuntimeType runtimeType2 = (RuntimeType)runtimeMethodInfo.DeclaringType; if (runtimeType2 != null) { typeContext = runtimeType2.GetTypeHandleInternal().GetInstantiationInternal(); } } for (int i = 0; i < genericArguments.Length; i++) { Type type = genericArguments[i]; Type type2 = genericArgumentsInternal[i]; if (!RuntimeTypeHandle.SatisfiesConstraints(type2.GetTypeHandleInternal().GetTypeChecked(), typeContext, methodContext, type.GetTypeHandleInternal().GetTypeChecked())) { throw new ArgumentException(SR.Format(SR.Argument_GenConstraintViolation, i.ToString(), type, definition, type2), e); } } } private static void SplitName(string fullname, out string name, out string ns) { name = null; ns = null; if (fullname == null) { return; } int num = fullname.LastIndexOf(".", StringComparison.Ordinal); if (num != -1) { ns = fullname.Substring(0, num); int num2 = fullname.Length - ns.Length - 1; if (num2 != 0) { name = fullname.Substring(num + 1, num2); } else { name = ""; } } else { name = fullname; } } internal static BindingFlags FilterPreCalculate(bool isPublic, bool isInherited, bool isStatic) { BindingFlags bindingFlags = (isPublic ? BindingFlags.Public : BindingFlags.NonPublic); if (isInherited) { bindingFlags |= BindingFlags.DeclaredOnly; if (isStatic) { return bindingFlags | (BindingFlags.Static | BindingFlags.FlattenHierarchy); } return bindingFlags | BindingFlags.Instance; } if (isStatic) { return bindingFlags | BindingFlags.Static; } return bindingFlags | BindingFlags.Instance; } private static void FilterHelper(BindingFlags bindingFlags, ref string name, bool allowPrefixLookup, out bool prefixLookup, out bool ignoreCase, out MemberListType listType) { prefixLookup = false; ignoreCase = false; if (name != null) { if ((bindingFlags & BindingFlags.IgnoreCase) != 0) { name = name.ToLowerInvariant(); ignoreCase = true; listType = MemberListType.CaseInsensitive; } else { listType = MemberListType.CaseSensitive; } if (allowPrefixLookup && name.EndsWith("*", StringComparison.Ordinal)) { name = name[0..^1]; prefixLookup = true; listType = MemberListType.All; } } else { listType = MemberListType.All; } } private static void FilterHelper(BindingFlags bindingFlags, ref string name, out bool ignoreCase, out MemberListType listType) { FilterHelper(bindingFlags, ref name, allowPrefixLookup: false, out var _, out ignoreCase, out listType); } private static bool FilterApplyPrefixLookup(MemberInfo memberInfo, string name, bool ignoreCase) { if (ignoreCase) { if (!memberInfo.Name.StartsWith(name, StringComparison.OrdinalIgnoreCase)) { return false; } } else if (!memberInfo.Name.StartsWith(name, StringComparison.Ordinal)) { return false; } return true; } private static bool FilterApplyBase(MemberInfo memberInfo, BindingFlags bindingFlags, bool isPublic, bool isNonProtectedInternal, bool isStatic, string name, bool prefixLookup) { if (isPublic) { if ((bindingFlags & BindingFlags.Public) == 0) { return false; } } else if ((bindingFlags & BindingFlags.NonPublic) == 0) { return false; } bool flag = (object)memberInfo.DeclaringType != memberInfo.ReflectedType; if ((bindingFlags & BindingFlags.DeclaredOnly) != 0 && flag) { return false; } if (memberInfo.MemberType != MemberTypes.TypeInfo && memberInfo.MemberType != MemberTypes.NestedType) { if (isStatic) { if ((bindingFlags & BindingFlags.FlattenHierarchy) == 0 && flag) { return false; } if ((bindingFlags & BindingFlags.Static) == 0) { return false; } } else if ((bindingFlags & BindingFlags.Instance) == 0) { return false; } } if (prefixLookup && !FilterApplyPrefixLookup(memberInfo, name, (bindingFlags & BindingFlags.IgnoreCase) != 0)) { return false; } if ((bindingFlags & BindingFlags.DeclaredOnly) == 0 && flag && isNonProtectedInternal && (bindingFlags & BindingFlags.NonPublic) != 0 && !isStatic && (bindingFlags & BindingFlags.Instance) != 0) { MethodInfo methodInfo = memberInfo as MethodInfo; if (methodInfo == null) { return false; } if (!methodInfo.IsVirtual && !methodInfo.IsAbstract) { return false; } } return true; } private static bool FilterApplyType(Type type, BindingFlags bindingFlags, string name, bool prefixLookup, string ns) { bool isPublic = type.IsNestedPublic || type.IsPublic; if (!FilterApplyBase(type, bindingFlags, isPublic, type.IsNestedAssembly, isStatic: false, name, prefixLookup)) { return false; } if (ns != null && ns != type.Namespace) { return false; } return true; } private static bool FilterApplyMethodInfo(RuntimeMethodInfo method, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes) { return FilterApplyMethodBase(method, method.BindingFlags, bindingFlags, callConv, argumentTypes); } private static bool FilterApplyConstructorInfo(RuntimeConstructorInfo constructor, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes) { return FilterApplyMethodBase(constructor, constructor.BindingFlags, bindingFlags, callConv, argumentTypes); } private static bool FilterApplyMethodBase(MethodBase methodBase, BindingFlags methodFlags, BindingFlags bindingFlags, CallingConventions callConv, Type[] argumentTypes) { bindingFlags ^= BindingFlags.DeclaredOnly; if ((bindingFlags & methodFlags) != methodFlags) { return false; } if ((callConv & CallingConventions.Any) == 0) { if ((callConv & CallingConventions.VarArgs) != 0 && (methodBase.CallingConvention & CallingConventions.VarArgs) == 0) { return false; } if ((callConv & CallingConventions.Standard) != 0 && (methodBase.CallingConvention & CallingConventions.Standard) == 0) { return false; } } if (argumentTypes != null) { ParameterInfo[] parametersNoCopy = methodBase.GetParametersNoCopy(); if (argumentTypes.Length != parametersNoCopy.Length) { if ((bindingFlags & (BindingFlags.InvokeMethod | BindingFlags.CreateInstance | BindingFlags.GetProperty | BindingFlags.SetProperty)) == 0) { return false; } bool flag = false; if (argumentTypes.Length > parametersNoCopy.Length) { if ((methodBase.CallingConvention & CallingConventions.VarArgs) == 0) { flag = true; } } else if ((bindingFlags & BindingFlags.OptionalParamBinding) == 0) { flag = true; } else if (!parametersNoCopy[argumentTypes.Length].IsOptional) { flag = true; } if (flag) { if (parametersNoCopy.Length == 0) { return false; } if (argumentTypes.Length < parametersNoCopy.Length - 1) { return false; } ParameterInfo parameterInfo = parametersNoCopy[^1]; if (!parameterInfo.ParameterType.IsArray) { return false; } if (!parameterInfo.IsDefined(typeof(ParamArrayAttribute), inherit: false)) { return false; } } } else if ((bindingFlags & BindingFlags.ExactBinding) != 0 && (bindingFlags & BindingFlags.InvokeMethod) == 0) { for (int i = 0; i < parametersNoCopy.Length; i++) { Type type = argumentTypes[i]; if ((object)type != null && !type.MatchesParameterTypeExactly(parametersNoCopy[i])) { return false; } } } } return true; } internal RuntimeType() { throw new NotSupportedException(); } internal IntPtr GetUnderlyingNativeHandle() { return m_handle; } internal override bool CacheEquals(object o) { if (o is RuntimeType runtimeType) { return runtimeType.m_handle == m_handle; } return false; } [MethodImpl(MethodImplOptions.NoInlining)] private RuntimeTypeCache InitializeCache() { if (m_cache == IntPtr.Zero) { RuntimeTypeHandle runtimeTypeHandle = new RuntimeTypeHandle(this); IntPtr gCHandle = runtimeTypeHandle.GetGCHandle(GCHandleType.WeakTrackResurrection); IntPtr intPtr = Interlocked.CompareExchange(ref m_cache, gCHandle, IntPtr.Zero); if (intPtr != IntPtr.Zero) { runtimeTypeHandle.FreeGCHandle(gCHandle); } } RuntimeTypeCache runtimeTypeCache = (RuntimeTypeCache)GCHandle.InternalGet(m_cache); if (runtimeTypeCache == null) { runtimeTypeCache = new RuntimeTypeCache(this); RuntimeTypeCache runtimeTypeCache2 = (RuntimeTypeCache)GCHandle.InternalCompareExchange(m_cache, runtimeTypeCache, null); if (runtimeTypeCache2 != null) { runtimeTypeCache = runtimeTypeCache2; } } return runtimeTypeCache; } internal void ClearCache() { if (!(Volatile.Read(ref m_cache) == IntPtr.Zero)) { GCHandle.InternalSet(m_cache, null); } } private string GetDefaultMemberName() { return Cache.GetDefaultMemberName(); } private ListBuilder GetMethodCandidates(string name, int genericParameterCount, BindingFlags bindingAttr, CallingConventions callConv, Type[] types, bool allowPrefixLookup) { FilterHelper(bindingAttr, ref name, allowPrefixLookup, out var prefixLookup, out var ignoreCase, out var listType); RuntimeMethodInfo[] methodList = Cache.GetMethodList(listType, name); ListBuilder result = new ListBuilder(methodList.Length); foreach (RuntimeMethodInfo runtimeMethodInfo in methodList) { if ((genericParameterCount == -1 || genericParameterCount == runtimeMethodInfo.GenericParameterCount) && FilterApplyMethodInfo(runtimeMethodInfo, bindingAttr, callConv, types) && (!prefixLookup || FilterApplyPrefixLookup(runtimeMethodInfo, name, ignoreCase))) { result.Add(runtimeMethodInfo); } } return result; } private ListBuilder GetConstructorCandidates(string name, BindingFlags bindingAttr, CallingConventions callConv, Type[] types, bool allowPrefixLookup) { FilterHelper(bindingAttr, ref name, allowPrefixLookup, out var prefixLookup, out var ignoreCase, out var listType); RuntimeConstructorInfo[] constructorList = Cache.GetConstructorList(listType, name); ListBuilder result = new ListBuilder(constructorList.Length); foreach (RuntimeConstructorInfo runtimeConstructorInfo in constructorList) { if (FilterApplyConstructorInfo(runtimeConstructorInfo, bindingAttr, callConv, types) && (!prefixLookup || FilterApplyPrefixLookup(runtimeConstructorInfo, name, ignoreCase))) { result.Add(runtimeConstructorInfo); } } return result; } private ListBuilder GetPropertyCandidates(string name, BindingFlags bindingAttr, Type[] types, bool allowPrefixLookup) { FilterHelper(bindingAttr, ref name, allowPrefixLookup, out var prefixLookup, out var ignoreCase, out var listType); RuntimePropertyInfo[] propertyList = Cache.GetPropertyList(listType, name); bindingAttr ^= BindingFlags.DeclaredOnly; ListBuilder result = new ListBuilder(propertyList.Length); foreach (RuntimePropertyInfo runtimePropertyInfo in propertyList) { if ((bindingAttr & runtimePropertyInfo.BindingFlags) == runtimePropertyInfo.BindingFlags && (!prefixLookup || FilterApplyPrefixLookup(runtimePropertyInfo, name, ignoreCase)) && (types == null || runtimePropertyInfo.GetIndexParameters().Length == types.Length)) { result.Add(runtimePropertyInfo); } } return result; } private ListBuilder GetEventCandidates(string name, BindingFlags bindingAttr, bool allowPrefixLookup) { FilterHelper(bindingAttr, ref name, allowPrefixLookup, out var prefixLookup, out var ignoreCase, out var listType); RuntimeEventInfo[] eventList = Cache.GetEventList(listType, name); bindingAttr ^= BindingFlags.DeclaredOnly; ListBuilder result = new ListBuilder(eventList.Length); foreach (RuntimeEventInfo runtimeEventInfo in eventList) { if ((bindingAttr & runtimeEventInfo.BindingFlags) == runtimeEventInfo.BindingFlags && (!prefixLookup || FilterApplyPrefixLookup(runtimeEventInfo, name, ignoreCase))) { result.Add(runtimeEventInfo); } } return result; } private ListBuilder GetFieldCandidates(string name, BindingFlags bindingAttr, bool allowPrefixLookup) { FilterHelper(bindingAttr, ref name, allowPrefixLookup, out var prefixLookup, out var ignoreCase, out var listType); RuntimeFieldInfo[] fieldList = Cache.GetFieldList(listType, name); bindingAttr ^= BindingFlags.DeclaredOnly; ListBuilder result = new ListBuilder(fieldList.Length); foreach (RuntimeFieldInfo runtimeFieldInfo in fieldList) { if ((bindingAttr & runtimeFieldInfo.BindingFlags) == runtimeFieldInfo.BindingFlags && (!prefixLookup || FilterApplyPrefixLookup(runtimeFieldInfo, name, ignoreCase))) { result.Add(runtimeFieldInfo); } } return result; } private ListBuilder GetNestedTypeCandidates(string fullname, BindingFlags bindingAttr, bool allowPrefixLookup) { bindingAttr &= ~BindingFlags.Static; SplitName(fullname, out var name, out var ns); FilterHelper(bindingAttr, ref name, allowPrefixLookup, out var prefixLookup, out var _, out var listType); RuntimeType[] nestedTypeList = Cache.GetNestedTypeList(listType, name); ListBuilder result = new ListBuilder(nestedTypeList.Length); foreach (RuntimeType runtimeType in nestedTypeList) { if (FilterApplyType(runtimeType, bindingAttr, name, prefixLookup, ns)) { result.Add(runtimeType); } } return result; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { return GetMethodCandidates(null, -1, bindingAttr, CallingConventions.Any, null, allowPrefixLookup: false).ToArray(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return GetConstructorCandidates(null, bindingAttr, CallingConventions.Any, null, allowPrefixLookup: false).ToArray(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { return GetPropertyCandidates(null, bindingAttr, null, allowPrefixLookup: false).ToArray(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo[] GetEvents(BindingFlags bindingAttr) { return GetEventCandidates(null, bindingAttr, allowPrefixLookup: false).ToArray(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo[] GetFields(BindingFlags bindingAttr) { return GetFieldCandidates(null, bindingAttr, allowPrefixLookup: false).ToArray(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type[] GetInterfaces() { RuntimeType[] interfaceList = Cache.GetInterfaceList(MemberListType.All, null); Type[] array = interfaceList; return new ReadOnlySpan(array).ToArray(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type[] GetNestedTypes(BindingFlags bindingAttr) { return GetNestedTypeCandidates(null, bindingAttr, allowPrefixLookup: false).ToArray(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { ListBuilder methodCandidates = GetMethodCandidates(null, -1, bindingAttr, CallingConventions.Any, null, allowPrefixLookup: false); ListBuilder constructorCandidates = GetConstructorCandidates(null, bindingAttr, CallingConventions.Any, null, allowPrefixLookup: false); ListBuilder propertyCandidates = GetPropertyCandidates(null, bindingAttr, null, allowPrefixLookup: false); ListBuilder eventCandidates = GetEventCandidates(null, bindingAttr, allowPrefixLookup: false); ListBuilder fieldCandidates = GetFieldCandidates(null, bindingAttr, allowPrefixLookup: false); ListBuilder nestedTypeCandidates = GetNestedTypeCandidates(null, bindingAttr, allowPrefixLookup: false); MemberInfo[] array = new MemberInfo[methodCandidates.Count + constructorCandidates.Count + propertyCandidates.Count + eventCandidates.Count + fieldCandidates.Count + nestedTypeCandidates.Count]; int num = 0; object[] array2 = array; methodCandidates.CopyTo(array2, num); num += methodCandidates.Count; array2 = array; constructorCandidates.CopyTo(array2, num); num += constructorCandidates.Count; array2 = array; propertyCandidates.CopyTo(array2, num); num += propertyCandidates.Count; array2 = array; eventCandidates.CopyTo(array2, num); num += eventCandidates.Count; array2 = array; fieldCandidates.CopyTo(array2, num); num += fieldCandidates.Count; array2 = array; nestedTypeCandidates.CopyTo(array2, num); num += nestedTypeCandidates.Count; return array; } public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type ifaceType) { if (IsGenericParameter) { throw new InvalidOperationException(SR.Arg_GenericParameter); } if ((object)ifaceType == null) { throw new ArgumentNullException("ifaceType"); } RuntimeType runtimeType = ifaceType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, "ifaceType"); } RuntimeTypeHandle typeHandleInternal = runtimeType.GetTypeHandleInternal(); GetTypeHandleInternal().VerifyInterfaceIsImplemented(typeHandleInternal); if (IsSZArray && ifaceType.IsGenericType) { throw new ArgumentException(SR.Argument_ArrayGetInterfaceMap); } int numVirtualsAndStaticVirtuals = RuntimeTypeHandle.GetNumVirtualsAndStaticVirtuals(runtimeType); System.Runtime.CompilerServices.Unsafe.SkipInit(out InterfaceMapping result); result.InterfaceType = ifaceType; result.TargetType = this; result.InterfaceMethods = new MethodInfo[numVirtualsAndStaticVirtuals]; result.TargetMethods = new MethodInfo[numVirtualsAndStaticVirtuals]; for (int i = 0; i < numVirtualsAndStaticVirtuals; i++) { RuntimeMethodHandleInternal methodAt = RuntimeTypeHandle.GetMethodAt(runtimeType, i); MethodBase methodBase = GetMethodBase(runtimeType, methodAt); result.InterfaceMethods[i] = (MethodInfo)methodBase; RuntimeMethodHandleInternal interfaceMethodImplementation = GetTypeHandleInternal().GetInterfaceMethodImplementation(typeHandleInternal, methodAt); if (!interfaceMethodImplementation.IsNullHandle()) { RuntimeType runtimeType2 = RuntimeMethodHandle.GetDeclaringType(interfaceMethodImplementation); if (!runtimeType2.IsInterface) { runtimeType2 = this; } MethodBase methodBase2 = GetMethodBase(runtimeType2, interfaceMethodImplementation); result.TargetMethods[i] = (MethodInfo)methodBase2; } } return result; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConv, Type[] types, ParameterModifier[] modifiers) { return GetMethodImplCommon(name, -1, bindingAttr, binder, callConv, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] protected override MethodInfo GetMethodImpl(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConv, Type[] types, ParameterModifier[] modifiers) { return GetMethodImplCommon(name, genericParameterCount, bindingAttr, binder, callConv, types, modifiers); } private MethodInfo GetMethodImplCommon(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConv, Type[] types, ParameterModifier[] modifiers) { ListBuilder methodCandidates = GetMethodCandidates(name, genericParameterCount, bindingAttr, callConv, types, allowPrefixLookup: false); if (methodCandidates.Count == 0) { return null; } MethodBase[] match; if (types == null || types.Length == 0) { MethodInfo methodInfo = methodCandidates[0]; if (methodCandidates.Count == 1) { return methodInfo; } if (types == null) { for (int i = 1; i < methodCandidates.Count; i++) { MethodInfo m = methodCandidates[i]; if (!System.DefaultBinder.CompareMethodSig(m, methodInfo)) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } } match = methodCandidates.ToArray(); return System.DefaultBinder.FindMostDerivedNewSlotMeth(match, methodCandidates.Count) as MethodInfo; } } if (binder == null) { binder = Type.DefaultBinder; } Binder binder2 = binder; match = methodCandidates.ToArray(); return binder2.SelectMethod(bindingAttr, match, types, modifiers) as MethodInfo; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { ListBuilder constructorCandidates = GetConstructorCandidates(null, bindingAttr, CallingConventions.Any, types, allowPrefixLookup: false); if (constructorCandidates.Count == 0) { return null; } if (types.Length == 0 && constructorCandidates.Count == 1) { ConstructorInfo constructorInfo = constructorCandidates[0]; ParameterInfo[] parametersNoCopy = constructorInfo.GetParametersNoCopy(); if (parametersNoCopy == null || parametersNoCopy.Length == 0) { return constructorInfo; } } MethodBase[] match; if ((bindingAttr & BindingFlags.ExactBinding) != 0) { match = constructorCandidates.ToArray(); return System.DefaultBinder.ExactBinding(match, types, modifiers) as ConstructorInfo; } if (binder == null) { binder = Type.DefaultBinder; } Binder binder2 = binder; match = constructorCandidates.ToArray(); return binder2.SelectMethod(bindingAttr, match, types, modifiers) as ConstructorInfo; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { if (name == null) { throw new ArgumentNullException("name"); } ListBuilder propertyCandidates = GetPropertyCandidates(name, bindingAttr, types, allowPrefixLookup: false); if (propertyCandidates.Count == 0) { return null; } if (types == null || types.Length == 0) { if (propertyCandidates.Count == 1) { PropertyInfo propertyInfo = propertyCandidates[0]; if ((object)returnType != null && !returnType.IsEquivalentTo(propertyInfo.PropertyType)) { return null; } return propertyInfo; } if ((object)returnType == null) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } } if ((bindingAttr & BindingFlags.ExactBinding) != 0) { return System.DefaultBinder.ExactPropertyBinding(propertyCandidates.ToArray(), returnType, types, modifiers); } if (binder == null) { binder = Type.DefaultBinder; } return binder.SelectProperty(bindingAttr, propertyCandidates.ToArray(), returnType, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo GetEvent(string name, BindingFlags bindingAttr) { if (name == null) { throw new ArgumentNullException("name"); } FilterHelper(bindingAttr, ref name, out var _, out var listType); RuntimeEventInfo[] eventList = Cache.GetEventList(listType, name); EventInfo eventInfo = null; bindingAttr ^= BindingFlags.DeclaredOnly; foreach (RuntimeEventInfo runtimeEventInfo in eventList) { if ((bindingAttr & runtimeEventInfo.BindingFlags) == runtimeEventInfo.BindingFlags) { if (eventInfo != null) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } eventInfo = runtimeEventInfo; } } return eventInfo; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo GetField(string name, BindingFlags bindingAttr) { if (name == null) { throw new ArgumentNullException(); } FilterHelper(bindingAttr, ref name, out var _, out var listType); RuntimeFieldInfo[] fieldList = Cache.GetFieldList(listType, name); FieldInfo fieldInfo = null; bindingAttr ^= BindingFlags.DeclaredOnly; bool flag = false; foreach (RuntimeFieldInfo runtimeFieldInfo in fieldList) { if ((bindingAttr & runtimeFieldInfo.BindingFlags) != runtimeFieldInfo.BindingFlags) { continue; } if (fieldInfo != null) { if ((object)runtimeFieldInfo.DeclaringType == fieldInfo.DeclaringType) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } if (fieldInfo.DeclaringType.IsInterface && runtimeFieldInfo.DeclaringType.IsInterface) { flag = true; } } if (fieldInfo == null || runtimeFieldInfo.DeclaringType.IsSubclassOf(fieldInfo.DeclaringType) || fieldInfo.DeclaringType.IsInterface) { fieldInfo = runtimeFieldInfo; } } if (flag && fieldInfo.DeclaringType.IsInterface) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } return fieldInfo; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type GetInterface(string fullname, bool ignoreCase) { if (fullname == null) { throw new ArgumentNullException("fullname"); } BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic; bindingFlags &= ~BindingFlags.Static; if (ignoreCase) { bindingFlags |= BindingFlags.IgnoreCase; } SplitName(fullname, out var name, out var ns); FilterHelper(bindingFlags, ref name, out var _, out var listType); RuntimeType[] interfaceList = Cache.GetInterfaceList(listType, name); RuntimeType runtimeType = null; foreach (RuntimeType runtimeType2 in interfaceList) { if (FilterApplyType(runtimeType2, bindingFlags, name, prefixLookup: false, ns)) { if (runtimeType != null) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } runtimeType = runtimeType2; } } return runtimeType; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type GetNestedType(string fullname, BindingFlags bindingAttr) { if (fullname == null) { throw new ArgumentNullException("fullname"); } bindingAttr &= ~BindingFlags.Static; SplitName(fullname, out var name, out var ns); FilterHelper(bindingAttr, ref name, out var _, out var listType); RuntimeType[] nestedTypeList = Cache.GetNestedTypeList(listType, name); RuntimeType runtimeType = null; foreach (RuntimeType runtimeType2 in nestedTypeList) { if (FilterApplyType(runtimeType2, bindingAttr, name, prefixLookup: false, ns)) { if (runtimeType != null) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } runtimeType = runtimeType2; } } return runtimeType; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { if (name == null) { throw new ArgumentNullException("name"); } ListBuilder listBuilder = default(ListBuilder); ListBuilder listBuilder2 = default(ListBuilder); ListBuilder listBuilder3 = default(ListBuilder); ListBuilder listBuilder4 = default(ListBuilder); ListBuilder listBuilder5 = default(ListBuilder); ListBuilder listBuilder6 = default(ListBuilder); int num = 0; if ((type & MemberTypes.Method) != 0) { listBuilder = GetMethodCandidates(name, -1, bindingAttr, CallingConventions.Any, null, allowPrefixLookup: true); if (type == MemberTypes.Method) { return listBuilder.ToArray(); } num += listBuilder.Count; } if ((type & MemberTypes.Constructor) != 0) { listBuilder2 = GetConstructorCandidates(name, bindingAttr, CallingConventions.Any, null, allowPrefixLookup: true); if (type == MemberTypes.Constructor) { return listBuilder2.ToArray(); } num += listBuilder2.Count; } if ((type & MemberTypes.Property) != 0) { listBuilder3 = GetPropertyCandidates(name, bindingAttr, null, allowPrefixLookup: true); if (type == MemberTypes.Property) { return listBuilder3.ToArray(); } num += listBuilder3.Count; } if ((type & MemberTypes.Event) != 0) { listBuilder4 = GetEventCandidates(name, bindingAttr, allowPrefixLookup: true); if (type == MemberTypes.Event) { return listBuilder4.ToArray(); } num += listBuilder4.Count; } if ((type & MemberTypes.Field) != 0) { listBuilder5 = GetFieldCandidates(name, bindingAttr, allowPrefixLookup: true); if (type == MemberTypes.Field) { return listBuilder5.ToArray(); } num += listBuilder5.Count; } if ((type & (MemberTypes.TypeInfo | MemberTypes.NestedType)) != 0) { listBuilder6 = GetNestedTypeCandidates(name, bindingAttr, allowPrefixLookup: true); if (type == MemberTypes.NestedType || type == MemberTypes.TypeInfo) { return listBuilder6.ToArray(); } num += listBuilder6.Count; } MemberInfo[] array; if (type != (MemberTypes.Constructor | MemberTypes.Method)) { array = new MemberInfo[num]; } else { MemberInfo[] array2 = new MethodBase[num]; array = array2; } MemberInfo[] array3 = array; int num2 = 0; object[] array4 = array3; listBuilder.CopyTo(array4, num2); num2 += listBuilder.Count; array4 = array3; listBuilder2.CopyTo(array4, num2); num2 += listBuilder2.Count; array4 = array3; listBuilder3.CopyTo(array4, num2); num2 += listBuilder3.Count; array4 = array3; listBuilder4.CopyTo(array4, num2); num2 += listBuilder4.Count; array4 = array3; listBuilder5.CopyTo(array4, num2); num2 += listBuilder5.Count; array4 = array3; listBuilder6.CopyTo(array4, num2); num2 += listBuilder6.Count; return array3; } public override MemberInfo GetMemberWithSameMetadataDefinitionAs(MemberInfo member) { if ((object)member == null) { throw new ArgumentNullException("member"); } RuntimeType runtimeType = this; while (runtimeType != null) { MemberInfo memberInfo = member.MemberType switch { MemberTypes.Method => GetMethodWithSameMetadataDefinitionAs(runtimeType, member), MemberTypes.Constructor => GetConstructorWithSameMetadataDefinitionAs(runtimeType, member), MemberTypes.Property => GetPropertyWithSameMetadataDefinitionAs(runtimeType, member), MemberTypes.Field => GetFieldWithSameMetadataDefinitionAs(runtimeType, member), MemberTypes.Event => GetEventWithSameMetadataDefinitionAs(runtimeType, member), MemberTypes.NestedType => GetNestedTypeWithSameMetadataDefinitionAs(runtimeType, member), _ => null, }; if (memberInfo != null) { return memberInfo; } runtimeType = runtimeType.GetBaseType(); } throw Type.CreateGetMemberWithSameMetadataDefinitionAsNotFoundException(member); } private static MemberInfo GetMethodWithSameMetadataDefinitionAs(RuntimeType runtimeType, MemberInfo method) { RuntimeMethodInfo[] methodList = runtimeType.Cache.GetMethodList(MemberListType.CaseSensitive, method.Name); foreach (RuntimeMethodInfo runtimeMethodInfo in methodList) { if (runtimeMethodInfo.HasSameMetadataDefinitionAs(method)) { return runtimeMethodInfo; } } return null; } private static MemberInfo GetConstructorWithSameMetadataDefinitionAs(RuntimeType runtimeType, MemberInfo constructor) { RuntimeConstructorInfo[] constructorList = runtimeType.Cache.GetConstructorList(MemberListType.CaseSensitive, constructor.Name); foreach (RuntimeConstructorInfo runtimeConstructorInfo in constructorList) { if (runtimeConstructorInfo.HasSameMetadataDefinitionAs(constructor)) { return runtimeConstructorInfo; } } return null; } private static MemberInfo GetPropertyWithSameMetadataDefinitionAs(RuntimeType runtimeType, MemberInfo property) { RuntimePropertyInfo[] propertyList = runtimeType.Cache.GetPropertyList(MemberListType.CaseSensitive, property.Name); foreach (RuntimePropertyInfo runtimePropertyInfo in propertyList) { if (runtimePropertyInfo.HasSameMetadataDefinitionAs(property)) { return runtimePropertyInfo; } } return null; } private static MemberInfo GetFieldWithSameMetadataDefinitionAs(RuntimeType runtimeType, MemberInfo field) { RuntimeFieldInfo[] fieldList = runtimeType.Cache.GetFieldList(MemberListType.CaseSensitive, field.Name); foreach (RuntimeFieldInfo runtimeFieldInfo in fieldList) { if (runtimeFieldInfo.HasSameMetadataDefinitionAs(field)) { return runtimeFieldInfo; } } return null; } private static MemberInfo GetEventWithSameMetadataDefinitionAs(RuntimeType runtimeType, MemberInfo eventInfo) { RuntimeEventInfo[] eventList = runtimeType.Cache.GetEventList(MemberListType.CaseSensitive, eventInfo.Name); foreach (RuntimeEventInfo runtimeEventInfo in eventList) { if (runtimeEventInfo.HasSameMetadataDefinitionAs(eventInfo)) { return runtimeEventInfo; } } return null; } private static MemberInfo GetNestedTypeWithSameMetadataDefinitionAs(RuntimeType runtimeType, MemberInfo nestedType) { RuntimeType[] nestedTypeList = runtimeType.Cache.GetNestedTypeList(MemberListType.CaseSensitive, nestedType.Name); foreach (RuntimeType runtimeType2 in nestedTypeList) { if (runtimeType2.HasSameMetadataDefinitionAs(nestedType)) { return runtimeType2; } } return null; } public override bool IsSubclassOf(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } RuntimeType runtimeType = type as RuntimeType; if (runtimeType == null) { return false; } RuntimeType baseType = GetBaseType(); while (baseType != null) { if (baseType == runtimeType) { return true; } baseType = baseType.GetBaseType(); } if (runtimeType == ObjectType && runtimeType != this) { return true; } return false; } public override bool IsEquivalentTo([NotNullWhen(true)] Type other) { if (!(other is RuntimeType runtimeType)) { return false; } if (runtimeType == this) { return true; } return RuntimeTypeHandle.IsEquivalentTo(this, runtimeType); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void GetGUID(ref Guid result); internal bool IsDelegate() { return GetBaseType() == typeof(MulticastDelegate); } internal object[] GetEmptyArray() { return Cache.GetEmptyArray(); } internal RuntimeType[] GetGenericArgumentsInternal() { return GetRootElementType().GetTypeHandleInternal().GetInstantiationInternal(); } public override Type[] GetGenericArguments() { Type[] instantiationPublic = GetRootElementType().GetTypeHandleInternal().GetInstantiationPublic(); return instantiationPublic ?? Type.EmptyTypes; } [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public override Type MakeGenericType(params Type[] instantiation) { if (instantiation == null) { throw new ArgumentNullException("instantiation"); } if (!IsGenericTypeDefinition) { throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this)); } RuntimeType[] genericArgumentsInternal = GetGenericArgumentsInternal(); if (genericArgumentsInternal.Length != instantiation.Length) { throw new ArgumentException(SR.Argument_GenericArgsCount, "instantiation"); } if (instantiation.Length == 1 && instantiation[0] is RuntimeType runtimeType) { ThrowIfTypeNeverValidGenericArgument(runtimeType); try { return new RuntimeTypeHandle(this).Instantiate(runtimeType); } catch (TypeLoadException e) { ValidateGenericArguments(this, new RuntimeType[1] { runtimeType }, e); throw; } } RuntimeType[] array = new RuntimeType[instantiation.Length]; bool flag = false; bool flag2 = false; for (int i = 0; i < instantiation.Length; i++) { Type type = instantiation[i]; if (type == null) { throw new ArgumentNullException(); } RuntimeType runtimeType2 = type as RuntimeType; if (runtimeType2 == null) { flag2 = true; if (type.IsSignatureType) { flag = true; } } array[i] = runtimeType2; } if (flag2) { if (flag) { return new SignatureConstructedGenericType(this, instantiation); } return TypeBuilderInstantiation.MakeGenericType(this, (Type[])instantiation.Clone()); } SanityCheckGenericArguments(array, genericArgumentsInternal); try { RuntimeTypeHandle runtimeTypeHandle = new RuntimeTypeHandle(this); Type[] inst = array; return runtimeTypeHandle.Instantiate(inst); } catch (TypeLoadException e2) { ValidateGenericArguments(this, array, e2); throw; } } public override Type[] GetGenericParameterConstraints() { if (!IsGenericParameter) { throw new InvalidOperationException(SR.Arg_NotGenericParameter); } Type[] constraints = new RuntimeTypeHandle(this).GetConstraints(); return constraints ?? Type.EmptyTypes; } public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) { return HasSameMetadataDefinitionAsCore(other); } public override Type MakePointerType() { return new RuntimeTypeHandle(this).MakePointer(); } public override Type MakeByRefType() { return new RuntimeTypeHandle(this).MakeByRef(); } public override Type MakeArrayType() { return new RuntimeTypeHandle(this).MakeSZArray(); } public override Type MakeArrayType(int rank) { if (rank <= 0) { throw new IndexOutOfRangeException(); } return new RuntimeTypeHandle(this).MakeArray(rank); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool CanValueSpecialCast(RuntimeType valueType, RuntimeType targetType); [MethodImpl(MethodImplOptions.InternalCall)] private static extern object AllocateValueType(RuntimeType type, object value, bool fForceTypeChange); internal object CheckValue(object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr) { if (IsInstanceOfType(value)) { Type type = value.GetType(); if ((object)type != this && RuntimeTypeHandle.IsValueType(this)) { return AllocateValueType(this, value, fForceTypeChange: true); } return value; } if (base.IsByRef) { RuntimeType elementType = RuntimeTypeHandle.GetElementType(this); if (elementType.IsInstanceOfType(value) || value == null) { return AllocateValueType(elementType, value, fForceTypeChange: false); } } else { if (value == null) { return value; } if (this == s_typedRef) { return value; } } bool flag = base.IsPointer || IsEnum || base.IsPrimitive; if (flag) { Pointer pointer = value as Pointer; RuntimeType valueType = ((pointer == null) ? ((RuntimeType)value.GetType()) : ((RuntimeType)pointer.GetPointerType())); if (CanValueSpecialCast(valueType, this)) { if (pointer != null) { return pointer.GetPointerValue(); } return value; } } if ((invokeAttr & BindingFlags.ExactBinding) == BindingFlags.ExactBinding) { throw new ArgumentException(SR.Format(SR.Arg_ObjObjEx, value.GetType(), this)); } return TryChangeType(value, binder, culture, flag); } private object TryChangeType(object value, Binder binder, CultureInfo culture, bool needsSpecialCast) { if (binder != null && binder != Type.DefaultBinder) { value = binder.ChangeType(value, this, culture); if (IsInstanceOfType(value)) { return value; } if (base.IsByRef) { RuntimeType elementType = RuntimeTypeHandle.GetElementType(this); if (elementType.IsInstanceOfType(value) || value == null) { return AllocateValueType(elementType, value, fForceTypeChange: false); } } else if (value == null) { return value; } if (needsSpecialCast) { Pointer pointer = value as Pointer; RuntimeType valueType = ((pointer == null) ? ((RuntimeType)value.GetType()) : ((RuntimeType)pointer.GetPointerType())); if (CanValueSpecialCast(valueType, this)) { if (pointer != null) { return pointer.GetPointerValue(); } return value; } } } throw new ArgumentException(SR.Format(SR.Arg_ObjObjEx, value.GetType(), this)); } public override string ToString() { return GetCachedName(TypeNameKind.ToString); } [MethodImpl(MethodImplOptions.NoInlining)] private string GetCachedName(TypeNameKind kind) { return Cache.GetName(kind); } private void CreateInstanceCheckThis() { if (ContainsGenericParameters) { throw new ArgumentException(SR.Format(SR.Acc_CreateGenericEx, this)); } Type rootElementType = GetRootElementType(); if ((object)rootElementType == typeof(ArgIterator)) { throw new NotSupportedException(SR.Acc_CreateArgIterator); } if ((object)rootElementType == typeof(void)) { throw new NotSupportedException(SR.Acc_CreateVoid); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2082:UnrecognizedReflectionPattern", Justification = "Implementation detail of Activator that linker intrinsically recognizes")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2085:UnrecognizedReflectionPattern", Justification = "Implementation detail of Activator that linker intrinsically recognizes")] internal object CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture) { CreateInstanceCheckThis(); if (args == null) { args = Array.Empty(); } if (binder == null) { binder = Type.DefaultBinder; } bool publicOnly = (bindingAttr & BindingFlags.NonPublic) == 0; bool wrapExceptions = (bindingAttr & BindingFlags.DoNotWrapExceptions) == 0; object result; if (args.Length == 0 && (bindingAttr & BindingFlags.Public) != 0 && (bindingAttr & BindingFlags.Instance) != 0 && (IsGenericCOMObjectImpl() || base.IsValueType)) { result = CreateInstanceDefaultCtor(publicOnly, wrapExceptions); } else { ConstructorInfo[] constructors = GetConstructors(bindingAttr); List list = new List(constructors.Length); Type[] array = new Type[args.Length]; for (int i = 0; i < args.Length; i++) { object obj = args[i]; if (obj != null) { array[i] = obj.GetType(); } } for (int j = 0; j < constructors.Length; j++) { if (FilterApplyConstructorInfo((RuntimeConstructorInfo)constructors[j], bindingAttr, CallingConventions.Any, array)) { list.Add(constructors[j]); } } if (list.Count == 0) { throw new MissingMethodException(SR.Format(SR.MissingConstructor_Name, FullName)); } MethodBase[] match = list.ToArray(); object state = null; MethodBase methodBase; try { methodBase = binder.BindToMethod(bindingAttr, match, ref args, null, culture, null, out state); } catch (MissingMethodException) { methodBase = null; } if ((object)methodBase == null) { throw new MissingMethodException(SR.Format(SR.MissingConstructor_Name, FullName)); } if (methodBase.GetParametersNoCopy().Length == 0) { if (args.Length != 0) { throw new NotSupportedException(SR.NotSupported_CallToVarArg); } result = Activator.CreateInstance(this, nonPublic: true, wrapExceptions); } else { result = ((ConstructorInfo)methodBase).Invoke(bindingAttr, binder, args, culture); if (state != null) { binder.ReorderArgumentArray(ref args, state); } } } return result; } [DebuggerStepThrough] [DebuggerHidden] internal object CreateInstanceDefaultCtor(bool publicOnly, bool wrapExceptions) { ActivatorCache activatorCache = GenericCache as ActivatorCache; if (activatorCache == null) { activatorCache = (ActivatorCache)(GenericCache = new ActivatorCache(this)); } if (!activatorCache.CtorIsPublic && publicOnly) { throw new MissingMethodException(SR.Format(SR.Arg_NoDefCTor, this)); } object obj = activatorCache.CreateUninitializedObject(this); try { activatorCache.CallConstructor(obj); return obj; } catch (Exception inner) when (wrapExceptions) { throw new TargetInvocationException(inner); } } [DebuggerStepThrough] [DebuggerHidden] internal object CreateInstanceOfT() { ActivatorCache activatorCache = GenericCache as ActivatorCache; if (activatorCache == null) { activatorCache = (ActivatorCache)(GenericCache = new ActivatorCache(this)); } if (!activatorCache.CtorIsPublic) { throw new MissingMethodException(SR.Format(SR.Arg_NoDefCTor, this)); } object obj = activatorCache.CreateUninitializedObject(this); try { activatorCache.CallConstructor(obj); return obj; } catch (Exception inner) { throw new TargetInvocationException(inner); } } internal void InvalidateCachedNestedType() { Cache.InvalidateCachedNestedType(); } internal bool IsGenericCOMObjectImpl() { return RuntimeTypeHandle.IsComObject(this, isGenericCOM: true); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern object _CreateEnum(RuntimeType enumType, long value); internal static object CreateEnum(RuntimeType enumType, long value) { return _CreateEnum(enumType, value); } [MethodImpl(MethodImplOptions.InternalCall)] private extern object InvokeDispMethod(string name, BindingFlags invokeAttr, object target, object[] args, bool[] byrefModifiers, int culture, string[] namedParameters); [RequiresUnreferencedCode("The member might be removed")] private object ForwardCallToInvokeMember(string memberName, BindingFlags flags, object target, object[] aArgs, bool[] aArgsIsByRef, int[] aArgsWrapperTypes, Type[] aArgsTypes, Type retType) { if (!Marshal.IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } int num = aArgs.Length; ParameterModifier[] array = null; if (num > 0) { ParameterModifier parameterModifier = new ParameterModifier(num); for (int i = 0; i < num; i++) { parameterModifier[i] = aArgsIsByRef[i]; } array = new ParameterModifier[1] { parameterModifier }; if (aArgsWrapperTypes != null) { WrapArgsForInvokeCall(aArgs, aArgsWrapperTypes); } } flags |= BindingFlags.DoNotWrapExceptions; object obj = InvokeMember(memberName, flags, null, target, aArgs, array, null, null); for (int j = 0; j < num; j++) { if (array[0][j] && aArgs[j] != null) { Type type = aArgsTypes[j]; if ((object)type != aArgs[j].GetType()) { aArgs[j] = ForwardCallBinder.ChangeType(aArgs[j], type, null); } } } if (obj != null && (object)retType != obj.GetType()) { obj = ForwardCallBinder.ChangeType(obj, retType, null); } return obj; } private static void WrapArgsForInvokeCall(object[] aArgs, int[] aArgsWrapperTypes) { int num = aArgs.Length; for (int i = 0; i < num; i++) { if (aArgsWrapperTypes[i] == 0) { continue; } if (((DispatchWrapperType)aArgsWrapperTypes[i]).HasFlag(DispatchWrapperType.SafeArray)) { Type type = null; bool flag = false; switch ((DispatchWrapperType)(aArgsWrapperTypes[i] & -65537)) { case DispatchWrapperType.Unknown: type = typeof(UnknownWrapper); break; case DispatchWrapperType.Dispatch: type = typeof(DispatchWrapper); break; case DispatchWrapperType.Error: type = typeof(ErrorWrapper); break; case DispatchWrapperType.Currency: type = typeof(CurrencyWrapper); break; case DispatchWrapperType.BStr: type = typeof(BStrWrapper); flag = true; break; } Array array = (Array)aArgs[i]; int length = array.Length; object[] array2 = (object[])Array.CreateInstance(type, length); ConstructorInfo constructorInfo = ((!flag) ? type.GetConstructor(new Type[1] { typeof(object) }) : type.GetConstructor(new Type[1] { typeof(string) })); for (int j = 0; j < length; j++) { if (flag) { array2[j] = constructorInfo.Invoke(new object[1] { (string)array.GetValue(j) }); } else { array2[j] = constructorInfo.Invoke(new object[1] { array.GetValue(j) }); } } aArgs[i] = array2; } else { switch ((DispatchWrapperType)aArgsWrapperTypes[i]) { case DispatchWrapperType.Unknown: aArgs[i] = new UnknownWrapper(aArgs[i]); break; case DispatchWrapperType.Dispatch: aArgs[i] = new DispatchWrapper(aArgs[i]); break; case DispatchWrapperType.Error: aArgs[i] = new ErrorWrapper(aArgs[i]); break; case DispatchWrapperType.Currency: aArgs[i] = new CurrencyWrapper(aArgs[i]); break; case DispatchWrapperType.BStr: aArgs[i] = new BStrWrapper((string)aArgs[i]); break; } } } } public object Clone() { return this; } public override bool Equals(object obj) { return obj == this; } public override int GetArrayRank() { if (!IsArrayImpl()) { throw new ArgumentException(SR.Argument_HasToBeArrayClass); } return RuntimeTypeHandle.GetArrayRank(this); } protected override TypeAttributes GetAttributeFlagsImpl() { return RuntimeTypeHandle.GetAttributes(this); } public override object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, ObjectType, inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { if ((object)attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.GetCustomAttributes(this, runtimeType, inherit); } public override IList GetCustomAttributesData() { return RuntimeCustomAttributeData.GetCustomAttributesInternal(this); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicEvents)] public override MemberInfo[] GetDefaultMembers() { MemberInfo[] array = null; string defaultMemberName = GetDefaultMemberName(); if (defaultMemberName != null) { array = GetMember(defaultMemberName); } return array ?? Array.Empty(); } public override Type GetElementType() { return RuntimeTypeHandle.GetElementType(this); } public override string GetEnumName(object value) { if (value == null) { throw new ArgumentNullException("value"); } Type type = value.GetType(); if (!type.IsEnum && !Type.IsIntegerType(type)) { throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, "value"); } ulong ulValue = Enum.ToUInt64(value); return Enum.GetEnumName(this, ulValue); } public override string[] GetEnumNames() { if (!IsEnum) { throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); } string[] array = Enum.InternalGetNames(this); return new ReadOnlySpan(array).ToArray(); } public override Array GetEnumValues() { if (!IsEnum) { throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); } ulong[] array = Enum.InternalGetValues(this); Array array2 = Array.CreateInstance(this, array.Length); for (int i = 0; i < array.Length; i++) { object value = Enum.ToObject(this, array[i]); array2.SetValue(value, i); } return array2; } public override Type GetEnumUnderlyingType() { if (!IsEnum) { throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); } return Enum.InternalGetUnderlyingType(this); } public override Type GetGenericTypeDefinition() { if (!IsGenericType) { throw new InvalidOperationException(SR.InvalidOperation_NotGenericType); } return RuntimeTypeHandle.GetGenericTypeDefinition(this); } public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } internal RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(this); } protected override TypeCode GetTypeCodeImpl() { TypeCode typeCode = Cache.TypeCode; if (typeCode != 0) { return typeCode; } typeCode = RuntimeTypeHandle.GetCorElementType(this) switch { CorElementType.ELEMENT_TYPE_BOOLEAN => TypeCode.Boolean, CorElementType.ELEMENT_TYPE_CHAR => TypeCode.Char, CorElementType.ELEMENT_TYPE_I1 => TypeCode.SByte, CorElementType.ELEMENT_TYPE_U1 => TypeCode.Byte, CorElementType.ELEMENT_TYPE_I2 => TypeCode.Int16, CorElementType.ELEMENT_TYPE_U2 => TypeCode.UInt16, CorElementType.ELEMENT_TYPE_I4 => TypeCode.Int32, CorElementType.ELEMENT_TYPE_U4 => TypeCode.UInt32, CorElementType.ELEMENT_TYPE_I8 => TypeCode.Int64, CorElementType.ELEMENT_TYPE_U8 => TypeCode.UInt64, CorElementType.ELEMENT_TYPE_R4 => TypeCode.Single, CorElementType.ELEMENT_TYPE_R8 => TypeCode.Double, CorElementType.ELEMENT_TYPE_VALUETYPE => ((object)this != typeof(decimal)) ? (((object)this != typeof(DateTime)) ? ((!IsEnum) ? TypeCode.Object : Type.GetTypeCode(Enum.InternalGetUnderlyingType(this))) : TypeCode.DateTime) : TypeCode.Decimal, _ => ((object)this != typeof(string)) ? (((object)this != typeof(DBNull)) ? TypeCode.Object : TypeCode.DBNull) : TypeCode.String, }; Cache.TypeCode = typeCode; return typeCode; } protected override bool HasElementTypeImpl() { return RuntimeTypeHandle.HasElementType(this); } protected override bool IsArrayImpl() { return RuntimeTypeHandle.IsArray(this); } protected override bool IsContextfulImpl() { return false; } public override bool IsDefined(Type attributeType, bool inherit) { if ((object)attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.IsDefined(this, runtimeType, inherit); } public override bool IsEnumDefined(object value) { if (value == null) { throw new ArgumentNullException("value"); } if (!IsEnum) { throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); } RuntimeType runtimeType = (RuntimeType)value.GetType(); if (runtimeType.IsEnum) { if (!runtimeType.IsEquivalentTo(this)) { throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, runtimeType, this)); } runtimeType = (RuntimeType)runtimeType.GetEnumUnderlyingType(); } if (runtimeType == StringType) { string[] array = Enum.InternalGetNames(this); object[] array2 = array; return Array.IndexOf(array2, value) >= 0; } if (Type.IsIntegerType(runtimeType)) { RuntimeType runtimeType2 = Enum.InternalGetUnderlyingType(this); if (runtimeType2 != runtimeType) { throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, runtimeType, runtimeType2)); } ulong[] array3 = Enum.InternalGetValues(this); ulong value2 = Enum.ToUInt64(value); return Array.BinarySearch(array3, value2) >= 0; } throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } protected override bool IsValueTypeImpl() { if (this == typeof(ValueType) || this == typeof(Enum)) { return false; } return IsSubclassOf(typeof(ValueType)); } protected override bool IsByRefImpl() { return RuntimeTypeHandle.IsByRef(this); } protected override bool IsPrimitiveImpl() { return RuntimeTypeHandle.IsPrimitive(this); } protected override bool IsPointerImpl() { return RuntimeTypeHandle.IsPointer(this); } protected override bool IsCOMObjectImpl() { return RuntimeTypeHandle.IsComObject(this, isGenericCOM: false); } public override bool IsInstanceOfType([NotNullWhen(true)] object o) { return RuntimeTypeHandle.IsInstanceOfType(this, o); } public override bool IsAssignableFrom([NotNullWhen(true)] TypeInfo typeInfo) { if (typeInfo == null) { return false; } return IsAssignableFrom(typeInfo.AsType()); } public override bool IsAssignableFrom([NotNullWhen(true)] Type c) { if ((object)c == null) { return false; } if ((object)c == this) { return true; } if (c.UnderlyingSystemType is RuntimeType type) { return RuntimeTypeHandle.CanCastTo(type, this); } if (c is TypeBuilder) { if (c.IsSubclassOf(this)) { return true; } if (base.IsInterface) { return c.ImplementInterface(this); } if (IsGenericParameter) { Type[] genericParameterConstraints = GetGenericParameterConstraints(); for (int i = 0; i < genericParameterConstraints.Length; i++) { if (!genericParameterConstraints[i].IsAssignableFrom(c)) { return false; } } return true; } } return false; } [DebuggerStepThrough] [DebuggerHidden] [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public override object InvokeMember(string name, BindingFlags bindingFlags, Binder binder, object target, object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParams) { if (IsGenericParameter) { throw new InvalidOperationException(SR.Arg_GenericParameter); } if ((bindingFlags & (BindingFlags.InvokeMethod | BindingFlags.CreateInstance | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty | BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) == 0) { throw new ArgumentException(SR.Arg_NoAccessSpec, "bindingFlags"); } if ((bindingFlags & (BindingFlags)255) == 0) { bindingFlags |= BindingFlags.Instance | BindingFlags.Public; if ((bindingFlags & BindingFlags.CreateInstance) == 0) { bindingFlags |= BindingFlags.Static; } } if (namedParams != null) { if (providedArgs != null) { if (namedParams.Length > providedArgs.Length) { throw new ArgumentException(SR.Arg_NamedParamTooBig, "namedParams"); } } else if (namedParams.Length != 0) { throw new ArgumentException(SR.Arg_NamedParamTooBig, "namedParams"); } } if (target != null && target.GetType().IsCOMObject) { if ((bindingFlags & (BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.SetProperty | BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) == 0) { throw new ArgumentException(SR.Arg_COMAccess, "bindingFlags"); } if ((bindingFlags & BindingFlags.GetProperty) != 0 && ((uint)(bindingFlags & (BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.SetProperty | BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) & 0xFFFFEEFFu) != 0) { throw new ArgumentException(SR.Arg_PropSetGet, "bindingFlags"); } if ((bindingFlags & BindingFlags.InvokeMethod) != 0 && ((uint)(bindingFlags & (BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.SetProperty | BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) & 0xFFFFEEFFu) != 0) { throw new ArgumentException(SR.Arg_PropSetInvoke, "bindingFlags"); } if ((bindingFlags & BindingFlags.SetProperty) != 0 && ((uint)(bindingFlags & (BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.SetProperty | BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) & 0xFFFFDFFFu) != 0) { throw new ArgumentException(SR.Arg_COMPropSetPut, "bindingFlags"); } if ((bindingFlags & BindingFlags.PutDispProperty) != 0 && ((uint)(bindingFlags & (BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.SetProperty | BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) & 0xFFFFBFFFu) != 0) { throw new ArgumentException(SR.Arg_COMPropSetPut, "bindingFlags"); } if ((bindingFlags & BindingFlags.PutRefDispProperty) != 0 && ((uint)(bindingFlags & (BindingFlags.InvokeMethod | BindingFlags.GetProperty | BindingFlags.SetProperty | BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) & 0xFFFF7FFFu) != 0) { throw new ArgumentException(SR.Arg_COMPropSetPut, "bindingFlags"); } if (name == null) { throw new ArgumentNullException("name"); } bool[] byrefModifiers = modifiers?[0].IsByRefArray; int culture2 = culture?.LCID ?? 1033; bool flag = (bindingFlags & BindingFlags.DoNotWrapExceptions) != 0; try { return InvokeDispMethod(name, bindingFlags, target, providedArgs, byrefModifiers, culture2, namedParams); } catch (TargetInvocationException ex) when (flag) { throw ex.InnerException; } } if (namedParams != null && Array.IndexOf(namedParams, null) != -1) { throw new ArgumentException(SR.Arg_NamedParamNull, "namedParams"); } int num = ((providedArgs != null) ? providedArgs.Length : 0); if (binder == null) { binder = Type.DefaultBinder; } if ((bindingFlags & BindingFlags.CreateInstance) != 0) { if ((bindingFlags & BindingFlags.CreateInstance) != 0 && (bindingFlags & (BindingFlags.InvokeMethod | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty | BindingFlags.SetProperty)) != 0) { throw new ArgumentException(SR.Arg_CreatInstAccess, "bindingFlags"); } return Activator.CreateInstance(this, bindingFlags, binder, providedArgs, culture); } if ((bindingFlags & (BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty)) != 0) { bindingFlags |= BindingFlags.SetProperty; } if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0 || name.Equals("[DISPID=0]")) { name = GetDefaultMemberName() ?? "ToString"; } bool flag2 = (bindingFlags & BindingFlags.GetField) != 0; bool flag3 = (bindingFlags & BindingFlags.SetField) != 0; if (flag2 || flag3) { if (flag2) { if (flag3) { throw new ArgumentException(SR.Arg_FldSetGet, "bindingFlags"); } if ((bindingFlags & BindingFlags.SetProperty) != 0) { throw new ArgumentException(SR.Arg_FldGetPropSet, "bindingFlags"); } } else { if (providedArgs == null) { throw new ArgumentNullException("providedArgs"); } if ((bindingFlags & BindingFlags.GetProperty) != 0) { throw new ArgumentException(SR.Arg_FldSetPropGet, "bindingFlags"); } if ((bindingFlags & BindingFlags.InvokeMethod) != 0) { throw new ArgumentException(SR.Arg_FldSetInvoke, "bindingFlags"); } } FieldInfo fieldInfo = null; FieldInfo[] array = GetMember(name, MemberTypes.Field, bindingFlags) as FieldInfo[]; if (array.Length == 1) { fieldInfo = array[0]; } else if (array.Length != 0) { fieldInfo = binder.BindToField(bindingFlags, array, flag2 ? Empty.Value : providedArgs[0], culture); } if (fieldInfo != null) { if (fieldInfo.FieldType.IsArray || (object)fieldInfo.FieldType == typeof(Array)) { int num2 = (((bindingFlags & BindingFlags.GetField) == 0) ? (num - 1) : num); if (num2 > 0) { int[] array2 = new int[num2]; for (int i = 0; i < num2; i++) { try { array2[i] = ((IConvertible)providedArgs[i]).ToInt32(null); } catch (InvalidCastException) { throw new ArgumentException(SR.Arg_IndexMustBeInt); } } Array array3 = (Array)fieldInfo.GetValue(target); if ((bindingFlags & BindingFlags.GetField) != 0) { return array3.GetValue(array2); } array3.SetValue(providedArgs[num2], array2); return null; } } if (flag2) { if (num != 0) { throw new ArgumentException(SR.Arg_FldGetArgErr, "bindingFlags"); } return fieldInfo.GetValue(target); } if (num != 1) { throw new ArgumentException(SR.Arg_FldSetArgErr, "bindingFlags"); } fieldInfo.SetValue(target, providedArgs[0], bindingFlags, binder, culture); return null; } if ((bindingFlags & (BindingFlags)16773888) == 0) { throw new MissingFieldException(FullName, name); } } bool flag4 = (bindingFlags & BindingFlags.GetProperty) != 0; bool flag5 = (bindingFlags & BindingFlags.SetProperty) != 0; if (flag4 || flag5) { if (flag4) { if (flag5) { throw new ArgumentException(SR.Arg_PropSetGet, "bindingFlags"); } } else if ((bindingFlags & BindingFlags.InvokeMethod) != 0) { throw new ArgumentException(SR.Arg_PropSetInvoke, "bindingFlags"); } } MethodInfo[] array4 = null; MethodInfo methodInfo = null; if ((bindingFlags & BindingFlags.InvokeMethod) != 0) { MethodInfo[] array5 = GetMember(name, MemberTypes.Method, bindingFlags) as MethodInfo[]; List list = null; foreach (MethodInfo methodInfo2 in array5) { if (!FilterApplyMethodInfo((RuntimeMethodInfo)methodInfo2, bindingFlags, CallingConventions.Any, new Type[num])) { continue; } if (methodInfo == null) { methodInfo = methodInfo2; continue; } if (list == null) { list = new List(array5.Length) { methodInfo }; } list.Add(methodInfo2); } if (list != null) { array4 = list.ToArray(); } } if ((methodInfo == null && flag4) || flag5) { PropertyInfo[] array6 = GetMember(name, MemberTypes.Property, bindingFlags) as PropertyInfo[]; List list2 = null; for (int k = 0; k < array6.Length; k++) { MethodInfo methodInfo3 = null; methodInfo3 = ((!flag5) ? array6[k].GetGetMethod(nonPublic: true) : array6[k].GetSetMethod(nonPublic: true)); if (methodInfo3 == null || !FilterApplyMethodInfo((RuntimeMethodInfo)methodInfo3, bindingFlags, CallingConventions.Any, new Type[num])) { continue; } if (methodInfo == null) { methodInfo = methodInfo3; continue; } if (list2 == null) { list2 = new List(array6.Length) { methodInfo }; } list2.Add(methodInfo3); } if (list2 != null) { array4 = list2.ToArray(); } } if (methodInfo != null) { if (array4 == null && num == 0 && methodInfo.GetParametersNoCopy().Length == 0 && (bindingFlags & BindingFlags.OptionalParamBinding) == 0) { return methodInfo.Invoke(target, bindingFlags, binder, providedArgs, culture); } if (array4 == null) { array4 = new MethodInfo[1] { methodInfo }; } if (providedArgs == null) { providedArgs = Array.Empty(); } object state = null; MethodBase methodBase = null; try { Binder binder2 = binder; BindingFlags bindingAttr = bindingFlags; MethodBase[] match = array4; methodBase = binder2.BindToMethod(bindingAttr, match, ref providedArgs, modifiers, culture, namedParams, out state); } catch (MissingMethodException) { } if (methodBase == null) { throw new MissingMethodException(FullName, name); } object result = ((MethodInfo)methodBase).Invoke(target, bindingFlags, binder, providedArgs, culture); if (state != null) { binder.ReorderArgumentArray(ref providedArgs, state); } return result; } throw new MissingMethodException(FullName, name); } private RuntimeType GetBaseType() { if (base.IsInterface) { return null; } if (RuntimeTypeHandle.IsGenericVariable(this)) { Type[] genericParameterConstraints = GetGenericParameterConstraints(); RuntimeType runtimeType = ObjectType; for (int i = 0; i < genericParameterConstraints.Length; i++) { RuntimeType runtimeType2 = (RuntimeType)genericParameterConstraints[i]; if (runtimeType2.IsInterface) { continue; } if (runtimeType2.IsGenericParameter) { GenericParameterAttributes genericParameterAttributes = runtimeType2.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask; if ((genericParameterAttributes & GenericParameterAttributes.ReferenceTypeConstraint) == 0 && (genericParameterAttributes & GenericParameterAttributes.NotNullableValueTypeConstraint) == 0) { continue; } } runtimeType = runtimeType2; } if (runtimeType == ObjectType) { GenericParameterAttributes genericParameterAttributes2 = GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask; if ((genericParameterAttributes2 & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) { runtimeType = ValueType; } } return runtimeType; } return RuntimeTypeHandle.GetBaseType(this); } private static void ThrowIfTypeNeverValidGenericArgument(RuntimeType type) { if (type.IsPointer || type.IsByRef || type == typeof(void)) { throw new ArgumentException(SR.Format(SR.Argument_NeverValidGenericArgument, type)); } } internal static void SanityCheckGenericArguments(RuntimeType[] genericArguments, RuntimeType[] genericParameters) { if (genericArguments == null) { throw new ArgumentNullException(); } for (int i = 0; i < genericArguments.Length; i++) { if (genericArguments[i] == null) { throw new ArgumentNullException(); } ThrowIfTypeNeverValidGenericArgument(genericArguments[i]); } if (genericArguments.Length != genericParameters.Length) { throw new ArgumentException(SR.Format(SR.Argument_NotEnoughGenArguments, genericArguments.Length, genericParameters.Length)); } } } internal enum TypeNameFormatFlags { FormatBasic = 0, FormatNamespace = 1, FormatFullInst = 2, FormatAssembly = 4, FormatSignature = 8, FormatNoVersion = 0x10, FormatAngleBrackets = 0x40, FormatStubInfo = 0x80, FormatGenericParam = 0x100 } internal enum TypeNameKind { Name, ToString, FullName } internal readonly struct MdUtf8String { private unsafe readonly byte* m_pStringHeap; private readonly int m_StringHeapByteLength; [DllImport("QCall", CharSet = CharSet.Unicode)] private unsafe static extern bool EqualsCaseInsensitive(void* szLhs, void* szRhs, int cSz); [DllImport("QCall", CharSet = CharSet.Unicode)] private unsafe static extern uint HashCaseInsensitive(void* sz, int cSz); internal unsafe MdUtf8String(void* pStringHeap) { if (pStringHeap != null) { m_StringHeapByteLength = string.strlen((byte*)pStringHeap); } else { m_StringHeapByteLength = 0; } m_pStringHeap = (byte*)pStringHeap; } internal unsafe MdUtf8String(byte* pUtf8String, int cUtf8String) { m_pStringHeap = pUtf8String; m_StringHeapByteLength = cUtf8String; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe bool Equals(MdUtf8String s) { if (s.m_StringHeapByteLength != m_StringHeapByteLength) { return false; } return SpanHelpers.SequenceEqual(ref *s.m_pStringHeap, ref *m_pStringHeap, (uint)m_StringHeapByteLength); } internal unsafe bool EqualsCaseInsensitive(MdUtf8String s) { if (s.m_StringHeapByteLength != m_StringHeapByteLength) { return false; } if (m_StringHeapByteLength != 0) { return EqualsCaseInsensitive(s.m_pStringHeap, m_pStringHeap, m_StringHeapByteLength); } return true; } internal unsafe uint HashCaseInsensitive() { return HashCaseInsensitive(m_pStringHeap, m_StringHeapByteLength); } public unsafe override string ToString() { return Encoding.UTF8.GetString(new ReadOnlySpan(m_pStringHeap, m_StringHeapByteLength)); } } internal static class StartupHookProvider { private struct StartupHookNameOrPath { public AssemblyName AssemblyName; public string Path; } private static bool IsSupported { get { if (!AppContext.TryGetSwitch("System.StartupHookProvider.IsSupported", out var isEnabled)) { return true; } return isEnabled; } } private static void ProcessStartupHooks() { if (!IsSupported) { return; } if (EventSource.IsSupported) { RuntimeEventSource.Initialize(); } if (!(AppContext.GetData("STARTUP_HOOKS") is string text)) { return; } Span span = stackalloc char[4] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar, ' ', ',' }; ReadOnlySpan readOnlySpan = span; string[] array = text.Split(Path.PathSeparator); StartupHookNameOrPath[] array2 = new StartupHookNameOrPath[array.Length]; for (int i = 0; i < array.Length; i++) { string text2 = array[i]; if (string.IsNullOrEmpty(text2)) { continue; } if (Path.IsPathFullyQualified(text2)) { array2[i].Path = text2; continue; } for (int j = 0; j < readOnlySpan.Length; j++) { if (text2.Contains(readOnlySpan[j])) { throw new ArgumentException(SR.Format(SR.Argument_InvalidStartupHookSimpleAssemblyName, text2)); } } if (text2.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidStartupHookSimpleAssemblyName, text2)); } try { array2[i].AssemblyName = new AssemblyName(text2); } catch (Exception innerException) { throw new ArgumentException(SR.Format(SR.Argument_InvalidStartupHookSimpleAssemblyName, text2), innerException); } } StartupHookNameOrPath[] array3 = array2; foreach (StartupHookNameOrPath startupHook in array3) { CallStartupHook(startupHook); } } [RequiresUnreferencedCode("The StartupHookSupport feature switch has been enabled for this app which is being trimmed. Startup hook code is not observable by the trimmer and so required assemblies, types and members may be removed")] private static void CallStartupHook(StartupHookNameOrPath startupHook) { Assembly assembly; try { if (startupHook.Path != null) { assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(startupHook.Path); } else { if (startupHook.AssemblyName == null) { return; } assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(startupHook.AssemblyName); } } catch (Exception innerException) { throw new ArgumentException(SR.Format(SR.Argument_StartupHookAssemblyLoadFailed, startupHook.Path ?? startupHook.AssemblyName.ToString()), innerException); } Type type = assembly.GetType("StartupHook", throwOnError: true); MethodInfo method = type.GetMethod("Initialize", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); bool flag = false; if (method == null) { try { method = type.GetMethod("Initialize", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } catch (AmbiguousMatchException) { } if (!(method != null)) { throw new MissingMethodException("StartupHook", "Initialize"); } flag = true; } else if (method.ReturnType != typeof(void)) { flag = true; } if (flag) { throw new ArgumentException(SR.Format(SR.Argument_InvalidStartupHookSignature, "StartupHook" + Type.Delimiter + "Initialize", startupHook.Path ?? startupHook.AssemblyName.ToString())); } method.Invoke(null, null); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class String : IComparable, System.Collections.IEnumerable, IConvertible, IEnumerable, IComparable, IEquatable, ICloneable { [StructLayout(LayoutKind.Explicit, Size = 32)] private struct ProbabilisticMap { } [Intrinsic] public static readonly string Empty; [NonSerialized] private readonly int _stringLength; [NonSerialized] private char _firstChar; [IndexerName("Chars")] public char this[int index] { [Intrinsic] get { if ((uint)index >= (uint)_stringLength) { ThrowHelper.ThrowIndexOutOfRangeException(); } return Unsafe.Add(ref _firstChar, (nint)(uint)index); } } public int Length { [Intrinsic] get { return _stringLength; } } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern string FastAllocateString(int length); [MethodImpl(MethodImplOptions.InternalCall)] internal extern void SetTrailByte(byte data); [MethodImpl(MethodImplOptions.InternalCall)] internal extern bool TryGetTrailByte(out byte data); [MethodImpl(MethodImplOptions.InternalCall)] private extern string Intern(); [MethodImpl(MethodImplOptions.InternalCall)] private extern string IsInterned(); public static string Intern(string str) { if ((object)str == null) { throw new ArgumentNullException("str"); } return str.Intern(); } public static string? IsInterned(string str) { if ((object)str == null) { throw new ArgumentNullException("str"); } return str.IsInterned(); } internal unsafe static void InternalCopy(string src, IntPtr dest, int len) { if (len != 0) { Buffer.Memmove(ref *(byte*)(void*)dest, ref Unsafe.As(ref src.GetRawStringData()), (nuint)len); } } internal unsafe int GetBytesFromEncoding(byte* pbNativeBuffer, int cbNativeBuffer, Encoding encoding) { fixed (char* chars = &_firstChar) { return encoding.GetBytes(chars, Length, pbNativeBuffer, cbNativeBuffer); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool EqualsHelper(string strA, string strB) { return SpanHelpers.SequenceEqual(ref Unsafe.As(ref strA.GetRawStringData()), ref Unsafe.As(ref strB.GetRawStringData()), (uint)(strA.Length * 2)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int CompareOrdinalHelper(string strA, int indexA, int countA, string strB, int indexB, int countB) { return SpanHelpers.SequenceCompareTo(ref Unsafe.Add(ref strA.GetRawStringData(), (nint)(uint)indexA), countA, ref Unsafe.Add(ref strB.GetRawStringData(), (nint)(uint)indexB), countB); } internal static bool EqualsOrdinalIgnoreCase(string strA, string strB) { if ((object)strA == strB) { return true; } if ((object)strA == null || (object)strB == null) { return false; } if (strA.Length != strB.Length) { return false; } return EqualsOrdinalIgnoreCaseNoLengthCheck(strA, strB); } private static bool EqualsOrdinalIgnoreCaseNoLengthCheck(string strA, string strB) { return Ordinal.EqualsIgnoreCase(ref strA.GetRawStringData(), ref strB.GetRawStringData(), strB.Length); } private unsafe static int CompareOrdinalHelper(string strA, string strB) { int num = Math.Min(strA.Length, strB.Length); fixed (char* ptr = &strA._firstChar) { fixed (char* ptr3 = &strB._firstChar) { char* ptr2 = ptr; char* ptr4 = ptr3; if (ptr2[1] == ptr4[1]) { num -= 2; ptr2 += 2; ptr4 += 2; while (true) { if (num >= 10) { if (*(int*)ptr2 != *(int*)ptr4) { break; } if (*(int*)(ptr2 + 2) == *(int*)(ptr4 + 2)) { if (*(int*)(ptr2 + 4) == *(int*)(ptr4 + 4)) { if (*(int*)(ptr2 + 6) == *(int*)(ptr4 + 6)) { if (*(int*)(ptr2 + 8) == *(int*)(ptr4 + 8)) { num -= 10; ptr2 += 10; ptr4 += 10; continue; } ptr2 += 8; ptr4 += 8; break; } ptr2 += 6; ptr4 += 6; break; } ptr2 += 2; ptr4 += 2; } ptr2 += 2; ptr4 += 2; break; } while (true) { if (num > 0) { if (*(int*)ptr2 != *(int*)ptr4) { break; } num -= 2; ptr2 += 2; ptr4 += 2; continue; } return strA.Length - strB.Length; } break; } if (*ptr2 != *ptr4) { return *ptr2 - *ptr4; } } return ptr2[1] - ptr4[1]; } } } public static int Compare(string? strA, string? strB) { return Compare(strA, strB, StringComparison.CurrentCulture); } public static int Compare(string? strA, string? strB, bool ignoreCase) { StringComparison comparisonType = (ignoreCase ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture); return Compare(strA, strB, comparisonType); } public static int Compare(string? strA, string? strB, StringComparison comparisonType) { if ((object)strA == strB) { CheckStringComparison(comparisonType); return 0; } if ((object)strA == null) { CheckStringComparison(comparisonType); return -1; } if ((object)strB == null) { CheckStringComparison(comparisonType); return 1; } switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, strB, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.Compare(strA, strB, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: if (strA._firstChar != strB._firstChar) { return strA._firstChar - strB._firstChar; } return CompareOrdinalHelper(strA, strB); case StringComparison.OrdinalIgnoreCase: return Ordinal.CompareStringIgnoreCase(ref strA.GetRawStringData(), strA.Length, ref strB.GetRawStringData(), strB.Length); default: throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType"); } } public static int Compare(string? strA, string? strB, CultureInfo? culture, CompareOptions options) { CultureInfo cultureInfo = culture ?? CultureInfo.CurrentCulture; return cultureInfo.CompareInfo.Compare(strA, strB, options); } public static int Compare(string? strA, string? strB, bool ignoreCase, CultureInfo? culture) { CompareOptions options = (ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); return Compare(strA, strB, culture, options); } public static int Compare(string? strA, int indexA, string? strB, int indexB, int length) { return Compare(strA, indexA, strB, indexB, length, ignoreCase: false); } public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase) { int num = length; int num2 = length; if ((object)strA != null) { num = Math.Min(num, strA.Length - indexA); } if ((object)strB != null) { num2 = Math.Min(num2, strB.Length - indexB); } CompareOptions options = (ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, num, strB, indexB, num2, options); } public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, bool ignoreCase, CultureInfo? culture) { CompareOptions options = (ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); return Compare(strA, indexA, strB, indexB, length, culture, options); } public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, CultureInfo? culture, CompareOptions options) { CultureInfo cultureInfo = culture ?? CultureInfo.CurrentCulture; int num = length; int num2 = length; if ((object)strA != null) { num = Math.Min(num, strA.Length - indexA); } if ((object)strB != null) { num2 = Math.Min(num2, strB.Length - indexB); } return cultureInfo.CompareInfo.Compare(strA, indexA, num, strB, indexB, num2, options); } public static int Compare(string? strA, int indexA, string? strB, int indexB, int length, StringComparison comparisonType) { CheckStringComparison(comparisonType); if ((object)strA == null || (object)strB == null) { if ((object)strA == strB) { return 0; } if ((object)strA != null) { return 1; } return -1; } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NegativeLength); } if (indexA < 0 || indexB < 0) { string paramName = ((indexA < 0) ? "indexA" : "indexB"); throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index); } if (strA.Length - indexA < 0 || strB.Length - indexB < 0) { string paramName2 = ((strA.Length - indexA < 0) ? "indexA" : "indexB"); throw new ArgumentOutOfRangeException(paramName2, SR.ArgumentOutOfRange_Index); } if (length == 0 || ((object)strA == strB && indexA == indexB)) { return 0; } int num = Math.Min(length, strA.Length - indexA); int num2 = Math.Min(length, strB.Length - indexB); switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.Compare(strA, indexA, num, strB, indexB, num2, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.Compare(strA, indexA, num, strB, indexB, num2, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: return CompareOrdinalHelper(strA, indexA, num, strB, indexB, num2); default: return Ordinal.CompareStringIgnoreCase(ref Unsafe.Add(ref strA.GetRawStringData(), indexA), num, ref Unsafe.Add(ref strB.GetRawStringData(), indexB), num2); } } public static int CompareOrdinal(string? strA, string? strB) { if ((object)strA == strB) { return 0; } if ((object)strA == null) { return -1; } if ((object)strB == null) { return 1; } if (strA._firstChar != strB._firstChar) { return strA._firstChar - strB._firstChar; } return CompareOrdinalHelper(strA, strB); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int CompareOrdinal(ReadOnlySpan strA, ReadOnlySpan strB) { return SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(strA), strA.Length, ref MemoryMarshal.GetReference(strB), strB.Length); } public static int CompareOrdinal(string? strA, int indexA, string? strB, int indexB, int length) { if ((object)strA == null || (object)strB == null) { if ((object)strA == strB) { return 0; } if ((object)strA != null) { return 1; } return -1; } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NegativeCount); } if (indexA < 0 || indexB < 0) { string paramName = ((indexA < 0) ? "indexA" : "indexB"); throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_Index); } int num = Math.Min(length, strA.Length - indexA); int num2 = Math.Min(length, strB.Length - indexB); if (num < 0 || num2 < 0) { string paramName2 = ((num < 0) ? "indexA" : "indexB"); throw new ArgumentOutOfRangeException(paramName2, SR.ArgumentOutOfRange_Index); } if (length == 0 || ((object)strA == strB && indexA == indexB)) { return 0; } return CompareOrdinalHelper(strA, indexA, num, strB, indexB, num2); } public int CompareTo(object? value) { if (value == null) { return 1; } if (!(value is string strB)) { throw new ArgumentException(SR.Arg_MustBeString); } return CompareTo(strB); } public int CompareTo(string? strB) { return Compare(this, strB, StringComparison.CurrentCulture); } public bool EndsWith(string value) { return EndsWith(value, StringComparison.CurrentCulture); } public bool EndsWith(string value, StringComparison comparisonType) { if ((object)value == null) { throw new ArgumentNullException("value"); } if ((object)this == value) { CheckStringComparison(comparisonType); return true; } if (value.Length == 0) { CheckStringComparison(comparisonType); return true; } switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IsSuffix(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: { int num = Length - value.Length; if ((uint)num <= (uint)Length) { return this.AsSpan(num).SequenceEqual(value); } return false; } case StringComparison.OrdinalIgnoreCase: if (Length >= value.Length) { return Ordinal.CompareStringIgnoreCase(ref Unsafe.Add(ref GetRawStringData(), Length - value.Length), value.Length, ref value.GetRawStringData(), value.Length) == 0; } return false; default: throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType"); } } public bool EndsWith(string value, bool ignoreCase, CultureInfo? culture) { if ((object)value == null) { throw new ArgumentNullException("value"); } if ((object)this == value) { return true; } CultureInfo cultureInfo = culture ?? CultureInfo.CurrentCulture; return cultureInfo.CompareInfo.IsSuffix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } public bool EndsWith(char value) { int num = Length - 1; if ((uint)num < (uint)Length) { return this[num] == value; } return false; } public override bool Equals([NotNullWhen(true)] object? obj) { if (this == obj) { return true; } if (!(obj is string text)) { return false; } if (Length != text.Length) { return false; } return EqualsHelper(this, text); } public bool Equals([NotNullWhen(true)] string? value) { if ((object)this == value) { return true; } if ((object)value == null) { return false; } if (Length != value.Length) { return false; } return EqualsHelper(this, value); } public bool Equals([NotNullWhen(true)] string? value, StringComparison comparisonType) { if ((object)this == value) { CheckStringComparison(comparisonType); return true; } if ((object)value == null) { CheckStringComparison(comparisonType); return false; } switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.Compare(this, value, GetCaseCompareOfComparisonCulture(comparisonType)) == 0; case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.Compare(this, value, GetCaseCompareOfComparisonCulture(comparisonType)) == 0; case StringComparison.Ordinal: if (Length != value.Length) { return false; } return EqualsHelper(this, value); case StringComparison.OrdinalIgnoreCase: if (Length != value.Length) { return false; } return EqualsOrdinalIgnoreCaseNoLengthCheck(this, value); default: throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType"); } } public static bool Equals(string? a, string? b) { if ((object)a == b) { return true; } if ((object)a == null || (object)b == null || a.Length != b.Length) { return false; } return EqualsHelper(a, b); } public static bool Equals(string? a, string? b, StringComparison comparisonType) { if ((object)a == b) { CheckStringComparison(comparisonType); return true; } if ((object)a == null || (object)b == null) { CheckStringComparison(comparisonType); return false; } switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.Compare(a, b, GetCaseCompareOfComparisonCulture(comparisonType)) == 0; case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.Compare(a, b, GetCaseCompareOfComparisonCulture(comparisonType)) == 0; case StringComparison.Ordinal: if (a.Length != b.Length) { return false; } return EqualsHelper(a, b); case StringComparison.OrdinalIgnoreCase: if (a.Length != b.Length) { return false; } return EqualsOrdinalIgnoreCaseNoLengthCheck(a, b); default: throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType"); } } public static bool operator ==(string? a, string? b) { return Equals(a, b); } public static bool operator !=(string? a, string? b) { return !Equals(a, b); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { ulong defaultSeed = Marvin.DefaultSeed; return Marvin.ComputeHash32(ref Unsafe.As(ref _firstChar), (uint)(_stringLength * 2), (uint)defaultSeed, (uint)(defaultSeed >> 32)); } public int GetHashCode(StringComparison comparisonType) { return StringComparer.FromComparison(comparisonType).GetHashCode(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal int GetHashCodeOrdinalIgnoreCase() { ulong defaultSeed = Marvin.DefaultSeed; return Marvin.ComputeHash32OrdinalIgnoreCase(ref _firstChar, _stringLength, (uint)defaultSeed, (uint)(defaultSeed >> 32)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetHashCode(ReadOnlySpan value) { ulong defaultSeed = Marvin.DefaultSeed; return Marvin.ComputeHash32(ref Unsafe.As(ref MemoryMarshal.GetReference(value)), (uint)(value.Length * 2), (uint)defaultSeed, (uint)(defaultSeed >> 32)); } public static int GetHashCode(ReadOnlySpan value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.GetHashCode(value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.GetHashCode(value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: return GetHashCode(value); case StringComparison.OrdinalIgnoreCase: return GetHashCodeOrdinalIgnoreCase(value); default: ThrowHelper.ThrowArgumentException(ExceptionResource.NotSupported_StringComparison, ExceptionArgument.comparisonType); return 0; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetHashCodeOrdinalIgnoreCase(ReadOnlySpan value) { ulong defaultSeed = Marvin.DefaultSeed; return Marvin.ComputeHash32OrdinalIgnoreCase(ref MemoryMarshal.GetReference(value), value.Length, (uint)defaultSeed, (uint)(defaultSeed >> 32)); } internal unsafe int GetNonRandomizedHashCode() { fixed (char* ptr = &_firstChar) { uint num = 352654597u; uint num2 = num; uint* ptr2 = (uint*)ptr; int num3 = Length; while (num3 > 2) { num3 -= 4; num = (BitOperations.RotateLeft(num, 5) + num) ^ *ptr2; num2 = (BitOperations.RotateLeft(num2, 5) + num2) ^ ptr2[1]; ptr2 += 2; } if (num3 > 0) { num2 = (BitOperations.RotateLeft(num2, 5) + num2) ^ *ptr2; } return (int)(num + num2 * 1566083941); } } internal unsafe int GetNonRandomizedHashCodeOrdinalIgnoreCase() { uint num = 352654597u; uint num2 = num; fixed (char* ptr = &_firstChar) { uint* ptr2 = (uint*)ptr; int num3 = Length; while (true) { if (num3 > 2) { uint num4 = *ptr2; uint num5 = ptr2[1]; if (Utf16Utility.AllCharsInUInt32AreAscii(num4 | num5)) { num3 -= 4; num = (BitOperations.RotateLeft(num, 5) + num) ^ (num4 | 0x200020u); num2 = (BitOperations.RotateLeft(num2, 5) + num2) ^ (num5 | 0x200020u); ptr2 += 2; continue; } } else { if (num3 <= 0) { break; } uint num6 = *ptr2; if (Utf16Utility.AllCharsInUInt32AreAscii(num6)) { num2 = (BitOperations.RotateLeft(num2, 5) + num2) ^ (num6 | 0x200020u); break; } } goto IL_00ab; } } return (int)(num + num2 * 1566083941); IL_00ab: return GetNonRandomizedHashCodeOrdinalIgnoreCaseSlow(this); unsafe static int GetNonRandomizedHashCodeOrdinalIgnoreCaseSlow(string str) { int num7 = str.Length; char[] array = null; Span span = (((uint)num7 >= 64u) ? ((Span)(array = ArrayPool.Shared.Rent(num7 + 1))) : stackalloc char[64]); Span destination = span; int num8 = Ordinal.ToUpperOrdinal(str, destination); destination[num7] = '\0'; uint num9 = 352654597u; uint num10 = num9; fixed (char* ptr3 = destination) { uint* ptr4 = (uint*)ptr3; while (num7 > 2) { num7 -= 4; num9 = (BitOperations.RotateLeft(num9, 5) + num9) ^ (*ptr4 | 0x200020u); num10 = (BitOperations.RotateLeft(num10, 5) + num10) ^ (ptr4[1] | 0x200020u); ptr4 += 2; } if (num7 > 0) { num10 = (BitOperations.RotateLeft(num10, 5) + num10) ^ (*ptr4 | 0x200020u); } } if (array != null) { ArrayPool.Shared.Return(array); } return (int)(num9 + num10 * 1566083941); } } public bool StartsWith(string value) { if ((object)value == null) { throw new ArgumentNullException("value"); } return StartsWith(value, StringComparison.CurrentCulture); } public bool StartsWith(string value, StringComparison comparisonType) { if ((object)value == null) { throw new ArgumentNullException("value"); } if ((object)this == value) { CheckStringComparison(comparisonType); return true; } if (value.Length == 0) { CheckStringComparison(comparisonType); return true; } switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IsPrefix(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: if (Length < value.Length || _firstChar != value._firstChar) { return false; } if (value.Length != 1) { return SpanHelpers.SequenceEqual(ref Unsafe.As(ref GetRawStringData()), ref Unsafe.As(ref value.GetRawStringData()), (nuint)value.Length * (nuint)2u); } return true; case StringComparison.OrdinalIgnoreCase: if (Length < value.Length) { return false; } return Ordinal.EqualsIgnoreCase(ref GetRawStringData(), ref value.GetRawStringData(), value.Length); default: throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType"); } } public bool StartsWith(string value, bool ignoreCase, CultureInfo? culture) { if ((object)value == null) { throw new ArgumentNullException("value"); } if ((object)this == value) { return true; } CultureInfo cultureInfo = culture ?? CultureInfo.CurrentCulture; return cultureInfo.CompareInfo.IsPrefix(this, value, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } public bool StartsWith(char value) { if (Length != 0) { return _firstChar == value; } return false; } internal static void CheckStringComparison(StringComparison comparisonType) { if ((uint)comparisonType > 5u) { ThrowHelper.ThrowArgumentException(ExceptionResource.NotSupported_StringComparison, ExceptionArgument.comparisonType); } } internal static CompareOptions GetCaseCompareOfComparisonCulture(StringComparison comparisonType) { return (CompareOptions)(comparisonType & StringComparison.CurrentCultureIgnoreCase); } private static CompareOptions GetCompareOptionsFromOrdinalStringComparison(StringComparison comparisonType) { return (CompareOptions)(((uint)comparisonType & (uint)(0 - comparisonType)) << 28); } [MethodImpl(MethodImplOptions.InternalCall)] [DynamicDependency("Ctor(System.Char[])")] public extern String(char[]? value); private string Ctor(char[] value) { if (value == null || value.Length == 0) { return Empty; } string text = FastAllocateString(value.Length); nuint elementCount = (uint)text.Length; Buffer.Memmove(ref text._firstChar, ref MemoryMarshal.GetArrayDataReference(value), elementCount); return text; } [MethodImpl(MethodImplOptions.InternalCall)] [DynamicDependency("Ctor(System.Char[],System.Int32,System.Int32)")] public extern String(char[] value, int startIndex, int length); private string Ctor(char[] value, int startIndex, int length) { if (value == null) { throw new ArgumentNullException("value"); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NegativeLength); } if (startIndex > value.Length - length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (length == 0) { return Empty; } string text = FastAllocateString(length); nuint elementCount = (uint)text.Length; Buffer.Memmove(ref text._firstChar, ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(value), startIndex), elementCount); return text; } [MethodImpl(MethodImplOptions.InternalCall)] [CLSCompliant(false)] [DynamicDependency("Ctor(System.Char*)")] public unsafe extern String(char* value); private unsafe string Ctor(char* ptr) { if (ptr == null) { return Empty; } int num = wcslen(ptr); if (num == 0) { return Empty; } string text = FastAllocateString(num); nuint elementCount = (uint)text.Length; Buffer.Memmove(ref text._firstChar, ref *ptr, elementCount); return text; } [MethodImpl(MethodImplOptions.InternalCall)] [CLSCompliant(false)] [DynamicDependency("Ctor(System.Char*,System.Int32,System.Int32)")] public unsafe extern String(char* value, int startIndex, int length); private unsafe string Ctor(char* ptr, int startIndex, int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NegativeLength); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex); } char* ptr2 = ptr + startIndex; if (ptr2 < ptr) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_PartialWCHAR); } if (length == 0) { return Empty; } if (ptr == null) { throw new ArgumentOutOfRangeException("ptr", SR.ArgumentOutOfRange_PartialWCHAR); } string text = FastAllocateString(length); nuint elementCount = (uint)text.Length; Buffer.Memmove(ref text._firstChar, ref *ptr2, elementCount); return text; } [MethodImpl(MethodImplOptions.InternalCall)] [CLSCompliant(false)] [DynamicDependency("Ctor(System.SByte*)")] public unsafe extern String(sbyte* value); private unsafe string Ctor(sbyte* value) { if (value == null) { return Empty; } int numBytes = strlen((byte*)value); return CreateStringForSByteConstructor((byte*)value, numBytes); } [MethodImpl(MethodImplOptions.InternalCall)] [CLSCompliant(false)] [DynamicDependency("Ctor(System.SByte*,System.Int32,System.Int32)")] public unsafe extern String(sbyte* value, int startIndex, int length); private unsafe string Ctor(sbyte* value, int startIndex, int length) { if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NegativeLength); } if (value == null) { if (length == 0) { return Empty; } throw new ArgumentNullException("value"); } byte* ptr = (byte*)(value + startIndex); if (ptr < value) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_PartialWCHAR); } return CreateStringForSByteConstructor(ptr, length); } private unsafe static string CreateStringForSByteConstructor(byte* pb, int numBytes) { if (numBytes == 0) { return Empty; } int num = Interop.Kernel32.MultiByteToWideChar(0u, 1u, pb, numBytes, null, 0); if (num == 0) { throw new ArgumentException(SR.Arg_InvalidANSIString); } string text = FastAllocateString(num); fixed (char* lpWideCharStr = &text._firstChar) { num = Interop.Kernel32.MultiByteToWideChar(0u, 1u, pb, numBytes, lpWideCharStr, num); } if (num == 0) { throw new ArgumentException(SR.Arg_InvalidANSIString); } return text; } [MethodImpl(MethodImplOptions.InternalCall)] [CLSCompliant(false)] [DynamicDependency("Ctor(System.SByte*,System.Int32,System.Int32,System.Text.Encoding)")] public unsafe extern String(sbyte* value, int startIndex, int length, Encoding enc); private unsafe string Ctor(sbyte* value, int startIndex, int length, Encoding enc) { if (enc == null) { return new string(value, startIndex, length); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NeedNonNegNum); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex); } if (value == null) { if (length == 0) { return Empty; } throw new ArgumentNullException("value"); } byte* ptr = (byte*)(value + startIndex); if (ptr < value) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_PartialWCHAR); } return enc.GetString(new ReadOnlySpan(ptr, length)); } [MethodImpl(MethodImplOptions.InternalCall)] [DynamicDependency("Ctor(System.Char,System.Int32)")] public extern String(char c, int count); private unsafe string Ctor(char c, int count) { if (count <= 0) { if (count == 0) { return Empty; } throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NegativeCount); } string text = FastAllocateString(count); if (c != 0) { fixed (char* ptr = &text._firstChar) { uint num = ((uint)c << 16) | c; uint* ptr2 = (uint*)ptr; if (count >= 4) { count -= 4; do { *ptr2 = num; ptr2[1] = num; ptr2 += 2; count -= 4; } while (count >= 0); } if (((uint)count & 2u) != 0) { *ptr2 = num; ptr2++; } if (((uint)count & (true ? 1u : 0u)) != 0) { *(char*)ptr2 = c; } } } return text; } [MethodImpl(MethodImplOptions.InternalCall)] [DynamicDependency("Ctor(System.ReadOnlySpan{System.Char})")] public extern String(ReadOnlySpan value); private string Ctor(ReadOnlySpan value) { if (value.Length == 0) { return Empty; } string text = FastAllocateString(value.Length); Buffer.Memmove(ref text._firstChar, ref MemoryMarshal.GetReference(value), (uint)value.Length); return text; } public static string Create(int length, TState state, SpanAction action) { if (action == null) { throw new ArgumentNullException("action"); } if (length <= 0) { if (length == 0) { return Empty; } throw new ArgumentOutOfRangeException("length"); } string text = FastAllocateString(length); action(new Span(ref text.GetRawStringData(), length), state); return text; } public static string Create(IFormatProvider? provider, [InterpolatedStringHandlerArgument("provider")] ref DefaultInterpolatedStringHandler handler) { return handler.ToStringAndClear(); } public static string Create(IFormatProvider? provider, Span initialBuffer, [InterpolatedStringHandlerArgument(new string[] { "provider", "initialBuffer" })] ref DefaultInterpolatedStringHandler handler) { return handler.ToStringAndClear(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator ReadOnlySpan(string? value) { if ((object)value == null) { return default(ReadOnlySpan); } return new ReadOnlySpan(ref value.GetRawStringData(), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool TryGetSpan(int startIndex, int count, out ReadOnlySpan slice) { if ((uint)startIndex > (uint)Length || (uint)count > (uint)(Length - startIndex)) { slice = default(ReadOnlySpan); return false; } slice = new ReadOnlySpan(ref Unsafe.Add(ref _firstChar, (nint)(uint)startIndex), count); return true; } public object Clone() { return this; } public static string Copy(string str) { if ((object)str == null) { throw new ArgumentNullException("str"); } string text = FastAllocateString(str.Length); nuint elementCount = (uint)text.Length; Buffer.Memmove(ref text._firstChar, ref str._firstChar, elementCount); return text; } public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) { throw new ArgumentNullException("destination"); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NegativeCount); } if (sourceIndex < 0) { throw new ArgumentOutOfRangeException("sourceIndex", SR.ArgumentOutOfRange_Index); } if (count > Length - sourceIndex) { throw new ArgumentOutOfRangeException("sourceIndex", SR.ArgumentOutOfRange_IndexCount); } if (destinationIndex > destination.Length - count || destinationIndex < 0) { throw new ArgumentOutOfRangeException("destinationIndex", SR.ArgumentOutOfRange_IndexCount); } Buffer.Memmove(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(destination), destinationIndex), ref Unsafe.Add(ref _firstChar, sourceIndex), (uint)count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(Span destination) { if ((uint)Length <= (uint)destination.Length) { Buffer.Memmove(ref destination._pointer.Value, ref _firstChar, (uint)Length); } else { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryCopyTo(Span destination) { bool result = false; if ((uint)Length <= (uint)destination.Length) { Buffer.Memmove(ref destination._pointer.Value, ref _firstChar, (uint)Length); result = true; } return result; } public char[] ToCharArray() { if (Length == 0) { return Array.Empty(); } char[] array = new char[Length]; Buffer.Memmove(ref MemoryMarshal.GetArrayDataReference(array), ref _firstChar, (uint)Length); return array; } public char[] ToCharArray(int startIndex, int length) { if (startIndex < 0 || startIndex > Length || startIndex > Length - length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (length <= 0) { if (length == 0) { return Array.Empty(); } throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_Index); } char[] array = new char[length]; Buffer.Memmove(ref MemoryMarshal.GetArrayDataReference(array), ref Unsafe.Add(ref _firstChar, startIndex), (uint)length); return array; } [NonVersionable] public static bool IsNullOrEmpty([NotNullWhen(false)] string? value) { if ((object)value != null && value.Length != 0) { return false; } return true; } public static bool IsNullOrWhiteSpace([NotNullWhen(false)] string? value) { if ((object)value == null) { return true; } for (int i = 0; i < value.Length; i++) { if (!char.IsWhiteSpace(value[i])) { return false; } } return true; } [EditorBrowsable(EditorBrowsableState.Never)] [NonVersionable] public ref readonly char GetPinnableReference() { return ref _firstChar; } internal ref char GetRawStringData() { return ref _firstChar; } internal unsafe static string CreateStringFromEncoding(byte* bytes, int byteLength, Encoding encoding) { int charCount = encoding.GetCharCount(bytes, byteLength); if (charCount == 0) { return Empty; } string text = FastAllocateString(charCount); fixed (char* chars = &text._firstChar) { int chars2 = encoding.GetChars(bytes, byteLength, chars, charCount); } return text; } internal static string CreateFromChar(char c) { string text = FastAllocateString(1); text._firstChar = c; return text; } internal static string CreateFromChar(char c1, char c2) { string text = FastAllocateString(2); text._firstChar = c1; Unsafe.Add(ref text._firstChar, 1) = c2; return text; } public override string ToString() { return this; } public string ToString(IFormatProvider? provider) { return this; } public CharEnumerator GetEnumerator() { return new CharEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new CharEnumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new CharEnumerator(this); } public StringRuneEnumerator EnumerateRunes() { return new StringRuneEnumerator(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe static int wcslen(char* ptr) { int num = SpanHelpers.IndexOf(ref *ptr, '\0', int.MaxValue); if (num < 0) { ThrowMustBeNullTerminatedString(); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe static int strlen(byte* ptr) { int num = SpanHelpers.IndexOf(ref *ptr, 0, int.MaxValue); if (num < 0) { ThrowMustBeNullTerminatedString(); } return num; } [DoesNotReturn] private static void ThrowMustBeNullTerminatedString() { throw new ArgumentException(SR.Arg_MustBeNullTerminatedString); } public TypeCode GetTypeCode() { return TypeCode.String; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(this, provider); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(this, provider); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this, provider); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this, provider); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this, provider); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this, provider); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this, provider); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this, provider); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this, provider); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this, provider); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this, provider); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this, provider); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this, provider); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { return Convert.ToDateTime(this, provider); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } public bool IsNormalized() { return IsNormalized(NormalizationForm.FormC); } public bool IsNormalized(NormalizationForm normalizationForm) { if (IsAscii() && (normalizationForm == NormalizationForm.FormC || normalizationForm == NormalizationForm.FormKC || normalizationForm == NormalizationForm.FormD || normalizationForm == NormalizationForm.FormKD)) { return true; } return Normalization.IsNormalized(this, normalizationForm); } public string Normalize() { return Normalize(NormalizationForm.FormC); } public string Normalize(NormalizationForm normalizationForm) { if (IsAscii() && (normalizationForm == NormalizationForm.FormC || normalizationForm == NormalizationForm.FormKC || normalizationForm == NormalizationForm.FormD || normalizationForm == NormalizationForm.FormKD)) { return this; } return Normalization.Normalize(this, normalizationForm); } private unsafe bool IsAscii() { fixed (char* pBuffer = &_firstChar) { return ASCIIUtility.GetIndexOfFirstNonAsciiChar(pBuffer, (uint)Length) == (uint)Length; } } private static void FillStringChecked(string dest, int destPos, string src) { if (src.Length > dest.Length - destPos) { throw new IndexOutOfRangeException(); } Buffer.Memmove(ref Unsafe.Add(ref dest._firstChar, destPos), ref src._firstChar, (uint)src.Length); } public static string Concat(object? arg0) { return arg0?.ToString() ?? Empty; } public static string Concat(object? arg0, object? arg1) { return arg0?.ToString() + arg1; } public static string Concat(object? arg0, object? arg1, object? arg2) { return arg0?.ToString() + arg1?.ToString() + arg2; } public static string Concat(params object?[] args) { if (args == null) { throw new ArgumentNullException("args"); } if (args.Length <= 1) { object obj; if (args.Length != 0) { obj = args[0]?.ToString(); if (obj == null) { return Empty; } } else { obj = Empty; } return (string)obj; } string[] array = new string[args.Length]; int num = 0; for (int i = 0; i < args.Length; i++) { num += (array[i] = args[i]?.ToString() ?? Empty).Length; if (num < 0) { throw new OutOfMemoryException(); } } if (num == 0) { return Empty; } string text = FastAllocateString(num); int num2 = 0; foreach (string text2 in array) { FillStringChecked(text, num2, text2); num2 += text2.Length; } return text; } public static string Concat(IEnumerable values) { if (values == null) { throw new ArgumentNullException("values"); } if (typeof(T) == typeof(char)) { using (IEnumerator enumerator = Unsafe.As>(values).GetEnumerator()) { if (!enumerator.MoveNext()) { return Empty; } char current = enumerator.Current; if (!enumerator.MoveNext()) { return CreateFromChar(current); } Span initialBuffer = stackalloc char[256]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); valueStringBuilder.Append(current); do { current = enumerator.Current; valueStringBuilder.Append(current); } while (enumerator.MoveNext()); return valueStringBuilder.ToString(); } } using IEnumerator enumerator2 = values.GetEnumerator(); if (!enumerator2.MoveNext()) { return Empty; } string text = enumerator2.Current?.ToString(); if (!enumerator2.MoveNext()) { return text ?? Empty; } Span initialBuffer = stackalloc char[256]; ValueStringBuilder valueStringBuilder2 = new ValueStringBuilder(initialBuffer); valueStringBuilder2.Append(text); do { T current2 = enumerator2.Current; if (current2 != null) { valueStringBuilder2.Append(current2.ToString()); } } while (enumerator2.MoveNext()); return valueStringBuilder2.ToString(); } public static string Concat(IEnumerable values) { if (values == null) { throw new ArgumentNullException("values"); } using IEnumerator enumerator = values.GetEnumerator(); if (!enumerator.MoveNext()) { return Empty; } string current = enumerator.Current; if (!enumerator.MoveNext()) { return current ?? Empty; } Span initialBuffer = stackalloc char[256]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); valueStringBuilder.Append(current); do { valueStringBuilder.Append(enumerator.Current); } while (enumerator.MoveNext()); return valueStringBuilder.ToString(); } public static string Concat(string? str0, string? str1) { if (IsNullOrEmpty(str0)) { if (IsNullOrEmpty(str1)) { return Empty; } return str1; } if (IsNullOrEmpty(str1)) { return str0; } int length = str0.Length; string text = FastAllocateString(length + str1.Length); FillStringChecked(text, 0, str0); FillStringChecked(text, length, str1); return text; } public static string Concat(string? str0, string? str1, string? str2) { if (IsNullOrEmpty(str0)) { return str1 + str2; } if (IsNullOrEmpty(str1)) { return str0 + str2; } if (IsNullOrEmpty(str2)) { return str0 + str1; } int length = str0.Length + str1.Length + str2.Length; string text = FastAllocateString(length); FillStringChecked(text, 0, str0); FillStringChecked(text, str0.Length, str1); FillStringChecked(text, str0.Length + str1.Length, str2); return text; } public static string Concat(string? str0, string? str1, string? str2, string? str3) { if (IsNullOrEmpty(str0)) { return str1 + str2 + str3; } if (IsNullOrEmpty(str1)) { return str0 + str2 + str3; } if (IsNullOrEmpty(str2)) { return str0 + str1 + str3; } if (IsNullOrEmpty(str3)) { return str0 + str1 + str2; } int length = str0.Length + str1.Length + str2.Length + str3.Length; string text = FastAllocateString(length); FillStringChecked(text, 0, str0); FillStringChecked(text, str0.Length, str1); FillStringChecked(text, str0.Length + str1.Length, str2); FillStringChecked(text, str0.Length + str1.Length + str2.Length, str3); return text; } public static string Concat(ReadOnlySpan str0, ReadOnlySpan str1) { int num = checked(str0.Length + str1.Length); if (num == 0) { return Empty; } string text = FastAllocateString(num); Span destination = new Span(ref text._firstChar, text.Length); str0.CopyTo(destination); str1.CopyTo(destination.Slice(str0.Length)); return text; } public static string Concat(ReadOnlySpan str0, ReadOnlySpan str1, ReadOnlySpan str2) { int num = checked(str0.Length + str1.Length + str2.Length); if (num == 0) { return Empty; } string text = FastAllocateString(num); Span destination = new Span(ref text._firstChar, text.Length); str0.CopyTo(destination); destination = destination.Slice(str0.Length); str1.CopyTo(destination); destination = destination.Slice(str1.Length); str2.CopyTo(destination); return text; } public static string Concat(ReadOnlySpan str0, ReadOnlySpan str1, ReadOnlySpan str2, ReadOnlySpan str3) { int num = checked(str0.Length + str1.Length + str2.Length + str3.Length); if (num == 0) { return Empty; } string text = FastAllocateString(num); Span destination = new Span(ref text._firstChar, text.Length); str0.CopyTo(destination); destination = destination.Slice(str0.Length); str1.CopyTo(destination); destination = destination.Slice(str1.Length); str2.CopyTo(destination); destination = destination.Slice(str2.Length); str3.CopyTo(destination); return text; } public static string Concat(params string?[] values) { if (values == null) { throw new ArgumentNullException("values"); } if (values.Length <= 1) { object obj; if (values.Length != 0) { obj = values[0]; if (obj == null) { return Empty; } } else { obj = Empty; } return (string)obj; } long num = 0L; foreach (string text in values) { if ((object)text != null) { num += text.Length; } } if (num > int.MaxValue) { throw new OutOfMemoryException(); } int num2 = (int)num; if (num2 == 0) { return Empty; } string text2 = FastAllocateString(num2); int num3 = 0; foreach (string text3 in values) { if (!IsNullOrEmpty(text3)) { int length = text3.Length; if (length > num2 - num3) { num3 = -1; break; } FillStringChecked(text2, num3, text3); num3 += length; } } if (num3 != num2) { return Concat((string[])values.Clone()); } return text2; } public static string Format(string format, object? arg0) { return FormatHelper(null, format, new ParamsArray(arg0)); } public static string Format(string format, object? arg0, object? arg1) { return FormatHelper(null, format, new ParamsArray(arg0, arg1)); } public static string Format(string format, object? arg0, object? arg1, object? arg2) { return FormatHelper(null, format, new ParamsArray(arg0, arg1, arg2)); } public static string Format(string format, params object?[] args) { if (args == null) { throw new ArgumentNullException(((object)format == null) ? "format" : "args"); } return FormatHelper(null, format, new ParamsArray(args)); } public static string Format(IFormatProvider? provider, string format, object? arg0) { return FormatHelper(provider, format, new ParamsArray(arg0)); } public static string Format(IFormatProvider? provider, string format, object? arg0, object? arg1) { return FormatHelper(provider, format, new ParamsArray(arg0, arg1)); } public static string Format(IFormatProvider? provider, string format, object? arg0, object? arg1, object? arg2) { return FormatHelper(provider, format, new ParamsArray(arg0, arg1, arg2)); } public static string Format(IFormatProvider? provider, string format, params object?[] args) { if (args == null) { throw new ArgumentNullException(((object)format == null) ? "format" : "args"); } return FormatHelper(provider, format, new ParamsArray(args)); } private static string FormatHelper(IFormatProvider provider, string format, ParamsArray args) { if ((object)format == null) { throw new ArgumentNullException("format"); } Span initialBuffer = stackalloc char[256]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); valueStringBuilder.EnsureCapacity(format.Length + args.Length * 8); valueStringBuilder.AppendFormatHelper(provider, format, args); return valueStringBuilder.ToString(); } public string Insert(int startIndex, string value) { if ((object)value == null) { throw new ArgumentNullException("value"); } if ((uint)startIndex > Length) { throw new ArgumentOutOfRangeException("startIndex"); } int length = Length; int length2 = value.Length; if (length == 0) { return value; } if (length2 == 0) { return this; } int length3 = length + length2; string text = FastAllocateString(length3); Buffer.Memmove(ref text._firstChar, ref _firstChar, (nuint)startIndex); Buffer.Memmove(ref Unsafe.Add(ref text._firstChar, startIndex), ref value._firstChar, (nuint)length2); Buffer.Memmove(ref Unsafe.Add(ref text._firstChar, startIndex + length2), ref Unsafe.Add(ref _firstChar, startIndex), (nuint)(length - startIndex)); return text; } public static string Join(char separator, params string?[] value) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } return JoinCore(MemoryMarshal.CreateReadOnlySpan(ref separator, 1), new ReadOnlySpan(value)); } public static string Join(string? separator, params string?[] value) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } return JoinCore(separator.AsSpan(), new ReadOnlySpan(value)); } public static string Join(char separator, string?[] value, int startIndex, int count) { return JoinCore(MemoryMarshal.CreateReadOnlySpan(ref separator, 1), value, startIndex, count); } public static string Join(string? separator, string?[] value, int startIndex, int count) { return JoinCore(separator.AsSpan(), value, startIndex, count); } private static string JoinCore(ReadOnlySpan separator, string[] value, int startIndex, int count) { if (value == null) { throw new ArgumentNullException("value"); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NegativeCount); } if (startIndex > value.Length - count) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_IndexCountBuffer); } return JoinCore(separator, new ReadOnlySpan(value, startIndex, count)); } public static string Join(string? separator, IEnumerable values) { if (values is List list) { return JoinCore(separator.AsSpan(), CollectionsMarshal.AsSpan(list)); } if (values is string[] array) { return JoinCore(separator.AsSpan(), new ReadOnlySpan(array)); } if (values == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); } using IEnumerator enumerator = values.GetEnumerator(); if (!enumerator.MoveNext()) { return Empty; } string current = enumerator.Current; if (!enumerator.MoveNext()) { return current ?? Empty; } Span initialBuffer = stackalloc char[256]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); valueStringBuilder.Append(current); do { valueStringBuilder.Append(separator); valueStringBuilder.Append(enumerator.Current); } while (enumerator.MoveNext()); return valueStringBuilder.ToString(); } public static string Join(char separator, params object?[] values) { return JoinCore(MemoryMarshal.CreateReadOnlySpan(ref separator, 1), values); } public static string Join(string? separator, params object?[] values) { return JoinCore(separator.AsSpan(), values); } private static string JoinCore(ReadOnlySpan separator, object[] values) { if (values == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); } if (values.Length == 0) { return Empty; } string text = values[0]?.ToString(); if (values.Length == 1) { return text ?? Empty; } Span initialBuffer = stackalloc char[256]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); valueStringBuilder.Append(text); for (int i = 1; i < values.Length; i++) { valueStringBuilder.Append(separator); object obj = values[i]; if (obj != null) { valueStringBuilder.Append(obj.ToString()); } } return valueStringBuilder.ToString(); } public static string Join(char separator, IEnumerable values) { return JoinCore(MemoryMarshal.CreateReadOnlySpan(ref separator, 1), values); } public static string Join(string? separator, IEnumerable values) { return JoinCore(separator.AsSpan(), values); } private static string JoinCore(ReadOnlySpan separator, IEnumerable values) { if (typeof(T) == typeof(string)) { if (values is List list) { return JoinCore(separator, CollectionsMarshal.AsSpan(list)); } if (values is string[] array) { return JoinCore(separator, new ReadOnlySpan(array)); } } if (values == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); } using IEnumerator enumerator = values.GetEnumerator(); if (!enumerator.MoveNext()) { return Empty; } string text = enumerator.Current?.ToString(); if (!enumerator.MoveNext()) { return text ?? Empty; } Span initialBuffer = stackalloc char[256]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); valueStringBuilder.Append(text); do { T current = enumerator.Current; valueStringBuilder.Append(separator); if (current != null) { valueStringBuilder.Append(current.ToString()); } } while (enumerator.MoveNext()); return valueStringBuilder.ToString(); } private static string JoinCore(ReadOnlySpan separator, ReadOnlySpan values) { if (values.Length <= 1) { object obj; if (!values.IsEmpty) { obj = values[0]; if (obj == null) { return Empty; } } else { obj = Empty; } return (string)obj; } long num = (long)(values.Length - 1) * (long)separator.Length; if (num > int.MaxValue) { ThrowHelper.ThrowOutOfMemoryException(); } int num2 = (int)num; ReadOnlySpan readOnlySpan = values; for (int i = 0; i < readOnlySpan.Length; i++) { string text = readOnlySpan[i]; if ((object)text != null) { num2 += text.Length; if (num2 < 0) { ThrowHelper.ThrowOutOfMemoryException(); } } } string text2 = FastAllocateString(num2); int num3 = 0; for (int j = 0; j < values.Length; j++) { string text3 = values[j]; if ((object)text3 != null) { int length = text3.Length; if (length > num2 - num3) { num3 = -1; break; } FillStringChecked(text2, num3, text3); num3 += length; } if (j < values.Length - 1) { ref char reference = ref Unsafe.Add(ref text2._firstChar, num3); if (separator.Length == 1) { reference = separator[0]; } else { separator.CopyTo(new Span(ref reference, separator.Length)); } num3 += separator.Length; } } if (num3 != num2) { return JoinCore(separator, values.ToArray().AsSpan()); } return text2; } public string PadLeft(int totalWidth) { return PadLeft(totalWidth, ' '); } public string PadLeft(int totalWidth, char paddingChar) { if (totalWidth < 0) { throw new ArgumentOutOfRangeException("totalWidth", SR.ArgumentOutOfRange_NeedNonNegNum); } int length = Length; int num = totalWidth - length; if (num <= 0) { return this; } string text = FastAllocateString(totalWidth); new Span(ref text._firstChar, num).Fill(paddingChar); Buffer.Memmove(ref Unsafe.Add(ref text._firstChar, num), ref _firstChar, (nuint)length); return text; } public string PadRight(int totalWidth) { return PadRight(totalWidth, ' '); } public string PadRight(int totalWidth, char paddingChar) { if (totalWidth < 0) { throw new ArgumentOutOfRangeException("totalWidth", SR.ArgumentOutOfRange_NeedNonNegNum); } int length = Length; int num = totalWidth - length; if (num <= 0) { return this; } string text = FastAllocateString(totalWidth); Buffer.Memmove(ref text._firstChar, ref _firstChar, (nuint)length); new Span(ref Unsafe.Add(ref text._firstChar, length), num).Fill(paddingChar); return text; } public string Remove(int startIndex, int count) { if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NegativeCount); } int length = Length; if (count > length - startIndex) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_IndexCount); } if (count == 0) { return this; } int num = length - count; if (num == 0) { return Empty; } string text = FastAllocateString(num); Buffer.Memmove(ref text._firstChar, ref _firstChar, (nuint)startIndex); Buffer.Memmove(ref Unsafe.Add(ref text._firstChar, startIndex), ref Unsafe.Add(ref _firstChar, startIndex + count), (nuint)(num - startIndex)); return text; } public string Remove(int startIndex) { if ((uint)startIndex > Length) { throw new ArgumentOutOfRangeException("startIndex", (startIndex < 0) ? SR.ArgumentOutOfRange_StartIndex : SR.ArgumentOutOfRange_StartIndexLargerThanLength); } return Substring(0, startIndex); } public string Replace(string oldValue, string? newValue, bool ignoreCase, CultureInfo? culture) { return ReplaceCore(oldValue, newValue, culture?.CompareInfo, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } public string Replace(string oldValue, string? newValue, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return ReplaceCore(oldValue, newValue, CultureInfo.CurrentCulture.CompareInfo, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return ReplaceCore(oldValue, newValue, CompareInfo.Invariant, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: return Replace(oldValue, newValue); case StringComparison.OrdinalIgnoreCase: return ReplaceCore(oldValue, newValue, CompareInfo.Invariant, CompareOptions.OrdinalIgnoreCase); default: throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType"); } } private string ReplaceCore(string oldValue, string newValue, CompareInfo ci, CompareOptions options) { if ((object)oldValue == null) { throw new ArgumentNullException("oldValue"); } if (oldValue.Length == 0) { throw new ArgumentException(SR.Argument_StringZeroLength, "oldValue"); } return ReplaceCore(this, oldValue.AsSpan(), newValue.AsSpan(), ci ?? CultureInfo.CurrentCulture.CompareInfo, options) ?? this; } private static string ReplaceCore(ReadOnlySpan searchSpace, ReadOnlySpan oldValue, ReadOnlySpan newValue, CompareInfo compareInfo, CompareOptions options) { Span initialBuffer = stackalloc char[256]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); valueStringBuilder.EnsureCapacity(searchSpace.Length); bool flag = false; while (true) { int matchLength; int num = compareInfo.IndexOf(searchSpace, oldValue, options, out matchLength); if (num < 0 || matchLength == 0) { break; } valueStringBuilder.Append(searchSpace.Slice(0, num)); valueStringBuilder.Append(newValue); searchSpace = searchSpace.Slice(num + matchLength); flag = true; } if (!flag) { valueStringBuilder.Dispose(); return null; } valueStringBuilder.Append(searchSpace); return valueStringBuilder.ToString(); } public string Replace(char oldChar, char newChar) { if (oldChar == newChar) { return this; } int num = IndexOf(oldChar); if (num < 0) { return this; } int num2 = Length - num; string text = FastAllocateString(Length); int num3 = num; if (num3 > 0) { Buffer.Memmove(ref text._firstChar, ref _firstChar, (uint)num3); } ref ushort reference = ref Unsafe.Add(ref Unsafe.As(ref _firstChar), num3); ref ushort reference2 = ref Unsafe.Add(ref Unsafe.As(ref text._firstChar), num3); if (Vector.IsHardwareAccelerated && num2 >= Vector.Count) { Vector right = new Vector(oldChar); Vector left = new Vector(newChar); do { Vector vector = Unsafe.ReadUnaligned>(ref Unsafe.As(ref reference)); Vector condition = Vector.Equals(vector, right); Vector value = Vector.ConditionalSelect(condition, left, vector); Unsafe.WriteUnaligned(ref Unsafe.As(ref reference2), value); reference = ref Unsafe.Add(ref reference, Vector.Count); reference2 = ref Unsafe.Add(ref reference2, Vector.Count); num2 -= Vector.Count; } while (num2 >= Vector.Count); } while (num2 > 0) { ushort num4 = reference; reference2 = ((num4 == oldChar) ? newChar : num4); reference = ref Unsafe.Add(ref reference, 1); reference2 = ref Unsafe.Add(ref reference2, 1); num2--; } return text; } public string Replace(string oldValue, string? newValue) { if ((object)oldValue == null) { throw new ArgumentNullException("oldValue"); } if (oldValue.Length == 0) { throw new ArgumentException(SR.Argument_StringZeroLength, "oldValue"); } if ((object)newValue == null) { newValue = Empty; } Span initialSpan = stackalloc int[128]; ValueListBuilder valueListBuilder = new ValueListBuilder(initialSpan); if (oldValue.Length == 1) { if (newValue.Length == 1) { return Replace(oldValue[0], newValue[0]); } char value = oldValue[0]; int num = 0; while (true) { int num2 = SpanHelpers.IndexOf(ref Unsafe.Add(ref _firstChar, num), value, Length - num); if (num2 == -1) { break; } valueListBuilder.Append(num + num2); num += num2 + 1; } } else { int num3 = 0; while (true) { int num4 = SpanHelpers.IndexOf(ref Unsafe.Add(ref _firstChar, num3), Length - num3, ref oldValue._firstChar, oldValue.Length); if (num4 == -1) { break; } valueListBuilder.Append(num3 + num4); num3 += num4 + oldValue.Length; } } if (valueListBuilder.Length == 0) { return this; } string result = ReplaceHelper(oldValue.Length, newValue, valueListBuilder.AsSpan()); valueListBuilder.Dispose(); return result; } private string ReplaceHelper(int oldValueLength, string newValue, ReadOnlySpan indices) { long num = Length + (long)(newValue.Length - oldValueLength) * (long)indices.Length; if (num > int.MaxValue) { throw new OutOfMemoryException(); } string text = FastAllocateString((int)num); Span span = new Span(ref text._firstChar, text.Length); int num2 = 0; int num3 = 0; for (int i = 0; i < indices.Length; i++) { int num4 = indices[i]; int num5 = num4 - num2; if (num5 != 0) { this.AsSpan(num2, num5).CopyTo(span.Slice(num3)); num3 += num5; } num2 = num4 + oldValueLength; newValue.CopyTo(span.Slice(num3)); num3 += newValue.Length; } this.AsSpan(num2).CopyTo(span.Slice(num3)); return text; } public string ReplaceLineEndings() { return ReplaceLineEndings("\r\n"); } public string ReplaceLineEndings(string replacementText) { if ((object)replacementText == null) { throw new ArgumentNullException("replacementText"); } int stride; int num = IndexOfNewlineChar(this, out stride); if (num < 0) { return this; } ReadOnlySpan readOnlySpan = this.AsSpan(0, num); ReadOnlySpan readOnlySpan2 = this.AsSpan(num + stride); Span initialBuffer = stackalloc char[256]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); while (true) { int num2 = IndexOfNewlineChar(readOnlySpan2, out stride); if (num2 < 0) { break; } valueStringBuilder.Append(replacementText); valueStringBuilder.Append(readOnlySpan2.Slice(0, num2)); readOnlySpan2 = readOnlySpan2.Slice(num2 + stride); } string result = Concat(readOnlySpan, valueStringBuilder.AsSpan(), replacementText, readOnlySpan2); valueStringBuilder.Dispose(); return result; } internal static int IndexOfNewlineChar(ReadOnlySpan text, out int stride) { stride = 0; int num = text.IndexOfAny("\r\n\f\u0085\u2028\u2029"); if ((uint)num < (uint)text.Length) { stride = 1; if (text[num] == '\r') { int num2 = num + 1; if ((uint)num2 < (uint)text.Length && text[num2] == '\n') { stride = 2; } } } return num; } public string[] Split(char separator, StringSplitOptions options = StringSplitOptions.None) { return SplitInternal(new ReadOnlySpan(ref separator, 1), int.MaxValue, options); } public string[] Split(char separator, int count, StringSplitOptions options = StringSplitOptions.None) { return SplitInternal(new ReadOnlySpan(ref separator, 1), count, options); } public string[] Split(params char[]? separator) { return SplitInternal(separator, int.MaxValue, StringSplitOptions.None); } public string[] Split(char[]? separator, int count) { return SplitInternal(separator, count, StringSplitOptions.None); } public string[] Split(char[]? separator, StringSplitOptions options) { return SplitInternal(separator, int.MaxValue, options); } public string[] Split(char[]? separator, int count, StringSplitOptions options) { return SplitInternal(separator, count, options); } private string[] SplitInternal(ReadOnlySpan separators, int count, StringSplitOptions options) { if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NegativeCount); } CheckStringSplitOptions(options); ValueListBuilder sepListBuilder; ReadOnlySpan sepList; while (true) { if (count <= 1 || Length == 0) { string text = this; if ((options & StringSplitOptions.TrimEntries) != 0 && count > 0) { text = text.Trim(); } if ((options & StringSplitOptions.RemoveEmptyEntries) != 0 && text.Length == 0) { count = 0; } if (count != 0) { return new string[1] { text }; } return Array.Empty(); } if (separators.IsEmpty) { options &= ~StringSplitOptions.TrimEntries; } Span initialSpan = stackalloc int[128]; sepListBuilder = new ValueListBuilder(initialSpan); MakeSeparatorList(separators, ref sepListBuilder); sepList = sepListBuilder.AsSpan(); if (sepList.Length != 0) { break; } count = 1; } string[] result = ((options != 0) ? SplitWithPostProcessing(sepList, default(ReadOnlySpan), 1, count, options) : SplitWithoutPostProcessing(sepList, default(ReadOnlySpan), 1, count)); sepListBuilder.Dispose(); return result; } public string[] Split(string? separator, StringSplitOptions options = StringSplitOptions.None) { return SplitInternal(separator ?? Empty, null, int.MaxValue, options); } public string[] Split(string? separator, int count, StringSplitOptions options = StringSplitOptions.None) { return SplitInternal(separator ?? Empty, null, count, options); } public string[] Split(string[]? separator, StringSplitOptions options) { return SplitInternal(null, separator, int.MaxValue, options); } public string[] Split(string[]? separator, int count, StringSplitOptions options) { return SplitInternal(null, separator, count, options); } private string[] SplitInternal(string separator, string[] separators, int count, StringSplitOptions options) { if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NegativeCount); } CheckStringSplitOptions(options); bool flag = (object)separator != null; if (!flag && (separators == null || separators.Length == 0)) { return SplitInternal(default(ReadOnlySpan), count, options); } while (true) { if (count <= 1 || Length == 0) { string text = this; if ((options & StringSplitOptions.TrimEntries) != 0 && count > 0) { text = text.Trim(); } if ((options & StringSplitOptions.RemoveEmptyEntries) != 0 && text.Length == 0) { count = 0; } if (count != 0) { return new string[1] { text }; } return Array.Empty(); } if (!flag) { break; } if (separator.Length == 0) { count = 1; continue; } return SplitInternal(separator, count, options); } Span initialSpan = stackalloc int[128]; ValueListBuilder sepListBuilder = new ValueListBuilder(initialSpan); initialSpan = stackalloc int[128]; ValueListBuilder lengthListBuilder = new ValueListBuilder(initialSpan); MakeSeparatorList(separators, ref sepListBuilder, ref lengthListBuilder); ReadOnlySpan sepList = sepListBuilder.AsSpan(); ReadOnlySpan lengthList = lengthListBuilder.AsSpan(); if (sepList.Length == 0) { return new string[1] { this }; } string[] result = ((options != 0) ? SplitWithPostProcessing(sepList, lengthList, 0, count, options) : SplitWithoutPostProcessing(sepList, lengthList, 0, count)); sepListBuilder.Dispose(); lengthListBuilder.Dispose(); return result; } private string[] SplitInternal(string separator, int count, StringSplitOptions options) { Span initialSpan = stackalloc int[128]; ValueListBuilder sepListBuilder = new ValueListBuilder(initialSpan); MakeSeparatorList(separator, ref sepListBuilder); ReadOnlySpan sepList = sepListBuilder.AsSpan(); if (sepList.Length == 0) { string text = this; if ((options & StringSplitOptions.TrimEntries) != 0) { text = text.Trim(); } if (text.Length != 0 || (options & StringSplitOptions.RemoveEmptyEntries) == 0) { return new string[1] { text }; } return Array.Empty(); } string[] result = ((options != 0) ? SplitWithPostProcessing(sepList, default(ReadOnlySpan), separator.Length, count, options) : SplitWithoutPostProcessing(sepList, default(ReadOnlySpan), separator.Length, count)); sepListBuilder.Dispose(); return result; } private string[] SplitWithoutPostProcessing(ReadOnlySpan sepList, ReadOnlySpan lengthList, int defaultLength, int count) { int num = 0; int num2 = 0; count--; int num3 = ((sepList.Length < count) ? sepList.Length : count); string[] array = new string[num3 + 1]; for (int i = 0; i < num3; i++) { if (num >= Length) { break; } array[num2++] = Substring(num, sepList[i] - num); num = sepList[i] + (lengthList.IsEmpty ? defaultLength : lengthList[i]); } if (num < Length && num3 >= 0) { array[num2] = Substring(num); } else if (num2 == num3) { array[num2] = Empty; } return array; } private string[] SplitWithPostProcessing(ReadOnlySpan sepList, ReadOnlySpan lengthList, int defaultLength, int count, StringSplitOptions options) { int length = sepList.Length; int num = ((length < count) ? (length + 1) : count); string[] array = new string[num]; int num2 = 0; int num3 = 0; ReadOnlySpan span; for (int i = 0; i < length; i++) { span = this.AsSpan(num2, sepList[i] - num2); if ((options & StringSplitOptions.TrimEntries) != 0) { span = span.Trim(); } if (!span.IsEmpty || (options & StringSplitOptions.RemoveEmptyEntries) == 0) { array[num3++] = span.ToString(); } num2 = sepList[i] + (lengthList.IsEmpty ? defaultLength : lengthList[i]); if (num3 != count - 1) { continue; } if ((options & StringSplitOptions.RemoveEmptyEntries) == 0) { break; } while (++i < length) { span = this.AsSpan(num2, sepList[i] - num2); if ((options & StringSplitOptions.TrimEntries) != 0) { span = span.Trim(); } if (!span.IsEmpty) { break; } num2 = sepList[i] + (lengthList.IsEmpty ? defaultLength : lengthList[i]); } break; } span = this.AsSpan(num2); if ((options & StringSplitOptions.TrimEntries) != 0) { span = span.Trim(); } if (!span.IsEmpty || (options & StringSplitOptions.RemoveEmptyEntries) == 0) { array[num3++] = span.ToString(); } Array.Resize(ref array, num3); return array; } private unsafe void MakeSeparatorList(ReadOnlySpan separators, ref ValueListBuilder sepListBuilder) { if (separators.Length == 0) { for (int i = 0; i < Length; i++) { if (char.IsWhiteSpace(this[i])) { sepListBuilder.Append(i); } } return; } if (separators.Length <= 3) { char c = separators[0]; char c2 = ((separators.Length > 1) ? separators[1] : c); char c3 = ((separators.Length > 2) ? separators[2] : c2); if (Length >= 16 && Sse41.IsSupported) { MakeSeparatorListVectorized(ref sepListBuilder, c, c2, c3); return; } for (int j = 0; j < Length; j++) { char c4 = this[j]; if (c4 == c || c4 == c2 || c4 == c3) { sepListBuilder.Append(j); } } return; } ProbabilisticMap probabilisticMap = default(ProbabilisticMap); uint* charMap = (uint*)(&probabilisticMap); InitializeProbabilisticMap(charMap, separators); for (int k = 0; k < Length; k++) { char c5 = this[k]; if (IsCharBitSet(charMap, (byte)c5) && IsCharBitSet(charMap, (byte)((int)c5 >> 8)) && separators.Contains(c5)) { sepListBuilder.Append(k); } } } private void MakeSeparatorListVectorized(ref ValueListBuilder sepListBuilder, char c, char c2, char c3) { if (!Sse41.IsSupported) { throw new PlatformNotSupportedException(); } Vector128 mask = Vector128.Create(0, 2, 4, 6, 8, 10, 12, 14, byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue); Vector128 right = Vector128.Create(c); Vector128 right2 = Vector128.Create(c2); Vector128 right3 = Vector128.Create(c3); ref char reference = ref MemoryMarshal.GetReference(this.AsSpan()); int num = Length & -Vector128.Count; int i; for (i = 0; i < num; i += Vector128.Count) { Vector128 left = ReadVector(ref reference, i); Vector128 right4 = Sse2.CompareEqual(left, right); right4 = Sse2.Or(Sse2.CompareEqual(left, right2), right4); right4 = Sse2.Or(Sse2.CompareEqual(left, right3), right4); if (Sse41.TestZ(right4, right4)) { continue; } Vector128 value = Sse2.ShiftRightLogical(right4.AsUInt64(), 4).AsByte(); value = Ssse3.Shuffle(value, mask); uint num2 = Sse2.ConvertToUInt32(value.AsUInt32()); value = Sse2.ShiftRightLogical(value.AsUInt64(), 32).AsByte(); uint num3 = Sse2.ConvertToUInt32(value.AsUInt32()); int num4 = i; while (num2 != 0) { if ((num2 & 0xFu) != 0) { sepListBuilder.Append(num4); } num2 >>= 8; num4++; } int num5 = i + 4; while (num3 != 0) { if ((num3 & 0xFu) != 0) { sepListBuilder.Append(num5); } num3 >>= 8; num5++; } } for (; i < Length; i++) { char c4 = Unsafe.Add(ref reference, (IntPtr)(uint)i); if (c4 == c || c4 == c2 || c4 == c3) { sepListBuilder.Append(i); } } static Vector128 ReadVector(ref char c0, int offset) { return Unsafe.ReadUnaligned>(ref Unsafe.As(ref Unsafe.Add(ref c0, (IntPtr)(uint)offset))); } } private void MakeSeparatorList(string separator, ref ValueListBuilder sepListBuilder) { int length = separator.Length; for (int i = 0; i < Length; i++) { if (this[i] == separator[0] && length <= Length - i && (length == 1 || this.AsSpan(i, length).SequenceEqual(separator))) { sepListBuilder.Append(i); i += length - 1; } } } private void MakeSeparatorList(string[] separators, ref ValueListBuilder sepListBuilder, ref ValueListBuilder lengthListBuilder) { for (int i = 0; i < Length; i++) { foreach (string text in separators) { if (!IsNullOrEmpty(text)) { int length = text.Length; if (this[i] == text[0] && length <= Length - i && (length == 1 || this.AsSpan(i, length).SequenceEqual(text))) { sepListBuilder.Append(i); lengthListBuilder.Append(length); i += length - 1; break; } } } } } private static void CheckStringSplitOptions(StringSplitOptions options) { if (((uint)options & 0xFFFFFFFCu) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidFlag, ExceptionArgument.options); } } public string Substring(int startIndex) { return Substring(startIndex, Length - startIndex); } public string Substring(int startIndex, int length) { if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex); } if (startIndex > Length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndexLargerThanLength); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NegativeLength); } if (startIndex > Length - length) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_IndexLength); } if (length == 0) { return Empty; } if (startIndex == 0 && length == Length) { return this; } return InternalSubString(startIndex, length); } private string InternalSubString(int startIndex, int length) { string text = FastAllocateString(length); nuint elementCount = (uint)text.Length; Buffer.Memmove(ref text._firstChar, ref Unsafe.Add(ref _firstChar, (nint)(uint)startIndex), elementCount); return text; } public string ToLower() { return ToLower(null); } public string ToLower(CultureInfo? culture) { CultureInfo cultureInfo = culture ?? CultureInfo.CurrentCulture; return cultureInfo.TextInfo.ToLower(this); } public string ToLowerInvariant() { return TextInfo.Invariant.ToLower(this); } public string ToUpper() { return ToUpper(null); } public string ToUpper(CultureInfo? culture) { CultureInfo cultureInfo = culture ?? CultureInfo.CurrentCulture; return cultureInfo.TextInfo.ToUpper(this); } public string ToUpperInvariant() { return TextInfo.Invariant.ToUpper(this); } public string Trim() { return TrimWhiteSpaceHelper(TrimType.Both); } public unsafe string Trim(char trimChar) { return TrimHelper(&trimChar, 1, TrimType.Both); } public unsafe string Trim(params char[]? trimChars) { if (trimChars == null || trimChars.Length == 0) { return TrimWhiteSpaceHelper(TrimType.Both); } fixed (char* trimChars2 = &trimChars[0]) { return TrimHelper(trimChars2, trimChars.Length, TrimType.Both); } } public string TrimStart() { return TrimWhiteSpaceHelper(TrimType.Head); } public unsafe string TrimStart(char trimChar) { return TrimHelper(&trimChar, 1, TrimType.Head); } public unsafe string TrimStart(params char[]? trimChars) { if (trimChars == null || trimChars.Length == 0) { return TrimWhiteSpaceHelper(TrimType.Head); } fixed (char* trimChars2 = &trimChars[0]) { return TrimHelper(trimChars2, trimChars.Length, TrimType.Head); } } public string TrimEnd() { return TrimWhiteSpaceHelper(TrimType.Tail); } public unsafe string TrimEnd(char trimChar) { return TrimHelper(&trimChar, 1, TrimType.Tail); } public unsafe string TrimEnd(params char[]? trimChars) { if (trimChars == null || trimChars.Length == 0) { return TrimWhiteSpaceHelper(TrimType.Tail); } fixed (char* trimChars2 = &trimChars[0]) { return TrimHelper(trimChars2, trimChars.Length, TrimType.Tail); } } private string TrimWhiteSpaceHelper(TrimType trimType) { int num = Length - 1; int i = 0; if ((trimType & TrimType.Head) != 0) { for (i = 0; i < Length && char.IsWhiteSpace(this[i]); i++) { } } if ((trimType & TrimType.Tail) != 0) { num = Length - 1; while (num >= i && char.IsWhiteSpace(this[num])) { num--; } } return CreateTrimmedString(i, num); } private unsafe string TrimHelper(char* trimChars, int trimCharsLength, TrimType trimType) { int num = Length - 1; int i = 0; if ((trimType & TrimType.Head) != 0) { for (i = 0; i < Length; i++) { int num2 = 0; char c = this[i]; for (num2 = 0; num2 < trimCharsLength && trimChars[num2] != c; num2++) { } if (num2 == trimCharsLength) { break; } } } if ((trimType & TrimType.Tail) != 0) { for (num = Length - 1; num >= i; num--) { int num3 = 0; char c2 = this[num]; for (num3 = 0; num3 < trimCharsLength && trimChars[num3] != c2; num3++) { } if (num3 == trimCharsLength) { break; } } } return CreateTrimmedString(i, num); } private string CreateTrimmedString(int start, int end) { int num = end - start + 1; if (num != Length) { if (num != 0) { return InternalSubString(start, num); } return Empty; } return this; } public bool Contains(string value) { if ((object)value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } return SpanHelpers.IndexOf(ref _firstChar, Length, ref value._firstChar, value.Length) >= 0; } public bool Contains(string value, StringComparison comparisonType) { return IndexOf(value, comparisonType) >= 0; } public bool Contains(char value) { return SpanHelpers.Contains(ref _firstChar, value, Length); } public bool Contains(char value, StringComparison comparisonType) { return IndexOf(value, comparisonType) != -1; } public int IndexOf(char value) { return SpanHelpers.IndexOf(ref _firstChar, value, Length); } public int IndexOf(char value, int startIndex) { return IndexOf(value, startIndex, Length - startIndex); } public int IndexOf(char value, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IndexOf(this, value, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: return IndexOf(value); case StringComparison.OrdinalIgnoreCase: return CompareInfo.Invariant.IndexOf(this, value, CompareOptions.OrdinalIgnoreCase); default: throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType"); } } public int IndexOf(char value, int startIndex, int count) { if ((uint)startIndex > (uint)Length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if ((uint)count > (uint)(Length - startIndex)) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } int num = SpanHelpers.IndexOf(ref Unsafe.Add(ref _firstChar, startIndex), value, count); if (num != -1) { return num + startIndex; } return num; } public int IndexOfAny(char[] anyOf) { return IndexOfAny(anyOf, 0, Length); } public int IndexOfAny(char[] anyOf, int startIndex) { return IndexOfAny(anyOf, startIndex, Length - startIndex); } public int IndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) { throw new ArgumentNullException("anyOf"); } if ((uint)startIndex > (uint)Length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if ((uint)count > (uint)(Length - startIndex)) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } if (anyOf.Length != 0 && anyOf.Length <= 5) { int num = new ReadOnlySpan(ref Unsafe.Add(ref _firstChar, startIndex), count).IndexOfAny(anyOf); if (num != -1) { return num + startIndex; } return num; } if (anyOf.Length > 5) { return IndexOfCharArray(anyOf, startIndex, count); } return -1; } private unsafe int IndexOfCharArray(char[] anyOf, int startIndex, int count) { ProbabilisticMap probabilisticMap = default(ProbabilisticMap); uint* charMap = (uint*)(&probabilisticMap); InitializeProbabilisticMap(charMap, anyOf); fixed (char* ptr = &_firstChar) { char* ptr2 = ptr + startIndex; while (count > 0) { int num = *ptr2; if (IsCharBitSet(charMap, (byte)num) && IsCharBitSet(charMap, (byte)(num >> 8)) && ArrayContains((char)num, anyOf)) { return (int)(ptr2 - ptr); } count--; ptr2++; } return -1; } } private unsafe static void InitializeProbabilisticMap(uint* charMap, ReadOnlySpan anyOf) { bool flag = false; for (int i = 0; i < anyOf.Length; i++) { int num = anyOf[i]; SetCharBit(charMap, (byte)num); num >>= 8; if (num == 0) { flag = true; } else { SetCharBit(charMap, (byte)num); } } if (flag) { *charMap |= 1u; } } private static bool ArrayContains(char searchChar, char[] anyOf) { for (int i = 0; i < anyOf.Length; i++) { if (anyOf[i] == searchChar) { return true; } } return false; } private unsafe static bool IsCharBitSet(uint* charMap, byte value) { return (charMap[(uint)(value & 7)] & (uint)(1 << (value >> 3))) != 0; } private unsafe static void SetCharBit(uint* charMap, byte value) { charMap[(uint)(value & 7)] |= (uint)(1 << (value >> 3)); } public int IndexOf(string value) { return IndexOf(value, StringComparison.CurrentCulture); } public int IndexOf(string value, int startIndex) { return IndexOf(value, startIndex, StringComparison.CurrentCulture); } public int IndexOf(string value, int startIndex, int count) { return IndexOf(value, startIndex, count, StringComparison.CurrentCulture); } public int IndexOf(string value, StringComparison comparisonType) { return IndexOf(value, 0, Length, comparisonType); } public int IndexOf(string value, int startIndex, StringComparison comparisonType) { return IndexOf(value, startIndex, Length - startIndex, comparisonType); } public int IndexOf(string value, int startIndex, int count, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IndexOf(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: case StringComparison.OrdinalIgnoreCase: return Ordinal.IndexOf(this, value, startIndex, count, comparisonType == StringComparison.OrdinalIgnoreCase); default: throw ((object)value == null) ? new ArgumentNullException("value") : new ArgumentException(SR.NotSupported_StringComparison, "comparisonType"); } } public int LastIndexOf(char value) { return SpanHelpers.LastIndexOf(ref _firstChar, value, Length); } public int LastIndexOf(char value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } public int LastIndexOf(char value, int startIndex, int count) { if (Length == 0) { return -1; } if ((uint)startIndex >= (uint)Length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if ((uint)count > (uint)(startIndex + 1)) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } int num = startIndex + 1 - count; int num2 = SpanHelpers.LastIndexOf(ref Unsafe.Add(ref _firstChar, num), value, count); if (num2 != -1) { return num2 + num; } return num2; } public int LastIndexOfAny(char[] anyOf) { return LastIndexOfAny(anyOf, Length - 1, Length); } public int LastIndexOfAny(char[] anyOf, int startIndex) { return LastIndexOfAny(anyOf, startIndex, startIndex + 1); } public int LastIndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) { throw new ArgumentNullException("anyOf"); } if (Length == 0) { return -1; } if ((uint)startIndex >= (uint)Length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0 || count - 1 > startIndex) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Count); } if (anyOf.Length > 1) { return LastIndexOfCharArray(anyOf, startIndex, count); } if (anyOf.Length == 1) { return LastIndexOf(anyOf[0], startIndex, count); } return -1; } private unsafe int LastIndexOfCharArray(char[] anyOf, int startIndex, int count) { ProbabilisticMap probabilisticMap = default(ProbabilisticMap); uint* charMap = (uint*)(&probabilisticMap); InitializeProbabilisticMap(charMap, anyOf); fixed (char* ptr = &_firstChar) { char* ptr2 = ptr + startIndex; while (count > 0) { int num = *ptr2; if (IsCharBitSet(charMap, (byte)num) && IsCharBitSet(charMap, (byte)(num >> 8)) && ArrayContains((char)num, anyOf)) { return (int)(ptr2 - ptr); } count--; ptr2--; } return -1; } } public int LastIndexOf(string value) { return LastIndexOf(value, Length - 1, Length, StringComparison.CurrentCulture); } public int LastIndexOf(string value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1, StringComparison.CurrentCulture); } public int LastIndexOf(string value, int startIndex, int count) { return LastIndexOf(value, startIndex, count, StringComparison.CurrentCulture); } public int LastIndexOf(string value, StringComparison comparisonType) { return LastIndexOf(value, Length - 1, Length, comparisonType); } public int LastIndexOf(string value, int startIndex, StringComparison comparisonType) { return LastIndexOf(value, startIndex, startIndex + 1, comparisonType); } public int LastIndexOf(string value, int startIndex, int count, StringComparison comparisonType) { switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.LastIndexOf(this, value, startIndex, count, GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: case StringComparison.OrdinalIgnoreCase: return CompareInfo.Invariant.LastIndexOf(this, value, startIndex, count, GetCompareOptionsFromOrdinalStringComparison(comparisonType)); default: throw ((object)value == null) ? new ArgumentNullException("value") : new ArgumentException(SR.NotSupported_StringComparison, "comparisonType"); } } } public abstract class Type : MemberInfo, IReflect { private static volatile Binder s_defaultBinder; public static readonly char Delimiter = '.'; public static readonly Type[] EmptyTypes = Array.Empty(); public static readonly object Missing = System.Reflection.Missing.Value; public static readonly MemberFilter FilterAttribute = FilterAttributeImpl; public static readonly MemberFilter FilterName = (MemberInfo m, object c) => FilterNameImpl(m, c, StringComparison.Ordinal); public static readonly MemberFilter FilterNameIgnoreCase = (MemberInfo m, object c) => FilterNameImpl(m, c, StringComparison.OrdinalIgnoreCase); public bool IsInterface { get { if (this is RuntimeType type) { return RuntimeTypeHandle.IsInterface(type); } return (GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == TypeAttributes.ClassSemanticsMask; } } public override MemberTypes MemberType => MemberTypes.TypeInfo; public abstract string? Namespace { get; } public abstract string? AssemblyQualifiedName { get; } public abstract string? FullName { get; } public abstract Assembly Assembly { get; } public new abstract Module Module { get; } public bool IsNested => DeclaringType != null; public override Type? DeclaringType => null; public virtual MethodBase? DeclaringMethod => null; public override Type? ReflectedType => null; public abstract Type UnderlyingSystemType { get; } public virtual bool IsTypeDefinition { get { throw NotImplemented.ByDesign; } } public bool IsArray => IsArrayImpl(); public bool IsByRef => IsByRefImpl(); public bool IsPointer => IsPointerImpl(); public virtual bool IsConstructedGenericType { get { throw NotImplemented.ByDesign; } } public virtual bool IsGenericParameter => false; public virtual bool IsGenericTypeParameter { get { if (IsGenericParameter) { return (object)DeclaringMethod == null; } return false; } } public virtual bool IsGenericMethodParameter { get { if (IsGenericParameter) { return DeclaringMethod != null; } return false; } } public virtual bool IsGenericType => false; public virtual bool IsGenericTypeDefinition => false; public virtual bool IsSZArray { get { throw NotImplemented.ByDesign; } } public virtual bool IsVariableBoundArray { get { if (IsArray) { return !IsSZArray; } return false; } } public virtual bool IsByRefLike { get { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } } public bool HasElementType => HasElementTypeImpl(); public virtual Type[] GenericTypeArguments { get { if (!IsGenericType || IsGenericTypeDefinition) { return EmptyTypes; } return GetGenericArguments(); } } public virtual int GenericParameterPosition { get { throw new InvalidOperationException(SR.Arg_NotGenericParameter); } } public virtual GenericParameterAttributes GenericParameterAttributes { get { throw new NotSupportedException(); } } public TypeAttributes Attributes => GetAttributeFlagsImpl(); public bool IsAbstract => (GetAttributeFlagsImpl() & TypeAttributes.Abstract) != 0; public bool IsImport => (GetAttributeFlagsImpl() & TypeAttributes.Import) != 0; public bool IsSealed => (GetAttributeFlagsImpl() & TypeAttributes.Sealed) != 0; public bool IsSpecialName => (GetAttributeFlagsImpl() & TypeAttributes.SpecialName) != 0; public bool IsClass { get { if ((GetAttributeFlagsImpl() & TypeAttributes.ClassSemanticsMask) == 0) { return !IsValueType; } return false; } } public bool IsNestedAssembly => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedAssembly; public bool IsNestedFamANDAssem => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamANDAssem; public bool IsNestedFamily => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedFamily; public bool IsNestedFamORAssem => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.VisibilityMask; public bool IsNestedPrivate => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate; public bool IsNestedPublic => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPublic; public bool IsNotPublic => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == 0; public bool IsPublic => (GetAttributeFlagsImpl() & TypeAttributes.VisibilityMask) == TypeAttributes.Public; public bool IsAutoLayout => (GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == 0; public bool IsExplicitLayout => (GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.ExplicitLayout; public bool IsLayoutSequential => (GetAttributeFlagsImpl() & TypeAttributes.LayoutMask) == TypeAttributes.SequentialLayout; public bool IsAnsiClass => (GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == 0; public bool IsAutoClass => (GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.AutoClass; public bool IsUnicodeClass => (GetAttributeFlagsImpl() & TypeAttributes.StringFormatMask) == TypeAttributes.UnicodeClass; public bool IsCOMObject => IsCOMObjectImpl(); public bool IsContextful => IsContextfulImpl(); public virtual bool IsEnum => IsSubclassOf(typeof(Enum)); public bool IsMarshalByRef => IsMarshalByRefImpl(); public bool IsPrimitive => IsPrimitiveImpl(); public bool IsValueType { [Intrinsic] get { return IsValueTypeImpl(); } } public virtual bool IsSignatureType => false; public virtual bool IsSecurityCritical { get { throw NotImplemented.ByDesign; } } public virtual bool IsSecuritySafeCritical { get { throw NotImplemented.ByDesign; } } public virtual bool IsSecurityTransparent { get { throw NotImplemented.ByDesign; } } public virtual StructLayoutAttribute? StructLayoutAttribute { get { throw new NotSupportedException(); } } public ConstructorInfo? TypeInitializer { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] get { return GetConstructorImpl(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, CallingConventions.Any, EmptyTypes, null); } } public virtual RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } } public abstract Guid GUID { get; } public abstract Type? BaseType { get; } public static Binder DefaultBinder { get { if (s_defaultBinder == null) { DefaultBinder value = new DefaultBinder(); Interlocked.CompareExchange(ref s_defaultBinder, value, null); } return s_defaultBinder; } } public virtual bool IsSerializable { get { if ((GetAttributeFlagsImpl() & TypeAttributes.Serializable) != 0) { return true; } Type type = UnderlyingSystemType; if (type.IsRuntimeImplemented()) { do { if (type == typeof(Delegate) || type == typeof(Enum)) { return true; } type = type.BaseType; } while (type != null); } return false; } } public virtual bool ContainsGenericParameters { get { if (HasElementType) { return GetRootElementType().ContainsGenericParameters; } if (IsGenericParameter) { return true; } if (!IsGenericType) { return false; } Type[] genericArguments = GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { if (genericArguments[i].ContainsGenericParameters) { return true; } } return false; } } public bool IsVisible { get { if (this is RuntimeType type) { return RuntimeTypeHandle.IsVisible(type); } if (IsGenericParameter) { return true; } if (HasElementType) { return GetElementType().IsVisible; } Type type2 = this; while (type2.IsNested) { if (!type2.IsNestedPublic) { return false; } type2 = type2.DeclaringType; } if (!type2.IsPublic) { return false; } if (IsGenericType && !IsGenericTypeDefinition) { Type[] genericArguments = GetGenericArguments(); foreach (Type type3 in genericArguments) { if (!type3.IsVisible) { return false; } } } return true; } } [RequiresUnreferencedCode("The type might be removed")] public static Type? GetType(string typeName, bool throwOnError, bool ignoreCase) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeType.GetType(typeName, throwOnError, ignoreCase, ref stackMark); } [RequiresUnreferencedCode("The type might be removed")] public static Type? GetType(string typeName, bool throwOnError) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeType.GetType(typeName, throwOnError, ignoreCase: false, ref stackMark); } [RequiresUnreferencedCode("The type might be removed")] public static Type? GetType(string typeName) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeType.GetType(typeName, throwOnError: false, ignoreCase: false, ref stackMark); } [RequiresUnreferencedCode("The type might be removed")] public static Type? GetType(string typeName, Func? assemblyResolver, Func? typeResolver) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return TypeNameParser.GetType(typeName, assemblyResolver, typeResolver, throwOnError: false, ignoreCase: false, ref stackMark); } [RequiresUnreferencedCode("The type might be removed")] public static Type? GetType(string typeName, Func? assemblyResolver, Func? typeResolver, bool throwOnError) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return TypeNameParser.GetType(typeName, assemblyResolver, typeResolver, throwOnError, ignoreCase: false, ref stackMark); } [RequiresUnreferencedCode("The type might be removed")] public static Type? GetType(string typeName, Func? assemblyResolver, Func? typeResolver, bool throwOnError, bool ignoreCase) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return TypeNameParser.GetType(typeName, assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark); } internal virtual RuntimeTypeHandle GetTypeHandleInternal() { return TypeHandle; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeType GetTypeFromHandleUnsafe(IntPtr handle); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern Type GetTypeFromHandle(RuntimeTypeHandle handle); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern bool operator ==(Type? left, Type? right); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern bool operator !=(Type? left, Type? right); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool IsRuntimeImplemented() { return this is RuntimeType; } public new Type GetType() { return base.GetType(); } protected abstract bool IsArrayImpl(); protected abstract bool IsByRefImpl(); protected abstract bool IsPointerImpl(); protected abstract bool HasElementTypeImpl(); public abstract Type? GetElementType(); public virtual int GetArrayRank() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } public virtual Type GetGenericTypeDefinition() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } public virtual Type[] GetGenericArguments() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } public virtual Type[] GetGenericParameterConstraints() { if (!IsGenericParameter) { throw new InvalidOperationException(SR.Arg_NotGenericParameter); } throw new InvalidOperationException(); } protected abstract TypeAttributes GetAttributeFlagsImpl(); protected abstract bool IsCOMObjectImpl(); protected virtual bool IsContextfulImpl() { return false; } protected virtual bool IsMarshalByRefImpl() { return false; } protected abstract bool IsPrimitiveImpl(); [Intrinsic] public bool IsAssignableTo([NotNullWhen(true)] Type? targetType) { return targetType?.IsAssignableFrom(this) ?? false; } protected virtual bool IsValueTypeImpl() { return IsSubclassOf(typeof(ValueType)); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] public ConstructorInfo? GetConstructor(Type[] types) { return GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, types, null); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] public ConstructorInfo? GetConstructor(BindingFlags bindingAttr, Type[] types) { return GetConstructor(bindingAttr, null, types, null); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] public ConstructorInfo? GetConstructor(BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) { return GetConstructor(bindingAttr, binder, CallingConventions.Any, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] public ConstructorInfo? GetConstructor(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { if (types == null) { throw new ArgumentNullException("types"); } for (int i = 0; i < types.Length; i++) { if (types[i] == null) { throw new ArgumentNullException("types"); } } return GetConstructorImpl(bindingAttr, binder, callConvention, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] protected abstract ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] public ConstructorInfo[] GetConstructors() { return GetConstructors(BindingFlags.Instance | BindingFlags.Public); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] public abstract ConstructorInfo[] GetConstructors(BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] public EventInfo? GetEvent(string name) { return GetEvent(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public abstract EventInfo? GetEvent(string name, BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] public virtual EventInfo[] GetEvents() { return GetEvents(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public abstract EventInfo[] GetEvents(BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] public FieldInfo? GetField(string name) { return GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public abstract FieldInfo? GetField(string name, BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] public FieldInfo[] GetFields() { return GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public abstract FieldInfo[] GetFields(BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicEvents)] public MemberInfo[] GetMember(string name) { return GetMember(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public virtual MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { return GetMember(name, MemberTypes.All, bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public virtual MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicEvents)] public MemberInfo[] GetMembers() { return GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2085: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 virtual MemberInfo GetMemberWithSameMetadataDefinitionAs(MemberInfo member) { if ((object)member == null) { throw new ArgumentNullException("member"); } MemberInfo[] members = GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (MemberInfo memberInfo in members) { if (memberInfo.HasSameMetadataDefinitionAs(member)) { return memberInfo; } } throw CreateGetMemberWithSameMetadataDefinitionAsNotFoundException(member); } private protected static ArgumentException CreateGetMemberWithSameMetadataDefinitionAsNotFoundException(MemberInfo member) { return new ArgumentException(SR.Format(SR.Arg_MemberInfoNotFound, member.Name), "member"); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public abstract MemberInfo[] GetMembers(BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] public MethodInfo? GetMethod(string name) { return GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public MethodInfo? GetMethod(string name, BindingFlags bindingAttr) { if (name == null) { throw new ArgumentNullException("name"); } return GetMethodImpl(name, bindingAttr, null, CallingConventions.Any, null, null); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Type[] types) { return GetMethod(name, bindingAttr, null, types, null); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] public MethodInfo? GetMethod(string name, Type[] types) { return GetMethod(name, types, null); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] public MethodInfo? GetMethod(string name, Type[] types, ParameterModifier[]? modifiers) { return GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) { return GetMethod(name, bindingAttr, binder, CallingConventions.Any, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { if (name == null) { throw new ArgumentNullException("name"); } if (types == null) { throw new ArgumentNullException("types"); } for (int i = 0; i < types.Length; i++) { if (types[i] == null) { throw new ArgumentNullException("types"); } } return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] protected abstract MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] public MethodInfo? GetMethod(string name, int genericParameterCount, Type[] types) { return GetMethod(name, genericParameterCount, types, null); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] public MethodInfo? GetMethod(string name, int genericParameterCount, Type[] types, ParameterModifier[]? modifiers) { return GetMethod(name, genericParameterCount, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public MethodInfo? GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers) { return GetMethod(name, genericParameterCount, bindingAttr, binder, CallingConventions.Any, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public MethodInfo? GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { if (name == null) { throw new ArgumentNullException("name"); } if (genericParameterCount < 0) { throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, "genericParameterCount"); } if (types == null) { throw new ArgumentNullException("types"); } for (int i = 0; i < types.Length; i++) { if (types[i] == null) { throw new ArgumentNullException("types"); } } return GetMethodImpl(name, genericParameterCount, bindingAttr, binder, callConvention, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] protected virtual MethodInfo? GetMethodImpl(string name, int genericParameterCount, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] public MethodInfo[] GetMethods() { return GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public abstract MethodInfo[] GetMethods(BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes)] public Type? GetNestedType(string name) { return GetNestedType(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public abstract Type? GetNestedType(string name, BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes)] public Type[] GetNestedTypes() { return GetNestedTypes(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public abstract Type[] GetNestedTypes(BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] public PropertyInfo? GetProperty(string name) { return GetProperty(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] public PropertyInfo? GetProperty(string name, BindingFlags bindingAttr) { if (name == null) { throw new ArgumentNullException("name"); } return GetPropertyImpl(name, bindingAttr, null, null, null, null); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2085:UnrecognizedReflectionPattern", Justification = "Linker doesn't recognize GetPropertyImpl(BindingFlags.Public) but this is what the body is doing")] public PropertyInfo? GetProperty(string name, Type? returnType) { if (name == null) { throw new ArgumentNullException("name"); } return GetPropertyImpl(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, returnType, null, null); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] public PropertyInfo? GetProperty(string name, Type[] types) { return GetProperty(name, null, types); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] public PropertyInfo? GetProperty(string name, Type? returnType, Type[] types) { return GetProperty(name, returnType, types, null); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] public PropertyInfo? GetProperty(string name, Type? returnType, Type[] types, ParameterModifier[]? modifiers) { return GetProperty(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, returnType, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] public PropertyInfo? GetProperty(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[] types, ParameterModifier[]? modifiers) { if (name == null) { throw new ArgumentNullException("name"); } if (types == null) { throw new ArgumentNullException("types"); } return GetPropertyImpl(name, bindingAttr, binder, returnType, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] protected abstract PropertyInfo? GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] public PropertyInfo[] GetProperties() { return GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] public abstract PropertyInfo[] GetProperties(BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicEvents)] public virtual MemberInfo[] GetDefaultMembers() { throw NotImplemented.ByDesign; } public static RuntimeTypeHandle GetTypeHandle(object o) { if (o == null) { throw new ArgumentNullException(null, SR.Arg_InvalidHandle); } Type type = o.GetType(); return type.TypeHandle; } public static Type[] GetTypeArray(object[] args) { if (args == null) { throw new ArgumentNullException("args"); } Type[] array = new Type[args.Length]; for (int i = 0; i < array.Length; i++) { if (args[i] == null) { throw new ArgumentException(SR.ArgumentNull_ArrayValue, "args"); } array[i] = args[i].GetType(); } return array; } public static TypeCode GetTypeCode(Type? type) { return type?.GetTypeCodeImpl() ?? TypeCode.Empty; } protected virtual TypeCode GetTypeCodeImpl() { Type underlyingSystemType = UnderlyingSystemType; if ((object)this != underlyingSystemType && (object)underlyingSystemType != null) { return GetTypeCode(underlyingSystemType); } return TypeCode.Object; } [SupportedOSPlatform("windows")] public static Type? GetTypeFromCLSID(Guid clsid) { return GetTypeFromCLSID(clsid, null, throwOnError: false); } [SupportedOSPlatform("windows")] public static Type? GetTypeFromCLSID(Guid clsid, bool throwOnError) { return GetTypeFromCLSID(clsid, null, throwOnError); } [SupportedOSPlatform("windows")] public static Type? GetTypeFromCLSID(Guid clsid, string? server) { return GetTypeFromCLSID(clsid, server, throwOnError: false); } [SupportedOSPlatform("windows")] public static Type? GetTypeFromCLSID(Guid clsid, string? server, bool throwOnError) { return Marshal.GetTypeFromCLSID(clsid, server, throwOnError); } [SupportedOSPlatform("windows")] public static Type? GetTypeFromProgID(string progID) { return GetTypeFromProgID(progID, null, throwOnError: false); } [SupportedOSPlatform("windows")] public static Type? GetTypeFromProgID(string progID, bool throwOnError) { return GetTypeFromProgID(progID, null, throwOnError); } [SupportedOSPlatform("windows")] public static Type? GetTypeFromProgID(string progID, string? server) { return GetTypeFromProgID(progID, server, throwOnError: false); } [SupportedOSPlatform("windows")] public static Type? GetTypeFromProgID(string progID, string? server, bool throwOnError) { return Marshal.GetTypeFromProgID(progID, server, throwOnError); } [DebuggerHidden] [DebuggerStepThrough] [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args) { return InvokeMember(name, invokeAttr, binder, target, args, null, null, null); } [DebuggerHidden] [DebuggerStepThrough] [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, CultureInfo? culture) { return InvokeMember(name, invokeAttr, binder, target, args, null, culture, null); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public abstract object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public Type? GetInterface(string name) { return GetInterface(name, ignoreCase: false); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public abstract Type? GetInterface(string name, bool ignoreCase); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public abstract Type[] GetInterfaces(); public virtual InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type interfaceType) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } public virtual bool IsInstanceOfType([NotNullWhen(true)] object? o) { if (o != null) { return IsAssignableFrom(o.GetType()); } return false; } public virtual bool IsEquivalentTo([NotNullWhen(true)] Type? other) { return this == other; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2085:UnrecognizedReflectionPattern", Justification = "The single instance field on enum types is never trimmed")] public virtual Type GetEnumUnderlyingType() { if (!IsEnum) { throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); } FieldInfo[] fields = GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (fields == null || fields.Length != 1) { throw new ArgumentException(SR.Argument_InvalidEnum, "enumType"); } return fields[0].FieldType; } public virtual Array GetEnumValues() { if (!IsEnum) { throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); } throw NotImplemented.ByDesign; } public virtual Type MakeArrayType() { throw new NotSupportedException(); } public virtual Type MakeArrayType(int rank) { throw new NotSupportedException(); } public virtual Type MakeByRefType() { throw new NotSupportedException(); } [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public virtual Type MakeGenericType(params Type[] typeArguments) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } public virtual Type MakePointerType() { throw new NotSupportedException(); } public static Type MakeGenericSignatureType(Type genericTypeDefinition, params Type[] typeArguments) { return new SignatureConstructedGenericType(genericTypeDefinition, typeArguments); } public static Type MakeGenericMethodParameter(int position) { if (position < 0) { throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, "position"); } return new SignatureGenericMethodParameterType(position); } internal string FormatTypeName() { Type rootElementType = GetRootElementType(); if (rootElementType.IsPrimitive || rootElementType.IsNested || rootElementType == typeof(void) || rootElementType == typeof(TypedReference)) { return Name; } return ToString(); } public override string ToString() { return "Type: " + Name; } public override bool Equals(object? o) { if (o != null) { return Equals(o as Type); } return false; } public override int GetHashCode() { Type underlyingSystemType = UnderlyingSystemType; if ((object)underlyingSystemType != this) { return underlyingSystemType.GetHashCode(); } return base.GetHashCode(); } public virtual bool Equals(Type? o) { if (!(o == null)) { return (object)UnderlyingSystemType == o.UnderlyingSystemType; } return false; } [Obsolete("ReflectionOnly loading is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0018", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public static Type? ReflectionOnlyGetType(string typeName, bool throwIfNotFound, bool ignoreCase) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } public virtual bool IsEnumDefined(object value) { if (value == null) { throw new ArgumentNullException("value"); } if (!IsEnum) { throw new ArgumentException(SR.Arg_MustBeEnum, "value"); } Type type = value.GetType(); if (type.IsEnum) { if (!type.IsEquivalentTo(this)) { throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, type, this)); } type = type.GetEnumUnderlyingType(); } if (type == typeof(string)) { string[] enumNames = GetEnumNames(); object[] array = enumNames; if (Array.IndexOf(array, value) >= 0) { return true; } return false; } if (IsIntegerType(type)) { Type enumUnderlyingType = GetEnumUnderlyingType(); if (enumUnderlyingType.GetTypeCodeImpl() != type.GetTypeCodeImpl()) { throw new ArgumentException(SR.Format(SR.Arg_EnumUnderlyingTypeAndObjectMustBeSameType, type, enumUnderlyingType)); } Array enumRawConstantValues = GetEnumRawConstantValues(); return BinarySearch(enumRawConstantValues, value) >= 0; } throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } public virtual string? GetEnumName(object value) { if (value == null) { throw new ArgumentNullException("value"); } if (!IsEnum) { throw new ArgumentException(SR.Arg_MustBeEnum, "value"); } Type type = value.GetType(); if (!type.IsEnum && !IsIntegerType(type)) { throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, "value"); } Array enumRawConstantValues = GetEnumRawConstantValues(); int num = BinarySearch(enumRawConstantValues, value); if (num >= 0) { string[] enumNames = GetEnumNames(); return enumNames[num]; } return null; } public virtual string[] GetEnumNames() { if (!IsEnum) { throw new ArgumentException(SR.Arg_MustBeEnum, "enumType"); } GetEnumData(out var enumNames, out var _); return enumNames; } private Array GetEnumRawConstantValues() { GetEnumData(out var _, out var enumValues); return enumValues; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2085:UnrecognizedReflectionPattern", Justification = "Literal fields on enums can never be trimmed")] private void GetEnumData(out string[] enumNames, out Array enumValues) { FieldInfo[] fields = GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); object[] array = new object[fields.Length]; string[] array2 = new string[fields.Length]; for (int i = 0; i < fields.Length; i++) { array2[i] = fields[i].Name; array[i] = fields[i].GetRawConstantValue(); } Comparer @default = Comparer.Default; for (int j = 1; j < array.Length; j++) { int num = j; string text = array2[j]; object obj = array[j]; bool flag = false; while (@default.Compare(array[num - 1], obj) > 0) { array2[num] = array2[num - 1]; array[num] = array[num - 1]; num--; flag = true; if (num == 0) { break; } } if (flag) { array2[num] = text; array[num] = obj; } } enumNames = array2; enumValues = array; } private static int BinarySearch(Array array, object value) { ulong[] array2 = new ulong[array.Length]; for (int i = 0; i < array.Length; i++) { array2[i] = Enum.ToUInt64(array.GetValue(i)); } ulong value2 = Enum.ToUInt64(value); return Array.BinarySearch(array2, value2); } internal static bool IsIntegerType(Type t) { if (!(t == typeof(int)) && !(t == typeof(short)) && !(t == typeof(ushort)) && !(t == typeof(byte)) && !(t == typeof(sbyte)) && !(t == typeof(uint)) && !(t == typeof(long)) && !(t == typeof(ulong)) && !(t == typeof(char))) { return t == typeof(bool); } return true; } internal Type GetRootElementType() { Type type = this; while (type.HasElementType) { type = type.GetElementType(); } return type; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public virtual Type[] FindInterfaces(TypeFilter filter, object? filterCriteria) { if (filter == null) { throw new ArgumentNullException("filter"); } Type[] interfaces = GetInterfaces(); int num = 0; for (int i = 0; i < interfaces.Length; i++) { if (!filter(interfaces[i], filterCriteria)) { interfaces[i] = null; } else { num++; } } if (num == interfaces.Length) { return interfaces; } Type[] array = new Type[num]; num = 0; foreach (Type type in interfaces) { if ((object)type != null) { array[num++] = type; } } return array; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public virtual MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter? filter, object? filterCriteria) { MethodInfo[] array = null; ConstructorInfo[] array2 = null; FieldInfo[] array3 = null; PropertyInfo[] array4 = null; EventInfo[] array5 = null; Type[] array6 = null; int num = 0; if ((memberType & MemberTypes.Method) != 0) { array = GetMethods(bindingAttr); if (filter != null) { for (int i = 0; i < array.Length; i++) { if (!filter(array[i], filterCriteria)) { array[i] = null; } else { num++; } } } else { num += array.Length; } } if ((memberType & MemberTypes.Constructor) != 0) { array2 = GetConstructors(bindingAttr); if (filter != null) { for (int i = 0; i < array2.Length; i++) { if (!filter(array2[i], filterCriteria)) { array2[i] = null; } else { num++; } } } else { num += array2.Length; } } if ((memberType & MemberTypes.Field) != 0) { array3 = GetFields(bindingAttr); if (filter != null) { for (int i = 0; i < array3.Length; i++) { if (!filter(array3[i], filterCriteria)) { array3[i] = null; } else { num++; } } } else { num += array3.Length; } } if ((memberType & MemberTypes.Property) != 0) { array4 = GetProperties(bindingAttr); if (filter != null) { for (int i = 0; i < array4.Length; i++) { if (!filter(array4[i], filterCriteria)) { array4[i] = null; } else { num++; } } } else { num += array4.Length; } } if ((memberType & MemberTypes.Event) != 0) { array5 = GetEvents(bindingAttr); if (filter != null) { for (int i = 0; i < array5.Length; i++) { if (!filter(array5[i], filterCriteria)) { array5[i] = null; } else { num++; } } } else { num += array5.Length; } } if ((memberType & MemberTypes.NestedType) != 0) { array6 = GetNestedTypes(bindingAttr); if (filter != null) { for (int i = 0; i < array6.Length; i++) { if (!filter(array6[i], filterCriteria)) { array6[i] = null; } else { num++; } } } else { num += array6.Length; } } MemberInfo[] array7 = new MemberInfo[num]; num = 0; if (array != null) { for (int i = 0; i < array.Length; i++) { if (array[i] != null) { array7[num++] = array[i]; } } } if (array2 != null) { foreach (ConstructorInfo constructorInfo in array2) { if ((object)constructorInfo != null) { array7[num++] = constructorInfo; } } } if (array3 != null) { foreach (FieldInfo fieldInfo in array3) { if ((object)fieldInfo != null) { array7[num++] = fieldInfo; } } } if (array4 != null) { foreach (PropertyInfo propertyInfo in array4) { if ((object)propertyInfo != null) { array7[num++] = propertyInfo; } } } if (array5 != null) { foreach (EventInfo eventInfo in array5) { if ((object)eventInfo != null) { array7[num++] = eventInfo; } } } if (array6 != null) { foreach (Type type in array6) { if ((object)type != null) { array7[num++] = type; } } } return array7; } public virtual bool IsSubclassOf(Type c) { Type type = this; if (type == c) { return false; } while (type != null) { if (type == c) { return true; } type = type.BaseType; } return false; } [Intrinsic] public virtual bool IsAssignableFrom([NotNullWhen(true)] Type? c) { if (c == null) { return false; } if (this == c) { return true; } Type underlyingSystemType = UnderlyingSystemType; if ((object)underlyingSystemType != null && underlyingSystemType.IsRuntimeImplemented()) { return underlyingSystemType.IsAssignableFrom(c); } if (c.IsSubclassOf(this)) { return true; } if (IsInterface) { return c.ImplementInterface(this); } if (IsGenericParameter) { Type[] genericParameterConstraints = GetGenericParameterConstraints(); for (int i = 0; i < genericParameterConstraints.Length; i++) { if (!genericParameterConstraints[i].IsAssignableFrom(c)) { return false; } } return true; } return false; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2085:UnrecognizedReflectionPattern", Justification = "The GetInterfaces technically requires all interfaces to be preservedBut this method only compares the result against the passed in ifaceType.So if ifaceType exists, then trimming should have kept it implemented on any type.")] internal bool ImplementInterface(Type ifaceType) { Type type = this; while (type != null) { Type[] interfaces = type.GetInterfaces(); if (interfaces != null) { for (int i = 0; i < interfaces.Length; i++) { if (interfaces[i] == ifaceType || (interfaces[i] != null && interfaces[i].ImplementInterface(ifaceType))) { return true; } } } type = type.BaseType; } return false; } private static bool FilterAttributeImpl(MemberInfo m, object filterCriteria) { if (filterCriteria == null) { throw new InvalidFilterCriteriaException(SR.InvalidFilterCriteriaException_CritInt); } switch (m.MemberType) { case MemberTypes.Constructor: case MemberTypes.Method: { MethodAttributes methodAttributes; try { int num2 = (int)filterCriteria; methodAttributes = (MethodAttributes)num2; } catch { throw new InvalidFilterCriteriaException(SR.InvalidFilterCriteriaException_CritInt); } MethodAttributes methodAttributes2 = ((m.MemberType != MemberTypes.Method) ? ((ConstructorInfo)m).Attributes : ((MethodInfo)m).Attributes); if ((methodAttributes & MethodAttributes.MemberAccessMask) != 0 && (methodAttributes2 & MethodAttributes.MemberAccessMask) != (methodAttributes & MethodAttributes.MemberAccessMask)) { return false; } if ((methodAttributes & MethodAttributes.Static) != 0 && (methodAttributes2 & MethodAttributes.Static) == 0) { return false; } if ((methodAttributes & MethodAttributes.Final) != 0 && (methodAttributes2 & MethodAttributes.Final) == 0) { return false; } if ((methodAttributes & MethodAttributes.Virtual) != 0 && (methodAttributes2 & MethodAttributes.Virtual) == 0) { return false; } if ((methodAttributes & MethodAttributes.Abstract) != 0 && (methodAttributes2 & MethodAttributes.Abstract) == 0) { return false; } if ((methodAttributes & MethodAttributes.SpecialName) != 0 && (methodAttributes2 & MethodAttributes.SpecialName) == 0) { return false; } return true; } case MemberTypes.Field: { FieldAttributes fieldAttributes; try { int num = (int)filterCriteria; fieldAttributes = (FieldAttributes)num; } catch { throw new InvalidFilterCriteriaException(SR.InvalidFilterCriteriaException_CritInt); } FieldAttributes attributes = ((FieldInfo)m).Attributes; if ((fieldAttributes & FieldAttributes.FieldAccessMask) != 0 && (attributes & FieldAttributes.FieldAccessMask) != (fieldAttributes & FieldAttributes.FieldAccessMask)) { return false; } if ((fieldAttributes & FieldAttributes.Static) != 0 && (attributes & FieldAttributes.Static) == 0) { return false; } if ((fieldAttributes & FieldAttributes.InitOnly) != 0 && (attributes & FieldAttributes.InitOnly) == 0) { return false; } if ((fieldAttributes & FieldAttributes.Literal) != 0 && (attributes & FieldAttributes.Literal) == 0) { return false; } if ((fieldAttributes & FieldAttributes.NotSerialized) != 0 && (attributes & FieldAttributes.NotSerialized) == 0) { return false; } if ((fieldAttributes & FieldAttributes.PinvokeImpl) != 0 && (attributes & FieldAttributes.PinvokeImpl) == 0) { return false; } return true; } default: return false; } } private static bool FilterNameImpl(MemberInfo m, object filterCriteria, StringComparison comparison) { if (!(filterCriteria is string text)) { throw new InvalidFilterCriteriaException(SR.InvalidFilterCriteriaException_CritString); } ReadOnlySpan readOnlySpan = text.AsSpan().Trim(); ReadOnlySpan span = m.Name; if (m.MemberType == MemberTypes.NestedType) { span = span.Slice(span.LastIndexOf('+') + 1); } if (readOnlySpan.Length > 0 && readOnlySpan[readOnlySpan.Length - 1] == '*') { readOnlySpan = readOnlySpan.Slice(0, readOnlySpan.Length - 1); return span.StartsWith(readOnlySpan, comparison); } return MemoryExtensions.Equals(span, readOnlySpan, comparison); } } [CLSCompliant(false)] [NonVersionable] public ref struct TypedReference { private readonly ByReference _value; private readonly IntPtr _type; internal bool IsNull { get { if (Unsafe.IsNullRef(ref _value.Value)) { return _type == IntPtr.Zero; } return false; } } public unsafe static TypedReference MakeTypedReference(object target, FieldInfo[] flds) { if (target == null) { throw new ArgumentNullException("target"); } if (flds == null) { throw new ArgumentNullException("flds"); } if (flds.Length == 0) { throw new ArgumentException(SR.Arg_ArrayZeroError, "flds"); } IntPtr[] array = new IntPtr[flds.Length]; RuntimeType runtimeType = (RuntimeType)target.GetType(); for (int i = 0; i < flds.Length; i++) { RuntimeFieldInfo runtimeFieldInfo = flds[i] as RuntimeFieldInfo; if (runtimeFieldInfo == null) { throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo); } if (runtimeFieldInfo.IsStatic) { throw new ArgumentException(SR.Format(SR.Argument_TypedReferenceInvalidField, runtimeFieldInfo.Name)); } if (runtimeType != runtimeFieldInfo.GetDeclaringTypeInternal() && !runtimeType.IsSubclassOf(runtimeFieldInfo.GetDeclaringTypeInternal())) { throw new MissingMemberException(SR.MissingMemberTypeRef); } RuntimeType runtimeType2 = (RuntimeType)runtimeFieldInfo.FieldType; if (runtimeType2.IsPrimitive) { throw new ArgumentException(SR.Format(SR.Arg_TypeRefPrimitve, runtimeFieldInfo.Name)); } if (i < flds.Length - 1 && !runtimeType2.IsValueType) { throw new MissingMemberException(SR.MissingMemberNestErr); } array[i] = runtimeFieldInfo.FieldHandle.Value; runtimeType = runtimeType2; } TypedReference result = default(TypedReference); InternalMakeTypedReference(&result, target, array, runtimeType); return result; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void InternalMakeTypedReference(void* result, object target, IntPtr[] flds, RuntimeType lastFieldType); public override int GetHashCode() { if (_type == IntPtr.Zero) { return 0; } return __reftype(this).GetHashCode(); } public override bool Equals(object? o) { throw new NotSupportedException(SR.NotSupported_NYI); } public unsafe static object ToObject(TypedReference value) { return InternalToObject(&value); } [MethodImpl(MethodImplOptions.InternalCall)] internal unsafe static extern object InternalToObject(void* value); public static Type GetTargetType(TypedReference value) { return __reftype(value); } public static RuntimeTypeHandle TargetTypeToken(TypedReference value) { return __reftype(value).TypeHandle; } public static void SetTypedReference(TypedReference target, object? value) { throw new NotSupportedException(); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class TypeLoadException : SystemException, ISerializable { private string _className; private string _assemblyName; private readonly string _messageArg; private readonly int _resourceId; public override string Message { get { SetMessageField(); return _message; } } public string TypeName => _className ?? string.Empty; private TypeLoadException(string className, string assemblyName, string messageArg, int resourceId) : base(null) { base.HResult = -2146233054; _className = className; _assemblyName = assemblyName; _messageArg = messageArg; _resourceId = resourceId; SetMessageField(); } private void SetMessageField() { if (_message != null) { return; } if (_className == null && _resourceId == 0) { _message = SR.Arg_TypeLoadException; return; } if (_assemblyName == null) { _assemblyName = SR.IO_UnknownFileName; } if (_className == null) { _className = SR.IO_UnknownFileName; } string s = null; GetTypeLoadExceptionMessage(_resourceId, new StringHandleOnStack(ref s)); _message = string.Format(s, _className, _assemblyName, _messageArg); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetTypeLoadExceptionMessage(int resourceId, StringHandleOnStack retString); public TypeLoadException() : base(SR.Arg_TypeLoadException) { base.HResult = -2146233054; } public TypeLoadException(string? message) : base(message) { base.HResult = -2146233054; } public TypeLoadException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233054; } protected TypeLoadException(SerializationInfo info, StreamingContext context) : base(info, context) { _className = info.GetString("TypeLoadClassName"); _assemblyName = info.GetString("TypeLoadAssemblyName"); _messageArg = info.GetString("TypeLoadMessageArg"); _resourceId = info.GetInt32("TypeLoadResourceID"); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("TypeLoadClassName", _className, typeof(string)); info.AddValue("TypeLoadAssemblyName", _assemblyName, typeof(string)); info.AddValue("TypeLoadMessageArg", _messageArg, typeof(string)); info.AddValue("TypeLoadResourceID", _resourceId); } } internal sealed class SafeTypeNameParserHandle : SafeHandleZeroOrMinusOneIsInvalid { [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void _ReleaseTypeNameParser(IntPtr pTypeNameParser); public SafeTypeNameParserHandle() : base(ownsHandle: true) { } protected override bool ReleaseHandle() { _ReleaseTypeNameParser(handle); handle = IntPtr.Zero; return true; } } internal sealed class TypeNameParser : IDisposable { private readonly SafeTypeNameParserHandle m_NativeParser; private static readonly char[] SPECIAL_CHARS = new char[7] { ',', '[', ']', '&', '*', '+', '\\' }; [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void _CreateTypeNameParser(string typeName, ObjectHandleOnStack retHandle, bool throwOnError); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void _GetNames(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void _GetTypeArguments(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void _GetModifiers(SafeTypeNameParserHandle pTypeNameParser, ObjectHandleOnStack retArray); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void _GetAssemblyName(SafeTypeNameParserHandle pTypeNameParser, StringHandleOnStack retString); [RequiresUnreferencedCode("The type might be removed")] internal static Type GetType(string typeName, Func assemblyResolver, Func typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { if (typeName == null) { throw new ArgumentNullException("typeName"); } if (typeName.Length > 0 && typeName[0] == '\0') { throw new ArgumentException(SR.Format_StringZeroLength); } Type result = null; SafeTypeNameParserHandle safeTypeNameParserHandle = CreateTypeNameParser(typeName, throwOnError); if (safeTypeNameParserHandle != null) { using TypeNameParser typeNameParser = new TypeNameParser(safeTypeNameParserHandle); result = typeNameParser.ConstructType(assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark); } return result; } private TypeNameParser(SafeTypeNameParserHandle handle) { m_NativeParser = handle; } public void Dispose() { m_NativeParser.Dispose(); } [RequiresUnreferencedCode("The type might be removed")] private unsafe Type ConstructType(Func assemblyResolver, Func typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { Assembly assembly = null; string assemblyName = GetAssemblyName(); if (assemblyName.Length > 0) { assembly = ResolveAssembly(assemblyName, assemblyResolver, throwOnError, ref stackMark); if (assembly == null) { return null; } } string[] names = GetNames(); if (names == null) { if (throwOnError) { throw new TypeLoadException(SR.Arg_TypeLoadNullStr); } return null; } Type type = ResolveType(assembly, names, typeResolver, throwOnError, ignoreCase, ref stackMark); if (type == null) { return null; } SafeTypeNameParserHandle[] typeArguments = GetTypeArguments(); Type[] array = null; if (typeArguments != null) { array = new Type[typeArguments.Length]; for (int i = 0; i < typeArguments.Length; i++) { using (TypeNameParser typeNameParser = new TypeNameParser(typeArguments[i])) { array[i] = typeNameParser.ConstructType(assemblyResolver, typeResolver, throwOnError, ignoreCase, ref stackMark); } if (array[i] == null) { return null; } } } int[] modifiers = GetModifiers(); fixed (int* value = modifiers) { IntPtr pModifiers = new IntPtr(value); return RuntimeTypeHandle.GetTypeHelper(type, array, pModifiers, (modifiers != null) ? modifiers.Length : 0); } } private static Assembly ResolveAssembly(string asmName, Func assemblyResolver, bool throwOnError, ref StackCrawlMark stackMark) { Assembly assembly; if (assemblyResolver == null) { if (throwOnError) { assembly = RuntimeAssembly.InternalLoad(asmName, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext); } else { try { assembly = RuntimeAssembly.InternalLoad(asmName, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext); } catch (FileNotFoundException) { return null; } } } else { assembly = assemblyResolver(new AssemblyName(asmName)); if (assembly == null && throwOnError) { throw new FileNotFoundException(SR.Format(SR.FileNotFound_ResolveAssembly, asmName)); } } return assembly; } [RequiresUnreferencedCode("The type might be removed")] private static Type ResolveType(Assembly assembly, string[] names, Func typeResolver, bool throwOnError, bool ignoreCase, ref StackCrawlMark stackMark) { string text = EscapeTypeName(names[0]); Type type; if (typeResolver == null) { type = ((!(assembly == null)) ? assembly.GetType(text, throwOnError, ignoreCase) : RuntimeType.GetType(text, throwOnError, ignoreCase, ref stackMark)); } else { type = typeResolver(assembly, text, ignoreCase); if (type == null && throwOnError) { string message = ((assembly == null) ? SR.Format(SR.TypeLoad_ResolveType, text) : SR.Format(SR.TypeLoad_ResolveTypeFromAssembly, text, assembly.FullName)); throw new TypeLoadException(message); } } if (type != null) { BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic; if (ignoreCase) { bindingFlags |= BindingFlags.IgnoreCase; } for (int i = 1; i < names.Length; i++) { type = type.GetNestedType(names[i], bindingFlags); if (type == null) { if (!throwOnError) { break; } throw new TypeLoadException(SR.Format(SR.TypeLoad_ResolveNestedType, names[i], names[i - 1])); } } } return type; } private static string EscapeTypeName(string name) { if (name.IndexOfAny(SPECIAL_CHARS) < 0) { return name; } Span initialBuffer = stackalloc char[64]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); foreach (char c in name) { if (Array.IndexOf(SPECIAL_CHARS, c) >= 0) { valueStringBuilder.Append('\\'); } valueStringBuilder.Append(c); } return valueStringBuilder.ToString(); } private static SafeTypeNameParserHandle CreateTypeNameParser(string typeName, bool throwOnError) { SafeTypeNameParserHandle o = null; _CreateTypeNameParser(typeName, ObjectHandleOnStack.Create(ref o), throwOnError); return o; } private string[] GetNames() { string[] o = null; _GetNames(m_NativeParser, ObjectHandleOnStack.Create(ref o)); return o; } private SafeTypeNameParserHandle[] GetTypeArguments() { SafeTypeNameParserHandle[] o = null; _GetTypeArguments(m_NativeParser, ObjectHandleOnStack.Create(ref o)); return o; } private int[] GetModifiers() { int[] o = null; _GetModifiers(m_NativeParser, ObjectHandleOnStack.Create(ref o)); return o; } private string GetAssemblyName() { string s = null; _GetAssemblyName(m_NativeParser, new StringHandleOnStack(ref s)); return s; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class ValueType { [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", Justification = "Trimmed fields don't make a difference for equality")] public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == null) { return false; } Type type = GetType(); Type type2 = obj.GetType(); if (type2 != type) { return false; } if (CanCompareBits(this)) { return FastEqualsCheck(this, obj); } FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < fields.Length; i++) { object value = fields[i].GetValue(this); object value2 = fields[i].GetValue(obj); if (value == null) { if (value2 != null) { return false; } } else if (!value.Equals(value2)) { return false; } } return true; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool CanCompareBits(object obj); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool FastEqualsCheck(object a, object b); [MethodImpl(MethodImplOptions.InternalCall)] public override extern int GetHashCode(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetHashCodeOfPtr(IntPtr ptr); public override string? ToString() { return GetType().ToString(); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class WeakReference : ISerializable { internal IntPtr m_handle; public virtual extern bool IsAlive { [MethodImpl(MethodImplOptions.InternalCall)] get; } public virtual bool TrackResurrection => IsTrackResurrection(); public virtual extern object? Target { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } protected WeakReference() { throw new NotImplementedException(); } [MethodImpl(MethodImplOptions.InternalCall)] extern ~WeakReference(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Create(object target, bool trackResurrection); [MethodImpl(MethodImplOptions.InternalCall)] private extern bool IsTrackResurrection(); public WeakReference(object? target) : this(target, trackResurrection: false) { } public WeakReference(object? target, bool trackResurrection) { Create(target, trackResurrection); } protected WeakReference(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } object value = info.GetValue("TrackedObject", typeof(object)); bool boolean = info.GetBoolean("TrackResurrection"); Create(value, boolean); } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("TrackedObject", Target, typeof(object)); info.AddValue("TrackResurrection", IsTrackResurrection()); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class WeakReference : ISerializable where T : class? { internal IntPtr m_handle; private extern T Target { [MethodImpl(MethodImplOptions.InternalCall)] [return: MaybeNull] get; [MethodImpl(MethodImplOptions.InternalCall)] set; } public void SetTarget(T target) { Target = target; } [MethodImpl(MethodImplOptions.InternalCall)] extern ~WeakReference(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Create(T target, bool trackResurrection); [MethodImpl(MethodImplOptions.InternalCall)] private extern bool IsTrackResurrection(); public WeakReference(T target) : this(target, trackResurrection: false) { } public WeakReference(T target, bool trackResurrection) { Create(target, trackResurrection); } private WeakReference(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } T target = (T)info.GetValue("TrackedObject", typeof(T)); bool boolean = info.GetBoolean("TrackResurrection"); Create(target, boolean); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetTarget([MaybeNullWhen(false)][NotNullWhen(true)] out T target) { return (target = Target) != null; } public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("TrackedObject", Target, typeof(T)); info.AddValue("TrackResurrection", IsTrackResurrection()); } } [SupportedOSPlatform("windows")] internal class __ComObject : MarshalByRefObject { private Hashtable m_ObjectToDataMap; protected __ComObject() { } internal object GetData(object key) { object result = null; lock (this) { if (m_ObjectToDataMap != null) { result = m_ObjectToDataMap[key]; } } return result; } internal bool SetData(object key, object data) { bool result = false; lock (this) { if (m_ObjectToDataMap == null) { m_ObjectToDataMap = new Hashtable(); } if (m_ObjectToDataMap[key] == null) { m_ObjectToDataMap[key] = data; result = true; } } return result; } internal void ReleaseAllData() { lock (this) { if (m_ObjectToDataMap == null) { return; } foreach (object value in m_ObjectToDataMap.Values) { if (value is IDisposable disposable) { disposable.Dispose(); } if (value is __ComObject o) { Marshal.ReleaseComObject(o); } } m_ObjectToDataMap = null; } } internal object GetEventProvider([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] RuntimeType t) { object data = GetData(t); if (data != null) { return data; } return CreateEventProvider(t); } internal int ReleaseSelf() { return Marshal.InternalReleaseComObject(this); } internal void FinalReleaseSelf() { Marshal.InternalFinalReleaseComObject(this); } private object CreateEventProvider([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] RuntimeType t) { object obj = Activator.CreateInstance(t, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, new object[1] { this }, null); if (!SetData(t, obj)) { if (obj is IDisposable disposable) { disposable.Dispose(); } obj = GetData(t); } return obj; } } internal sealed class OleAutBinder : DefaultBinder { public override object ChangeType(object value, Type type, CultureInfo cultureInfo) { Variant source = new Variant(value); if (cultureInfo == null) { cultureInfo = CultureInfo.CurrentCulture; } if (type.IsByRef) { type = type.GetElementType(); } if (!type.IsPrimitive && type.IsInstanceOfType(value)) { return value; } Type type2 = value.GetType(); if (type.IsEnum && type2.IsPrimitive) { return Enum.Parse(type, value.ToString()); } try { return OAVariantLib.ChangeType(source, type, 16, cultureInfo).ToObject(); } catch (NotSupportedException) { throw new COMException(SR.Interop_COM_TypeMismatch, -2147352571); } } } internal struct Variant { private object _objref; private long _data; private int _flags; internal const int CV_EMPTY = 0; internal const int CV_VOID = 1; internal const int CV_BOOLEAN = 2; internal const int CV_CHAR = 3; internal const int CV_I1 = 4; internal const int CV_U1 = 5; internal const int CV_I2 = 6; internal const int CV_U2 = 7; internal const int CV_I4 = 8; internal const int CV_U4 = 9; internal const int CV_I8 = 10; internal const int CV_U8 = 11; internal const int CV_R4 = 12; internal const int CV_R8 = 13; internal const int CV_STRING = 14; internal const int CV_PTR = 15; internal const int CV_DATETIME = 16; internal const int CV_TIMESPAN = 17; internal const int CV_OBJECT = 18; internal const int CV_DECIMAL = 19; internal const int CV_ENUM = 21; internal const int CV_MISSING = 22; internal const int CV_NULL = 23; internal const int CV_LAST = 24; internal const int TypeCodeBitMask = 65535; internal const int VTBitMask = -16777216; internal const int VTBitShift = 24; internal const int ArrayBitMask = 65536; internal const int EnumI1 = 1048576; internal const int EnumU1 = 2097152; internal const int EnumI2 = 3145728; internal const int EnumU2 = 4194304; internal const int EnumI4 = 5242880; internal const int EnumU4 = 6291456; internal const int EnumI8 = 7340032; internal const int EnumU8 = 8388608; internal const int EnumMask = 15728640; internal static readonly Type[] ClassTypes = new Type[23] { typeof(Empty), typeof(void), typeof(bool), typeof(char), typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(string), typeof(void), typeof(DateTime), typeof(TimeSpan), typeof(object), typeof(decimal), typeof(object), typeof(Missing), typeof(DBNull) }; internal static readonly Variant Empty; internal static readonly Variant Missing = new Variant(22, Type.Missing, 0L); internal static readonly Variant DBNull = new Variant(23, System.DBNull.Value, 0L); internal int CVType => _flags & 0xFFFF; [MethodImpl(MethodImplOptions.InternalCall)] internal extern void SetFieldsObject(object val); internal Variant(int flags, object or, long data) { _flags = flags; _objref = or; _data = data; } public Variant(bool val) { _objref = null; _flags = 2; _data = (val ? 1 : 0); } public Variant(sbyte val) { _objref = null; _flags = 4; _data = val; } public Variant(byte val) { _objref = null; _flags = 5; _data = val; } public Variant(short val) { _objref = null; _flags = 6; _data = val; } public Variant(ushort val) { _objref = null; _flags = 7; _data = val; } public Variant(char val) { _objref = null; _flags = 3; _data = val; } public Variant(int val) { _objref = null; _flags = 8; _data = val; } public Variant(uint val) { _objref = null; _flags = 9; _data = val; } public Variant(long val) { _objref = null; _flags = 10; _data = val; } public Variant(ulong val) { _objref = null; _flags = 11; _data = (long)val; } public Variant(float val) { _objref = null; _flags = 12; _data = BitConverter.SingleToUInt32Bits(val); } public Variant(double val) { _objref = null; _flags = 13; _data = BitConverter.DoubleToInt64Bits(val); } public Variant(DateTime val) { _objref = null; _flags = 16; _data = val.Ticks; } public Variant(decimal val) { _objref = val; _flags = 19; _data = 0L; } public Variant(object obj) { _data = 0L; VarEnum varEnum = VarEnum.VT_EMPTY; if (obj is DateTime) { _objref = null; _flags = 16; _data = ((DateTime)obj).Ticks; return; } if (obj is string) { _flags = 14; _objref = obj; return; } if (obj == null) { this = Empty; return; } if (obj == System.DBNull.Value) { this = DBNull; return; } if (obj == Type.Missing) { this = Missing; return; } if (obj is Array) { _flags = 65554; _objref = obj; return; } _flags = 0; _objref = null; if (obj is UnknownWrapper) { varEnum = VarEnum.VT_UNKNOWN; obj = ((UnknownWrapper)obj).WrappedObject; } else if (obj is DispatchWrapper) { varEnum = VarEnum.VT_DISPATCH; obj = ((DispatchWrapper)obj).WrappedObject; } else if (obj is ErrorWrapper) { varEnum = VarEnum.VT_ERROR; obj = ((ErrorWrapper)obj).ErrorCode; } else if (obj is CurrencyWrapper) { varEnum = VarEnum.VT_CY; obj = ((CurrencyWrapper)obj).WrappedObject; } else if (obj is BStrWrapper) { varEnum = VarEnum.VT_BSTR; obj = ((BStrWrapper)obj).WrappedObject; } if (obj != null) { SetFieldsObject(obj); } if (varEnum != 0) { _flags |= (int)varEnum << 24; } } public object ToObject() { return CVType switch { 0 => null, 2 => (int)_data != 0, 4 => (sbyte)_data, 5 => (byte)_data, 3 => (char)_data, 6 => (short)_data, 7 => (ushort)_data, 8 => (int)_data, 9 => (uint)_data, 10 => _data, 11 => (ulong)_data, 12 => BitConverter.UInt32BitsToSingle((uint)_data), 13 => BitConverter.Int64BitsToDouble(_data), 16 => new DateTime(_data), 17 => new TimeSpan(_data), 21 => BoxEnum(), 22 => Type.Missing, 23 => System.DBNull.Value, _ => _objref, }; } [MethodImpl(MethodImplOptions.InternalCall)] private extern object BoxEnum(); internal static void MarshalHelperConvertObjectToVariant(object o, ref Variant v) { if (o == null) { v = Empty; } else if (o is IConvertible convertible) { IFormatProvider invariantCulture = CultureInfo.InvariantCulture; v = convertible.GetTypeCode() switch { TypeCode.Empty => Empty, TypeCode.Object => new Variant(o), TypeCode.DBNull => DBNull, TypeCode.Boolean => new Variant(convertible.ToBoolean(invariantCulture)), TypeCode.Char => new Variant(convertible.ToChar(invariantCulture)), TypeCode.SByte => new Variant(convertible.ToSByte(invariantCulture)), TypeCode.Byte => new Variant(convertible.ToByte(invariantCulture)), TypeCode.Int16 => new Variant(convertible.ToInt16(invariantCulture)), TypeCode.UInt16 => new Variant(convertible.ToUInt16(invariantCulture)), TypeCode.Int32 => new Variant(convertible.ToInt32(invariantCulture)), TypeCode.UInt32 => new Variant(convertible.ToUInt32(invariantCulture)), TypeCode.Int64 => new Variant(convertible.ToInt64(invariantCulture)), TypeCode.UInt64 => new Variant(convertible.ToUInt64(invariantCulture)), TypeCode.Single => new Variant(convertible.ToSingle(invariantCulture)), TypeCode.Double => new Variant(convertible.ToDouble(invariantCulture)), TypeCode.Decimal => new Variant(convertible.ToDecimal(invariantCulture)), TypeCode.DateTime => new Variant(convertible.ToDateTime(invariantCulture)), TypeCode.String => new Variant(convertible.ToString(invariantCulture)), _ => throw new NotSupportedException(SR.Format(SR.NotSupported_UnknownTypeCode, convertible.GetTypeCode())), }; } else { v = new Variant(o); } } internal static object MarshalHelperConvertVariantToObject(ref Variant v) { return v.ToObject(); } internal static void MarshalHelperCastVariant(object pValue, int vt, ref Variant v) { if (!(pValue is IConvertible convertible)) { switch (vt) { case 9: v = new Variant(new DispatchWrapper(pValue)); return; case 12: v = new Variant(pValue); return; case 13: v = new Variant(new UnknownWrapper(pValue)); return; case 36: v = new Variant(pValue); return; case 8: if (pValue == null) { v = new Variant(null) { _flags = 14 }; return; } break; } throw new InvalidCastException(SR.InvalidCast_CannotCoerceByRefVariant); } IFormatProvider invariantCulture = CultureInfo.InvariantCulture; v = vt switch { 0 => Empty, 1 => DBNull, 2 => new Variant(convertible.ToInt16(invariantCulture)), 3 => new Variant(convertible.ToInt32(invariantCulture)), 4 => new Variant(convertible.ToSingle(invariantCulture)), 5 => new Variant(convertible.ToDouble(invariantCulture)), 6 => new Variant(new CurrencyWrapper(convertible.ToDecimal(invariantCulture))), 7 => new Variant(convertible.ToDateTime(invariantCulture)), 8 => new Variant(convertible.ToString(invariantCulture)), 9 => new Variant(new DispatchWrapper(convertible)), 10 => new Variant(new ErrorWrapper(convertible.ToInt32(invariantCulture))), 11 => new Variant(convertible.ToBoolean(invariantCulture)), 12 => new Variant(convertible), 13 => new Variant(new UnknownWrapper(convertible)), 14 => new Variant(convertible.ToDecimal(invariantCulture)), 16 => new Variant(convertible.ToSByte(invariantCulture)), 17 => new Variant(convertible.ToByte(invariantCulture)), 18 => new Variant(convertible.ToUInt16(invariantCulture)), 19 => new Variant(convertible.ToUInt32(invariantCulture)), 20 => new Variant(convertible.ToInt64(invariantCulture)), 21 => new Variant(convertible.ToUInt64(invariantCulture)), 22 => new Variant(convertible.ToInt32(invariantCulture)), 23 => new Variant(convertible.ToUInt32(invariantCulture)), _ => throw new InvalidCastException(SR.InvalidCast_CannotCoerceByRefVariant), }; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class AccessViolationException : SystemException { private IntPtr _ip; private IntPtr _target; private int _accessType; public AccessViolationException() : base(SR.Arg_AccessViolationException) { base.HResult = -2147467261; } public AccessViolationException(string? message) : base(message) { base.HResult = -2147467261; } public AccessViolationException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2147467261; } protected AccessViolationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public delegate void Action(); public delegate void Action(T obj); public delegate void Action(T1 arg1, T2 arg2); public delegate void Action(T1 arg1, T2 arg2, T3 arg3); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15); public delegate void Action(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16); public delegate int Comparison(T x, T y); public delegate TOutput Converter(TInput input); public delegate bool Predicate(T obj); public static class Activator { [DebuggerHidden] [DebuggerStepThrough] public static object? CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type type, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture) { return CreateInstance(type, bindingAttr, binder, args, culture, null); } [DebuggerHidden] [DebuggerStepThrough] public static object? CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type, params object?[]? args) { return CreateInstance(type, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, null, args, null, null); } [DebuggerHidden] [DebuggerStepThrough] public static object? CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type, object?[]? args, object?[]? activationAttributes) { return CreateInstance(type, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, null, args, null, activationAttributes); } [DebuggerHidden] [DebuggerStepThrough] public static object? CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type type) { return CreateInstance(type, nonPublic: false); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public static ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName) { return CreateInstanceFrom(assemblyFile, typeName, ignoreCase: false, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, null, null, null, null); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public static ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName, object?[]? activationAttributes) { return CreateInstanceFrom(assemblyFile, typeName, ignoreCase: false, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, null, null, null, activationAttributes); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public static ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture, object?[]? activationAttributes) { Assembly assembly = Assembly.LoadFrom(assemblyFile); Type type = assembly.GetType(typeName, throwOnError: true, ignoreCase); object obj = CreateInstance(type, bindingAttr, binder, args, culture, activationAttributes); if (obj == null) { return null; } return new ObjectHandle(obj); } public static object? CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type type, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture, object?[]? activationAttributes) { if ((object)type == null) { throw new ArgumentNullException("type"); } if (type is TypeBuilder) { throw new NotSupportedException(SR.NotSupported_CreateInstanceWithTypeBuilder); } if ((bindingAttr & (BindingFlags)255) == 0) { bindingAttr |= BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance; } if (activationAttributes != null && activationAttributes.Length != 0) { throw new PlatformNotSupportedException(SR.NotSupported_ActivAttr); } if (type.UnderlyingSystemType is RuntimeType runtimeType) { return runtimeType.CreateInstanceImpl(bindingAttr, binder, args, culture); } throw new ArgumentException(SR.Arg_MustBeType, "type"); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public static ObjectHandle? CreateInstance(string assemblyName, string typeName) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstanceInternal(assemblyName, typeName, ignoreCase: false, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, null, null, null, null, ref stackMark); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public static ObjectHandle? CreateInstance(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture, object?[]? activationAttributes) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstanceInternal(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes, ref stackMark); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public static ObjectHandle? CreateInstance(string assemblyName, string typeName, object?[]? activationAttributes) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return CreateInstanceInternal(assemblyName, typeName, ignoreCase: false, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, null, null, null, activationAttributes, ref stackMark); } public static object? CreateInstance([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type type, bool nonPublic) { return CreateInstance(type, nonPublic, wrapExceptions: true); } internal static object CreateInstance(Type type, bool nonPublic, bool wrapExceptions) { if ((object)type == null) { throw new ArgumentNullException("type"); } if (!(type.UnderlyingSystemType is RuntimeType runtimeType)) { throw new ArgumentException(SR.Arg_MustBeType, "type"); } return runtimeType.CreateInstanceDefaultCtor(!nonPublic, wrapExceptions); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Implementation detail of Activator that linker intrinsically recognizes")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2072:UnrecognizedReflectionPattern", Justification = "Implementation detail of Activator that linker intrinsically recognizes")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2096:UnrecognizedReflectionPattern", Justification = "Implementation detail of Activator that linker intrinsically recognizes")] private static ObjectHandle CreateInstanceInternal(string assemblyString, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, CultureInfo culture, object[] activationAttributes, ref StackCrawlMark stackMark) { Assembly assembly; if (assemblyString == null) { assembly = Assembly.GetExecutingAssembly(ref stackMark); } else { AssemblyName assemblyName = new AssemblyName(assemblyString); assembly = RuntimeAssembly.InternalLoad(assemblyName, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext); } Type type = assembly.GetType(typeName, throwOnError: true, ignoreCase); object obj = CreateInstance(type, bindingAttr, binder, args, culture, activationAttributes); if (obj == null) { return null; } return new ObjectHandle(obj); } [Intrinsic] public static T CreateInstance<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] T>() { return (T)((RuntimeType)typeof(T)).CreateInstanceOfT(); } private static T CreateDefaultInstance() where T : struct { return default(T); } } [Serializable] [DebuggerDisplay("Count = {InnerExceptionCount}")] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class AggregateException : Exception { private readonly Exception[] _innerExceptions; private ReadOnlyCollection _rocView; public ReadOnlyCollection InnerExceptions => _rocView ?? (_rocView = new ReadOnlyCollection(_innerExceptions)); public override string Message { get { if (_innerExceptions.Length == 0) { return base.Message; } StringBuilder stringBuilder = StringBuilderCache.Acquire(); stringBuilder.Append(base.Message); stringBuilder.Append(' '); for (int i = 0; i < _innerExceptions.Length; i++) { stringBuilder.Append('('); stringBuilder.Append(_innerExceptions[i].Message); stringBuilder.Append(") "); } stringBuilder.Length--; return StringBuilderCache.GetStringAndRelease(stringBuilder); } } internal int InnerExceptionCount => _innerExceptions.Length; internal Exception[] InternalInnerExceptions => _innerExceptions; public AggregateException() : this(SR.AggregateException_ctor_DefaultMessage) { } public AggregateException(string? message) : base(message) { _innerExceptions = Array.Empty(); } public AggregateException(string? message, Exception innerException) : base(message, innerException) { if (innerException == null) { throw new ArgumentNullException("innerException"); } _innerExceptions = new Exception[1] { innerException }; } public AggregateException(IEnumerable innerExceptions) : this(SR.AggregateException_ctor_DefaultMessage, innerExceptions) { } public AggregateException(params Exception[] innerExceptions) : this(SR.AggregateException_ctor_DefaultMessage, innerExceptions) { } public AggregateException(string? message, IEnumerable innerExceptions) : this(message, (innerExceptions == null) ? null : new List(innerExceptions).ToArray(), cloneExceptions: false) { } public AggregateException(string? message, params Exception[] innerExceptions) : this(message, innerExceptions, cloneExceptions: true) { } private AggregateException(string message, Exception[] innerExceptions, bool cloneExceptions) : base(message, (innerExceptions != null && innerExceptions.Length != 0) ? innerExceptions[0] : null) { if (innerExceptions == null) { throw new ArgumentNullException("innerExceptions"); } _innerExceptions = (cloneExceptions ? new Exception[innerExceptions.Length] : innerExceptions); for (int i = 0; i < _innerExceptions.Length; i++) { _innerExceptions[i] = innerExceptions[i]; if (innerExceptions[i] == null) { throw new ArgumentException(SR.AggregateException_ctor_InnerExceptionNull); } } } internal AggregateException(List innerExceptionInfos) : this(SR.AggregateException_ctor_DefaultMessage, innerExceptionInfos) { } internal AggregateException(string message, List innerExceptionInfos) : base(message, (innerExceptionInfos.Count != 0) ? innerExceptionInfos[0].SourceException : null) { _innerExceptions = new Exception[innerExceptionInfos.Count]; for (int i = 0; i < _innerExceptions.Length; i++) { _innerExceptions[i] = innerExceptionInfos[i].SourceException; } } protected AggregateException(SerializationInfo info, StreamingContext context) : base(info, context) { if (!(info.GetValue("InnerExceptions", typeof(Exception[])) is Exception[] innerExceptions)) { throw new SerializationException(SR.AggregateException_DeserializationFailure); } _innerExceptions = innerExceptions; } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("InnerExceptions", _innerExceptions, typeof(Exception[])); } public override Exception GetBaseException() { Exception ex = this; AggregateException ex2 = this; while (ex2 != null && ex2.InnerExceptions.Count == 1) { ex = ex.InnerException; ex2 = ex as AggregateException; } return ex; } public void Handle(Func predicate) { if (predicate == null) { throw new ArgumentNullException("predicate"); } List list = null; for (int i = 0; i < _innerExceptions.Length; i++) { if (!predicate(_innerExceptions[i])) { if (list == null) { list = new List(); } list.Add(_innerExceptions[i]); } } if (list != null) { throw new AggregateException(Message, list.ToArray(), cloneExceptions: false); } } public AggregateException Flatten() { List list = new List(); List list2 = new List { this }; int num = 0; while (list2.Count > num) { ReadOnlyCollection innerExceptions = list2[num++].InnerExceptions; for (int i = 0; i < innerExceptions.Count; i++) { Exception ex = innerExceptions[i]; if (ex != null) { if (ex is AggregateException item) { list2.Add(item); } else { list.Add(ex); } } } } return new AggregateException((GetType() == typeof(AggregateException)) ? base.Message : Message, list.ToArray(), cloneExceptions: false); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(base.ToString()); for (int i = 0; i < _innerExceptions.Length; i++) { if (_innerExceptions[i] != base.InnerException) { stringBuilder.Append("\r\n ---> "); stringBuilder.AppendFormat(CultureInfo.InvariantCulture, SR.AggregateException_InnerException, i); stringBuilder.Append(_innerExceptions[i].ToString()); stringBuilder.Append("<---"); stringBuilder.AppendLine(); } } return stringBuilder.ToString(); } } public static class AppContext { private static Dictionary s_dataStore; private static Dictionary s_switches; private static string s_defaultBaseDirectory; public static string BaseDirectory => (GetData("APP_CONTEXT_BASE_DIRECTORY") as string) ?? s_defaultBaseDirectory ?? (s_defaultBaseDirectory = GetBaseDirectoryCore()); public static string? TargetFrameworkName => Assembly.GetEntryAssembly()?.GetCustomAttribute()?.FrameworkName; [field: DynamicDependency(DynamicallyAccessedMemberTypes.PublicConstructors, typeof(UnhandledExceptionEventArgs))] public static event UnhandledExceptionEventHandler? UnhandledException; [field: DynamicDependency(DynamicallyAccessedMemberTypes.PublicConstructors, typeof(FirstChanceExceptionEventArgs))] public static event EventHandler? FirstChanceException; public static event EventHandler? ProcessExit; public static object? GetData(string name) { if (name == null) { throw new ArgumentNullException("name"); } if (s_dataStore == null) { return null; } lock (s_dataStore) { s_dataStore.TryGetValue(name, out var value); return value; } } public static void SetData(string name, object? data) { if (name == null) { throw new ArgumentNullException("name"); } if (s_dataStore == null) { Interlocked.CompareExchange(ref s_dataStore, new Dictionary(), null); } lock (s_dataStore) { s_dataStore[name] = data; } } internal static void OnProcessExit() { AssemblyLoadContext.OnProcessExit(); if (EventSource.IsSupported) { EventListener.DisposeOnShutdown(); } AppContext.ProcessExit?.Invoke(AppDomain.CurrentDomain, EventArgs.Empty); } public static bool TryGetSwitch(string switchName, out bool isEnabled) { if (switchName == null) { throw new ArgumentNullException("switchName"); } if (switchName.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "switchName"); } if (s_switches != null) { lock (s_switches) { if (s_switches.TryGetValue(switchName, out isEnabled)) { return true; } } } if (GetData(switchName) is string value && bool.TryParse(value, out isEnabled)) { return true; } isEnabled = false; return false; } public static void SetSwitch(string switchName, bool isEnabled) { if (switchName == null) { throw new ArgumentNullException("switchName"); } if (switchName.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "switchName"); } if (s_switches == null) { Interlocked.CompareExchange(ref s_switches, new Dictionary(), null); } lock (s_switches) { s_switches[switchName] = isEnabled; } } internal unsafe static void Setup(char** pNames, char** pValues, int count) { s_dataStore = new Dictionary(count); for (int i = 0; i < count; i++) { s_dataStore.Add(new string(pNames[i]), new string(pValues[i])); } } [UnconditionalSuppressMessage("SingleFile", "IL3000: Avoid accessing Assembly file path when publishing as a single file", Justification = "Single File apps should always set APP_CONTEXT_BASE_DIRECTORY therefore code handles Assembly.Location equals null")] private static string GetBaseDirectoryCore() { string path = Assembly.GetEntryAssembly()?.Location; string text = Path.GetDirectoryName(path); if (text == null) { return string.Empty; } if (!Path.EndsInDirectorySeparator(text)) { text += "\\"; } return text; } internal static void LogSwitchValues(RuntimeEventSource ev) { if (s_switches != null) { lock (s_switches) { foreach (KeyValuePair s_switch in s_switches) { ev.LogAppContextSwitch(s_switch.Key, s_switch.Value ? 1 : 0); } } } if (s_dataStore == null) { return; } lock (s_dataStore) { if (s_switches != null) { lock (s_switches) { LogDataStore(ev, s_switches); return; } } LogDataStore(ev, null); } static void LogDataStore(RuntimeEventSource ev, Dictionary switches) { foreach (KeyValuePair item in s_dataStore) { if (item.Value is string value && bool.TryParse(value, out var result) && (switches == null || !switches.ContainsKey(item.Key))) { ev.LogAppContextSwitch(item.Key, result ? 1 : 0); } } } } } internal static class AppContextConfigHelper { internal static bool GetBooleanConfig(string configName, bool defaultValue) { if (!AppContext.TryGetSwitch(configName, out var isEnabled)) { return defaultValue; } return isEnabled; } internal static bool GetBooleanConfig(string switchName, string envVariable, bool defaultValue = false) { if (!AppContext.TryGetSwitch(switchName, out var isEnabled)) { string environmentVariable = Environment.GetEnvironmentVariable(envVariable); return (environmentVariable == null) ? defaultValue : (bool.IsTrueStringIgnoreCase(environmentVariable) || environmentVariable.Equals("1")); } return isEnabled; } internal static int GetInt32Config(string configName, int defaultValue, bool allowNegative = true) { try { object data = AppContext.GetData(configName); int num = defaultValue; if (!(data is uint num2)) { if (data is string text) { num = ((!text.StartsWith('0')) ? int.Parse(text, NumberStyles.AllowLeadingSign, NumberFormatInfo.InvariantInfo) : ((text.Length < 2 || text[1] != 'x') ? Convert.ToInt32(text, 8) : Convert.ToInt32(text, 16))); } else if (data is IConvertible convertible) { num = convertible.ToInt32(NumberFormatInfo.InvariantInfo); } } else { num = (int)num2; } return (!allowNegative && num < 0) ? defaultValue : num; } catch (FormatException) { return defaultValue; } catch (OverflowException) { return defaultValue; } } internal static short GetInt16Config(string configName, short defaultValue, bool allowNegative = true) { try { object data = AppContext.GetData(configName); short num = defaultValue; if (!(data is uint num2)) { if (data is string text) { num = (text.StartsWith("0x") ? Convert.ToInt16(text, 16) : ((!text.StartsWith("0")) ? short.Parse(text, NumberStyles.AllowLeadingSign, NumberFormatInfo.InvariantInfo) : Convert.ToInt16(text, 8))); } else if (data is IConvertible convertible) { num = convertible.ToInt16(NumberFormatInfo.InvariantInfo); } } else { num = (short)num2; if ((uint)num != num2) { return defaultValue; } } return (!allowNegative && num < 0) ? defaultValue : num; } catch (FormatException) { return defaultValue; } catch (OverflowException) { return defaultValue; } } } public sealed class AppDomain : MarshalByRefObject { private static readonly AppDomain s_domain = new AppDomain(); private IPrincipal _defaultPrincipal; private PrincipalPolicy _principalPolicy = PrincipalPolicy.NoPrincipal; private Func s_getWindowsPrincipal; private Func s_getUnauthenticatedPrincipal; public static AppDomain CurrentDomain => s_domain; public string BaseDirectory => AppContext.BaseDirectory; public string? RelativeSearchPath => null; public AppDomainSetup SetupInformation => new AppDomainSetup(); [Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId = "SYSLIB0003", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public PermissionSet PermissionSet => new PermissionSet(PermissionState.Unrestricted); public string? DynamicDirectory => null; public string FriendlyName { get { Assembly entryAssembly = Assembly.GetEntryAssembly(); if (!(entryAssembly != null)) { return "DefaultDomain"; } return entryAssembly.GetName().Name; } } public int Id => 1; public bool IsFullyTrusted => true; public bool IsHomogenous => true; public static bool MonitoringIsEnabled { get { return true; } set { if (!value) { throw new ArgumentException(SR.Arg_MustBeTrue); } } } public long MonitoringSurvivedMemorySize => MonitoringSurvivedProcessMemorySize; public static long MonitoringSurvivedProcessMemorySize { get { GCMemoryInfo gCMemoryInfo = GC.GetGCMemoryInfo(); return gCMemoryInfo.HeapSizeBytes - gCMemoryInfo.FragmentedBytes; } } public long MonitoringTotalAllocatedMemorySize => GC.GetTotalAllocatedBytes(); public bool ShadowCopyFiles => false; public TimeSpan MonitoringTotalProcessorTime { get { if (!Interop.Kernel32.GetProcessTimes(Interop.Kernel32.GetCurrentProcess(), out var _, out var _, out var _, out var user)) { return TimeSpan.Zero; } return new TimeSpan(user); } } public event UnhandledExceptionEventHandler? UnhandledException { add { AppContext.UnhandledException += value; } remove { AppContext.UnhandledException -= value; } } public event EventHandler? DomainUnload; public event EventHandler? FirstChanceException { add { AppContext.FirstChanceException += value; } remove { AppContext.FirstChanceException -= value; } } public event EventHandler? ProcessExit { add { AppContext.ProcessExit += value; } remove { AppContext.ProcessExit -= value; } } public event AssemblyLoadEventHandler? AssemblyLoad { add { AssemblyLoadContext.AssemblyLoad += value; } remove { AssemblyLoadContext.AssemblyLoad -= value; } } public event ResolveEventHandler? AssemblyResolve { add { AssemblyLoadContext.AssemblyResolve += value; } remove { AssemblyLoadContext.AssemblyResolve -= value; } } public event ResolveEventHandler? ReflectionOnlyAssemblyResolve; public event ResolveEventHandler? TypeResolve { add { AssemblyLoadContext.TypeResolve += value; } remove { AssemblyLoadContext.TypeResolve -= value; } } public event ResolveEventHandler? ResourceResolve { add { AssemblyLoadContext.ResourceResolve += value; } remove { AssemblyLoadContext.ResourceResolve -= value; } } private AppDomain() { } [Obsolete("AppDomain.SetDynamicBase has been deprecated and is not supported.")] public void SetDynamicBase(string? path) { } public string ApplyPolicy(string assemblyName) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } if (assemblyName.Length == 0 || assemblyName[0] == '\0') { throw new ArgumentException(SR.Argument_StringZeroLength, "assemblyName"); } return assemblyName; } [Obsolete("Creating and unloading AppDomains is not supported and throws an exception.", DiagnosticId = "SYSLIB0024", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public static AppDomain CreateDomain(string friendlyName) { if (friendlyName == null) { throw new ArgumentNullException("friendlyName"); } throw new PlatformNotSupportedException(SR.PlatformNotSupported_AppDomains); } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public int ExecuteAssembly(string assemblyFile) { return ExecuteAssembly(assemblyFile, null); } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public int ExecuteAssembly(string assemblyFile, string?[]? args) { if (assemblyFile == null) { throw new ArgumentNullException("assemblyFile"); } string fullPath = Path.GetFullPath(assemblyFile); Assembly assembly = Assembly.LoadFile(fullPath); return ExecuteAssembly(assembly, args); } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] [Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId = "SYSLIB0003", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public int ExecuteAssembly(string assemblyFile, string?[]? args, byte[]? hashValue, AssemblyHashAlgorithm hashAlgorithm) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); } private static int ExecuteAssembly(Assembly assembly, string[] args) { MethodInfo entryPoint = assembly.EntryPoint; if (entryPoint == null) { throw new MissingMethodException(SR.Arg_EntryPointNotFoundException); } object obj = entryPoint.Invoke(null, BindingFlags.DoNotWrapExceptions, null, (entryPoint.GetParameters().Length == 0) ? null : new object[1] { args }, null); if (obj == null) { return 0; } return (int)obj; } public int ExecuteAssemblyByName(AssemblyName assemblyName, params string?[]? args) { return ExecuteAssembly(Assembly.Load(assemblyName), args); } public int ExecuteAssemblyByName(string assemblyName) { return ExecuteAssemblyByName(assemblyName, (string?[]?)null); } public int ExecuteAssemblyByName(string assemblyName, params string?[]? args) { return ExecuteAssembly(Assembly.Load(assemblyName), args); } public object? GetData(string name) { return AppContext.GetData(name); } public void SetData(string name, object? data) { AppContext.SetData(name, data); } public bool? IsCompatibilitySwitchSet(string value) { if (!AppContext.TryGetSwitch(value, out var isEnabled)) { return null; } return isEnabled; } public bool IsDefaultAppDomain() { return true; } public bool IsFinalizingForUnload() { return false; } public override string ToString() { return SR.AppDomain_Name + FriendlyName + "\r\n" + SR.AppDomain_NoContextPolicies; } [Obsolete("Creating and unloading AppDomains is not supported and throws an exception.", DiagnosticId = "SYSLIB0024", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public static void Unload(AppDomain domain) { if (domain == null) { throw new ArgumentNullException("domain"); } throw new CannotUnloadAppDomainException(SR.Arg_PlatformNotSupported); } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public Assembly Load(byte[] rawAssembly) { return Assembly.Load(rawAssembly); } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public Assembly Load(byte[] rawAssembly, byte[]? rawSymbolStore) { return Assembly.Load(rawAssembly, rawSymbolStore); } public Assembly Load(AssemblyName assemblyRef) { return Assembly.Load(assemblyRef); } public Assembly Load(string assemblyString) { return Assembly.Load(assemblyString); } public Assembly[] ReflectionOnlyGetAssemblies() { return Array.Empty(); } [Obsolete("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread instead.")] public static int GetCurrentThreadId() { return Environment.CurrentManagedThreadId; } [Obsolete("AppDomain.AppendPrivatePath has been deprecated and is not supported.")] public void AppendPrivatePath(string? path) { } [Obsolete("AppDomain.ClearPrivatePath has been deprecated and is not supported.")] public void ClearPrivatePath() { } [Obsolete("AppDomain.ClearShadowCopyPath has been deprecated and is not supported.")] public void ClearShadowCopyPath() { } [Obsolete("AppDomain.SetCachePath has been deprecated and is not supported.")] public void SetCachePath(string? path) { } [Obsolete("AppDomain.SetShadowCopyFiles has been deprecated and is not supported.")] public void SetShadowCopyFiles() { } [Obsolete("AppDomain.SetShadowCopyPath has been deprecated and is not supported.")] public void SetShadowCopyPath(string? path) { } public Assembly[] GetAssemblies() { return AssemblyLoadContext.GetLoadedAssemblies(); } public void SetPrincipalPolicy(PrincipalPolicy policy) { _principalPolicy = policy; } public void SetThreadPrincipal(IPrincipal principal) { if (principal == null) { throw new ArgumentNullException("principal"); } if (Interlocked.CompareExchange(ref _defaultPrincipal, principal, null) != null) { throw new SystemException(SR.AppDomain_Policy_PrincipalTwice); } } [RequiresUnreferencedCode("Type and its constructor could be removed")] public ObjectHandle? CreateInstance(string assemblyName, string typeName) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } return Activator.CreateInstance(assemblyName, typeName); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public ObjectHandle? CreateInstance(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture, object?[]? activationAttributes) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } return Activator.CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public ObjectHandle? CreateInstance(string assemblyName, string typeName, object?[]? activationAttributes) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } return Activator.CreateInstance(assemblyName, typeName, activationAttributes); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public object? CreateInstanceAndUnwrap(string assemblyName, string typeName) { return CreateInstance(assemblyName, typeName)?.Unwrap(); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public object? CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture, object?[]? activationAttributes) { return CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes)?.Unwrap(); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public object? CreateInstanceAndUnwrap(string assemblyName, string typeName, object?[]? activationAttributes) { return CreateInstance(assemblyName, typeName, activationAttributes)?.Unwrap(); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName) { return Activator.CreateInstanceFrom(assemblyFile, typeName); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture, object?[]? activationAttributes) { return Activator.CreateInstanceFrom(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public ObjectHandle? CreateInstanceFrom(string assemblyFile, string typeName, object?[]? activationAttributes) { return Activator.CreateInstanceFrom(assemblyFile, typeName, activationAttributes); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public object? CreateInstanceFromAndUnwrap(string assemblyFile, string typeName) { return CreateInstanceFrom(assemblyFile, typeName)?.Unwrap(); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public object? CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object?[]? args, CultureInfo? culture, object?[]? activationAttributes) { return CreateInstanceFrom(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes)?.Unwrap(); } [RequiresUnreferencedCode("Type and its constructor could be removed")] public object? CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, object?[]? activationAttributes) { return CreateInstanceFrom(assemblyFile, typeName, activationAttributes)?.Unwrap(); } internal IPrincipal GetThreadPrincipal() { IPrincipal principal = _defaultPrincipal; if (principal == null) { switch (_principalPolicy) { case PrincipalPolicy.UnauthenticatedPrincipal: if (s_getUnauthenticatedPrincipal == null) { Type type2 = Type.GetType("System.Security.Principal.GenericPrincipal, System.Security.Claims", throwOnError: true); MethodInfo method2 = type2.GetMethod("GetDefaultInstance", BindingFlags.Static | BindingFlags.NonPublic); Volatile.Write(ref s_getUnauthenticatedPrincipal, method2.CreateDelegate>()); } principal = s_getUnauthenticatedPrincipal(); break; case PrincipalPolicy.WindowsPrincipal: if (s_getWindowsPrincipal == null) { Type type = Type.GetType("System.Security.Principal.WindowsPrincipal, System.Security.Principal.Windows", throwOnError: true); MethodInfo method = type.GetMethod("GetDefaultInstance", BindingFlags.Static | BindingFlags.NonPublic); if (method == null) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Principal); } Volatile.Write(ref s_getWindowsPrincipal, method.CreateDelegate>()); } principal = s_getWindowsPrincipal(); break; } } return principal; } } public sealed class AppDomainSetup { public string? ApplicationBase => AppContext.BaseDirectory; public string? TargetFrameworkName => AppContext.TargetFrameworkName; internal AppDomainSetup() { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class AppDomainUnloadedException : SystemException { public AppDomainUnloadedException() : base(SR.Arg_AppDomainUnloadedException) { base.HResult = -2146234348; } public AppDomainUnloadedException(string? message) : base(message) { base.HResult = -2146234348; } public AppDomainUnloadedException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146234348; } protected AppDomainUnloadedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ApplicationException : Exception { public ApplicationException() : base(SR.Arg_ApplicationException) { base.HResult = -2146232832; } public ApplicationException(string? message) : base(message) { base.HResult = -2146232832; } public ApplicationException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146232832; } protected ApplicationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public sealed class ApplicationId { private readonly byte[] _publicKeyToken; public string? Culture { get; } public string Name { get; } public string? ProcessorArchitecture { get; } public Version Version { get; } public byte[] PublicKeyToken => (byte[])_publicKeyToken.Clone(); public ApplicationId(byte[] publicKeyToken, string name, Version version, string? processorArchitecture, string? culture) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyApplicationName); } if (version == null) { throw new ArgumentNullException("version"); } if (publicKeyToken == null) { throw new ArgumentNullException("publicKeyToken"); } _publicKeyToken = (byte[])publicKeyToken.Clone(); Name = name; Version = version; ProcessorArchitecture = processorArchitecture; Culture = culture; } public ApplicationId Copy() { return new ApplicationId(_publicKeyToken, Name, Version, ProcessorArchitecture, Culture); } public override string ToString() { Span initialBuffer = stackalloc char[128]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); valueStringBuilder.Append(Name); if (Culture != null) { valueStringBuilder.Append(", culture=\""); valueStringBuilder.Append(Culture); valueStringBuilder.Append('"'); } valueStringBuilder.Append(", version=\""); valueStringBuilder.Append(Version.ToString()); valueStringBuilder.Append('"'); if (_publicKeyToken != null) { valueStringBuilder.Append(", publicKeyToken=\""); HexConverter.EncodeToUtf16(_publicKeyToken, valueStringBuilder.AppendSpan(2 * _publicKeyToken.Length)); valueStringBuilder.Append('"'); } if (ProcessorArchitecture != null) { valueStringBuilder.Append(", processorArchitecture =\""); valueStringBuilder.Append(ProcessorArchitecture); valueStringBuilder.Append('"'); } return valueStringBuilder.ToString(); } public override bool Equals([NotNullWhen(true)] object? o) { if (!(o is ApplicationId applicationId)) { return false; } if (!object.Equals(Name, applicationId.Name) || !object.Equals(Version, applicationId.Version) || !object.Equals(ProcessorArchitecture, applicationId.ProcessorArchitecture) || !object.Equals(Culture, applicationId.Culture)) { return false; } if (_publicKeyToken.Length != applicationId._publicKeyToken.Length) { return false; } for (int i = 0; i < _publicKeyToken.Length; i++) { if (_publicKeyToken[i] != applicationId._publicKeyToken[i]) { return false; } } return true; } public override int GetHashCode() { return Name.GetHashCode() ^ Version.GetHashCode(); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ArgumentException : SystemException { private readonly string _paramName; public override string Message { get { SetMessageField(); string text = base.Message; if (!string.IsNullOrEmpty(_paramName)) { text = text + " " + SR.Format(SR.Arg_ParamName_Name, _paramName); } return text; } } public virtual string? ParamName => _paramName; public ArgumentException() : base(SR.Arg_ArgumentException) { base.HResult = -2147024809; } public ArgumentException(string? message) : base(message) { base.HResult = -2147024809; } public ArgumentException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2147024809; } public ArgumentException(string? message, string? paramName, Exception? innerException) : base(message, innerException) { _paramName = paramName; base.HResult = -2147024809; } public ArgumentException(string? message, string? paramName) : base(message) { _paramName = paramName; base.HResult = -2147024809; } protected ArgumentException(SerializationInfo info, StreamingContext context) : base(info, context) { _paramName = info.GetString("ParamName"); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("ParamName", _paramName, typeof(string)); } private void SetMessageField() { if (_message == null && base.HResult == -2147024809) { _message = SR.Arg_ArgumentException; } } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ArgumentNullException : ArgumentException { public ArgumentNullException() : base(SR.ArgumentNull_Generic) { base.HResult = -2147467261; } public ArgumentNullException(string? paramName) : base(SR.ArgumentNull_Generic, paramName) { base.HResult = -2147467261; } public ArgumentNullException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2147467261; } public ArgumentNullException(string? paramName, string? message) : base(message, paramName) { base.HResult = -2147467261; } protected ArgumentNullException(SerializationInfo info, StreamingContext context) : base(info, context) { } public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null) { if (argument == null) { Throw(paramName); } } [DoesNotReturn] private static void Throw(string paramName) { throw new ArgumentNullException(paramName); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ArgumentOutOfRangeException : ArgumentException { private readonly object _actualValue; public override string Message { get { string message = base.Message; if (_actualValue != null) { string text = SR.Format(SR.ArgumentOutOfRange_ActualValue, _actualValue); if (message == null) { return text; } return message + "\r\n" + text; } return message; } } public virtual object? ActualValue => _actualValue; public ArgumentOutOfRangeException() : base(SR.Arg_ArgumentOutOfRangeException) { base.HResult = -2146233086; } public ArgumentOutOfRangeException(string? paramName) : base(SR.Arg_ArgumentOutOfRangeException, paramName) { base.HResult = -2146233086; } public ArgumentOutOfRangeException(string? paramName, string? message) : base(message, paramName) { base.HResult = -2146233086; } public ArgumentOutOfRangeException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233086; } public ArgumentOutOfRangeException(string? paramName, object? actualValue, string? message) : base(message, paramName) { _actualValue = actualValue; base.HResult = -2146233086; } protected ArgumentOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) { _actualValue = info.GetValue("ActualValue", typeof(object)); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("ActualValue", _actualValue, typeof(object)); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ArithmeticException : SystemException { public ArithmeticException() : base(SR.Arg_ArithmeticException) { base.HResult = -2147024362; } public ArithmeticException(string? message) : base(message) { base.HResult = -2147024362; } public ArithmeticException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2147024362; } protected ArithmeticException(SerializationInfo info, StreamingContext context) : base(info, context) { } } internal sealed class ArrayEnumerator : System.Collections.IEnumerator, ICloneable { private readonly Array _array; private nint _index; public object Current { get { nint index = _index; Array array = _array; if ((nuint)index >= array.NativeLength) { if (index < 0) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); } else { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); } } return array.InternalGetValue(index); } } internal ArrayEnumerator(Array array) { _array = array; _index = -1; } public object Clone() { return MemberwiseClone(); } public bool MoveNext() { nint num = _index + 1; if ((nuint)num >= _array.NativeLength) { _index = (nint)_array.NativeLength; return false; } _index = num; return true; } public void Reset() { _index = -1; } } internal sealed class SZGenericArrayEnumerator : IEnumerator, IDisposable, System.Collections.IEnumerator { private readonly T[] _array; private int _index; internal static readonly SZGenericArrayEnumerator Empty = new SZGenericArrayEnumerator(new T[0]); public T Current { get { int index = _index; T[] array = _array; if ((uint)index >= (uint)array.Length) { ThrowHelper.ThrowInvalidOperationException_EnumCurrent(index); } return array[index]; } } object System.Collections.IEnumerator.Current => Current; internal SZGenericArrayEnumerator(T[] array) { _array = array; _index = -1; } public bool MoveNext() { int num = _index + 1; if ((uint)num >= (uint)_array.Length) { _index = _array.Length; return false; } _index = num; return true; } void System.Collections.IEnumerator.Reset() { _index = -1; } public void Dispose() { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct ArraySegment : IList, ICollection, IEnumerable, System.Collections.IEnumerable, IReadOnlyList, IReadOnlyCollection { public struct Enumerator : IEnumerator, IDisposable, System.Collections.IEnumerator { private readonly T[] _array; private readonly int _start; private readonly int _end; private int _current; public T Current { get { if (_current < _start) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted(); } if (_current >= _end) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded(); } return _array[_current]; } } object? System.Collections.IEnumerator.Current => Current; internal Enumerator(ArraySegment arraySegment) { _array = arraySegment.Array; _start = arraySegment.Offset; _end = arraySegment.Offset + arraySegment.Count; _current = arraySegment.Offset - 1; } public bool MoveNext() { if (_current < _end) { _current++; return _current < _end; } return false; } void System.Collections.IEnumerator.Reset() { _current = _start - 1; } public void Dispose() { } } private readonly T[] _array; private readonly int _offset; private readonly int _count; public static ArraySegment Empty { get; } = new ArraySegment(new T[0]); public T[]? Array => _array; public int Offset => _offset; public int Count => _count; public T this[int index] { get { if ((uint)index >= (uint)_count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return _array[_offset + index]; } set { if ((uint)index >= (uint)_count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } _array[_offset + index] = value; } } T IList.this[int index] { get { ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return _array[_offset + index]; } set { ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } _array[_offset + index] = value; } } T IReadOnlyList.this[int index] { get { ThrowInvalidOperationIfDefault(); if (index < 0 || index >= _count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return _array[_offset + index]; } } bool ICollection.IsReadOnly => true; public ArraySegment(T[] array) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } _array = array; _offset = 0; _count = array.Length; } public ArraySegment(T[] array, int offset, int count) { if (array == null || (uint)offset > (uint)array.Length || (uint)count > (uint)(array.Length - offset)) { ThrowHelper.ThrowArraySegmentCtorValidationFailedExceptions(array, offset, count); } _array = array; _offset = offset; _count = count; } public Enumerator GetEnumerator() { ThrowInvalidOperationIfDefault(); return new Enumerator(this); } public override int GetHashCode() { if (_array != null) { return HashCode.Combine(_offset, _count, _array.GetHashCode()); } return 0; } public void CopyTo(T[] destination) { CopyTo(destination, 0); } public void CopyTo(T[] destination, int destinationIndex) { ThrowInvalidOperationIfDefault(); System.Array.Copy(_array, _offset, destination, destinationIndex, _count); } public void CopyTo(ArraySegment destination) { ThrowInvalidOperationIfDefault(); destination.ThrowInvalidOperationIfDefault(); if (_count > destination._count) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } System.Array.Copy(_array, _offset, destination._array, destination._offset, _count); } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ArraySegment) { return Equals((ArraySegment)obj); } return false; } public bool Equals(ArraySegment obj) { if (obj._array == _array && obj._offset == _offset) { return obj._count == _count; } return false; } public ArraySegment Slice(int index) { ThrowInvalidOperationIfDefault(); if ((uint)index > (uint)_count) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return new ArraySegment(_array, _offset + index, _count - index); } public ArraySegment Slice(int index, int count) { ThrowInvalidOperationIfDefault(); if ((uint)index > (uint)_count || (uint)count > (uint)(_count - index)) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return new ArraySegment(_array, _offset + index, count); } public T[] ToArray() { ThrowInvalidOperationIfDefault(); if (_count == 0) { return Empty._array; } T[] array = new T[_count]; System.Array.Copy(_array, _offset, array, 0, _count); return array; } public static bool operator ==(ArraySegment a, ArraySegment b) { return a.Equals(b); } public static bool operator !=(ArraySegment a, ArraySegment b) { return !(a == b); } public static implicit operator ArraySegment(T[] array) { if (array == null) { return default(ArraySegment); } return new ArraySegment(array); } int IList.IndexOf(T item) { ThrowInvalidOperationIfDefault(); int num = System.Array.IndexOf(_array, item, _offset, _count); if (num < 0) { return -1; } return num - _offset; } void IList.Insert(int index, T item) { ThrowHelper.ThrowNotSupportedException(); } void IList.RemoveAt(int index) { ThrowHelper.ThrowNotSupportedException(); } void ICollection.Add(T item) { ThrowHelper.ThrowNotSupportedException(); } void ICollection.Clear() { ThrowHelper.ThrowNotSupportedException(); } bool ICollection.Contains(T item) { ThrowInvalidOperationIfDefault(); int num = System.Array.IndexOf(_array, item, _offset, _count); return num >= 0; } bool ICollection.Remove(T item) { ThrowHelper.ThrowNotSupportedException(); return false; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } private void ThrowInvalidOperationIfDefault() { if (_array == null) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NullArray); } } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ArrayTypeMismatchException : SystemException { public ArrayTypeMismatchException() : base(SR.Arg_ArrayTypeMismatchException) { base.HResult = -2146233085; } public ArrayTypeMismatchException(string? message) : base(message) { base.HResult = -2146233085; } public ArrayTypeMismatchException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233085; } protected ArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class AssemblyLoadEventArgs : EventArgs { public Assembly LoadedAssembly { get; } public AssemblyLoadEventArgs(Assembly loadedAssembly) { LoadedAssembly = loadedAssembly; } } public delegate void AssemblyLoadEventHandler(object? sender, AssemblyLoadEventArgs args); public delegate void AsyncCallback(IAsyncResult ar); [Flags] public enum AttributeTargets { Assembly = 1, Module = 2, Class = 4, Struct = 8, Enum = 0x10, Constructor = 0x20, Method = 0x40, Property = 0x80, Field = 0x100, Event = 0x200, Interface = 0x400, Parameter = 0x800, Delegate = 0x1000, ReturnValue = 0x2000, GenericParameter = 0x4000, All = 0x7FFF } [AttributeUsage(AttributeTargets.Class, Inherited = true)] public sealed class AttributeUsageAttribute : Attribute { private readonly AttributeTargets _attributeTarget; private bool _allowMultiple; private bool _inherited; internal static readonly AttributeUsageAttribute Default = new AttributeUsageAttribute(AttributeTargets.All); public AttributeTargets ValidOn => _attributeTarget; public bool AllowMultiple { get { return _allowMultiple; } set { _allowMultiple = value; } } public bool Inherited { get { return _inherited; } set { _inherited = value; } } public AttributeUsageAttribute(AttributeTargets validOn) { _attributeTarget = validOn; _inherited = true; } internal AttributeUsageAttribute(AttributeTargets validOn, bool allowMultiple, bool inherited) { _attributeTarget = validOn; _allowMultiple = allowMultiple; _inherited = inherited; } } public static class BitConverter { [Intrinsic] public static readonly bool IsLittleEndian = true; public static byte[] GetBytes(bool value) { return new byte[1] { (byte)(value ? 1 : 0) }; } public static bool TryWriteBytes(Span destination, bool value) { if (destination.Length < 1) { return false; } Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), (byte)(value ? 1 : 0)); return true; } public static byte[] GetBytes(char value) { byte[] array = new byte[2]; Unsafe.As(ref array[0]) = value; return array; } public static bool TryWriteBytes(Span destination, char value) { if (destination.Length < 2) { return false; } Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value); return true; } public static byte[] GetBytes(short value) { byte[] array = new byte[2]; Unsafe.As(ref array[0]) = value; return array; } public static bool TryWriteBytes(Span destination, short value) { if (destination.Length < 2) { return false; } Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value); return true; } public static byte[] GetBytes(int value) { byte[] array = new byte[4]; Unsafe.As(ref array[0]) = value; return array; } public static bool TryWriteBytes(Span destination, int value) { if (destination.Length < 4) { return false; } Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value); return true; } public static byte[] GetBytes(long value) { byte[] array = new byte[8]; Unsafe.As(ref array[0]) = value; return array; } public static bool TryWriteBytes(Span destination, long value) { if (destination.Length < 8) { return false; } Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value); return true; } [CLSCompliant(false)] public static byte[] GetBytes(ushort value) { byte[] array = new byte[2]; Unsafe.As(ref array[0]) = value; return array; } [CLSCompliant(false)] public static bool TryWriteBytes(Span destination, ushort value) { if (destination.Length < 2) { return false; } Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value); return true; } [CLSCompliant(false)] public static byte[] GetBytes(uint value) { byte[] array = new byte[4]; Unsafe.As(ref array[0]) = value; return array; } [CLSCompliant(false)] public static bool TryWriteBytes(Span destination, uint value) { if (destination.Length < 4) { return false; } Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value); return true; } [CLSCompliant(false)] public static byte[] GetBytes(ulong value) { byte[] array = new byte[8]; Unsafe.As(ref array[0]) = value; return array; } [CLSCompliant(false)] public static bool TryWriteBytes(Span destination, ulong value) { if (destination.Length < 8) { return false; } Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value); return true; } public unsafe static byte[] GetBytes(Half value) { byte[] array = new byte[sizeof(Half)]; Unsafe.As(ref array[0]) = value; return array; } public unsafe static bool TryWriteBytes(Span destination, Half value) { if (destination.Length < sizeof(Half)) { return false; } Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value); return true; } public static byte[] GetBytes(float value) { byte[] array = new byte[4]; Unsafe.As(ref array[0]) = value; return array; } public static bool TryWriteBytes(Span destination, float value) { if (destination.Length < 4) { return false; } Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value); return true; } public static byte[] GetBytes(double value) { byte[] array = new byte[8]; Unsafe.As(ref array[0]) = value; return array; } public static bool TryWriteBytes(Span destination, double value) { if (destination.Length < 8) { return false; } Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), value); return true; } public static char ToChar(byte[] value, int startIndex) { return (char)ToInt16(value, startIndex); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char ToChar(ReadOnlySpan value) { if (value.Length < 2) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } return Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(value)); } public static short ToInt16(byte[] value, int startIndex) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint)startIndex >= (uint)value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if (startIndex > value.Length - 2) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); } return Unsafe.ReadUnaligned(ref value[startIndex]); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short ToInt16(ReadOnlySpan value) { if (value.Length < 2) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } return Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(value)); } public static int ToInt32(byte[] value, int startIndex) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint)startIndex >= (uint)value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if (startIndex > value.Length - 4) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); } return Unsafe.ReadUnaligned(ref value[startIndex]); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ToInt32(ReadOnlySpan value) { if (value.Length < 4) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } return Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(value)); } public static long ToInt64(byte[] value, int startIndex) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if ((uint)startIndex >= (uint)value.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if (startIndex > value.Length - 8) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); } return Unsafe.ReadUnaligned(ref value[startIndex]); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long ToInt64(ReadOnlySpan value) { if (value.Length < 8) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } return Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(value)); } [CLSCompliant(false)] public static ushort ToUInt16(byte[] value, int startIndex) { return (ushort)ToInt16(value, startIndex); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ushort ToUInt16(ReadOnlySpan value) { if (value.Length < 2) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } return Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(value)); } [CLSCompliant(false)] public static uint ToUInt32(byte[] value, int startIndex) { return (uint)ToInt32(value, startIndex); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint ToUInt32(ReadOnlySpan value) { if (value.Length < 4) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } return Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(value)); } [CLSCompliant(false)] public static ulong ToUInt64(byte[] value, int startIndex) { return (ulong)ToInt64(value, startIndex); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong ToUInt64(ReadOnlySpan value) { if (value.Length < 8) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } return Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(value)); } public static Half ToHalf(byte[] value, int startIndex) { return Int16BitsToHalf(ToInt16(value, startIndex)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static Half ToHalf(ReadOnlySpan value) { if (value.Length < sizeof(Half)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } return Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(value)); } public static float ToSingle(byte[] value, int startIndex) { return Int32BitsToSingle(ToInt32(value, startIndex)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float ToSingle(ReadOnlySpan value) { if (value.Length < 4) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } return Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(value)); } public static double ToDouble(byte[] value, int startIndex) { return Int64BitsToDouble(ToInt64(value, startIndex)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double ToDouble(ReadOnlySpan value) { if (value.Length < 8) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } return Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(value)); } public static string ToString(byte[] value, int startIndex, int length) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if (startIndex < 0 || (startIndex >= value.Length && startIndex > 0)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_GenericPositive); } if (startIndex > value.Length - length) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall, ExceptionArgument.value); } if (length == 0) { return string.Empty; } if (length > 715827882) { throw new ArgumentOutOfRangeException("length", SR.Format(SR.ArgumentOutOfRange_LengthTooLarge, 715827882)); } return string.Create(length * 3 - 1, (value, startIndex, length), delegate(Span dst, (byte[] value, int startIndex, int length) state) { ReadOnlySpan readOnlySpan = new ReadOnlySpan(state.value, state.startIndex, state.length); int num = 0; int num2 = 0; byte b = readOnlySpan[num++]; dst[num2++] = HexConverter.ToCharUpper(b >> 4); dst[num2++] = HexConverter.ToCharUpper(b); while (num < readOnlySpan.Length) { b = readOnlySpan[num++]; dst[num2++] = '-'; dst[num2++] = HexConverter.ToCharUpper(b >> 4); dst[num2++] = HexConverter.ToCharUpper(b); } }); } public static string ToString(byte[] value) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } return ToString(value, 0, value.Length); } public static string ToString(byte[] value, int startIndex) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } return ToString(value, startIndex, value.Length - startIndex); } public static bool ToBoolean(byte[] value, int startIndex) { if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if (startIndex < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if (startIndex > value.Length - 1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } return value[startIndex] != 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool ToBoolean(ReadOnlySpan value) { if (value.Length < 1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } return Unsafe.ReadUnaligned(ref MemoryMarshal.GetReference(value)) != 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static long DoubleToInt64Bits(double value) { if (Sse2.X64.IsSupported) { Vector128 value2 = Vector128.CreateScalarUnsafe(value).AsInt64(); return Sse2.X64.ConvertToInt64(value2); } return *(long*)(&value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static double Int64BitsToDouble(long value) { if (Sse2.X64.IsSupported) { Vector128 vector = Vector128.CreateScalarUnsafe(value).AsDouble(); return vector.ToScalar(); } return *(double*)(&value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static int SingleToInt32Bits(float value) { if (Sse2.IsSupported) { Vector128 value2 = Vector128.CreateScalarUnsafe(value).AsInt32(); return Sse2.ConvertToInt32(value2); } return *(int*)(&value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static float Int32BitsToSingle(int value) { if (Sse2.IsSupported) { Vector128 vector = Vector128.CreateScalarUnsafe(value).AsSingle(); return vector.ToScalar(); } return *(float*)(&value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static short HalfToInt16Bits(Half value) { return *(short*)(&value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static Half Int16BitsToHalf(short value) { return *(Half*)(&value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong DoubleToUInt64Bits(double value) { return (ulong)DoubleToInt64Bits(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static double UInt64BitsToDouble(ulong value) { return Int64BitsToDouble((long)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint SingleToUInt32Bits(float value) { return (uint)SingleToInt32Bits(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static float UInt32BitsToSingle(uint value) { return Int32BitsToSingle((int)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ushort HalfToUInt16Bits(Half value) { return (ushort)HalfToInt16Bits(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Half UInt16BitsToHalf(ushort value) { return Int16BitsToHalf((short)value); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Boolean : IComparable, IConvertible, IComparable, IEquatable { private readonly bool m_value; public static readonly string TrueString = "True"; public static readonly string FalseString = "False"; public override int GetHashCode() { if (!this) { return 0; } return 1; } public override string ToString() { if (!this) { return "False"; } return "True"; } public string ToString(IFormatProvider? provider) { return ToString(); } public bool TryFormat(Span destination, out int charsWritten) { if (this) { if ((uint)destination.Length > 3u) { destination[0] = 'T'; destination[1] = 'r'; destination[2] = 'u'; destination[3] = 'e'; charsWritten = 4; return true; } } else if ((uint)destination.Length > 4u) { destination[0] = 'F'; destination[1] = 'a'; destination[2] = 'l'; destination[3] = 's'; destination[4] = 'e'; charsWritten = 5; return true; } charsWritten = 0; return false; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is bool)) { return false; } return this == (bool)obj; } [NonVersionable] public bool Equals(bool obj) { return this == obj; } public int CompareTo(object? obj) { if (obj == null) { return 1; } if (!(obj is bool)) { throw new ArgumentException(SR.Arg_MustBeBoolean); } if (this == (bool)obj) { return 0; } if (!this) { return -1; } return 1; } public int CompareTo(bool value) { if (this == value) { return 0; } if (!this) { return -1; } return 1; } internal static bool IsTrueStringIgnoreCase(ReadOnlySpan value) { if (value.Length == 4 && (value[0] == 't' || value[0] == 'T') && (value[1] == 'r' || value[1] == 'R') && (value[2] == 'u' || value[2] == 'U')) { if (value[3] != 'e') { return value[3] == 'E'; } return true; } return false; } internal static bool IsFalseStringIgnoreCase(ReadOnlySpan value) { if (value.Length == 5 && (value[0] == 'f' || value[0] == 'F') && (value[1] == 'a' || value[1] == 'A') && (value[2] == 'l' || value[2] == 'L') && (value[3] == 's' || value[3] == 'S')) { if (value[4] != 'e') { return value[4] == 'E'; } return true; } return false; } public static bool Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } return Parse(value.AsSpan()); } public static bool Parse(ReadOnlySpan value) { if (!TryParse(value, out var result)) { throw new FormatException(SR.Format(SR.Format_BadBoolean, new string(value))); } return result; } public static bool TryParse([NotNullWhen(true)] string? value, out bool result) { if (value == null) { result = false; return false; } return TryParse(value.AsSpan(), out result); } public static bool TryParse(ReadOnlySpan value, out bool result) { if (IsTrueStringIgnoreCase(value)) { result = true; return true; } if (IsFalseStringIgnoreCase(value)) { result = false; return true; } value = TrimWhiteSpaceAndNull(value); if (IsTrueStringIgnoreCase(value)) { result = true; return true; } if (IsFalseStringIgnoreCase(value)) { result = false; return true; } result = false; return false; } private static ReadOnlySpan TrimWhiteSpaceAndNull(ReadOnlySpan value) { int i; for (i = 0; i < value.Length && (char.IsWhiteSpace(value[i]) || value[i] == '\0'); i++) { } int num = value.Length - 1; while (num >= i && (char.IsWhiteSpace(value[num]) || value[num] == '\0')) { num--; } return value.Slice(i, num - i + 1); } public TypeCode GetTypeCode() { return TypeCode.Boolean; } bool IConvertible.ToBoolean(IFormatProvider provider) { return this; } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Boolean", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } } [NonVersionable] internal readonly ref struct ByReference { private readonly IntPtr _value; public ref T Value { [Intrinsic] get { throw new PlatformNotSupportedException(); } } [Intrinsic] public ByReference(ref T value) { throw new PlatformNotSupportedException(); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Byte : IComparable, IConvertible, ISpanFormattable, IFormattable, IComparable, IEquatable, IBinaryInteger, IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IShiftOperators, IMinMaxValue, IUnsignedNumber { private readonly byte m_value; public const byte MaxValue = 255; public const byte MinValue = 0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IAdditiveIdentity.AdditiveIdentity => 0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IMinMaxValue.MinValue => 0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IMinMaxValue.MaxValue => byte.MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IMultiplicativeIdentity.MultiplicativeIdentity => 1; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte INumber.One => 1; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte INumber.Zero => 0; public int CompareTo(object? value) { if (value == null) { return 1; } if (!(value is byte)) { throw new ArgumentException(SR.Arg_MustBeByte); } return this - (byte)value; } public int CompareTo(byte value) { return this - value; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is byte)) { return false; } return this == (byte)obj; } [NonVersionable] public bool Equals(byte obj) { return this == obj; } public override int GetHashCode() { return this; } public static byte Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static byte Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, style, NumberFormatInfo.CurrentInfo); } public static byte Parse(string s, IFormatProvider? provider) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static byte Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, style, NumberFormatInfo.GetInstance(provider)); } public static byte Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static byte Parse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info) { uint result; Number.ParsingStatus parsingStatus = Number.TryParseUInt32(s, style, info, out result); if (parsingStatus != 0) { Number.ThrowOverflowOrFormatException(parsingStatus, TypeCode.Byte); } if (result > 255) { Number.ThrowOverflowException(TypeCode.Byte); } return (byte)result; } public static bool TryParse([NotNullWhen(true)] string? s, out byte result) { if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan s, out byte result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out byte result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan)s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out byte result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out byte result) { if (Number.TryParseUInt32(s, style, info, out var result2) != 0 || result2 > 255) { result = 0; return false; } result = (byte)result2; return true; } public override string ToString() { return Number.UInt32ToDecStr(this); } public string ToString(string? format) { return Number.FormatUInt32(this, format, null); } public string ToString(IFormatProvider? provider) { return Number.UInt32ToDecStr(this); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatUInt32(this, format, provider); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return Number.TryFormatUInt32(this, format, provider, destination, out charsWritten); } public TypeCode GetTypeCode() { return TypeCode.Byte; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(this); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(this); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return this; } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Byte", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IAdditionOperators.op_Addition(byte left, byte right) { return (byte)(left + right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IBinaryInteger.LeadingZeroCount(byte value) { return (byte)(BitOperations.LeadingZeroCount(value) - 24); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IBinaryInteger.PopCount(byte value) { return (byte)BitOperations.PopCount(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IBinaryInteger.RotateLeft(byte value, int rotateAmount) { return (byte)((value << (rotateAmount & 7)) | (value >> ((8 - rotateAmount) & 7))); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IBinaryInteger.RotateRight(byte value, int rotateAmount) { return (byte)((value >> (rotateAmount & 7)) | (value << ((8 - rotateAmount) & 7))); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IBinaryInteger.TrailingZeroCount(byte value) { return (byte)(BitOperations.TrailingZeroCount(value << 24) - 24); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IBinaryNumber.IsPow2(byte value) { return BitOperations.IsPow2((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IBinaryNumber.Log2(byte value) { return (byte)BitOperations.Log2(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IBitwiseOperators.op_BitwiseAnd(byte left, byte right) { return (byte)(left & right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IBitwiseOperators.op_BitwiseOr(byte left, byte right) { return (byte)(left | right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IBitwiseOperators.op_ExclusiveOr(byte left, byte right) { return (byte)(left ^ right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IBitwiseOperators.op_OnesComplement(byte value) { return (byte)(~value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(byte left, byte right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(byte left, byte right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(byte left, byte right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(byte left, byte right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IDecrementOperators.op_Decrement(byte value) { return --value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IDivisionOperators.op_Division(byte left, byte right) { return (byte)(left / right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(byte left, byte right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(byte left, byte right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IIncrementOperators.op_Increment(byte value) { return ++value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IModulusOperators.op_Modulus(byte left, byte right) { return (byte)(left % right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IMultiplyOperators.op_Multiply(byte left, byte right) { return (byte)(left * right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte INumber.Abs(byte value) { return value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte INumber.Clamp(byte value, byte min, byte max) { return Math.Clamp(value, min, max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte INumber.Create(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } checked { if (typeof(TOther) == typeof(char)) { return (byte)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (byte)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (byte)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (byte)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (byte)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (byte)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (byte)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (byte)(sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (byte)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (byte)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (byte)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (byte)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (byte)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { char c = (char)(object)value; if (c <= 'ÿ') { return (byte)c; } return byte.MaxValue; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (!(num > 255m)) { if (!(num < 0m)) { return (byte)num; } return 0; } return byte.MaxValue; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (!(num2 > 255.0)) { if (!(num2 < 0.0)) { return (byte)num2; } return 0; } return byte.MaxValue; } if (typeof(TOther) == typeof(short)) { short num3 = (short)(object)value; if (num3 <= 255) { if (num3 >= 0) { return (byte)num3; } return 0; } return byte.MaxValue; } if (typeof(TOther) == typeof(int)) { int num4 = (int)(object)value; if (num4 <= 255) { if (num4 >= 0) { return (byte)num4; } return 0; } return byte.MaxValue; } if (typeof(TOther) == typeof(long)) { long num5 = (long)(object)value; if (num5 <= 255) { if (num5 >= 0) { return (byte)num5; } return 0; } return byte.MaxValue; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr <= 255) { if ((nint)intPtr >= 0) { return (byte)(nint)intPtr; } return 0; } return byte.MaxValue; } if (typeof(TOther) == typeof(sbyte)) { sbyte b = (sbyte)(object)value; if (b >= 0) { return (byte)b; } return 0; } if (typeof(TOther) == typeof(float)) { float num6 = (float)(object)value; if (!(num6 > 255f)) { if (!(num6 < 0f)) { return (byte)num6; } return 0; } return byte.MaxValue; } if (typeof(TOther) == typeof(ushort)) { ushort num7 = (ushort)(object)value; if (num7 <= 255) { return (byte)num7; } return byte.MaxValue; } if (typeof(TOther) == typeof(uint)) { uint num8 = (uint)(object)value; if (num8 <= 255) { return (byte)num8; } return byte.MaxValue; } if (typeof(TOther) == typeof(ulong)) { ulong num9 = (ulong)(object)value; if (num9 <= 255) { return (byte)num9; } return byte.MaxValue; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr <= 255) { return (byte)(nuint)uIntPtr; } return byte.MaxValue; } ThrowHelper.ThrowNotSupportedException(); return 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (byte)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (byte)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (byte)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (byte)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (byte)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (byte)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (byte)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (byte)(sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (byte)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (byte)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (byte)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (byte)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (byte)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (byte Quotient, byte Remainder) INumber.DivRem(byte left, byte right) { return Math.DivRem(left, right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte INumber.Max(byte x, byte y) { return Math.Max(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte INumber.Min(byte x, byte y) { return Math.Min(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte INumber.Sign(byte value) { return (byte)((value != 0) ? 1u : 0u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out byte result) { if (typeof(TOther) == typeof(byte)) { result = (byte)(object)value; return true; } if (typeof(TOther) == typeof(char)) { char c = (char)(object)value; if (c > 'ÿ') { result = 0; return false; } result = (byte)c; return true; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (num < 0m || num > 255m) { result = 0; return false; } result = (byte)num; return true; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (num2 < 0.0 || num2 > 255.0) { result = 0; return false; } result = (byte)num2; return true; } if (typeof(TOther) == typeof(short)) { short num3 = (short)(object)value; if (num3 < 0 || num3 > 255) { result = 0; return false; } result = (byte)num3; return true; } if (typeof(TOther) == typeof(int)) { int num4 = (int)(object)value; if (num4 < 0 || num4 > 255) { result = 0; return false; } result = (byte)num4; return true; } if (typeof(TOther) == typeof(long)) { long num5 = (long)(object)value; if (num5 < 0 || num5 > 255) { result = 0; return false; } result = (byte)num5; return true; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr < 0 || (nint)intPtr > 255) { result = 0; return false; } result = (byte)(nint)intPtr; return true; } if (typeof(TOther) == typeof(sbyte)) { sbyte b = (sbyte)(object)value; if (b < 0) { result = 0; return false; } result = (byte)b; return true; } if (typeof(TOther) == typeof(float)) { float num6 = (float)(object)value; if (num6 < 0f || num6 > 255f) { result = 0; return false; } result = (byte)num6; return true; } if (typeof(TOther) == typeof(ushort)) { ushort num7 = (ushort)(object)value; if (num7 > 255) { result = 0; return false; } result = (byte)num7; return true; } if (typeof(TOther) == typeof(uint)) { uint num8 = (uint)(object)value; if (num8 > 255) { result = 0; return false; } result = (byte)num8; return true; } if (typeof(TOther) == typeof(ulong)) { ulong num9 = (ulong)(object)value; if (num9 > 255) { result = 0; return false; } result = (byte)num9; return true; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr > 255) { result = 0; return false; } result = (byte)(nuint)uIntPtr; return true; } ThrowHelper.ThrowNotSupportedException(); result = 0; return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out byte result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out byte result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out byte result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IShiftOperators.op_LeftShift(byte value, int shiftAmount) { return (byte)(value << shiftAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IShiftOperators.op_RightShift(byte value, int shiftAmount) { return (byte)(value >> shiftAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out byte result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte ISubtractionOperators.op_Subtraction(byte left, byte right) { return (byte)(left - right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IUnaryNegationOperators.op_UnaryNegation(byte value) { return (byte)(-value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static byte IUnaryPlusOperators.op_UnaryPlus(byte value) { return value; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class CannotUnloadAppDomainException : SystemException { public CannotUnloadAppDomainException() : base(SR.Arg_CannotUnloadAppDomainException) { base.HResult = -2146234347; } public CannotUnloadAppDomainException(string? message) : base(message) { base.HResult = -2146234347; } public CannotUnloadAppDomainException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146234347; } protected CannotUnloadAppDomainException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Char : IComparable, IComparable, IEquatable, IConvertible, ISpanFormattable, IFormattable, IBinaryInteger, IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IShiftOperators, IMinMaxValue, IUnsignedNumber { private readonly char m_value; public const char MaxValue = '\uffff'; public const char MinValue = '\0'; private static ReadOnlySpan Latin1CharInfo => new byte[256] { 14, 14, 14, 14, 14, 14, 14, 14, 14, 142, 142, 142, 142, 142, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 139, 24, 24, 24, 26, 24, 24, 24, 20, 21, 24, 25, 24, 19, 24, 24, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 24, 24, 25, 25, 25, 24, 24, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 20, 24, 21, 27, 18, 27, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 20, 25, 21, 25, 14, 14, 14, 14, 14, 14, 142, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 139, 24, 26, 26, 26, 26, 28, 24, 27, 28, 4, 22, 25, 15, 28, 27, 28, 25, 10, 10, 27, 33, 24, 24, 27, 10, 4, 23, 10, 10, 10, 24, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 25, 64, 64, 64, 64, 64, 64, 64, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 25, 33, 33, 33, 33, 33, 33, 33, 33 }; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IAdditiveIdentity.AdditiveIdentity => '\0'; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IMinMaxValue.MinValue => '\0'; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IMinMaxValue.MaxValue => '\uffff'; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IMultiplicativeIdentity.MultiplicativeIdentity => '\u0001'; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char INumber.One => '\u0001'; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char INumber.Zero => '\0'; private static bool IsLatin1(char c) { return (uint)c < (uint)Latin1CharInfo.Length; } public static bool IsAscii(char c) { return (uint)c <= 127u; } private static UnicodeCategory GetLatin1UnicodeCategory(char c) { return (UnicodeCategory)(Latin1CharInfo[c] & 0x1F); } public override int GetHashCode() { return (int)(this | ((uint)this << 16)); } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is char)) { return false; } return this == (char)obj; } [NonVersionable] public bool Equals(char obj) { return this == obj; } public int CompareTo(object? value) { if (value == null) { return 1; } if (!(value is char)) { throw new ArgumentException(SR.Arg_MustBeChar); } return this - (char)value; } public int CompareTo(char value) { return this - value; } public override string ToString() { return ToString(this); } public string ToString(IFormatProvider? provider) { return ToString(this); } public static string ToString(char c) { return string.CreateFromChar(c); } bool ISpanFormattable.TryFormat(Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider provider) { if (!destination.IsEmpty) { destination[0] = this; charsWritten = 1; return true; } charsWritten = 0; return false; } string IFormattable.ToString(string format, IFormatProvider formatProvider) { return ToString(this); } public static char Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if (s.Length != 1) { throw new FormatException(SR.Format_NeedSingleChar); } return s[0]; } public static bool TryParse([NotNullWhen(true)] string? s, out char result) { result = '\0'; if (s == null) { return false; } if (s.Length != 1) { return false; } result = s[0]; return true; } public static bool IsDigit(char c) { if (IsLatin1(c)) { return IsInRange(c, '0', '9'); } return CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber; } internal static bool IsInRange(char c, char min, char max) { return (uint)(c - min) <= (uint)(max - min); } private static bool IsInRange(UnicodeCategory c, UnicodeCategory min, UnicodeCategory max) { return (uint)(c - min) <= (uint)(max - min); } internal static bool CheckLetter(UnicodeCategory uc) { return IsInRange(uc, UnicodeCategory.UppercaseLetter, UnicodeCategory.OtherLetter); } public static bool IsLetter(char c) { if (IsAscii(c)) { return (Latin1CharInfo[c] & 0x60) != 0; } return CheckLetter(CharUnicodeInfo.GetUnicodeCategory(c)); } private static bool IsWhiteSpaceLatin1(char c) { return (Latin1CharInfo[c] & 0x80) != 0; } public static bool IsWhiteSpace(char c) { if (IsLatin1(c)) { return IsWhiteSpaceLatin1(c); } return CharUnicodeInfo.GetIsWhiteSpace(c); } public static bool IsUpper(char c) { if (IsLatin1(c)) { return (Latin1CharInfo[c] & 0x40) != 0; } return CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter; } public static bool IsLower(char c) { if (IsLatin1(c)) { return (Latin1CharInfo[c] & 0x20) != 0; } return CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter; } internal static bool CheckPunctuation(UnicodeCategory uc) { return IsInRange(uc, UnicodeCategory.ConnectorPunctuation, UnicodeCategory.OtherPunctuation); } public static bool IsPunctuation(char c) { if (IsLatin1(c)) { return CheckPunctuation(GetLatin1UnicodeCategory(c)); } return CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(c)); } internal static bool CheckLetterOrDigit(UnicodeCategory uc) { if (!CheckLetter(uc)) { return uc == UnicodeCategory.DecimalDigitNumber; } return true; } public static bool IsLetterOrDigit(char c) { if (IsLatin1(c)) { return CheckLetterOrDigit(GetLatin1UnicodeCategory(c)); } return CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(c)); } public static char ToUpper(char c, CultureInfo culture) { if (culture == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.culture); } return culture.TextInfo.ToUpper(c); } public static char ToUpper(char c) { return CultureInfo.CurrentCulture.TextInfo.ToUpper(c); } public static char ToUpperInvariant(char c) { return TextInfo.ToUpperInvariant(c); } public static char ToLower(char c, CultureInfo culture) { if (culture == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.culture); } return culture.TextInfo.ToLower(c); } public static char ToLower(char c) { return CultureInfo.CurrentCulture.TextInfo.ToLower(c); } public static char ToLowerInvariant(char c) { return TextInfo.ToLowerInvariant(c); } public TypeCode GetTypeCode() { return TypeCode.Char; } bool IConvertible.ToBoolean(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Boolean")); } char IConvertible.ToChar(IFormatProvider provider) { return this; } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Single")); } double IConvertible.ToDouble(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Double")); } decimal IConvertible.ToDecimal(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "Decimal")); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Char", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } public static bool IsControl(char c) { return (uint)((c + 1) & -129) <= 32u; } public static bool IsControl(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return IsControl(s[index]); } public static bool IsDigit(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } char c = s[index]; if (IsLatin1(c)) { return IsInRange(c, '0', '9'); } return CharUnicodeInfo.GetUnicodeCategoryInternal(s, index) == UnicodeCategory.DecimalDigitNumber; } public static bool IsLetter(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } char c = s[index]; if (IsAscii(c)) { return (Latin1CharInfo[c] & 0x60) != 0; } return CheckLetter(CharUnicodeInfo.GetUnicodeCategoryInternal(s, index)); } public static bool IsLetterOrDigit(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } char c = s[index]; if (IsLatin1(c)) { return CheckLetterOrDigit(GetLatin1UnicodeCategory(c)); } return CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategoryInternal(s, index)); } public static bool IsLower(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } char c = s[index]; if (IsLatin1(c)) { return (Latin1CharInfo[c] & 0x20) != 0; } return CharUnicodeInfo.GetUnicodeCategoryInternal(s, index) == UnicodeCategory.LowercaseLetter; } internal static bool CheckNumber(UnicodeCategory uc) { return IsInRange(uc, UnicodeCategory.DecimalDigitNumber, UnicodeCategory.OtherNumber); } public static bool IsNumber(char c) { if (IsLatin1(c)) { if (IsAscii(c)) { return IsInRange(c, '0', '9'); } return CheckNumber(GetLatin1UnicodeCategory(c)); } return CheckNumber(CharUnicodeInfo.GetUnicodeCategory(c)); } public static bool IsNumber(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } char c = s[index]; if (IsLatin1(c)) { if (IsAscii(c)) { return IsInRange(c, '0', '9'); } return CheckNumber(GetLatin1UnicodeCategory(c)); } return CheckNumber(CharUnicodeInfo.GetUnicodeCategoryInternal(s, index)); } public static bool IsPunctuation(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } char c = s[index]; if (IsLatin1(c)) { return CheckPunctuation(GetLatin1UnicodeCategory(c)); } return CheckPunctuation(CharUnicodeInfo.GetUnicodeCategoryInternal(s, index)); } internal static bool CheckSeparator(UnicodeCategory uc) { return IsInRange(uc, UnicodeCategory.SpaceSeparator, UnicodeCategory.ParagraphSeparator); } private static bool IsSeparatorLatin1(char c) { if (c != ' ') { return c == '\u00a0'; } return true; } public static bool IsSeparator(char c) { if (IsLatin1(c)) { return IsSeparatorLatin1(c); } return CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(c)); } public static bool IsSeparator(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } char c = s[index]; if (IsLatin1(c)) { return IsSeparatorLatin1(c); } return CheckSeparator(CharUnicodeInfo.GetUnicodeCategoryInternal(s, index)); } public static bool IsSurrogate(char c) { return IsInRange(c, '\ud800', '\udfff'); } public static bool IsSurrogate(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return IsSurrogate(s[index]); } internal static bool CheckSymbol(UnicodeCategory uc) { return IsInRange(uc, UnicodeCategory.MathSymbol, UnicodeCategory.OtherSymbol); } public static bool IsSymbol(char c) { if (IsLatin1(c)) { return CheckSymbol(GetLatin1UnicodeCategory(c)); } return CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(c)); } public static bool IsSymbol(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } char c = s[index]; if (IsLatin1(c)) { return CheckSymbol(GetLatin1UnicodeCategory(c)); } return CheckSymbol(CharUnicodeInfo.GetUnicodeCategoryInternal(s, index)); } public static bool IsUpper(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } char c = s[index]; if (IsLatin1(c)) { return (Latin1CharInfo[c] & 0x40) != 0; } return CharUnicodeInfo.GetUnicodeCategoryInternal(s, index) == UnicodeCategory.UppercaseLetter; } public static bool IsWhiteSpace(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return IsWhiteSpace(s[index]); } public static UnicodeCategory GetUnicodeCategory(char c) { if (IsLatin1(c)) { return GetLatin1UnicodeCategory(c); } return CharUnicodeInfo.GetUnicodeCategory((int)c); } public static UnicodeCategory GetUnicodeCategory(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } if (IsLatin1(s[index])) { return GetLatin1UnicodeCategory(s[index]); } return CharUnicodeInfo.GetUnicodeCategoryInternal(s, index); } public static double GetNumericValue(char c) { return CharUnicodeInfo.GetNumericValue(c); } public static double GetNumericValue(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return CharUnicodeInfo.GetNumericValueInternal(s, index); } public static bool IsHighSurrogate(char c) { return IsInRange(c, '\ud800', '\udbff'); } public static bool IsHighSurrogate(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return IsHighSurrogate(s[index]); } public static bool IsLowSurrogate(char c) { return IsInRange(c, '\udc00', '\udfff'); } public static bool IsLowSurrogate(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return IsLowSurrogate(s[index]); } public static bool IsSurrogatePair(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } if (index + 1 < s.Length) { return IsSurrogatePair(s[index], s[index + 1]); } return false; } public static bool IsSurrogatePair(char highSurrogate, char lowSurrogate) { uint num = (uint)(highSurrogate - 55296); uint num2 = (uint)(lowSurrogate - 56320); return (num | num2) <= 1023; } public static string ConvertFromUtf32(int utf32) { if (!UnicodeUtility.IsValidUnicodeScalar((uint)utf32)) { throw new ArgumentOutOfRangeException("utf32", SR.ArgumentOutOfRange_InvalidUTF32); } return Rune.UnsafeCreate((uint)utf32).ToString(); } public static int ConvertToUtf32(char highSurrogate, char lowSurrogate) { uint num = (uint)(highSurrogate - 55296); uint num2 = (uint)(lowSurrogate - 56320); if ((num | num2) > 1023) { ConvertToUtf32_ThrowInvalidArgs(num); } return (int)(num << 10) + (lowSurrogate - 56320) + 65536; } [StackTraceHidden] private static void ConvertToUtf32_ThrowInvalidArgs(uint highSurrogateOffset) { if (highSurrogateOffset > 1023) { throw new ArgumentOutOfRangeException("highSurrogate", SR.ArgumentOutOfRange_InvalidHighSurrogate); } throw new ArgumentOutOfRangeException("lowSurrogate", SR.ArgumentOutOfRange_InvalidLowSurrogate); } public static int ConvertToUtf32(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if (index < 0 || index >= s.Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } int num = s[index] - 55296; if (num >= 0 && num <= 2047) { if (num <= 1023) { if (index < s.Length - 1) { int num2 = s[index + 1] - 56320; if (num2 >= 0 && num2 <= 1023) { return num * 1024 + num2 + 65536; } throw new ArgumentException(SR.Format(SR.Argument_InvalidHighSurrogate, index), "s"); } throw new ArgumentException(SR.Format(SR.Argument_InvalidHighSurrogate, index), "s"); } throw new ArgumentException(SR.Format(SR.Argument_InvalidLowSurrogate, index), "s"); } return s[index]; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IAdditionOperators.op_Addition(char left, char right) { return (char)(left + right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IBinaryInteger.LeadingZeroCount(char value) { return (char)(BitOperations.LeadingZeroCount(value) - 16); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IBinaryInteger.PopCount(char value) { return (char)BitOperations.PopCount(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IBinaryInteger.RotateLeft(char value, int rotateAmount) { return (char)(((uint)value << (rotateAmount & 0xF)) | (uint)((int)value >> ((16 - rotateAmount) & 0xF))); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IBinaryInteger.RotateRight(char value, int rotateAmount) { return (char)((uint)((int)value >> (rotateAmount & 0xF)) | ((uint)value << ((16 - rotateAmount) & 0xF))); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IBinaryInteger.TrailingZeroCount(char value) { return (char)(BitOperations.TrailingZeroCount((int)((uint)value << 16)) - 16); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IBinaryNumber.IsPow2(char value) { return BitOperations.IsPow2((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IBinaryNumber.Log2(char value) { return (char)BitOperations.Log2(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IBitwiseOperators.op_BitwiseAnd(char left, char right) { return (char)(left & right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IBitwiseOperators.op_BitwiseOr(char left, char right) { return (char)(left | right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IBitwiseOperators.op_ExclusiveOr(char left, char right) { return (char)(left ^ right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IBitwiseOperators.op_OnesComplement(char value) { return (char)(~(uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(char left, char right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(char left, char right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(char left, char right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(char left, char right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IDecrementOperators.op_Decrement(char value) { return value = (char)(value - 1); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IDivisionOperators.op_Division(char left, char right) { return (char)(left / right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(char left, char right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(char left, char right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IIncrementOperators.op_Increment(char value) { return value = (char)(value + 1); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IModulusOperators.op_Modulus(char left, char right) { return (char)(left % right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IMultiplyOperators.op_Multiply(char left, char right) { return (char)(left * right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char INumber.Abs(char value) { return value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char INumber.Clamp(char value, char min, char max) { return (char)Math.Clamp(value, min, max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char INumber.Create(TOther value) { if (typeof(TOther) == typeof(byte)) { return (char)(byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (char)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (char)checked((ushort)(double)(object)value); } if (typeof(TOther) == typeof(short)) { return (char)checked((ushort)(short)(object)value); } if (typeof(TOther) == typeof(int)) { return (char)checked((ushort)(int)(object)value); } if (typeof(TOther) == typeof(long)) { return (char)checked((ushort)(long)(object)value); } if (typeof(TOther) == typeof(IntPtr)) { return (char)checked((ushort)(nint)(IntPtr)(object)value); } if (typeof(TOther) == typeof(sbyte)) { return (char)checked((ushort)(sbyte)(object)value); } if (typeof(TOther) == typeof(float)) { return (char)checked((ushort)(float)(object)value); } if (typeof(TOther) == typeof(ushort)) { return (char)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (char)checked((ushort)(uint)(object)value); } if (typeof(TOther) == typeof(ulong)) { return (char)checked((ushort)(ulong)(object)value); } if (typeof(TOther) == typeof(UIntPtr)) { return (char)checked((ushort)(nuint)(UIntPtr)(object)value); } ThrowHelper.ThrowNotSupportedException(); return '\0'; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (char)(byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (!(num > 65535m)) { if (!(num < 0m)) { return (char)num; } return '\0'; } return '\uffff'; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (!(num2 > 65535.0)) { if (!(num2 < 0.0)) { return (char)num2; } return '\0'; } return '\uffff'; } if (typeof(TOther) == typeof(short)) { short num3 = (short)(object)value; if (num3 >= 0) { return (char)num3; } return '\0'; } if (typeof(TOther) == typeof(int)) { int num4 = (int)(object)value; if (num4 <= 65535) { if (num4 >= 0) { return (char)num4; } return '\0'; } return '\uffff'; } if (typeof(TOther) == typeof(long)) { long num5 = (long)(object)value; if (num5 <= 65535) { if (num5 >= 0) { return (char)num5; } return '\0'; } return '\uffff'; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr <= 65535) { if ((nint)intPtr >= 0) { return (char)(nint)intPtr; } return '\0'; } return '\uffff'; } if (typeof(TOther) == typeof(sbyte)) { sbyte b = (sbyte)(object)value; if (b >= 0) { return (char)b; } return '\0'; } if (typeof(TOther) == typeof(float)) { float num6 = (float)(object)value; if (!(num6 > 65535f)) { if (!(num6 < 0f)) { return (char)num6; } return '\0'; } return '\uffff'; } if (typeof(TOther) == typeof(ushort)) { return (char)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { uint num7 = (uint)(object)value; if (num7 <= 65535) { return (char)num7; } return '\uffff'; } if (typeof(TOther) == typeof(ulong)) { ulong num8 = (ulong)(object)value; if (num8 <= 65535) { return (char)num8; } return '\uffff'; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr <= 65535) { return (char)(nuint)uIntPtr; } return '\uffff'; } ThrowHelper.ThrowNotSupportedException(); return '\0'; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (char)(byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (char)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (char)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (char)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (char)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (char)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (char)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (char)(sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (char)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (char)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (char)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (char)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (char)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return '\0'; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (char Quotient, char Remainder) INumber.DivRem(char left, char right) { (ushort, ushort) tuple = Math.DivRem(left, right); return ((char)tuple.Item1, (char)tuple.Item2); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char INumber.Max(char x, char y) { return (char)Math.Max(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char INumber.Min(char x, char y) { return (char)Math.Min(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { if (s.Length != 1) { throw new FormatException(SR.Format_NeedSingleChar); } return s[0]; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char INumber.Sign(char value) { return (char)((value != 0) ? 1u : 0u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out char result) { if (typeof(TOther) == typeof(byte)) { result = (char)(byte)(object)value; return true; } if (typeof(TOther) == typeof(char)) { result = (char)(object)value; return true; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (num < 0m || num > 65535m) { result = '\0'; return false; } result = (char)num; return true; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (num2 < 0.0 || num2 > 65535.0) { result = '\0'; return false; } result = (char)num2; return true; } if (typeof(TOther) == typeof(short)) { short num3 = (short)(object)value; if (num3 < 0) { result = '\0'; return false; } result = (char)num3; return true; } if (typeof(TOther) == typeof(int)) { int num4 = (int)(object)value; if (num4 < 0 || num4 > 65535) { result = '\0'; return false; } result = (char)num4; return true; } if (typeof(TOther) == typeof(long)) { long num5 = (long)(object)value; if (num5 < 0 || num5 > 65535) { result = '\0'; return false; } result = (char)num5; return true; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr < 0 || (nint)intPtr > 65535) { result = '\0'; return false; } result = (char)(nint)intPtr; return true; } if (typeof(TOther) == typeof(sbyte)) { sbyte b = (sbyte)(object)value; if (b < 0) { result = '\0'; return false; } result = (char)b; return true; } if (typeof(TOther) == typeof(float)) { float num6 = (float)(object)value; if (num6 < 0f || num6 > 65535f) { result = '\0'; return false; } result = (char)num6; return true; } if (typeof(TOther) == typeof(ushort)) { ushort num7 = (ushort)(object)value; if (num7 > ushort.MaxValue) { result = '\0'; return false; } result = (char)num7; return true; } if (typeof(TOther) == typeof(uint)) { uint num8 = (uint)(object)value; if (num8 > 65535) { result = '\0'; return false; } result = (char)num8; return true; } if (typeof(TOther) == typeof(ulong)) { ulong num9 = (ulong)(object)value; if (num9 > 65535) { result = '\0'; return false; } result = (char)num9; return true; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr > 65535) { result = '\0'; return false; } result = (char)(nuint)uIntPtr; return true; } ThrowHelper.ThrowNotSupportedException(); result = '\0'; return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out char result) { return TryParse(s, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out char result) { if (s.Length != 1) { result = '\0'; return false; } result = s[0]; return true; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IParseable.Parse(string s, IFormatProvider provider) { return Parse(s); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out char result) { return TryParse(s, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IShiftOperators.op_LeftShift(char value, int shiftAmount) { return (char)((uint)value << shiftAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IShiftOperators.op_RightShift(char value, int shiftAmount) { return (char)((int)value >> shiftAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { if (s.Length != 1) { throw new FormatException(SR.Format_NeedSingleChar); } return s[0]; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out char result) { if (s.Length != 1) { result = '\0'; return false; } result = s[0]; return true; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char ISubtractionOperators.op_Subtraction(char left, char right) { return (char)(left - right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IUnaryNegationOperators.op_UnaryNegation(char value) { return (char)(0 - value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static char IUnaryPlusOperators.op_UnaryPlus(char value) { return value; } } public sealed class CharEnumerator : System.Collections.IEnumerator, IEnumerator, IDisposable, ICloneable { private string _str; private int _index; private char _currentElement; object? System.Collections.IEnumerator.Current => Current; public char Current { get { if (_index == -1) { throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); } if (_index >= _str.Length) { throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } return _currentElement; } } internal CharEnumerator(string str) { _str = str; _index = -1; } public object Clone() { return MemberwiseClone(); } public bool MoveNext() { if (_index < _str.Length - 1) { _index++; _currentElement = _str[_index]; return true; } _index = _str.Length; return false; } public void Dispose() { if (_str != null) { _index = _str.Length; } _str = null; } public void Reset() { _currentElement = '\0'; _index = -1; } } [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)] public sealed class CLSCompliantAttribute : Attribute { private readonly bool _compliant; public bool IsCompliant => _compliant; public CLSCompliantAttribute(bool isCompliant) { _compliant = isCompliant; } } public abstract class ContextBoundObject : MarshalByRefObject { } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ContextMarshalException : SystemException { public ContextMarshalException() : this(SR.Arg_ContextMarshalException, null) { } public ContextMarshalException(string? message) : this(message, null) { } public ContextMarshalException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233084; } protected ContextMarshalException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [AttributeUsage(AttributeTargets.Field, Inherited = false)] public class ContextStaticAttribute : Attribute { } public static class Convert { internal static readonly Type[] ConvertTypes = new Type[19] { typeof(Empty), typeof(object), typeof(DBNull), typeof(bool), typeof(char), typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(decimal), typeof(DateTime), typeof(object), typeof(string) }; private static readonly Type EnumType = typeof(Enum); internal static readonly char[] base64Table = new char[65] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', '=' }; public static readonly object DBNull = System.DBNull.Value; private static ReadOnlySpan DecodingMap => new sbyte[256] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; private static bool TryDecodeFromUtf16(ReadOnlySpan utf16, Span bytes, out int consumed, out int written) { ref char reference = ref MemoryMarshal.GetReference(utf16); ref byte reference2 = ref MemoryMarshal.GetReference(bytes); int num = utf16.Length & -4; int length = bytes.Length; int num2 = 0; int num3 = 0; if (utf16.Length != 0) { ref sbyte reference3 = ref MemoryMarshal.GetReference(DecodingMap); int num4 = ((length < (num >> 2) * 3) ? (length / 3 * 4) : (num - 4)); while (true) { if (num2 < num4) { int num5 = Decode(ref Unsafe.Add(ref reference, num2), ref reference3); if (num5 >= 0) { WriteThreeLowOrderBytes(ref Unsafe.Add(ref reference2, num3), num5); num3 += 3; num2 += 4; continue; } } else if (num4 == num - 4 && num2 != num) { int num6 = Unsafe.Add(ref reference, num - 4); int num7 = Unsafe.Add(ref reference, num - 3); int num8 = Unsafe.Add(ref reference, num - 2); int num9 = Unsafe.Add(ref reference, num - 1); if (((num6 | num7 | num8 | num9) & 0xFFFFFF00u) == 0L) { num6 = Unsafe.Add(ref reference3, num6); num7 = Unsafe.Add(ref reference3, num7); num6 <<= 18; num7 <<= 12; num6 |= num7; if (num9 != 61) { num8 = Unsafe.Add(ref reference3, num8); num9 = Unsafe.Add(ref reference3, num9); num8 <<= 6; num6 |= num9; num6 |= num8; if (num6 >= 0 && num3 <= length - 3) { WriteThreeLowOrderBytes(ref Unsafe.Add(ref reference2, num3), num6); num3 += 3; goto IL_01e6; } } else if (num8 != 61) { num8 = Unsafe.Add(ref reference3, num8); num8 <<= 6; num6 |= num8; if (num6 >= 0 && num3 <= length - 2) { Unsafe.Add(ref reference2, num3) = (byte)(num6 >> 16); Unsafe.Add(ref reference2, num3 + 1) = (byte)(num6 >> 8); num3 += 2; goto IL_01e6; } } else if (num6 >= 0 && num3 <= length - 1) { Unsafe.Add(ref reference2, num3) = (byte)(num6 >> 16); num3++; goto IL_01e6; } } } goto IL_0200; IL_0200: consumed = num2; written = num3; return false; IL_01e6: num2 += 4; if (num == utf16.Length) { break; } goto IL_0200; } } consumed = num2; written = num3; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int Decode(ref char encodedChars, ref sbyte decodingMap) { int num = encodedChars; int num2 = Unsafe.Add(ref encodedChars, 1); int num3 = Unsafe.Add(ref encodedChars, 2); int num4 = Unsafe.Add(ref encodedChars, 3); if (((num | num2 | num3 | num4) & 0xFFFFFF00u) != 0L) { return -1; } num = Unsafe.Add(ref decodingMap, num); num2 = Unsafe.Add(ref decodingMap, num2); num3 = Unsafe.Add(ref decodingMap, num3); num4 = Unsafe.Add(ref decodingMap, num4); num <<= 18; num2 <<= 12; num3 <<= 6; num |= num4; num2 |= num3; return num | num2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteThreeLowOrderBytes(ref byte destination, int value) { destination = (byte)(value >> 16); Unsafe.Add(ref destination, 1) = (byte)(value >> 8); Unsafe.Add(ref destination, 2) = (byte)value; } public static TypeCode GetTypeCode(object? value) { if (value == null) { return TypeCode.Empty; } if (value is IConvertible convertible) { return convertible.GetTypeCode(); } return TypeCode.Object; } public static bool IsDBNull([NotNullWhen(true)] object? value) { if (value == System.DBNull.Value) { return true; } if (!(value is IConvertible convertible)) { return false; } return convertible.GetTypeCode() == TypeCode.DBNull; } [return: NotNullIfNotNull("value")] public static object? ChangeType(object? value, TypeCode typeCode) { return ChangeType(value, typeCode, CultureInfo.CurrentCulture); } [return: NotNullIfNotNull("value")] public static object? ChangeType(object? value, TypeCode typeCode, IFormatProvider? provider) { if (value == null && (typeCode == TypeCode.Empty || typeCode == TypeCode.String || typeCode == TypeCode.Object)) { return null; } if (!(value is IConvertible convertible)) { throw new InvalidCastException(SR.InvalidCast_IConvertible); } return typeCode switch { TypeCode.Boolean => convertible.ToBoolean(provider), TypeCode.Char => convertible.ToChar(provider), TypeCode.SByte => convertible.ToSByte(provider), TypeCode.Byte => convertible.ToByte(provider), TypeCode.Int16 => convertible.ToInt16(provider), TypeCode.UInt16 => convertible.ToUInt16(provider), TypeCode.Int32 => convertible.ToInt32(provider), TypeCode.UInt32 => convertible.ToUInt32(provider), TypeCode.Int64 => convertible.ToInt64(provider), TypeCode.UInt64 => convertible.ToUInt64(provider), TypeCode.Single => convertible.ToSingle(provider), TypeCode.Double => convertible.ToDouble(provider), TypeCode.Decimal => convertible.ToDecimal(provider), TypeCode.DateTime => convertible.ToDateTime(provider), TypeCode.String => convertible.ToString(provider), TypeCode.Object => value, TypeCode.DBNull => throw new InvalidCastException(SR.InvalidCast_DBNull), TypeCode.Empty => throw new InvalidCastException(SR.InvalidCast_Empty), _ => throw new ArgumentException(SR.Arg_UnknownTypeCode), }; } internal static object DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) { if (targetType == null) { throw new ArgumentNullException("targetType"); } if ((object)value.GetType() == targetType) { return value; } if ((object)targetType == ConvertTypes[3]) { return value.ToBoolean(provider); } if ((object)targetType == ConvertTypes[4]) { return value.ToChar(provider); } if ((object)targetType == ConvertTypes[5]) { return value.ToSByte(provider); } if ((object)targetType == ConvertTypes[6]) { return value.ToByte(provider); } if ((object)targetType == ConvertTypes[7]) { return value.ToInt16(provider); } if ((object)targetType == ConvertTypes[8]) { return value.ToUInt16(provider); } if ((object)targetType == ConvertTypes[9]) { return value.ToInt32(provider); } if ((object)targetType == ConvertTypes[10]) { return value.ToUInt32(provider); } if ((object)targetType == ConvertTypes[11]) { return value.ToInt64(provider); } if ((object)targetType == ConvertTypes[12]) { return value.ToUInt64(provider); } if ((object)targetType == ConvertTypes[13]) { return value.ToSingle(provider); } if ((object)targetType == ConvertTypes[14]) { return value.ToDouble(provider); } if ((object)targetType == ConvertTypes[15]) { return value.ToDecimal(provider); } if ((object)targetType == ConvertTypes[16]) { return value.ToDateTime(provider); } if ((object)targetType == ConvertTypes[18]) { return value.ToString(provider); } if ((object)targetType == ConvertTypes[1]) { return value; } if ((object)targetType == EnumType) { return (Enum)value; } if ((object)targetType == ConvertTypes[2]) { throw new InvalidCastException(SR.InvalidCast_DBNull); } if ((object)targetType == ConvertTypes[0]) { throw new InvalidCastException(SR.InvalidCast_Empty); } throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, value.GetType().FullName, targetType.FullName)); } [return: NotNullIfNotNull("value")] public static object? ChangeType(object? value, Type conversionType) { return ChangeType(value, conversionType, CultureInfo.CurrentCulture); } [return: NotNullIfNotNull("value")] public static object? ChangeType(object? value, Type conversionType, IFormatProvider? provider) { if ((object)conversionType == null) { throw new ArgumentNullException("conversionType"); } if (value == null) { if (conversionType.IsValueType) { throw new InvalidCastException(SR.InvalidCast_CannotCastNullToValueType); } return null; } if (!(value is IConvertible convertible)) { if (value.GetType() == conversionType) { return value; } throw new InvalidCastException(SR.InvalidCast_IConvertible); } if ((object)conversionType == ConvertTypes[3]) { return convertible.ToBoolean(provider); } if ((object)conversionType == ConvertTypes[4]) { return convertible.ToChar(provider); } if ((object)conversionType == ConvertTypes[5]) { return convertible.ToSByte(provider); } if ((object)conversionType == ConvertTypes[6]) { return convertible.ToByte(provider); } if ((object)conversionType == ConvertTypes[7]) { return convertible.ToInt16(provider); } if ((object)conversionType == ConvertTypes[8]) { return convertible.ToUInt16(provider); } if ((object)conversionType == ConvertTypes[9]) { return convertible.ToInt32(provider); } if ((object)conversionType == ConvertTypes[10]) { return convertible.ToUInt32(provider); } if ((object)conversionType == ConvertTypes[11]) { return convertible.ToInt64(provider); } if ((object)conversionType == ConvertTypes[12]) { return convertible.ToUInt64(provider); } if ((object)conversionType == ConvertTypes[13]) { return convertible.ToSingle(provider); } if ((object)conversionType == ConvertTypes[14]) { return convertible.ToDouble(provider); } if ((object)conversionType == ConvertTypes[15]) { return convertible.ToDecimal(provider); } if ((object)conversionType == ConvertTypes[16]) { return convertible.ToDateTime(provider); } if ((object)conversionType == ConvertTypes[18]) { return convertible.ToString(provider); } if ((object)conversionType == ConvertTypes[1]) { return value; } return convertible.ToType(conversionType, provider); } [DoesNotReturn] private static void ThrowCharOverflowException() { throw new OverflowException(SR.Overflow_Char); } [DoesNotReturn] private static void ThrowByteOverflowException() { throw new OverflowException(SR.Overflow_Byte); } [DoesNotReturn] private static void ThrowSByteOverflowException() { throw new OverflowException(SR.Overflow_SByte); } [DoesNotReturn] private static void ThrowInt16OverflowException() { throw new OverflowException(SR.Overflow_Int16); } [DoesNotReturn] private static void ThrowUInt16OverflowException() { throw new OverflowException(SR.Overflow_UInt16); } [DoesNotReturn] private static void ThrowInt32OverflowException() { throw new OverflowException(SR.Overflow_Int32); } [DoesNotReturn] private static void ThrowUInt32OverflowException() { throw new OverflowException(SR.Overflow_UInt32); } [DoesNotReturn] private static void ThrowInt64OverflowException() { throw new OverflowException(SR.Overflow_Int64); } [DoesNotReturn] private static void ThrowUInt64OverflowException() { throw new OverflowException(SR.Overflow_UInt64); } public static bool ToBoolean([NotNullWhen(true)] object? value) { if (value != null) { return ((IConvertible)value).ToBoolean(null); } return false; } public static bool ToBoolean([NotNullWhen(true)] object? value, IFormatProvider? provider) { if (value != null) { return ((IConvertible)value).ToBoolean(provider); } return false; } public static bool ToBoolean(bool value) { return value; } [CLSCompliant(false)] public static bool ToBoolean(sbyte value) { return value != 0; } public static bool ToBoolean(char value) { return ((IConvertible)value).ToBoolean((IFormatProvider?)null); } public static bool ToBoolean(byte value) { return value != 0; } public static bool ToBoolean(short value) { return value != 0; } [CLSCompliant(false)] public static bool ToBoolean(ushort value) { return value != 0; } public static bool ToBoolean(int value) { return value != 0; } [CLSCompliant(false)] public static bool ToBoolean(uint value) { return value != 0; } public static bool ToBoolean(long value) { return value != 0; } [CLSCompliant(false)] public static bool ToBoolean(ulong value) { return value != 0; } public static bool ToBoolean([NotNullWhen(true)] string? value) { if (value == null) { return false; } return bool.Parse(value); } public static bool ToBoolean([NotNullWhen(true)] string? value, IFormatProvider? provider) { if (value == null) { return false; } return bool.Parse(value); } public static bool ToBoolean(float value) { return value != 0f; } public static bool ToBoolean(double value) { return value != 0.0; } public static bool ToBoolean(decimal value) { return value != 0m; } public static bool ToBoolean(DateTime value) { return ((IConvertible)value).ToBoolean((IFormatProvider?)null); } public static char ToChar(object? value) { if (value != null) { return ((IConvertible)value).ToChar(null); } return '\0'; } public static char ToChar(object? value, IFormatProvider? provider) { if (value != null) { return ((IConvertible)value).ToChar(provider); } return '\0'; } public static char ToChar(bool value) { return ((IConvertible)value).ToChar((IFormatProvider?)null); } public static char ToChar(char value) { return value; } [CLSCompliant(false)] public static char ToChar(sbyte value) { if (value < 0) { ThrowCharOverflowException(); } return (char)value; } public static char ToChar(byte value) { return (char)value; } public static char ToChar(short value) { if (value < 0) { ThrowCharOverflowException(); } return (char)value; } [CLSCompliant(false)] public static char ToChar(ushort value) { return (char)value; } public static char ToChar(int value) { return ToChar((uint)value); } [CLSCompliant(false)] public static char ToChar(uint value) { if (value > 65535) { ThrowCharOverflowException(); } return (char)value; } public static char ToChar(long value) { return ToChar((ulong)value); } [CLSCompliant(false)] public static char ToChar(ulong value) { if (value > 65535) { ThrowCharOverflowException(); } return (char)value; } public static char ToChar(string value) { return ToChar(value, null); } public static char ToChar(string value, IFormatProvider? provider) { if (value == null) { throw new ArgumentNullException("value"); } if (value.Length != 1) { throw new FormatException(SR.Format_NeedSingleChar); } return value[0]; } public static char ToChar(float value) { return ((IConvertible)value).ToChar((IFormatProvider?)null); } public static char ToChar(double value) { return ((IConvertible)value).ToChar((IFormatProvider?)null); } public static char ToChar(decimal value) { return ((IConvertible)value).ToChar((IFormatProvider?)null); } public static char ToChar(DateTime value) { return ((IConvertible)value).ToChar((IFormatProvider?)null); } [CLSCompliant(false)] public static sbyte ToSByte(object? value) { if (value != null) { return ((IConvertible)value).ToSByte(null); } return 0; } [CLSCompliant(false)] public static sbyte ToSByte(object? value, IFormatProvider? provider) { if (value != null) { return ((IConvertible)value).ToSByte(provider); } return 0; } [CLSCompliant(false)] public static sbyte ToSByte(bool value) { if (!value) { return 0; } return 1; } [CLSCompliant(false)] public static sbyte ToSByte(sbyte value) { return value; } [CLSCompliant(false)] public static sbyte ToSByte(char value) { if (value > '\u007f') { ThrowSByteOverflowException(); } return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(byte value) { if (value > 127) { ThrowSByteOverflowException(); } return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(short value) { if (value < -128 || value > 127) { ThrowSByteOverflowException(); } return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(ushort value) { if (value > 127) { ThrowSByteOverflowException(); } return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(int value) { if (value < -128 || value > 127) { ThrowSByteOverflowException(); } return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(uint value) { if (value > 127) { ThrowSByteOverflowException(); } return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(long value) { if (value < -128 || value > 127) { ThrowSByteOverflowException(); } return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(ulong value) { if (value > 127) { ThrowSByteOverflowException(); } return (sbyte)value; } [CLSCompliant(false)] public static sbyte ToSByte(float value) { return ToSByte((double)value); } [CLSCompliant(false)] public static sbyte ToSByte(double value) { return ToSByte(ToInt32(value)); } [CLSCompliant(false)] public static sbyte ToSByte(decimal value) { return decimal.ToSByte(decimal.Round(value, 0)); } [CLSCompliant(false)] public static sbyte ToSByte(string? value) { if (value == null) { return 0; } return sbyte.Parse(value); } [CLSCompliant(false)] public static sbyte ToSByte(string value, IFormatProvider? provider) { return sbyte.Parse(value, provider); } [CLSCompliant(false)] public static sbyte ToSByte(DateTime value) { return ((IConvertible)value).ToSByte((IFormatProvider?)null); } public static byte ToByte(object? value) { if (value != null) { return ((IConvertible)value).ToByte(null); } return 0; } public static byte ToByte(object? value, IFormatProvider? provider) { if (value != null) { return ((IConvertible)value).ToByte(provider); } return 0; } public static byte ToByte(bool value) { if (!value) { return 0; } return 1; } public static byte ToByte(byte value) { return value; } public static byte ToByte(char value) { if (value > 'ÿ') { ThrowByteOverflowException(); } return (byte)value; } [CLSCompliant(false)] public static byte ToByte(sbyte value) { if (value < 0) { ThrowByteOverflowException(); } return (byte)value; } public static byte ToByte(short value) { if ((uint)value > 255u) { ThrowByteOverflowException(); } return (byte)value; } [CLSCompliant(false)] public static byte ToByte(ushort value) { if (value > 255) { ThrowByteOverflowException(); } return (byte)value; } public static byte ToByte(int value) { return ToByte((uint)value); } [CLSCompliant(false)] public static byte ToByte(uint value) { if (value > 255) { ThrowByteOverflowException(); } return (byte)value; } public static byte ToByte(long value) { return ToByte((ulong)value); } [CLSCompliant(false)] public static byte ToByte(ulong value) { if (value > 255) { ThrowByteOverflowException(); } return (byte)value; } public static byte ToByte(float value) { return ToByte((double)value); } public static byte ToByte(double value) { return ToByte(ToInt32(value)); } public static byte ToByte(decimal value) { return decimal.ToByte(decimal.Round(value, 0)); } public static byte ToByte(string? value) { if (value == null) { return 0; } return byte.Parse(value); } public static byte ToByte(string? value, IFormatProvider? provider) { if (value == null) { return 0; } return byte.Parse(value, provider); } public static byte ToByte(DateTime value) { return ((IConvertible)value).ToByte((IFormatProvider?)null); } public static short ToInt16(object? value) { if (value != null) { return ((IConvertible)value).ToInt16(null); } return 0; } public static short ToInt16(object? value, IFormatProvider? provider) { if (value != null) { return ((IConvertible)value).ToInt16(provider); } return 0; } public static short ToInt16(bool value) { if (!value) { return 0; } return 1; } public static short ToInt16(char value) { if (value > '翿') { ThrowInt16OverflowException(); } return (short)value; } [CLSCompliant(false)] public static short ToInt16(sbyte value) { return value; } public static short ToInt16(byte value) { return value; } [CLSCompliant(false)] public static short ToInt16(ushort value) { if (value > 32767) { ThrowInt16OverflowException(); } return (short)value; } public static short ToInt16(int value) { if (value < -32768 || value > 32767) { ThrowInt16OverflowException(); } return (short)value; } [CLSCompliant(false)] public static short ToInt16(uint value) { if (value > 32767) { ThrowInt16OverflowException(); } return (short)value; } public static short ToInt16(short value) { return value; } public static short ToInt16(long value) { if (value < -32768 || value > 32767) { ThrowInt16OverflowException(); } return (short)value; } [CLSCompliant(false)] public static short ToInt16(ulong value) { if (value > 32767) { ThrowInt16OverflowException(); } return (short)value; } public static short ToInt16(float value) { return ToInt16((double)value); } public static short ToInt16(double value) { return ToInt16(ToInt32(value)); } public static short ToInt16(decimal value) { return decimal.ToInt16(decimal.Round(value, 0)); } public static short ToInt16(string? value) { if (value == null) { return 0; } return short.Parse(value); } public static short ToInt16(string? value, IFormatProvider? provider) { if (value == null) { return 0; } return short.Parse(value, provider); } public static short ToInt16(DateTime value) { return ((IConvertible)value).ToInt16((IFormatProvider?)null); } [CLSCompliant(false)] public static ushort ToUInt16(object? value) { if (value != null) { return ((IConvertible)value).ToUInt16(null); } return 0; } [CLSCompliant(false)] public static ushort ToUInt16(object? value, IFormatProvider? provider) { if (value != null) { return ((IConvertible)value).ToUInt16(provider); } return 0; } [CLSCompliant(false)] public static ushort ToUInt16(bool value) { if (!value) { return 0; } return 1; } [CLSCompliant(false)] public static ushort ToUInt16(char value) { return value; } [CLSCompliant(false)] public static ushort ToUInt16(sbyte value) { if (value < 0) { ThrowUInt16OverflowException(); } return (ushort)value; } [CLSCompliant(false)] public static ushort ToUInt16(byte value) { return value; } [CLSCompliant(false)] public static ushort ToUInt16(short value) { if (value < 0) { ThrowUInt16OverflowException(); } return (ushort)value; } [CLSCompliant(false)] public static ushort ToUInt16(int value) { return ToUInt16((uint)value); } [CLSCompliant(false)] public static ushort ToUInt16(ushort value) { return value; } [CLSCompliant(false)] public static ushort ToUInt16(uint value) { if (value > 65535) { ThrowUInt16OverflowException(); } return (ushort)value; } [CLSCompliant(false)] public static ushort ToUInt16(long value) { return ToUInt16((ulong)value); } [CLSCompliant(false)] public static ushort ToUInt16(ulong value) { if (value > 65535) { ThrowUInt16OverflowException(); } return (ushort)value; } [CLSCompliant(false)] public static ushort ToUInt16(float value) { return ToUInt16((double)value); } [CLSCompliant(false)] public static ushort ToUInt16(double value) { return ToUInt16(ToInt32(value)); } [CLSCompliant(false)] public static ushort ToUInt16(decimal value) { return decimal.ToUInt16(decimal.Round(value, 0)); } [CLSCompliant(false)] public static ushort ToUInt16(string? value) { if (value == null) { return 0; } return ushort.Parse(value); } [CLSCompliant(false)] public static ushort ToUInt16(string? value, IFormatProvider? provider) { if (value == null) { return 0; } return ushort.Parse(value, provider); } [CLSCompliant(false)] public static ushort ToUInt16(DateTime value) { return ((IConvertible)value).ToUInt16((IFormatProvider?)null); } public static int ToInt32(object? value) { if (value != null) { return ((IConvertible)value).ToInt32(null); } return 0; } public static int ToInt32(object? value, IFormatProvider? provider) { if (value != null) { return ((IConvertible)value).ToInt32(provider); } return 0; } public static int ToInt32(bool value) { if (!value) { return 0; } return 1; } public static int ToInt32(char value) { return value; } [CLSCompliant(false)] public static int ToInt32(sbyte value) { return value; } public static int ToInt32(byte value) { return value; } public static int ToInt32(short value) { return value; } [CLSCompliant(false)] public static int ToInt32(ushort value) { return value; } [CLSCompliant(false)] public static int ToInt32(uint value) { if ((int)value < 0) { ThrowInt32OverflowException(); } return (int)value; } public static int ToInt32(int value) { return value; } public static int ToInt32(long value) { if (value < int.MinValue || value > int.MaxValue) { ThrowInt32OverflowException(); } return (int)value; } [CLSCompliant(false)] public static int ToInt32(ulong value) { if (value > int.MaxValue) { ThrowInt32OverflowException(); } return (int)value; } public static int ToInt32(float value) { return ToInt32((double)value); } public static int ToInt32(double value) { if (value >= 0.0) { if (value < 2147483647.5) { int num = (int)value; double num2 = value - (double)num; if (num2 > 0.5 || (num2 == 0.5 && ((uint)num & (true ? 1u : 0u)) != 0)) { num++; } return num; } } else if (value >= -2147483648.5) { int num3 = (int)value; double num4 = value - (double)num3; if (num4 < -0.5 || (num4 == -0.5 && ((uint)num3 & (true ? 1u : 0u)) != 0)) { num3--; } return num3; } throw new OverflowException(SR.Overflow_Int32); } public static int ToInt32(decimal value) { return decimal.ToInt32(decimal.Round(value, 0)); } public static int ToInt32(string? value) { if (value == null) { return 0; } return int.Parse(value); } public static int ToInt32(string? value, IFormatProvider? provider) { if (value == null) { return 0; } return int.Parse(value, provider); } public static int ToInt32(DateTime value) { return ((IConvertible)value).ToInt32((IFormatProvider?)null); } [CLSCompliant(false)] public static uint ToUInt32(object? value) { if (value != null) { return ((IConvertible)value).ToUInt32(null); } return 0u; } [CLSCompliant(false)] public static uint ToUInt32(object? value, IFormatProvider? provider) { if (value != null) { return ((IConvertible)value).ToUInt32(provider); } return 0u; } [CLSCompliant(false)] public static uint ToUInt32(bool value) { if (!value) { return 0u; } return 1u; } [CLSCompliant(false)] public static uint ToUInt32(char value) { return value; } [CLSCompliant(false)] public static uint ToUInt32(sbyte value) { if (value < 0) { ThrowUInt32OverflowException(); } return (uint)value; } [CLSCompliant(false)] public static uint ToUInt32(byte value) { return value; } [CLSCompliant(false)] public static uint ToUInt32(short value) { if (value < 0) { ThrowUInt32OverflowException(); } return (uint)value; } [CLSCompliant(false)] public static uint ToUInt32(ushort value) { return value; } [CLSCompliant(false)] public static uint ToUInt32(int value) { if (value < 0) { ThrowUInt32OverflowException(); } return (uint)value; } [CLSCompliant(false)] public static uint ToUInt32(uint value) { return value; } [CLSCompliant(false)] public static uint ToUInt32(long value) { return ToUInt32((ulong)value); } [CLSCompliant(false)] public static uint ToUInt32(ulong value) { if (value > uint.MaxValue) { ThrowUInt32OverflowException(); } return (uint)value; } [CLSCompliant(false)] public static uint ToUInt32(float value) { return ToUInt32((double)value); } [CLSCompliant(false)] public static uint ToUInt32(double value) { if (value >= -0.5 && value < 4294967295.5) { uint num = (uint)value; double num2 = value - (double)num; if (num2 > 0.5 || (num2 == 0.5 && (num & (true ? 1u : 0u)) != 0)) { num++; } return num; } throw new OverflowException(SR.Overflow_UInt32); } [CLSCompliant(false)] public static uint ToUInt32(decimal value) { return decimal.ToUInt32(decimal.Round(value, 0)); } [CLSCompliant(false)] public static uint ToUInt32(string? value) { if (value == null) { return 0u; } return uint.Parse(value); } [CLSCompliant(false)] public static uint ToUInt32(string? value, IFormatProvider? provider) { if (value == null) { return 0u; } return uint.Parse(value, provider); } [CLSCompliant(false)] public static uint ToUInt32(DateTime value) { return ((IConvertible)value).ToUInt32((IFormatProvider?)null); } public static long ToInt64(object? value) { if (value != null) { return ((IConvertible)value).ToInt64(null); } return 0L; } public static long ToInt64(object? value, IFormatProvider? provider) { if (value != null) { return ((IConvertible)value).ToInt64(provider); } return 0L; } public static long ToInt64(bool value) { return value ? 1 : 0; } public static long ToInt64(char value) { return value; } [CLSCompliant(false)] public static long ToInt64(sbyte value) { return value; } public static long ToInt64(byte value) { return value; } public static long ToInt64(short value) { return value; } [CLSCompliant(false)] public static long ToInt64(ushort value) { return value; } public static long ToInt64(int value) { return value; } [CLSCompliant(false)] public static long ToInt64(uint value) { return value; } [CLSCompliant(false)] public static long ToInt64(ulong value) { if ((long)value < 0L) { ThrowInt64OverflowException(); } return (long)value; } public static long ToInt64(long value) { return value; } public static long ToInt64(float value) { return ToInt64((double)value); } public static long ToInt64(double value) { return checked((long)Math.Round(value)); } public static long ToInt64(decimal value) { return decimal.ToInt64(decimal.Round(value, 0)); } public static long ToInt64(string? value) { if (value == null) { return 0L; } return long.Parse(value); } public static long ToInt64(string? value, IFormatProvider? provider) { if (value == null) { return 0L; } return long.Parse(value, provider); } public static long ToInt64(DateTime value) { return ((IConvertible)value).ToInt64((IFormatProvider?)null); } [CLSCompliant(false)] public static ulong ToUInt64(object? value) { if (value != null) { return ((IConvertible)value).ToUInt64(null); } return 0uL; } [CLSCompliant(false)] public static ulong ToUInt64(object? value, IFormatProvider? provider) { if (value != null) { return ((IConvertible)value).ToUInt64(provider); } return 0uL; } [CLSCompliant(false)] public static ulong ToUInt64(bool value) { if (!value) { return 0uL; } return 1uL; } [CLSCompliant(false)] public static ulong ToUInt64(char value) { return value; } [CLSCompliant(false)] public static ulong ToUInt64(sbyte value) { if (value < 0) { ThrowUInt64OverflowException(); } return (ulong)value; } [CLSCompliant(false)] public static ulong ToUInt64(byte value) { return value; } [CLSCompliant(false)] public static ulong ToUInt64(short value) { if (value < 0) { ThrowUInt64OverflowException(); } return (ulong)value; } [CLSCompliant(false)] public static ulong ToUInt64(ushort value) { return value; } [CLSCompliant(false)] public static ulong ToUInt64(int value) { if (value < 0) { ThrowUInt64OverflowException(); } return (ulong)value; } [CLSCompliant(false)] public static ulong ToUInt64(uint value) { return value; } [CLSCompliant(false)] public static ulong ToUInt64(long value) { if (value < 0) { ThrowUInt64OverflowException(); } return (ulong)value; } [CLSCompliant(false)] public static ulong ToUInt64(ulong value) { return value; } [CLSCompliant(false)] public static ulong ToUInt64(float value) { return ToUInt64((double)value); } [CLSCompliant(false)] public static ulong ToUInt64(double value) { return checked((ulong)Math.Round(value)); } [CLSCompliant(false)] public static ulong ToUInt64(decimal value) { return decimal.ToUInt64(decimal.Round(value, 0)); } [CLSCompliant(false)] public static ulong ToUInt64(string? value) { if (value == null) { return 0uL; } return ulong.Parse(value); } [CLSCompliant(false)] public static ulong ToUInt64(string? value, IFormatProvider? provider) { if (value == null) { return 0uL; } return ulong.Parse(value, provider); } [CLSCompliant(false)] public static ulong ToUInt64(DateTime value) { return ((IConvertible)value).ToUInt64((IFormatProvider?)null); } public static float ToSingle(object? value) { if (value != null) { return ((IConvertible)value).ToSingle(null); } return 0f; } public static float ToSingle(object? value, IFormatProvider? provider) { if (value != null) { return ((IConvertible)value).ToSingle(provider); } return 0f; } [CLSCompliant(false)] public static float ToSingle(sbyte value) { return value; } public static float ToSingle(byte value) { return (int)value; } public static float ToSingle(char value) { return ((IConvertible)value).ToSingle((IFormatProvider?)null); } public static float ToSingle(short value) { return value; } [CLSCompliant(false)] public static float ToSingle(ushort value) { return (int)value; } public static float ToSingle(int value) { return value; } [CLSCompliant(false)] public static float ToSingle(uint value) { return value; } public static float ToSingle(long value) { return value; } [CLSCompliant(false)] public static float ToSingle(ulong value) { return value; } public static float ToSingle(float value) { return value; } public static float ToSingle(double value) { return (float)value; } public static float ToSingle(decimal value) { return (float)value; } public static float ToSingle(string? value) { if (value == null) { return 0f; } return float.Parse(value); } public static float ToSingle(string? value, IFormatProvider? provider) { if (value == null) { return 0f; } return float.Parse(value, provider); } public static float ToSingle(bool value) { return value ? 1 : 0; } public static float ToSingle(DateTime value) { return ((IConvertible)value).ToSingle((IFormatProvider?)null); } public static double ToDouble(object? value) { if (value != null) { return ((IConvertible)value).ToDouble(null); } return 0.0; } public static double ToDouble(object? value, IFormatProvider? provider) { if (value != null) { return ((IConvertible)value).ToDouble(provider); } return 0.0; } [CLSCompliant(false)] public static double ToDouble(sbyte value) { return value; } public static double ToDouble(byte value) { return (int)value; } public static double ToDouble(short value) { return value; } public static double ToDouble(char value) { return ((IConvertible)value).ToDouble((IFormatProvider?)null); } [CLSCompliant(false)] public static double ToDouble(ushort value) { return (int)value; } public static double ToDouble(int value) { return value; } [CLSCompliant(false)] public static double ToDouble(uint value) { return value; } public static double ToDouble(long value) { return value; } [CLSCompliant(false)] public static double ToDouble(ulong value) { return value; } public static double ToDouble(float value) { return value; } public static double ToDouble(double value) { return value; } public static double ToDouble(decimal value) { return (double)value; } public static double ToDouble(string? value) { if (value == null) { return 0.0; } return double.Parse(value); } public static double ToDouble(string? value, IFormatProvider? provider) { if (value == null) { return 0.0; } return double.Parse(value, provider); } public static double ToDouble(bool value) { return value ? 1 : 0; } public static double ToDouble(DateTime value) { return ((IConvertible)value).ToDouble((IFormatProvider?)null); } public static decimal ToDecimal(object? value) { if (value != null) { return ((IConvertible)value).ToDecimal(null); } return 0m; } public static decimal ToDecimal(object? value, IFormatProvider? provider) { if (value != null) { return ((IConvertible)value).ToDecimal(provider); } return 0m; } [CLSCompliant(false)] public static decimal ToDecimal(sbyte value) { return value; } public static decimal ToDecimal(byte value) { return value; } public static decimal ToDecimal(char value) { return ((IConvertible)value).ToDecimal((IFormatProvider?)null); } public static decimal ToDecimal(short value) { return value; } [CLSCompliant(false)] public static decimal ToDecimal(ushort value) { return value; } public static decimal ToDecimal(int value) { return value; } [CLSCompliant(false)] public static decimal ToDecimal(uint value) { return value; } public static decimal ToDecimal(long value) { return value; } [CLSCompliant(false)] public static decimal ToDecimal(ulong value) { return value; } public static decimal ToDecimal(float value) { return (decimal)value; } public static decimal ToDecimal(double value) { return (decimal)value; } public static decimal ToDecimal(string? value) { if (value == null) { return 0m; } return decimal.Parse(value); } public static decimal ToDecimal(string? value, IFormatProvider? provider) { if (value == null) { return 0m; } return decimal.Parse(value, provider); } public static decimal ToDecimal(decimal value) { return value; } public static decimal ToDecimal(bool value) { return value ? 1 : 0; } public static decimal ToDecimal(DateTime value) { return ((IConvertible)value).ToDecimal((IFormatProvider?)null); } public static DateTime ToDateTime(DateTime value) { return value; } public static DateTime ToDateTime(object? value) { if (value != null) { return ((IConvertible)value).ToDateTime(null); } return DateTime.MinValue; } public static DateTime ToDateTime(object? value, IFormatProvider? provider) { if (value != null) { return ((IConvertible)value).ToDateTime(provider); } return DateTime.MinValue; } public static DateTime ToDateTime(string? value) { if (value == null) { return new DateTime(0L); } return DateTime.Parse(value); } public static DateTime ToDateTime(string? value, IFormatProvider? provider) { if (value == null) { return new DateTime(0L); } return DateTime.Parse(value, provider); } [CLSCompliant(false)] public static DateTime ToDateTime(sbyte value) { return ((IConvertible)value).ToDateTime((IFormatProvider?)null); } public static DateTime ToDateTime(byte value) { return ((IConvertible)value).ToDateTime((IFormatProvider?)null); } public static DateTime ToDateTime(short value) { return ((IConvertible)value).ToDateTime((IFormatProvider?)null); } [CLSCompliant(false)] public static DateTime ToDateTime(ushort value) { return ((IConvertible)value).ToDateTime((IFormatProvider?)null); } public static DateTime ToDateTime(int value) { return ((IConvertible)value).ToDateTime((IFormatProvider?)null); } [CLSCompliant(false)] public static DateTime ToDateTime(uint value) { return ((IConvertible)value).ToDateTime((IFormatProvider?)null); } public static DateTime ToDateTime(long value) { return ((IConvertible)value).ToDateTime((IFormatProvider?)null); } [CLSCompliant(false)] public static DateTime ToDateTime(ulong value) { return ((IConvertible)value).ToDateTime((IFormatProvider?)null); } public static DateTime ToDateTime(bool value) { return ((IConvertible)value).ToDateTime((IFormatProvider?)null); } public static DateTime ToDateTime(char value) { return ((IConvertible)value).ToDateTime((IFormatProvider?)null); } public static DateTime ToDateTime(float value) { return ((IConvertible)value).ToDateTime((IFormatProvider?)null); } public static DateTime ToDateTime(double value) { return ((IConvertible)value).ToDateTime((IFormatProvider?)null); } public static DateTime ToDateTime(decimal value) { return ((IConvertible)value).ToDateTime((IFormatProvider?)null); } public static string? ToString(object? value) { return ToString(value, null); } public static string? ToString(object? value, IFormatProvider? provider) { if (value is IConvertible convertible) { return convertible.ToString(provider); } if (value is IFormattable formattable) { return formattable.ToString(null, provider); } if (value != null) { return value.ToString(); } return string.Empty; } public static string ToString(bool value) { return value.ToString(); } public static string ToString(bool value, IFormatProvider? provider) { return value.ToString(); } public static string ToString(char value) { return char.ToString(value); } public static string ToString(char value, IFormatProvider? provider) { return value.ToString(); } [CLSCompliant(false)] public static string ToString(sbyte value) { return value.ToString(); } [CLSCompliant(false)] public static string ToString(sbyte value, IFormatProvider? provider) { return value.ToString(provider); } public static string ToString(byte value) { return value.ToString(); } public static string ToString(byte value, IFormatProvider? provider) { return value.ToString(provider); } public static string ToString(short value) { return value.ToString(); } public static string ToString(short value, IFormatProvider? provider) { return value.ToString(provider); } [CLSCompliant(false)] public static string ToString(ushort value) { return value.ToString(); } [CLSCompliant(false)] public static string ToString(ushort value, IFormatProvider? provider) { return value.ToString(provider); } public static string ToString(int value) { return value.ToString(); } public static string ToString(int value, IFormatProvider? provider) { return value.ToString(provider); } [CLSCompliant(false)] public static string ToString(uint value) { return value.ToString(); } [CLSCompliant(false)] public static string ToString(uint value, IFormatProvider? provider) { return value.ToString(provider); } public static string ToString(long value) { return value.ToString(); } public static string ToString(long value, IFormatProvider? provider) { return value.ToString(provider); } [CLSCompliant(false)] public static string ToString(ulong value) { return value.ToString(); } [CLSCompliant(false)] public static string ToString(ulong value, IFormatProvider? provider) { return value.ToString(provider); } public static string ToString(float value) { return value.ToString(); } public static string ToString(float value, IFormatProvider? provider) { return value.ToString(provider); } public static string ToString(double value) { return value.ToString(); } public static string ToString(double value, IFormatProvider? provider) { return value.ToString(provider); } public static string ToString(decimal value) { return value.ToString(); } public static string ToString(decimal value, IFormatProvider? provider) { return value.ToString(provider); } public static string ToString(DateTime value) { return value.ToString(); } public static string ToString(DateTime value, IFormatProvider? provider) { return value.ToString(provider); } [return: NotNullIfNotNull("value")] public static string? ToString(string? value) { return value; } [return: NotNullIfNotNull("value")] public static string? ToString(string? value, IFormatProvider? provider) { return value; } public static byte ToByte(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { throw new ArgumentException(SR.Arg_InvalidBase); } if (value == null) { return 0; } int num = ParseNumbers.StringToInt(value.AsSpan(), fromBase, 4608); if ((uint)num > 255u) { ThrowByteOverflowException(); } return (byte)num; } [CLSCompliant(false)] public static sbyte ToSByte(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { throw new ArgumentException(SR.Arg_InvalidBase); } if (value == null) { return 0; } int num = ParseNumbers.StringToInt(value.AsSpan(), fromBase, 5120); if (fromBase != 10 && num <= 255) { return (sbyte)num; } if (num < -128 || num > 127) { ThrowSByteOverflowException(); } return (sbyte)num; } public static short ToInt16(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { throw new ArgumentException(SR.Arg_InvalidBase); } if (value == null) { return 0; } int num = ParseNumbers.StringToInt(value.AsSpan(), fromBase, 6144); if (fromBase != 10 && num <= 65535) { return (short)num; } if (num < -32768 || num > 32767) { ThrowInt16OverflowException(); } return (short)num; } [CLSCompliant(false)] public static ushort ToUInt16(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { throw new ArgumentException(SR.Arg_InvalidBase); } if (value == null) { return 0; } int num = ParseNumbers.StringToInt(value.AsSpan(), fromBase, 4608); if ((uint)num > 65535u) { ThrowUInt16OverflowException(); } return (ushort)num; } public static int ToInt32(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { throw new ArgumentException(SR.Arg_InvalidBase); } if (value == null) { return 0; } return ParseNumbers.StringToInt(value.AsSpan(), fromBase, 4096); } [CLSCompliant(false)] public static uint ToUInt32(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { throw new ArgumentException(SR.Arg_InvalidBase); } if (value == null) { return 0u; } return (uint)ParseNumbers.StringToInt(value.AsSpan(), fromBase, 4608); } public static long ToInt64(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { throw new ArgumentException(SR.Arg_InvalidBase); } if (value == null) { return 0L; } return ParseNumbers.StringToLong(value.AsSpan(), fromBase, 4096); } [CLSCompliant(false)] public static ulong ToUInt64(string? value, int fromBase) { if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16) { throw new ArgumentException(SR.Arg_InvalidBase); } if (value == null) { return 0uL; } return (ulong)ParseNumbers.StringToLong(value.AsSpan(), fromBase, 4608); } public static string ToString(byte value, int toBase) { if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) { throw new ArgumentException(SR.Arg_InvalidBase); } return ParseNumbers.IntToString(value, toBase, -1, ' ', 64); } public static string ToString(short value, int toBase) { if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) { throw new ArgumentException(SR.Arg_InvalidBase); } return ParseNumbers.IntToString(value, toBase, -1, ' ', 128); } public static string ToString(int value, int toBase) { if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) { throw new ArgumentException(SR.Arg_InvalidBase); } return ParseNumbers.IntToString(value, toBase, -1, ' ', 0); } public static string ToString(long value, int toBase) { if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16) { throw new ArgumentException(SR.Arg_InvalidBase); } return ParseNumbers.LongToString(value, toBase, -1, ' ', 0); } public static string ToBase64String(byte[] inArray) { if (inArray == null) { throw new ArgumentNullException("inArray"); } return ToBase64String(new ReadOnlySpan(inArray)); } public static string ToBase64String(byte[] inArray, Base64FormattingOptions options) { if (inArray == null) { throw new ArgumentNullException("inArray"); } return ToBase64String(new ReadOnlySpan(inArray), options); } public static string ToBase64String(byte[] inArray, int offset, int length) { return ToBase64String(inArray, offset, length, Base64FormattingOptions.None); } public static string ToBase64String(byte[] inArray, int offset, int length, Base64FormattingOptions options) { if (inArray == null) { throw new ArgumentNullException("inArray"); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_Index); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_GenericPositive); } if (offset > inArray.Length - length) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_OffsetLength); } return ToBase64String(new ReadOnlySpan(inArray, offset, length), options); } public unsafe static string ToBase64String(ReadOnlySpan bytes, Base64FormattingOptions options = Base64FormattingOptions.None) { if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options), "options"); } if (bytes.Length == 0) { return string.Empty; } bool insertLineBreaks = options == Base64FormattingOptions.InsertLineBreaks; string text = string.FastAllocateString(ToBase64_CalculateAndValidateOutputLength(bytes.Length, insertLineBreaks)); fixed (byte* inData = &MemoryMarshal.GetReference(bytes)) { fixed (char* outChars = text) { int num = ConvertToBase64Array(outChars, inData, 0, bytes.Length, insertLineBreaks); } } return text; } public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut) { return ToBase64CharArray(inArray, offsetIn, length, outArray, offsetOut, Base64FormattingOptions.None); } public unsafe static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options) { if (inArray == null) { throw new ArgumentNullException("inArray"); } if (outArray == null) { throw new ArgumentNullException("outArray"); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_Index); } if (offsetIn < 0) { throw new ArgumentOutOfRangeException("offsetIn", SR.ArgumentOutOfRange_GenericPositive); } if (offsetOut < 0) { throw new ArgumentOutOfRangeException("offsetOut", SR.ArgumentOutOfRange_GenericPositive); } if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options), "options"); } int num = inArray.Length; if (offsetIn > num - length) { throw new ArgumentOutOfRangeException("offsetIn", SR.ArgumentOutOfRange_OffsetLength); } if (num == 0) { return 0; } bool insertLineBreaks = options == Base64FormattingOptions.InsertLineBreaks; int num2 = outArray.Length; int num3 = ToBase64_CalculateAndValidateOutputLength(length, insertLineBreaks); if (offsetOut > num2 - num3) { throw new ArgumentOutOfRangeException("offsetOut", SR.ArgumentOutOfRange_OffsetOut); } int result; fixed (char* outChars = &outArray[offsetOut]) { fixed (byte* inData = &inArray[0]) { result = ConvertToBase64Array(outChars, inData, offsetIn, length, insertLineBreaks); } } return result; } public unsafe static bool TryToBase64Chars(ReadOnlySpan bytes, Span chars, out int charsWritten, Base64FormattingOptions options = Base64FormattingOptions.None) { if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)options), "options"); } if (bytes.Length == 0) { charsWritten = 0; return true; } bool insertLineBreaks = options == Base64FormattingOptions.InsertLineBreaks; int num = ToBase64_CalculateAndValidateOutputLength(bytes.Length, insertLineBreaks); if (num > chars.Length) { charsWritten = 0; return false; } fixed (char* outChars = &MemoryMarshal.GetReference(chars)) { fixed (byte* inData = &MemoryMarshal.GetReference(bytes)) { charsWritten = ConvertToBase64Array(outChars, inData, 0, bytes.Length, insertLineBreaks); return true; } } } private unsafe static int ConvertToBase64Array(char* outChars, byte* inData, int offset, int length, bool insertLineBreaks) { int num = length % 3; int num2 = offset + (length - num); int num3 = 0; int num4 = 0; fixed (char* ptr = &base64Table[0]) { int i; for (i = offset; i < num2; i += 3) { if (insertLineBreaks) { if (num4 == 76) { outChars[num3++] = '\r'; outChars[num3++] = '\n'; num4 = 0; } num4 += 4; } outChars[num3] = ptr[(inData[i] & 0xFC) >> 2]; outChars[num3 + 1] = ptr[((inData[i] & 3) << 4) | ((inData[i + 1] & 0xF0) >> 4)]; outChars[num3 + 2] = ptr[((inData[i + 1] & 0xF) << 2) | ((inData[i + 2] & 0xC0) >> 6)]; outChars[num3 + 3] = ptr[inData[i + 2] & 0x3F]; num3 += 4; } i = num2; if (insertLineBreaks && num != 0 && num4 == 76) { outChars[num3++] = '\r'; outChars[num3++] = '\n'; } switch (num) { case 2: outChars[num3] = ptr[(inData[i] & 0xFC) >> 2]; outChars[num3 + 1] = ptr[((inData[i] & 3) << 4) | ((inData[i + 1] & 0xF0) >> 4)]; outChars[num3 + 2] = ptr[(inData[i + 1] & 0xF) << 2]; outChars[num3 + 3] = ptr[64]; num3 += 4; break; case 1: outChars[num3] = ptr[(inData[i] & 0xFC) >> 2]; outChars[num3 + 1] = ptr[(inData[i] & 3) << 4]; outChars[num3 + 2] = ptr[64]; outChars[num3 + 3] = ptr[64]; num3 += 4; break; } } return num3; } private static int ToBase64_CalculateAndValidateOutputLength(int inputLength, bool insertLineBreaks) { long num = ((long)inputLength + 2L) / 3 * 4; if (num == 0L) { return 0; } if (insertLineBreaks) { var (num2, num3) = Math.DivRem(num, 76L); if (num3 == 0L) { num2--; } num += num2 * 2; } if (num > int.MaxValue) { throw new OutOfMemoryException(); } return (int)num; } public unsafe static byte[] FromBase64String(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } fixed (char* inputPtr = s) { return FromBase64CharPtr(inputPtr, s.Length); } } public static bool TryFromBase64String(string s, Span bytes, out int bytesWritten) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return TryFromBase64Chars(s.AsSpan(), bytes, out bytesWritten); } public static bool TryFromBase64Chars(ReadOnlySpan chars, Span bytes, out int bytesWritten) { Span span = stackalloc char[4]; bytesWritten = 0; while (chars.Length != 0) { int consumed; int written; bool flag = TryDecodeFromUtf16(chars, bytes, out consumed, out written); bytesWritten += written; if (flag) { return true; } chars = chars.Slice(consumed); bytes = bytes.Slice(written); if (chars[0].IsSpace()) { int i; for (i = 1; i != chars.Length && chars[i].IsSpace(); i++) { } chars = chars.Slice(i); if (written % 3 != 0 && chars.Length != 0) { bytesWritten = 0; return false; } continue; } CopyToTempBufferWithoutWhiteSpace(chars, span, out var consumed2, out var charsWritten); if (((uint)charsWritten & 3u) != 0) { bytesWritten = 0; return false; } span = span.Slice(0, charsWritten); if (!TryDecodeFromUtf16(span, bytes, out var _, out var written2)) { bytesWritten = 0; return false; } bytesWritten += written2; chars = chars.Slice(consumed2); bytes = bytes.Slice(written2); if (written2 % 3 == 0) { continue; } for (int j = 0; j < chars.Length; j++) { if (!chars[j].IsSpace()) { bytesWritten = 0; return false; } } return true; } return true; } private static void CopyToTempBufferWithoutWhiteSpace(ReadOnlySpan chars, Span tempBuffer, out int consumed, out int charsWritten) { charsWritten = 0; for (int i = 0; i < chars.Length; i++) { char c = chars[i]; if (!c.IsSpace()) { tempBuffer[charsWritten++] = c; if (charsWritten == tempBuffer.Length) { consumed = i + 1; return; } } } consumed = chars.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsSpace(this char c) { if (c != ' ' && c != '\t' && c != '\r') { return c == '\n'; } return true; } public unsafe static byte[] FromBase64CharArray(char[] inArray, int offset, int length) { if (inArray == null) { throw new ArgumentNullException("inArray"); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_Index); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_GenericPositive); } if (offset > inArray.Length - length) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_OffsetLength); } if (inArray.Length == 0) { return Array.Empty(); } fixed (char* ptr = &inArray[0]) { return FromBase64CharPtr(ptr + offset, length); } } private unsafe static byte[] FromBase64CharPtr(char* inputPtr, int inputLength) { while (inputLength > 0) { int num = inputPtr[inputLength - 1]; if (num != 32 && num != 10 && num != 13 && num != 9) { break; } inputLength--; } int num2 = FromBase64_ComputeResultLength(inputPtr, inputLength); byte[] array = new byte[num2]; if (!TryFromBase64Chars(new ReadOnlySpan(inputPtr, inputLength), array, out var _)) { throw new FormatException(SR.Format_BadBase64Char); } return array; } private unsafe static int FromBase64_ComputeResultLength(char* inputPtr, int inputLength) { char* ptr = inputPtr + inputLength; int num = inputLength; int num2 = 0; while (inputPtr < ptr) { uint num3 = *inputPtr; inputPtr++; switch (num3) { case 0u: case 1u: case 2u: case 3u: case 4u: case 5u: case 6u: case 7u: case 8u: case 9u: case 10u: case 11u: case 12u: case 13u: case 14u: case 15u: case 16u: case 17u: case 18u: case 19u: case 20u: case 21u: case 22u: case 23u: case 24u: case 25u: case 26u: case 27u: case 28u: case 29u: case 30u: case 31u: case 32u: num--; break; case 61u: num--; num2++; break; } } switch (num2) { case 1: num2 = 2; break; case 2: num2 = 1; break; default: throw new FormatException(SR.Format_BadBase64Char); case 0: break; } return num / 4 * 3 + num2; } public static byte[] FromHexString(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return FromHexString(s.AsSpan()); } public static byte[] FromHexString(ReadOnlySpan chars) { if (chars.Length == 0) { return Array.Empty(); } if ((uint)chars.Length % 2u != 0) { throw new FormatException(SR.Format_BadHexLength); } byte[] array = GC.AllocateUninitializedArray(chars.Length >> 1); if (!HexConverter.TryDecodeFromUtf16(chars, array)) { throw new FormatException(SR.Format_BadHexChar); } return array; } public static string ToHexString(byte[] inArray) { if (inArray == null) { throw new ArgumentNullException("inArray"); } return ToHexString(new ReadOnlySpan(inArray)); } public static string ToHexString(byte[] inArray, int offset, int length) { if (inArray == null) { throw new ArgumentNullException("inArray"); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_Index); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_GenericPositive); } if (offset > inArray.Length - length) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_OffsetLength); } return ToHexString(new ReadOnlySpan(inArray, offset, length)); } public static string ToHexString(ReadOnlySpan bytes) { if (bytes.Length == 0) { return string.Empty; } if (bytes.Length > 1073741823) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_InputTooLarge); } return HexConverter.ToString(bytes); } } [Flags] public enum Base64FormattingOptions { None = 0, InsertLineBreaks = 1 } [Obsolete("System.CurrentSystemTimeZone has been deprecated. Investigate the use of System.TimeZoneInfo.Local instead.")] internal sealed class CurrentSystemTimeZone : TimeZone { private readonly long m_ticksOffset; private readonly string m_standardName; private readonly string m_daylightName; private readonly Hashtable m_CachedDaylightChanges = new Hashtable(); public override string StandardName => m_standardName; public override string DaylightName => m_daylightName; internal CurrentSystemTimeZone() { TimeZoneInfo local = TimeZoneInfo.Local; m_ticksOffset = local.BaseUtcOffset.Ticks; m_standardName = local.StandardName; m_daylightName = local.DaylightName; } internal long GetUtcOffsetFromUniversalTime(DateTime time, ref bool isAmbiguousLocalDst) { TimeSpan timeSpan = new TimeSpan(m_ticksOffset); DaylightTime daylightChanges = GetDaylightChanges(time.Year); isAmbiguousLocalDst = false; if (daylightChanges == null || daylightChanges.Delta.Ticks == 0L) { return timeSpan.Ticks; } DateTime dateTime = daylightChanges.Start - timeSpan; DateTime dateTime2 = daylightChanges.End - timeSpan - daylightChanges.Delta; DateTime dateTime3; DateTime dateTime4; if (daylightChanges.Delta.Ticks > 0) { dateTime3 = dateTime2 - daylightChanges.Delta; dateTime4 = dateTime2; } else { dateTime3 = dateTime; dateTime4 = dateTime - daylightChanges.Delta; } if ((!(dateTime > dateTime2)) ? (time >= dateTime && time < dateTime2) : (time < dateTime2 || time >= dateTime)) { timeSpan += daylightChanges.Delta; if (time >= dateTime3 && time < dateTime4) { isAmbiguousLocalDst = true; } } return timeSpan.Ticks; } public override DateTime ToLocalTime(DateTime time) { if (time.Kind == DateTimeKind.Local) { return time; } bool isAmbiguousLocalDst = false; long utcOffsetFromUniversalTime = GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst); long num = time.Ticks + utcOffsetFromUniversalTime; if (num > 3155378975999999999L) { return new DateTime(3155378975999999999L, DateTimeKind.Local); } if (num < 0) { return new DateTime(0L, DateTimeKind.Local); } return new DateTime(num, DateTimeKind.Local, isAmbiguousLocalDst); } public override DaylightTime GetDaylightChanges(int year) { if (year < 1 || year > 9999) { throw new ArgumentOutOfRangeException("year", SR.Format(SR.ArgumentOutOfRange_Range, 1, 9999)); } return GetCachedDaylightChanges(year); } private static DaylightTime CreateDaylightChanges(int year) { DateTime start = DateTime.MinValue; DateTime end = DateTime.MinValue; TimeSpan delta = TimeSpan.Zero; if (TimeZoneInfo.Local.SupportsDaylightSavingTime) { TimeZoneInfo.AdjustmentRule[] adjustmentRules = TimeZoneInfo.Local.GetAdjustmentRules(); foreach (TimeZoneInfo.AdjustmentRule adjustmentRule in adjustmentRules) { if (adjustmentRule.DateStart.Year <= year && adjustmentRule.DateEnd.Year >= year && adjustmentRule.DaylightDelta != TimeSpan.Zero) { start = TimeZoneInfo.TransitionTimeToDateTime(year, adjustmentRule.DaylightTransitionStart); end = TimeZoneInfo.TransitionTimeToDateTime(year, adjustmentRule.DaylightTransitionEnd); delta = adjustmentRule.DaylightDelta; break; } } } return new DaylightTime(start, end, delta); } public override TimeSpan GetUtcOffset(DateTime time) { if (time.Kind == DateTimeKind.Utc) { return TimeSpan.Zero; } return new TimeSpan(TimeZone.CalculateUtcOffset(time, GetDaylightChanges(time.Year)).Ticks + m_ticksOffset); } private DaylightTime GetCachedDaylightChanges(int year) { object key = year; if (!m_CachedDaylightChanges.Contains(key)) { DaylightTime value = CreateDaylightChanges(year); lock (m_CachedDaylightChanges) { if (!m_CachedDaylightChanges.Contains(key)) { m_CachedDaylightChanges.Add(key, value); } } } return (DaylightTime)m_CachedDaylightChanges[key]; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class DataMisalignedException : SystemException { public DataMisalignedException() : base(SR.Arg_DataMisalignedException) { base.HResult = -2146233023; } public DataMisalignedException(string? message) : base(message) { base.HResult = -2146233023; } public DataMisalignedException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233023; } private DataMisalignedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public readonly struct DateOnly : IComparable, IComparable, IEquatable, ISpanFormattable, IFormattable, IComparisonOperators, IEqualityOperators, IMinMaxValue, ISpanParseable, IParseable { private readonly int _dayNumber; public static DateOnly MinValue => new DateOnly(0); public static DateOnly MaxValue => new DateOnly(3652058); public int Year => GetEquivalentDateTime().Year; public int Month => GetEquivalentDateTime().Month; public int Day => GetEquivalentDateTime().Day; public DayOfWeek DayOfWeek => GetEquivalentDateTime().DayOfWeek; public int DayOfYear => GetEquivalentDateTime().DayOfYear; public int DayNumber => _dayNumber; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateOnly IMinMaxValue.MinValue => MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateOnly IMinMaxValue.MaxValue => MaxValue; private static int DayNumberFromDateTime(DateTime dt) { return (int)(dt.Ticks / 864000000000L); } private DateTime GetEquivalentDateTime() { return DateTime.UnsafeCreate(_dayNumber * 864000000000L); } private DateOnly(int dayNumber) { _dayNumber = dayNumber; } public DateOnly(int year, int month, int day) { _dayNumber = DayNumberFromDateTime(new DateTime(year, month, day)); } public DateOnly(int year, int month, int day, Calendar calendar) { _dayNumber = DayNumberFromDateTime(new DateTime(year, month, day, calendar)); } public static DateOnly FromDayNumber(int dayNumber) { if ((uint)dayNumber > 3652058u) { ThrowHelper.ThrowArgumentOutOfRange_DayNumber(dayNumber); } return new DateOnly(dayNumber); } public DateOnly AddDays(int value) { int num = _dayNumber + value; if ((uint)num > 3652058u) { ThrowOutOfRange(); } return new DateOnly(num); static void ThrowOutOfRange() { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_AddValue); } } public DateOnly AddMonths(int value) { return new DateOnly(DayNumberFromDateTime(GetEquivalentDateTime().AddMonths(value))); } public DateOnly AddYears(int value) { return new DateOnly(DayNumberFromDateTime(GetEquivalentDateTime().AddYears(value))); } public static bool operator ==(DateOnly left, DateOnly right) { return left._dayNumber == right._dayNumber; } public static bool operator !=(DateOnly left, DateOnly right) { return left._dayNumber != right._dayNumber; } public static bool operator >(DateOnly left, DateOnly right) { return left._dayNumber > right._dayNumber; } public static bool operator >=(DateOnly left, DateOnly right) { return left._dayNumber >= right._dayNumber; } public static bool operator <(DateOnly left, DateOnly right) { return left._dayNumber < right._dayNumber; } public static bool operator <=(DateOnly left, DateOnly right) { return left._dayNumber <= right._dayNumber; } public DateTime ToDateTime(TimeOnly time) { return new DateTime(_dayNumber * 864000000000L + time.Ticks); } public DateTime ToDateTime(TimeOnly time, DateTimeKind kind) { return new DateTime(_dayNumber * 864000000000L + time.Ticks, kind); } public static DateOnly FromDateTime(DateTime dateTime) { return new DateOnly(DayNumberFromDateTime(dateTime)); } public int CompareTo(DateOnly value) { return _dayNumber.CompareTo(value._dayNumber); } public int CompareTo(object? value) { if (value == null) { return 1; } if (!(value is DateOnly value2)) { throw new ArgumentException(SR.Arg_MustBeDateOnly); } return CompareTo(value2); } public bool Equals(DateOnly value) { return _dayNumber == value._dayNumber; } public override bool Equals([NotNullWhen(true)] object? value) { if (value is DateOnly dateOnly) { return _dayNumber == dateOnly._dayNumber; } return false; } public override int GetHashCode() { return _dayNumber; } public static DateOnly Parse(ReadOnlySpan s, IFormatProvider? provider = null, DateTimeStyles style = DateTimeStyles.None) { DateOnly result; ParseFailureKind parseFailureKind = TryParseInternal(s, provider, style, out result); if (parseFailureKind != 0) { ThrowOnError(parseFailureKind, s); } return result; } public static DateOnly ParseExact(ReadOnlySpan s, ReadOnlySpan format, IFormatProvider? provider = null, DateTimeStyles style = DateTimeStyles.None) { DateOnly result; ParseFailureKind parseFailureKind = TryParseExactInternal(s, format, provider, style, out result); if (parseFailureKind != 0) { ThrowOnError(parseFailureKind, s); } return result; } public static DateOnly ParseExact(ReadOnlySpan s, string[] formats) { return ParseExact(s, formats, null); } public static DateOnly ParseExact(ReadOnlySpan s, string[] formats, IFormatProvider? provider, DateTimeStyles style = DateTimeStyles.None) { DateOnly result; ParseFailureKind parseFailureKind = TryParseExactInternal(s, formats, provider, style, out result); if (parseFailureKind != 0) { ThrowOnError(parseFailureKind, s); } return result; } public static DateOnly Parse(string s) { return Parse(s, null); } public static DateOnly Parse(string s, IFormatProvider? provider, DateTimeStyles style = DateTimeStyles.None) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse(s.AsSpan(), provider, style); } public static DateOnly ParseExact(string s, string format) { return ParseExact(s, format, null); } public static DateOnly ParseExact(string s, string format, IFormatProvider? provider, DateTimeStyles style = DateTimeStyles.None) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if (format == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); } return ParseExact(s.AsSpan(), format.AsSpan(), provider, style); } public static DateOnly ParseExact(string s, string[] formats) { return ParseExact(s, formats, null); } public static DateOnly ParseExact(string s, string[] formats, IFormatProvider? provider, DateTimeStyles style = DateTimeStyles.None) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return ParseExact(s.AsSpan(), formats, provider, style); } public static bool TryParse(ReadOnlySpan s, out DateOnly result) { return TryParse(s, null, DateTimeStyles.None, out result); } public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, DateTimeStyles style, out DateOnly result) { return TryParseInternal(s, provider, style, out result) == ParseFailureKind.None; } private static ParseFailureKind TryParseInternal(ReadOnlySpan s, IFormatProvider provider, DateTimeStyles style, out DateOnly result) { if (((uint)style & 0xFFFFFFF8u) != 0) { result = default(DateOnly); return ParseFailureKind.FormatWithParameter; } DateTimeResult result2 = default(DateTimeResult); result2.Init(s); if (!DateTimeParse.TryParse(s, DateTimeFormatInfo.GetInstance(provider), style, ref result2)) { result = default(DateOnly); return ParseFailureKind.FormatWithOriginalDateTime; } if ((result2.flags & (ParseFlags.HaveHour | ParseFlags.HaveMinute | ParseFlags.HaveSecond | ParseFlags.HaveTime | ParseFlags.TimeZoneUsed | ParseFlags.TimeZoneUtc | ParseFlags.CaptureOffset | ParseFlags.UtcSortPattern)) != 0) { result = default(DateOnly); return ParseFailureKind.WrongParts; } result = new DateOnly(DayNumberFromDateTime(result2.parsedDate)); return ParseFailureKind.None; } public static bool TryParseExact(ReadOnlySpan s, ReadOnlySpan format, out DateOnly result) { return TryParseExact(s, format, null, DateTimeStyles.None, out result); } public static bool TryParseExact(ReadOnlySpan s, ReadOnlySpan format, IFormatProvider? provider, DateTimeStyles style, out DateOnly result) { return TryParseExactInternal(s, format, provider, style, out result) == ParseFailureKind.None; } private static ParseFailureKind TryParseExactInternal(ReadOnlySpan s, ReadOnlySpan format, IFormatProvider provider, DateTimeStyles style, out DateOnly result) { if (((uint)style & 0xFFFFFFF8u) != 0) { result = default(DateOnly); return ParseFailureKind.FormatWithParameter; } if (format.Length == 1) { switch (format[0]) { case 'O': case 'o': format = "yyyy'-'MM'-'dd"; provider = CultureInfo.InvariantCulture.DateTimeFormat; break; case 'R': case 'r': format = "ddd, dd MMM yyyy"; provider = CultureInfo.InvariantCulture.DateTimeFormat; break; } } DateTimeResult result2 = default(DateTimeResult); result2.Init(s); if (!DateTimeParse.TryParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style, ref result2)) { result = default(DateOnly); return ParseFailureKind.FormatWithOriginalDateTime; } if ((result2.flags & (ParseFlags.HaveHour | ParseFlags.HaveMinute | ParseFlags.HaveSecond | ParseFlags.HaveTime | ParseFlags.TimeZoneUsed | ParseFlags.TimeZoneUtc | ParseFlags.CaptureOffset | ParseFlags.UtcSortPattern)) != 0) { result = default(DateOnly); return ParseFailureKind.WrongParts; } result = new DateOnly(DayNumberFromDateTime(result2.parsedDate)); return ParseFailureKind.None; } public static bool TryParseExact(ReadOnlySpan s, [NotNullWhen(true)] string?[]? formats, out DateOnly result) { return TryParseExact(s, formats, null, DateTimeStyles.None, out result); } public static bool TryParseExact(ReadOnlySpan s, [NotNullWhen(true)] string?[]? formats, IFormatProvider? provider, DateTimeStyles style, out DateOnly result) { return TryParseExactInternal(s, formats, provider, style, out result) == ParseFailureKind.None; } private static ParseFailureKind TryParseExactInternal(ReadOnlySpan s, string[] formats, IFormatProvider provider, DateTimeStyles style, out DateOnly result) { if (((uint)style & 0xFFFFFFF8u) != 0 || formats == null) { result = default(DateOnly); return ParseFailureKind.FormatWithParameter; } DateTimeFormatInfo instance = DateTimeFormatInfo.GetInstance(provider); for (int i = 0; i < formats.Length; i++) { DateTimeFormatInfo dtfi = instance; string text = formats[i]; if (string.IsNullOrEmpty(text)) { result = default(DateOnly); return ParseFailureKind.FormatWithFormatSpecifier; } if (text.Length == 1) { switch (text[0]) { case 'O': case 'o': text = "yyyy'-'MM'-'dd"; dtfi = CultureInfo.InvariantCulture.DateTimeFormat; break; case 'R': case 'r': text = "ddd, dd MMM yyyy"; dtfi = CultureInfo.InvariantCulture.DateTimeFormat; break; } } DateTimeResult result2 = default(DateTimeResult); result2.Init(s); if (DateTimeParse.TryParseExact(s, text, dtfi, style, ref result2) && (result2.flags & (ParseFlags.HaveHour | ParseFlags.HaveMinute | ParseFlags.HaveSecond | ParseFlags.HaveTime | ParseFlags.TimeZoneUsed | ParseFlags.TimeZoneUtc | ParseFlags.CaptureOffset | ParseFlags.UtcSortPattern)) == 0) { result = new DateOnly(DayNumberFromDateTime(result2.parsedDate)); return ParseFailureKind.None; } } result = default(DateOnly); return ParseFailureKind.FormatWithOriginalDateTime; } public static bool TryParse([NotNullWhen(true)] string? s, out DateOnly result) { return TryParse(s, null, DateTimeStyles.None, out result); } public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, DateTimeStyles style, out DateOnly result) { if (s == null) { result = default(DateOnly); return false; } return TryParse(s.AsSpan(), provider, style, out result); } public static bool TryParseExact([NotNullWhen(true)] string? s, [NotNullWhen(true)] string? format, out DateOnly result) { return TryParseExact(s, format, null, DateTimeStyles.None, out result); } public static bool TryParseExact([NotNullWhen(true)] string? s, [NotNullWhen(true)] string? format, IFormatProvider? provider, DateTimeStyles style, out DateOnly result) { if (s == null || format == null) { result = default(DateOnly); return false; } return TryParseExact(s.AsSpan(), format.AsSpan(), provider, style, out result); } public static bool TryParseExact([NotNullWhen(true)] string? s, [NotNullWhen(true)] string?[]? formats, out DateOnly result) { return TryParseExact(s, formats, null, DateTimeStyles.None, out result); } public static bool TryParseExact([NotNullWhen(true)] string? s, [NotNullWhen(true)] string?[]? formats, IFormatProvider? provider, DateTimeStyles style, out DateOnly result) { if (s == null) { result = default(DateOnly); return false; } return TryParseExact(s.AsSpan(), formats, provider, style, out result); } private static void ThrowOnError(ParseFailureKind result, ReadOnlySpan s) { switch (result) { case ParseFailureKind.FormatWithParameter: throw new ArgumentException(SR.Argument_InvalidDateStyles, "style"); case ParseFailureKind.FormatWithOriginalDateTime: throw new FormatException(SR.Format(SR.Format_BadDateOnly, s.ToString())); case ParseFailureKind.FormatWithFormatSpecifier: throw new FormatException(SR.Argument_BadFormatSpecifier); default: throw new FormatException(SR.Format(SR.Format_DateTimeOnlyContainsNoneDateParts, s.ToString(), "DateOnly")); } } public string ToLongDateString() { return ToString("D"); } public string ToShortDateString() { return ToString(); } public override string ToString() { return ToString("d"); } public string ToString(string? format) { return ToString(format, null); } public string ToString(IFormatProvider? provider) { return ToString("d", provider); } public string ToString(string? format, IFormatProvider? provider) { if (format == null || format.Length == 0) { format = "d"; } if (format.Length == 1) { switch (format[0]) { case 'O': case 'o': return string.Create(10, this, delegate(Span destination, DateOnly value) { bool flag = DateTimeFormat.TryFormatDateOnlyO(value.Year, value.Month, value.Day, destination); }); case 'R': case 'r': return string.Create(16, this, delegate(Span destination, DateOnly value) { bool flag2 = DateTimeFormat.TryFormatDateOnlyR(value.DayOfWeek, value.Year, value.Month, value.Day, destination); }); case 'D': case 'M': case 'Y': case 'd': case 'm': case 'y': return DateTimeFormat.Format(GetEquivalentDateTime(), format, provider); default: throw new FormatException(SR.Format_InvalidString); } } DateTimeFormat.IsValidCustomDateFormat(format.AsSpan(), throwOnError: true); return DateTimeFormat.Format(GetEquivalentDateTime(), format, provider); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { if (format.Length == 0) { format = "d"; } if (format.Length == 1) { switch (format[0]) { case 'O': case 'o': if (!DateTimeFormat.TryFormatDateOnlyO(Year, Month, Day, destination)) { charsWritten = 0; return false; } charsWritten = 10; return true; case 'R': case 'r': if (!DateTimeFormat.TryFormatDateOnlyR(DayOfWeek, Year, Month, Day, destination)) { charsWritten = 0; return false; } charsWritten = 16; return true; case 'D': case 'M': case 'Y': case 'd': case 'm': case 'y': return DateTimeFormat.TryFormat(GetEquivalentDateTime(), destination, out charsWritten, format, provider); default: throw new FormatException(SR.Argument_BadFormatSpecifier); } } if (!DateTimeFormat.IsValidCustomDateFormat(format, throwOnError: false)) { throw new FormatException(SR.Format(SR.Format_DateTimeOnlyContainsNoneDateParts, format.ToString(), "DateOnly")); } return DateTimeFormat.TryFormat(GetEquivalentDateTime(), destination, out charsWritten, format, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(DateOnly left, DateOnly right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(DateOnly left, DateOnly right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(DateOnly left, DateOnly right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(DateOnly left, DateOnly right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(DateOnly left, DateOnly right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(DateOnly left, DateOnly right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateOnly IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out DateOnly result) { return TryParse(s, provider, DateTimeStyles.None, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateOnly ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out DateOnly result) { return TryParse(s, provider, DateTimeStyles.None, out result); } } [Serializable] [StructLayout(LayoutKind.Auto)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct DateTime : IComparable, ISpanFormattable, IFormattable, IConvertible, IComparable, IEquatable, ISerializable, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IMinMaxValue, ISpanParseable, IParseable, ISubtractionOperators, ISubtractionOperators { private sealed class LeapSecondCache { internal ulong OSFileTimeTicksAtStartOfValidityWindow; internal ulong DotnetDateDataAtStartOfValidityWindow; } private static readonly uint[] s_daysToMonth365 = new uint[13] { 0u, 31u, 59u, 90u, 120u, 151u, 181u, 212u, 243u, 273u, 304u, 334u, 365u }; private static readonly uint[] s_daysToMonth366 = new uint[13] { 0u, 31u, 60u, 91u, 121u, 152u, 182u, 213u, 244u, 274u, 305u, 335u, 366u }; public static readonly DateTime MinValue; public static readonly DateTime MaxValue = new DateTime(3155378975999999999L, DateTimeKind.Unspecified); public static readonly DateTime UnixEpoch = new DateTime(621355968000000000L, DateTimeKind.Utc); private readonly ulong _dateData; internal static readonly bool s_systemSupportsLeapSeconds = SystemSupportsLeapSeconds(); private unsafe static readonly delegate* unmanaged[SuppressGCTransition] s_pfnGetSystemTimeAsFileTime = GetGetSystemTimeAsFileTimeFnPtr(); private static LeapSecondCache s_leapSecondCache = new LeapSecondCache(); private static ReadOnlySpan DaysInMonth365 => new byte[12] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; private static ReadOnlySpan DaysInMonth366 => new byte[12] { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; private ulong UTicks => _dateData & 0x3FFFFFFFFFFFFFFFuL; private ulong InternalKind => _dateData & 0xC000000000000000uL; public DateTime Date { get { ulong uTicks = UTicks; return new DateTime((uTicks - uTicks % 864000000000L) | InternalKind); } } public int Day => GetDatePart(3); public DayOfWeek DayOfWeek => (DayOfWeek)((uint)((int)(UTicks / 864000000000L) + 1) % 7u); public int DayOfYear => GetDatePart(1); public int Hour => (int)((uint)(UTicks / 36000000000L) % 24); public DateTimeKind Kind { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return InternalKind switch { 0uL => DateTimeKind.Unspecified, 4611686018427387904uL => DateTimeKind.Utc, _ => DateTimeKind.Local, }; } } public int Millisecond => (int)(UTicks / 10000 % 1000); public int Minute => (int)(UTicks / 600000000 % 60); public int Month => GetDatePart(2); public static DateTime Now { get { DateTime utcNow = UtcNow; bool isAmbiguousLocalDst; long ticks = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utcNow, out isAmbiguousLocalDst).Ticks; long num = utcNow.Ticks + ticks; if ((ulong)num <= 3155378975999999999uL) { if (!isAmbiguousLocalDst) { return new DateTime((ulong)num | 0x8000000000000000uL); } return new DateTime((ulong)num | 0xC000000000000000uL); } return new DateTime((num < 0) ? 9223372036854775808uL : 12378751012854775807uL); } } public int Second => (int)(UTicks / 10000000 % 60); public long Ticks => (long)(_dateData & 0x3FFFFFFFFFFFFFFFL); public TimeSpan TimeOfDay => new TimeSpan((long)(UTicks % 864000000000L)); public static DateTime Today => Now.Date; public int Year => GetDatePart(0); [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan IAdditiveIdentity.AdditiveIdentity => default(TimeSpan); [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateTime IMinMaxValue.MinValue => MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateTime IMinMaxValue.MaxValue => MaxValue; public unsafe static DateTime UtcNow { get { System.Runtime.CompilerServices.Unsafe.SkipInit(out ulong num); s_pfnGetSystemTimeAsFileTime(&num); ulong num2 = num; if (s_systemSupportsLeapSeconds) { LeapSecondCache leapSecondCache = s_leapSecondCache; ulong num3 = num2 - leapSecondCache.OSFileTimeTicksAtStartOfValidityWindow; if (num3 < 3000000000u) { return new DateTime(leapSecondCache.DotnetDateDataAtStartOfValidityWindow + num3); } return UpdateLeapSecondCacheAndReturnUtcNow(); } return new DateTime(num2 + 5116597250427387904L); } } public DateTime(long ticks) { if ((ulong)ticks > 3155378975999999999uL) { ThrowTicksOutOfRange(); } _dateData = (ulong)ticks; } private DateTime(ulong dateData) { _dateData = dateData; } internal static DateTime UnsafeCreate(long ticks) { return new DateTime((ulong)ticks); } public DateTime(long ticks, DateTimeKind kind) { if ((ulong)ticks > 3155378975999999999uL) { ThrowTicksOutOfRange(); } if ((uint)kind > 2u) { ThrowInvalidKind(); } _dateData = (ulong)ticks | ((ulong)(uint)kind << 62); } internal DateTime(long ticks, DateTimeKind kind, bool isAmbiguousDst) { if ((ulong)ticks > 3155378975999999999uL) { ThrowTicksOutOfRange(); } _dateData = (ulong)ticks | (isAmbiguousDst ? 13835058055282163712uL : 9223372036854775808uL); } private static void ThrowTicksOutOfRange() { throw new ArgumentOutOfRangeException("ticks", SR.ArgumentOutOfRange_DateTimeBadTicks); } private static void ThrowInvalidKind() { throw new ArgumentException(SR.Argument_InvalidDateTimeKind, "kind"); } private static void ThrowMillisecondOutOfRange() { throw new ArgumentOutOfRangeException("millisecond", SR.Format(SR.ArgumentOutOfRange_Range, 0, 999)); } private static void ThrowDateArithmetic(int param) { throw new ArgumentOutOfRangeException(param switch { 0 => "value", 1 => "t", _ => "months", }, SR.ArgumentOutOfRange_DateArithmetic); } public DateTime(int year, int month, int day) { _dateData = DateToTicks(year, month, day); } public DateTime(int year, int month, int day, Calendar calendar) : this(year, month, day, 0, 0, 0, calendar) { } public DateTime(int year, int month, int day, int hour, int minute, int second) { if (second != 60 || !s_systemSupportsLeapSeconds) { _dateData = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); return; } this = new DateTime(year, month, day, hour, minute, 59); ValidateLeapSecond(); } public DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind) { if ((uint)kind > 2u) { ThrowInvalidKind(); } if (second != 60 || !s_systemSupportsLeapSeconds) { ulong num = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); _dateData = num | (ulong)((long)kind << 62); } else { this = new DateTime(year, month, day, hour, minute, 59, kind); ValidateLeapSecond(); } } public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar) { if (calendar == null) { throw new ArgumentNullException("calendar"); } if (second != 60 || !s_systemSupportsLeapSeconds) { _dateData = calendar.ToDateTime(year, month, day, hour, minute, second, 0).UTicks; return; } this = new DateTime(year, month, day, hour, minute, 59, calendar); ValidateLeapSecond(); } public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { if ((uint)millisecond >= 1000u) { ThrowMillisecondOutOfRange(); } if (second != 60 || !s_systemSupportsLeapSeconds) { ulong num = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); num += (uint)(millisecond * 10000); _dateData = num; } else { this = new DateTime(year, month, day, hour, minute, 59, millisecond); ValidateLeapSecond(); } } public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind) { if ((uint)millisecond >= 1000u) { ThrowMillisecondOutOfRange(); } if ((uint)kind > 2u) { ThrowInvalidKind(); } if (second != 60 || !s_systemSupportsLeapSeconds) { ulong num = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second); num += (uint)(millisecond * 10000); _dateData = num | (ulong)((long)kind << 62); } else { this = new DateTime(year, month, day, hour, minute, 59, millisecond, kind); ValidateLeapSecond(); } } public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar) { if (calendar == null) { throw new ArgumentNullException("calendar"); } if (second != 60 || !s_systemSupportsLeapSeconds) { _dateData = calendar.ToDateTime(year, month, day, hour, minute, second, millisecond).UTicks; return; } this = new DateTime(year, month, day, hour, minute, 59, millisecond, calendar); ValidateLeapSecond(); } public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, DateTimeKind kind) { if (calendar == null) { throw new ArgumentNullException("calendar"); } if ((uint)millisecond >= 1000u) { ThrowMillisecondOutOfRange(); } if ((uint)kind > 2u) { ThrowInvalidKind(); } if (second != 60 || !s_systemSupportsLeapSeconds) { ulong uTicks = calendar.ToDateTime(year, month, day, hour, minute, second, millisecond).UTicks; _dateData = uTicks | (ulong)((long)kind << 62); } else { this = new DateTime(year, month, day, hour, minute, 59, millisecond, calendar, kind); ValidateLeapSecond(); } } private void ValidateLeapSecond() { if (!IsValidTimeWithLeapSeconds(Year, Month, Day, Hour, Minute, Kind)) { ThrowHelper.ThrowArgumentOutOfRange_BadHourMinuteSecond(); } } private DateTime(SerializationInfo info, StreamingContext context) { if (info == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info); } bool flag = false; SerializationInfoEnumerator enumerator = info.GetEnumerator(); while (true) { if (enumerator.MoveNext()) { string name = enumerator.Name; if (!(name == "ticks")) { if (name == "dateData") { _dateData = Convert.ToUInt64(enumerator.Value, CultureInfo.InvariantCulture); break; } } else { _dateData = (ulong)Convert.ToInt64(enumerator.Value, CultureInfo.InvariantCulture); flag = true; } continue; } if (flag) { break; } throw new SerializationException(SR.Serialization_MissingDateTimeData); } if (UTicks > 3155378975999999999L) { throw new SerializationException(SR.Serialization_DateTimeTicksOutOfRange); } } public DateTime Add(TimeSpan value) { return AddTicks(value._ticks); } private DateTime Add(double value, int scale) { double num = value * (double)scale + ((value >= 0.0) ? 0.5 : (-0.5)); if (num <= -315537897600000.0 || num >= 315537897600000.0) { ThrowOutOfRange(); } return AddTicks((long)num * 10000); static void ThrowOutOfRange() { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_AddValue); } } public DateTime AddDays(double value) { return Add(value, 86400000); } public DateTime AddHours(double value) { return Add(value, 3600000); } public DateTime AddMilliseconds(double value) { return Add(value, 1); } public DateTime AddMinutes(double value) { return Add(value, 60000); } public DateTime AddMonths(int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException("months", SR.ArgumentOutOfRange_DateTimeBadMonths); } GetDate(out var year, out var month, out var day); int num = year; int num2 = day; int num3 = month + months; if (num3 > 0) { int num4 = (int)((uint)(num3 - 1) / 12u); num += num4; num3 -= num4 * 12; } else { num += num3 / 12 - 1; num3 = 12 + num3 % 12; } if (num < 1 || num > 9999) { ThrowDateArithmetic(2); } uint[] array = (IsLeapYear(num) ? s_daysToMonth366 : s_daysToMonth365); uint num5 = array[num3 - 1]; int num6 = (int)(array[num3] - num5); if (num2 > num6) { num2 = num6; } uint num7 = (uint)((int)(DaysToYear((uint)num) + num5) + num2 - 1); return new DateTime(((ulong)((long)num7 * 864000000000L) + UTicks % 864000000000L) | InternalKind); } public DateTime AddSeconds(double value) { return Add(value, 1000); } public DateTime AddTicks(long value) { ulong num = (ulong)(Ticks + value); if (num > 3155378975999999999L) { ThrowDateArithmetic(0); } return new DateTime(num | InternalKind); } internal bool TryAddTicks(long value, out DateTime result) { ulong num = (ulong)(Ticks + value); if (num > 3155378975999999999L) { result = default(DateTime); return false; } result = new DateTime(num | InternalKind); return true; } public DateTime AddYears(int value) { if (value < -10000 || value > 10000) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_DateTimeBadYears); } GetDate(out var year, out var month, out var day); int num = year + value; if (num < 1 || num > 9999) { ThrowDateArithmetic(0); } uint num2 = DaysToYear((uint)num); int num3 = month - 1; int num4 = day - 1; if (IsLeapYear(num)) { num2 += s_daysToMonth366[num3]; } else { if (num4 == 28 && num3 == 1) { num4--; } num2 += s_daysToMonth365[num3]; } num2 += (uint)num4; return new DateTime(((ulong)((long)num2 * 864000000000L) + UTicks % 864000000000L) | InternalKind); } public static int Compare(DateTime t1, DateTime t2) { long ticks = t1.Ticks; long ticks2 = t2.Ticks; if (ticks > ticks2) { return 1; } if (ticks < ticks2) { return -1; } return 0; } public int CompareTo(object? value) { if (value == null) { return 1; } if (!(value is DateTime)) { throw new ArgumentException(SR.Arg_MustBeDateTime); } return Compare(this, (DateTime)value); } public int CompareTo(DateTime value) { return Compare(this, value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ulong DateToTicks(int year, int month, int day) { if (year < 1 || year > 9999 || month < 1 || month > 12 || day < 1) { ThrowHelper.ThrowArgumentOutOfRange_BadYearMonthDay(); } uint[] array = (IsLeapYear(year) ? s_daysToMonth366 : s_daysToMonth365); if ((uint)day > array[month] - array[month - 1]) { ThrowHelper.ThrowArgumentOutOfRange_BadYearMonthDay(); } uint num = (uint)((int)(DaysToYear((uint)year) + array[month - 1]) + day - 1); return (ulong)num * 864000000000uL; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint DaysToYear(uint year) { uint num = year - 1; uint num2 = num / 100; return num * 1461 / 4 - num2 + num2 / 4; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ulong TimeToTicks(int hour, int minute, int second) { if ((uint)hour >= 24u || (uint)minute >= 60u || (uint)second >= 60u) { ThrowHelper.ThrowArgumentOutOfRange_BadHourMinuteSecond(); } int num = hour * 3600 + minute * 60 + second; return (ulong)(uint)num * 10000000uL; } internal static ulong TimeToTicks(int hour, int minute, int second, int millisecond) { ulong num = TimeToTicks(hour, minute, second); if ((uint)millisecond >= 1000u) { ThrowMillisecondOutOfRange(); } return num + (uint)(millisecond * 10000); } public static int DaysInMonth(int year, int month) { if (month < 1 || month > 12) { ThrowHelper.ThrowArgumentOutOfRange_Month(month); } return (IsLeapYear(year) ? DaysInMonth366 : DaysInMonth365)[month - 1]; } internal static long DoubleDateToTicks(double value) { if (!(value < 2958466.0) || !(value > -657435.0)) { throw new ArgumentException(SR.Arg_OleAutDateInvalid); } long num = (long)(value * 86400000.0 + ((value >= 0.0) ? 0.5 : (-0.5))); if (num < 0) { num -= num % 86400000 * 2; } num += 59926435200000L; if (num < 0 || num >= 315537897600000L) { throw new ArgumentException(SR.Arg_OleAutDateScale); } return num * 10000; } public override bool Equals([NotNullWhen(true)] object? value) { if (value is DateTime) { return Ticks == ((DateTime)value).Ticks; } return false; } public bool Equals(DateTime value) { return Ticks == value.Ticks; } public static bool Equals(DateTime t1, DateTime t2) { return t1.Ticks == t2.Ticks; } public static DateTime FromBinary(long dateData) { if ((dateData & long.MinValue) != 0L) { long num = dateData & 0x3FFFFFFFFFFFFFFFL; if (num > 4611685154427387904L) { num -= 4611686018427387904L; } bool isAmbiguousLocalDst = false; long ticks; if (num < 0) { ticks = TimeZoneInfo.GetLocalUtcOffset(MinValue, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks; } else if (num > 3155378975999999999L) { ticks = TimeZoneInfo.GetLocalUtcOffset(MaxValue, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks; } else { DateTime time = new DateTime(num, DateTimeKind.Utc); ticks = TimeZoneInfo.GetUtcOffsetFromUtc(time, TimeZoneInfo.Local, out var _, out isAmbiguousLocalDst).Ticks; } num += ticks; if (num < 0) { num += 864000000000L; } if ((ulong)num > 3155378975999999999uL) { throw new ArgumentException(SR.Argument_DateTimeBadBinaryData, "dateData"); } return new DateTime(num, DateTimeKind.Local, isAmbiguousLocalDst); } if ((ulong)(dateData & 0x3FFFFFFFFFFFFFFFL) > 3155378975999999999uL) { throw new ArgumentException(SR.Argument_DateTimeBadBinaryData, "dateData"); } return new DateTime((ulong)dateData); } public static DateTime FromFileTime(long fileTime) { return FromFileTimeUtc(fileTime).ToLocalTime(); } public static DateTime FromFileTimeUtc(long fileTime) { if ((ulong)fileTime > 2650467743999999999uL) { throw new ArgumentOutOfRangeException("fileTime", SR.ArgumentOutOfRange_FileTimeInvalid); } if (s_systemSupportsLeapSeconds) { return FromFileTimeLeapSecondsAware((ulong)fileTime); } ulong num = (ulong)(fileTime + 504911232000000000L); return new DateTime(num | 0x4000000000000000uL); } public static DateTime FromOADate(double d) { return new DateTime(DoubleDateToTicks(d), DateTimeKind.Unspecified); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.info); } info.AddValue("ticks", Ticks); info.AddValue("dateData", _dateData); } public bool IsDaylightSavingTime() { if (InternalKind == 4611686018427387904L) { return false; } return TimeZoneInfo.Local.IsDaylightSavingTime(this, TimeZoneInfoOptions.NoThrowOnInvalidTime); } public static DateTime SpecifyKind(DateTime value, DateTimeKind kind) { if ((uint)kind > 2u) { ThrowInvalidKind(); } return new DateTime(value.UTicks | (ulong)((long)kind << 62)); } public long ToBinary() { if ((_dateData & 0x8000000000000000uL) != 0L) { TimeSpan localUtcOffset = TimeZoneInfo.GetLocalUtcOffset(this, TimeZoneInfoOptions.NoThrowOnInvalidTime); long ticks = Ticks; long num = ticks - localUtcOffset.Ticks; if (num < 0) { num = 4611686018427387904L + num; } return num | long.MinValue; } return (long)_dateData; } private int GetDatePart(int part) { uint num = (uint)(UTicks / 864000000000L); uint num2 = num / 146097; num -= num2 * 146097; uint num3 = num / 36524; if (num3 == 4) { num3 = 3u; } num -= num3 * 36524; uint num4 = num / 1461; num -= num4 * 1461; uint num5 = num / 365; if (num5 == 4) { num5 = 3u; } if (part == 0) { return (int)(num2 * 400 + num3 * 100 + num4 * 4 + num5 + 1); } num -= num5 * 365; if (part == 1) { return (int)(num + 1); } uint[] array = ((num5 == 3 && (num4 != 24 || num3 == 3)) ? s_daysToMonth366 : s_daysToMonth365); uint num6; for (num6 = (num >> 5) + 1; num >= array[num6]; num6++) { } if (part == 2) { return (int)num6; } return (int)(num - array[num6 - 1] + 1); } internal void GetDate(out int year, out int month, out int day) { uint num = (uint)(UTicks / 864000000000L); uint num2 = num / 146097; num -= num2 * 146097; uint num3 = num / 36524; if (num3 == 4) { num3 = 3u; } num -= num3 * 36524; uint num4 = num / 1461; num -= num4 * 1461; uint num5 = num / 365; if (num5 == 4) { num5 = 3u; } year = (int)(num2 * 400 + num3 * 100 + num4 * 4 + num5 + 1); num -= num5 * 365; uint[] array = ((num5 == 3 && (num4 != 24 || num3 == 3)) ? s_daysToMonth366 : s_daysToMonth365); uint num6; for (num6 = (num >> 5) + 1; num >= array[num6]; num6++) { } month = (int)num6; day = (int)(num - array[num6 - 1] + 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void GetTime(out int hour, out int minute, out int second) { ulong num = UTicks / 10000000; ulong num2 = num / 60; second = (int)(num - num2 * 60); ulong num3 = num2 / 60; minute = (int)(num2 - num3 * 60); hour = (int)((uint)num3 % 24); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void GetTime(out int hour, out int minute, out int second, out int millisecond) { ulong num = UTicks / 10000; ulong num2 = num / 1000; millisecond = (int)(num - num2 * 1000); ulong num3 = num2 / 60; second = (int)(num2 - num3 * 60); ulong num4 = num3 / 60; minute = (int)(num3 - num4 * 60); hour = (int)((uint)num4 % 24); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void GetTimePrecise(out int hour, out int minute, out int second, out int tick) { ulong uTicks = UTicks; ulong num = uTicks / 10000000; tick = (int)(uTicks - num * 10000000); ulong num2 = num / 60; second = (int)(num - num2 * 60); ulong num3 = num2 / 60; minute = (int)(num2 - num3 * 60); hour = (int)((uint)num3 % 24); } public override int GetHashCode() { long ticks = Ticks; return (int)ticks ^ (int)(ticks >> 32); } internal bool IsAmbiguousDaylightSavingTime() { return InternalKind == 13835058055282163712uL; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsLeapYear(int year) { if (year < 1 || year > 9999) { ThrowHelper.ThrowArgumentOutOfRange_Year(); } if (((uint)year & 3u) != 0) { return false; } if ((year & 0xF) == 0) { return true; } if ((uint)year % 25u == 0) { return false; } return true; } public static DateTime Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return DateTimeParse.Parse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None); } public static DateTime Parse(string s, IFormatProvider? provider) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), DateTimeStyles.None); } public static DateTime Parse(string s, IFormatProvider? provider, DateTimeStyles styles) { DateTimeFormatInfo.ValidateStyles(styles, styles: true); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), styles); } public static DateTime Parse(ReadOnlySpan s, IFormatProvider? provider = null, DateTimeStyles styles = DateTimeStyles.None) { DateTimeFormatInfo.ValidateStyles(styles, styles: true); return DateTimeParse.Parse(s, DateTimeFormatInfo.GetInstance(provider), styles); } public static DateTime ParseExact(string s, string format, IFormatProvider? provider) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if (format == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); } return DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), DateTimeStyles.None); } public static DateTime ParseExact(string s, string format, IFormatProvider? provider, DateTimeStyles style) { DateTimeFormatInfo.ValidateStyles(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if (format == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); } return DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style); } public static DateTime ParseExact(ReadOnlySpan s, ReadOnlySpan format, IFormatProvider? provider, DateTimeStyles style = DateTimeStyles.None) { DateTimeFormatInfo.ValidateStyles(style); return DateTimeParse.ParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style); } public static DateTime ParseExact(string s, string[] formats, IFormatProvider? provider, DateTimeStyles style) { DateTimeFormatInfo.ValidateStyles(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return DateTimeParse.ParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style); } public static DateTime ParseExact(ReadOnlySpan s, string[] formats, IFormatProvider? provider, DateTimeStyles style = DateTimeStyles.None) { DateTimeFormatInfo.ValidateStyles(style); return DateTimeParse.ParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style); } public TimeSpan Subtract(DateTime value) { return new TimeSpan(Ticks - value.Ticks); } public DateTime Subtract(TimeSpan value) { ulong num = (ulong)(Ticks - value._ticks); if (num > 3155378975999999999L) { ThrowDateArithmetic(0); } return new DateTime(num | InternalKind); } private static double TicksToOADate(long value) { if (value == 0L) { return 0.0; } if (value < 864000000000L) { value += 599264352000000000L; } if (value < 31241376000000000L) { throw new OverflowException(SR.Arg_OleAutDateInvalid); } long num = (value - 599264352000000000L) / 10000; if (num < 0) { long num2 = num % 86400000; if (num2 != 0L) { num -= (86400000 + num2) * 2; } } return (double)num / 86400000.0; } public double ToOADate() { return TicksToOADate(Ticks); } public long ToFileTime() { return ToUniversalTime().ToFileTimeUtc(); } public long ToFileTimeUtc() { long num = (((_dateData & 0x8000000000000000uL) != 0L) ? ToUniversalTime().Ticks : Ticks); if (s_systemSupportsLeapSeconds) { return (long)ToFileTimeLeapSecondsAware(num); } num -= 504911232000000000L; if (num < 0) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_FileTimeInvalid); } return num; } public DateTime ToLocalTime() { if ((_dateData & 0x8000000000000000uL) != 0L) { return this; } bool isDaylightSavings; bool isAmbiguousLocalDst; long ticks = TimeZoneInfo.GetUtcOffsetFromUtc(this, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst).Ticks; long num = Ticks + ticks; if ((ulong)num <= 3155378975999999999uL) { if (!isAmbiguousLocalDst) { return new DateTime((ulong)num | 0x8000000000000000uL); } return new DateTime((ulong)num | 0xC000000000000000uL); } return new DateTime((num < 0) ? 9223372036854775808uL : 12378751012854775807uL); } public string ToLongDateString() { return DateTimeFormat.Format(this, "D", null); } public string ToLongTimeString() { return DateTimeFormat.Format(this, "T", null); } public string ToShortDateString() { return DateTimeFormat.Format(this, "d", null); } public string ToShortTimeString() { return DateTimeFormat.Format(this, "t", null); } public override string ToString() { return DateTimeFormat.Format(this, null, null); } public string ToString(string? format) { return DateTimeFormat.Format(this, format, null); } public string ToString(IFormatProvider? provider) { return DateTimeFormat.Format(this, null, provider); } public string ToString(string? format, IFormatProvider? provider) { return DateTimeFormat.Format(this, format, provider); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return DateTimeFormat.TryFormat(this, destination, out charsWritten, format, provider); } public DateTime ToUniversalTime() { return TimeZoneInfo.ConvertTimeToUtc(this, TimeZoneInfoOptions.NoThrowOnInvalidTime); } public static bool TryParse([NotNullWhen(true)] string? s, out DateTime result) { if (s == null) { result = default(DateTime); return false; } return DateTimeParse.TryParse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out result); } public static bool TryParse(ReadOnlySpan s, out DateTime result) { return DateTimeParse.TryParse(s, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out result); } public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, DateTimeStyles styles, out DateTime result) { DateTimeFormatInfo.ValidateStyles(styles, styles: true); if (s == null) { result = default(DateTime); return false; } return DateTimeParse.TryParse(s, DateTimeFormatInfo.GetInstance(provider), styles, out result); } public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, DateTimeStyles styles, out DateTime result) { DateTimeFormatInfo.ValidateStyles(styles, styles: true); return DateTimeParse.TryParse(s, DateTimeFormatInfo.GetInstance(provider), styles, out result); } public static bool TryParseExact([NotNullWhen(true)] string? s, [NotNullWhen(true)] string? format, IFormatProvider? provider, DateTimeStyles style, out DateTime result) { DateTimeFormatInfo.ValidateStyles(style); if (s == null || format == null) { result = default(DateTime); return false; } return DateTimeParse.TryParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style, out result); } public static bool TryParseExact(ReadOnlySpan s, ReadOnlySpan format, IFormatProvider? provider, DateTimeStyles style, out DateTime result) { DateTimeFormatInfo.ValidateStyles(style); return DateTimeParse.TryParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style, out result); } public static bool TryParseExact([NotNullWhen(true)] string? s, [NotNullWhen(true)] string?[]? formats, IFormatProvider? provider, DateTimeStyles style, out DateTime result) { DateTimeFormatInfo.ValidateStyles(style); if (s == null) { result = default(DateTime); return false; } return DateTimeParse.TryParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style, out result); } public static bool TryParseExact(ReadOnlySpan s, [NotNullWhen(true)] string?[]? formats, IFormatProvider? provider, DateTimeStyles style, out DateTime result) { DateTimeFormatInfo.ValidateStyles(style); return DateTimeParse.TryParseExactMultiple(s, formats, DateTimeFormatInfo.GetInstance(provider), style, out result); } public static DateTime operator +(DateTime d, TimeSpan t) { ulong num = (ulong)(d.Ticks + t._ticks); if (num > 3155378975999999999L) { ThrowDateArithmetic(1); } return new DateTime(num | d.InternalKind); } public static DateTime operator -(DateTime d, TimeSpan t) { ulong num = (ulong)(d.Ticks - t._ticks); if (num > 3155378975999999999L) { ThrowDateArithmetic(1); } return new DateTime(num | d.InternalKind); } public static TimeSpan operator -(DateTime d1, DateTime d2) { return new TimeSpan(d1.Ticks - d2.Ticks); } public static bool operator ==(DateTime d1, DateTime d2) { return d1.Ticks == d2.Ticks; } public static bool operator !=(DateTime d1, DateTime d2) { return d1.Ticks != d2.Ticks; } public static bool operator <(DateTime t1, DateTime t2) { return t1.Ticks < t2.Ticks; } public static bool operator <=(DateTime t1, DateTime t2) { return t1.Ticks <= t2.Ticks; } public static bool operator >(DateTime t1, DateTime t2) { return t1.Ticks > t2.Ticks; } public static bool operator >=(DateTime t1, DateTime t2) { return t1.Ticks >= t2.Ticks; } public string[] GetDateTimeFormats() { return GetDateTimeFormats(CultureInfo.CurrentCulture); } public string[] GetDateTimeFormats(IFormatProvider? provider) { return DateTimeFormat.GetAllDateTimes(this, DateTimeFormatInfo.GetInstance(provider)); } public string[] GetDateTimeFormats(char format) { return GetDateTimeFormats(format, CultureInfo.CurrentCulture); } public string[] GetDateTimeFormats(char format, IFormatProvider? provider) { return DateTimeFormat.GetAllDateTimes(this, format, DateTimeFormatInfo.GetInstance(provider)); } public TypeCode GetTypeCode() { return TypeCode.DateTime; } bool IConvertible.ToBoolean(IFormatProvider provider) { throw InvalidCast("Boolean"); } char IConvertible.ToChar(IFormatProvider provider) { throw InvalidCast("Char"); } sbyte IConvertible.ToSByte(IFormatProvider provider) { throw InvalidCast("SByte"); } byte IConvertible.ToByte(IFormatProvider provider) { throw InvalidCast("Byte"); } short IConvertible.ToInt16(IFormatProvider provider) { throw InvalidCast("Int16"); } ushort IConvertible.ToUInt16(IFormatProvider provider) { throw InvalidCast("UInt16"); } int IConvertible.ToInt32(IFormatProvider provider) { throw InvalidCast("Int32"); } uint IConvertible.ToUInt32(IFormatProvider provider) { throw InvalidCast("UInt32"); } long IConvertible.ToInt64(IFormatProvider provider) { throw InvalidCast("Int64"); } ulong IConvertible.ToUInt64(IFormatProvider provider) { throw InvalidCast("UInt64"); } float IConvertible.ToSingle(IFormatProvider provider) { throw InvalidCast("Single"); } double IConvertible.ToDouble(IFormatProvider provider) { throw InvalidCast("Double"); } decimal IConvertible.ToDecimal(IFormatProvider provider) { throw InvalidCast("Decimal"); } private static Exception InvalidCast(string to) { return new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "DateTime", to)); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { return this; } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } internal static bool TryCreate(int year, int month, int day, int hour, int minute, int second, int millisecond, out DateTime result) { result = default(DateTime); if (year < 1 || year > 9999 || month < 1 || month > 12 || day < 1) { return false; } if ((uint)hour >= 24u || (uint)minute >= 60u || (uint)millisecond >= 1000u) { return false; } uint[] array = (IsLeapYear(year) ? s_daysToMonth366 : s_daysToMonth365); if ((uint)day > array[month] - array[month - 1]) { return false; } ulong num = (ulong)(uint)((int)(DaysToYear((uint)year) + array[month - 1]) + day - 1) * 864000000000uL; if ((uint)second < 60u) { num += TimeToTicks(hour, minute, second) + (uint)(millisecond * 10000); } else { if (second != 60 || !s_systemSupportsLeapSeconds || !IsValidTimeWithLeapSeconds(year, month, day, hour, minute, DateTimeKind.Unspecified)) { return false; } num += TimeToTicks(hour, minute, 59) + 9990000; } result = new DateTime(num); return true; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateTime IAdditionOperators.op_Addition(DateTime left, TimeSpan right) { return left + right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(DateTime left, DateTime right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(DateTime left, DateTime right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(DateTime left, DateTime right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(DateTime left, DateTime right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(DateTime left, DateTime right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(DateTime left, DateTime right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateTime IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out DateTime result) { return TryParse(s, provider, DateTimeStyles.None, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateTime ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out DateTime result) { return TryParse(s, provider, DateTimeStyles.None, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateTime ISubtractionOperators.op_Subtraction(DateTime left, TimeSpan right) { return left - right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan ISubtractionOperators.op_Subtraction(DateTime left, DateTime right) { return left - right; } private unsafe static bool SystemSupportsLeapSeconds() { System.Runtime.CompilerServices.Unsafe.SkipInit(out Interop.NtDll.SYSTEM_LEAP_SECOND_INFORMATION sYSTEM_LEAP_SECOND_INFORMATION); if (Interop.NtDll.NtQuerySystemInformation(206, &sYSTEM_LEAP_SECOND_INFORMATION, (uint)sizeof(Interop.NtDll.SYSTEM_LEAP_SECOND_INFORMATION), null) == 0) { return sYSTEM_LEAP_SECOND_INFORMATION.Enabled != Interop.BOOLEAN.FALSE; } return false; } [MethodImpl(MethodImplOptions.NoInlining)] internal unsafe static bool IsValidTimeWithLeapSeconds(int year, int month, int day, int hour, int minute, DateTimeKind kind) { System.Runtime.CompilerServices.Unsafe.SkipInit(out Interop.Kernel32.SYSTEMTIME sYSTEMTIME); sYSTEMTIME.Year = (ushort)year; sYSTEMTIME.Month = (ushort)month; sYSTEMTIME.DayOfWeek = 0; sYSTEMTIME.Day = (ushort)day; sYSTEMTIME.Hour = (ushort)hour; sYSTEMTIME.Minute = (ushort)minute; sYSTEMTIME.Second = 60; sYSTEMTIME.Milliseconds = 0; System.Runtime.CompilerServices.Unsafe.SkipInit(out Interop.Kernel32.SYSTEMTIME sYSTEMTIME2); if (kind != DateTimeKind.Utc && Interop.Kernel32.TzSpecificLocalTimeToSystemTime(IntPtr.Zero, &sYSTEMTIME, &sYSTEMTIME2) != 0) { return true; } System.Runtime.CompilerServices.Unsafe.SkipInit(out ulong num); if (kind != DateTimeKind.Local && Interop.Kernel32.SystemTimeToFileTime(&sYSTEMTIME, &num) != 0) { return true; } return false; } private unsafe static DateTime FromFileTimeLeapSecondsAware(ulong fileTime) { System.Runtime.CompilerServices.Unsafe.SkipInit(out Interop.Kernel32.SYSTEMTIME time); if (Interop.Kernel32.FileTimeToSystemTime(&fileTime, &time) == Interop.BOOL.FALSE) { throw new ArgumentOutOfRangeException("fileTime", SR.ArgumentOutOfRange_DateTimeBadTicks); } return CreateDateTimeFromSystemTime(in time, fileTime % 10000); } private unsafe static ulong ToFileTimeLeapSecondsAware(long ticks) { DateTime dateTime = new DateTime(ticks); dateTime.GetDate(out var year, out var month, out var day); System.Runtime.CompilerServices.Unsafe.SkipInit(out Interop.Kernel32.SYSTEMTIME sYSTEMTIME); sYSTEMTIME.Year = (ushort)year; sYSTEMTIME.Month = (ushort)month; sYSTEMTIME.DayOfWeek = 0; sYSTEMTIME.Day = (ushort)day; dateTime.GetTimePrecise(out var hour, out var minute, out var second, out var tick); sYSTEMTIME.Hour = (ushort)hour; sYSTEMTIME.Minute = (ushort)minute; sYSTEMTIME.Second = (ushort)second; sYSTEMTIME.Milliseconds = 0; System.Runtime.CompilerServices.Unsafe.SkipInit(out ulong num); if (Interop.Kernel32.SystemTimeToFileTime(&sYSTEMTIME, &num) == Interop.BOOL.FALSE) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_FileTimeInvalid); } return num + (uint)tick; } private static DateTime CreateDateTimeFromSystemTime(in Interop.Kernel32.SYSTEMTIME time, ulong hundredNanoSecond) { uint year = time.Year; uint[] array = (IsLeapYear((int)year) ? s_daysToMonth366 : s_daysToMonth365); int num = time.Month - 1; uint num2 = DaysToYear(year) + array[num] + time.Day - 1; ulong num3 = (ulong)num2 * 864000000000uL; num3 += (ulong)(time.Hour * 36000000000L); num3 += (ulong)((long)time.Minute * 600000000L); uint second = time.Second; if (second <= 59) { ulong num4 = (uint)((int)(second * 10000000) + time.Milliseconds * 10000) + hundredNanoSecond; return new DateTime((num3 + num4) | 0x4000000000000000uL); } num3 += 4611686019027387903L; return new DateTime(num3); } private unsafe static delegate* unmanaged[SuppressGCTransition] GetGetSystemTimeAsFileTimeFnPtr() { IntPtr handle = Interop.Kernel32.LoadLibraryEx("kernel32.dll", IntPtr.Zero, 2048); IntPtr intPtr = NativeLibrary.GetExport(handle, "GetSystemTimeAsFileTime"); if (NativeLibrary.TryGetExport(handle, "GetSystemTimePreciseAsFileTime", out var address)) { System.Runtime.CompilerServices.Unsafe.SkipInit(out long num); System.Runtime.CompilerServices.Unsafe.SkipInit(out long num2); for (int i = 0; i < 10; i++) { ((delegate* unmanaged[SuppressGCTransition])(void*)intPtr)(&num); ((delegate* unmanaged[SuppressGCTransition])(void*)address)(&num2); if (Math.Abs(num2 - num) <= 1000000) { intPtr = address; break; } } } return (delegate* unmanaged[SuppressGCTransition])(void*)intPtr; } private unsafe static DateTime UpdateLeapSecondCacheAndReturnUtcNow() { System.Runtime.CompilerServices.Unsafe.SkipInit(out ulong num); s_pfnGetSystemTimeAsFileTime(&num); ulong hundredNanoSecond = num % 10000; System.Runtime.CompilerServices.Unsafe.SkipInit(out Interop.Kernel32.SYSTEMTIME time); if (Interop.Kernel32.FileTimeToSystemTime(&num, &time) == Interop.BOOL.FALSE) { return LowGranularityNonCachedFallback(); } if (time.Second >= 60) { return CreateDateTimeFromSystemTime(in time, hundredNanoSecond); } ulong num2 = num + 3000000000u; System.Runtime.CompilerServices.Unsafe.SkipInit(out Interop.Kernel32.SYSTEMTIME sYSTEMTIME); if (Interop.Kernel32.FileTimeToSystemTime(&num2, &sYSTEMTIME) == Interop.BOOL.FALSE) { return LowGranularityNonCachedFallback(); } ulong num3; ulong num4; if (sYSTEMTIME.Second == time.Second) { num3 = num; num4 = CreateDateTimeFromSystemTime(in time, hundredNanoSecond)._dateData; } else { Interop.Kernel32.SYSTEMTIME time2 = time; time2.Hour = 0; time2.Minute = 0; time2.Second = 0; time2.Milliseconds = 0; System.Runtime.CompilerServices.Unsafe.SkipInit(out ulong num5); if (Interop.Kernel32.SystemTimeToFileTime(&time2, &num5) == Interop.BOOL.FALSE) { return LowGranularityNonCachedFallback(); } num3 = num5 + 863990000000L - 3000000000u; if (num - num3 >= 3000000000u) { return CreateDateTimeFromSystemTime(in time, hundredNanoSecond); } num4 = CreateDateTimeFromSystemTime(in time2, 0uL)._dateData + 863990000000L - 3000000000u; } Volatile.Write(ref s_leapSecondCache, new LeapSecondCache { OSFileTimeTicksAtStartOfValidityWindow = num3, DotnetDateDataAtStartOfValidityWindow = num4 }); return new DateTime(num4 + num - num3); [MethodImpl(MethodImplOptions.NoInlining)] static unsafe DateTime LowGranularityNonCachedFallback() { System.Runtime.CompilerServices.Unsafe.SkipInit(out Interop.Kernel32.SYSTEMTIME time3); Interop.Kernel32.GetSystemTime(&time3); return CreateDateTimeFromSystemTime(in time3, 0uL); } } } public enum DateTimeKind { Unspecified, Utc, Local } [Serializable] [StructLayout(LayoutKind.Auto)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct DateTimeOffset : IComparable, ISpanFormattable, IFormattable, IComparable, IEquatable, ISerializable, IDeserializationCallback, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IMinMaxValue, ISpanParseable, IParseable, ISubtractionOperators, ISubtractionOperators { public static readonly DateTimeOffset MinValue = new DateTimeOffset(0L, TimeSpan.Zero); public static readonly DateTimeOffset MaxValue = new DateTimeOffset(3155378975999999999L, TimeSpan.Zero); public static readonly DateTimeOffset UnixEpoch = new DateTimeOffset(621355968000000000L, TimeSpan.Zero); private readonly DateTime _dateTime; private readonly short _offsetMinutes; public static DateTimeOffset Now => ToLocalTime(DateTime.UtcNow, throwOnOverflow: true); public static DateTimeOffset UtcNow { get { DateTime utcNow = DateTime.UtcNow; return new DateTimeOffset(0, utcNow); } } public DateTime DateTime => ClockDateTime; public DateTime UtcDateTime => DateTime.SpecifyKind(_dateTime, DateTimeKind.Utc); public DateTime LocalDateTime => UtcDateTime.ToLocalTime(); private DateTime ClockDateTime => new DateTime((_dateTime + Offset).Ticks, DateTimeKind.Unspecified); public DateTime Date => ClockDateTime.Date; public int Day => ClockDateTime.Day; public DayOfWeek DayOfWeek => ClockDateTime.DayOfWeek; public int DayOfYear => ClockDateTime.DayOfYear; public int Hour => ClockDateTime.Hour; public int Millisecond => ClockDateTime.Millisecond; public int Minute => ClockDateTime.Minute; public int Month => ClockDateTime.Month; public TimeSpan Offset => new TimeSpan(0, _offsetMinutes, 0); public int Second => ClockDateTime.Second; public long Ticks => ClockDateTime.Ticks; public long UtcTicks => UtcDateTime.Ticks; public TimeSpan TimeOfDay => ClockDateTime.TimeOfDay; public int Year => ClockDateTime.Year; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan IAdditiveIdentity.AdditiveIdentity => default(TimeSpan); [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateTimeOffset IMinMaxValue.MinValue => MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateTimeOffset IMinMaxValue.MaxValue => MaxValue; private DateTimeOffset(short validOffsetMinutes, DateTime validDateTime) { _dateTime = validDateTime; _offsetMinutes = validOffsetMinutes; } public DateTimeOffset(long ticks, TimeSpan offset) : this(ValidateOffset(offset), ValidateDate(new DateTime(ticks), offset)) { } public DateTimeOffset(DateTime dateTime) { TimeSpan offset = ((dateTime.Kind == DateTimeKind.Utc) ? new TimeSpan(0L) : TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime)); _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(dateTime, offset); } public DateTimeOffset(DateTime dateTime, TimeSpan offset) { if (dateTime.Kind == DateTimeKind.Local) { if (offset != TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime)) { throw new ArgumentException(SR.Argument_OffsetLocalMismatch, "offset"); } } else if (dateTime.Kind == DateTimeKind.Utc && offset != TimeSpan.Zero) { throw new ArgumentException(SR.Argument_OffsetUtcMismatch, "offset"); } _offsetMinutes = ValidateOffset(offset); _dateTime = ValidateDate(dateTime, offset); } public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); int num = second; if (second == 60 && DateTime.s_systemSupportsLeapSeconds) { second = 59; } _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second), offset); if (num == 60 && !DateTime.IsValidTimeWithLeapSeconds(_dateTime.Year, _dateTime.Month, _dateTime.Day, _dateTime.Hour, _dateTime.Minute, DateTimeKind.Utc)) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } } public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); int num = second; if (second == 60 && DateTime.s_systemSupportsLeapSeconds) { second = 59; } _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond), offset); if (num == 60 && !DateTime.IsValidTimeWithLeapSeconds(_dateTime.Year, _dateTime.Month, _dateTime.Day, _dateTime.Hour, _dateTime.Minute, DateTimeKind.Utc)) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } } public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, TimeSpan offset) { _offsetMinutes = ValidateOffset(offset); int num = second; if (second == 60 && DateTime.s_systemSupportsLeapSeconds) { second = 59; } _dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond, calendar), offset); if (num == 60 && !DateTime.IsValidTimeWithLeapSeconds(_dateTime.Year, _dateTime.Month, _dateTime.Day, _dateTime.Hour, _dateTime.Minute, DateTimeKind.Utc)) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } } public DateTimeOffset ToOffset(TimeSpan offset) { return new DateTimeOffset((_dateTime + offset).Ticks, offset); } public DateTimeOffset Add(TimeSpan timeSpan) { return new DateTimeOffset(ClockDateTime.Add(timeSpan), Offset); } public DateTimeOffset AddDays(double days) { return new DateTimeOffset(ClockDateTime.AddDays(days), Offset); } public DateTimeOffset AddHours(double hours) { return new DateTimeOffset(ClockDateTime.AddHours(hours), Offset); } public DateTimeOffset AddMilliseconds(double milliseconds) { return new DateTimeOffset(ClockDateTime.AddMilliseconds(milliseconds), Offset); } public DateTimeOffset AddMinutes(double minutes) { return new DateTimeOffset(ClockDateTime.AddMinutes(minutes), Offset); } public DateTimeOffset AddMonths(int months) { return new DateTimeOffset(ClockDateTime.AddMonths(months), Offset); } public DateTimeOffset AddSeconds(double seconds) { return new DateTimeOffset(ClockDateTime.AddSeconds(seconds), Offset); } public DateTimeOffset AddTicks(long ticks) { return new DateTimeOffset(ClockDateTime.AddTicks(ticks), Offset); } public DateTimeOffset AddYears(int years) { return new DateTimeOffset(ClockDateTime.AddYears(years), Offset); } public static int Compare(DateTimeOffset first, DateTimeOffset second) { return DateTime.Compare(first.UtcDateTime, second.UtcDateTime); } int IComparable.CompareTo(object obj) { if (obj == null) { return 1; } if (!(obj is DateTimeOffset dateTimeOffset)) { throw new ArgumentException(SR.Arg_MustBeDateTimeOffset); } DateTime utcDateTime = dateTimeOffset.UtcDateTime; DateTime utcDateTime2 = UtcDateTime; if (utcDateTime2 > utcDateTime) { return 1; } if (utcDateTime2 < utcDateTime) { return -1; } return 0; } public int CompareTo(DateTimeOffset other) { DateTime utcDateTime = other.UtcDateTime; DateTime utcDateTime2 = UtcDateTime; if (utcDateTime2 > utcDateTime) { return 1; } if (utcDateTime2 < utcDateTime) { return -1; } return 0; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is DateTimeOffset) { return UtcDateTime.Equals(((DateTimeOffset)obj).UtcDateTime); } return false; } public bool Equals(DateTimeOffset other) { return UtcDateTime.Equals(other.UtcDateTime); } public bool EqualsExact(DateTimeOffset other) { if (ClockDateTime == other.ClockDateTime && Offset == other.Offset) { return ClockDateTime.Kind == other.ClockDateTime.Kind; } return false; } public static bool Equals(DateTimeOffset first, DateTimeOffset second) { return DateTime.Equals(first.UtcDateTime, second.UtcDateTime); } public static DateTimeOffset FromFileTime(long fileTime) { return ToLocalTime(DateTime.FromFileTimeUtc(fileTime), throwOnOverflow: true); } public static DateTimeOffset FromUnixTimeSeconds(long seconds) { if (seconds < -62135596800L || seconds > 253402300799L) { throw new ArgumentOutOfRangeException("seconds", SR.Format(SR.ArgumentOutOfRange_Range, -62135596800L, 253402300799L)); } long ticks = seconds * 10000000 + 621355968000000000L; return new DateTimeOffset(ticks, TimeSpan.Zero); } public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds) { if (milliseconds < -62135596800000L || milliseconds > 253402300799999L) { throw new ArgumentOutOfRangeException("milliseconds", SR.Format(SR.ArgumentOutOfRange_Range, -62135596800000L, 253402300799999L)); } long ticks = milliseconds * 10000 + 621355968000000000L; return new DateTimeOffset(ticks, TimeSpan.Zero); } void IDeserializationCallback.OnDeserialization(object sender) { try { ValidateOffset(Offset); ValidateDate(ClockDateTime, Offset); } catch (ArgumentException innerException) { throw new SerializationException(SR.Serialization_InvalidData, innerException); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("DateTime", _dateTime); info.AddValue("OffsetMinutes", _offsetMinutes); } private DateTimeOffset(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } _dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime)); _offsetMinutes = (short)info.GetValue("OffsetMinutes", typeof(short)); } public override int GetHashCode() { return UtcDateTime.GetHashCode(); } public static DateTimeOffset Parse(string input) { if (input == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); } TimeSpan offset; return new DateTimeOffset(DateTimeParse.Parse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out offset).Ticks, offset); } public static DateTimeOffset Parse(string input, IFormatProvider? formatProvider) { if (input == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); } return Parse(input, formatProvider, DateTimeStyles.None); } public static DateTimeOffset Parse(string input, IFormatProvider? formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, "styles"); if (input == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); } TimeSpan offset; return new DateTimeOffset(DateTimeParse.Parse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset).Ticks, offset); } public static DateTimeOffset Parse(ReadOnlySpan input, IFormatProvider? formatProvider = null, DateTimeStyles styles = DateTimeStyles.None) { styles = ValidateStyles(styles, "styles"); TimeSpan offset; return new DateTimeOffset(DateTimeParse.Parse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset).Ticks, offset); } public static DateTimeOffset ParseExact(string input, string format, IFormatProvider? formatProvider) { if (input == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); } if (format == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); } return ParseExact(input, format, formatProvider, DateTimeStyles.None); } public static DateTimeOffset ParseExact(string input, string format, IFormatProvider? formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, "styles"); if (input == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); } if (format == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); } TimeSpan offset; return new DateTimeOffset(DateTimeParse.ParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset).Ticks, offset); } public static DateTimeOffset ParseExact(ReadOnlySpan input, ReadOnlySpan format, IFormatProvider? formatProvider, DateTimeStyles styles = DateTimeStyles.None) { styles = ValidateStyles(styles, "styles"); TimeSpan offset; return new DateTimeOffset(DateTimeParse.ParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset).Ticks, offset); } public static DateTimeOffset ParseExact(string input, string[] formats, IFormatProvider? formatProvider, DateTimeStyles styles) { styles = ValidateStyles(styles, "styles"); if (input == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); } TimeSpan offset; return new DateTimeOffset(DateTimeParse.ParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset).Ticks, offset); } public static DateTimeOffset ParseExact(ReadOnlySpan input, string[] formats, IFormatProvider? formatProvider, DateTimeStyles styles = DateTimeStyles.None) { styles = ValidateStyles(styles, "styles"); TimeSpan offset; return new DateTimeOffset(DateTimeParse.ParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out offset).Ticks, offset); } public TimeSpan Subtract(DateTimeOffset value) { return UtcDateTime.Subtract(value.UtcDateTime); } public DateTimeOffset Subtract(TimeSpan value) { return new DateTimeOffset(ClockDateTime.Subtract(value), Offset); } public long ToFileTime() { return UtcDateTime.ToFileTime(); } public long ToUnixTimeSeconds() { long num = UtcDateTime.Ticks / 10000000; return num - 62135596800L; } public long ToUnixTimeMilliseconds() { long num = UtcDateTime.Ticks / 10000; return num - 62135596800000L; } public DateTimeOffset ToLocalTime() { return ToLocalTime(throwOnOverflow: false); } internal DateTimeOffset ToLocalTime(bool throwOnOverflow) { return ToLocalTime(UtcDateTime, throwOnOverflow); } private static DateTimeOffset ToLocalTime(DateTime utcDateTime, bool throwOnOverflow) { TimeSpan localUtcOffset = TimeZoneInfo.GetLocalUtcOffset(utcDateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); long num = utcDateTime.Ticks + localUtcOffset.Ticks; if (num < 0 || num > 3155378975999999999L) { if (throwOnOverflow) { throw new ArgumentException(SR.Arg_ArgumentOutOfRangeException); } num = ((num < 0) ? 0 : 3155378975999999999L); } return new DateTimeOffset(num, localUtcOffset); } public override string ToString() { return DateTimeFormat.Format(ClockDateTime, null, null, Offset); } public string ToString(string? format) { return DateTimeFormat.Format(ClockDateTime, format, null, Offset); } public string ToString(IFormatProvider? formatProvider) { return DateTimeFormat.Format(ClockDateTime, null, formatProvider, Offset); } public string ToString(string? format, IFormatProvider? formatProvider) { return DateTimeFormat.Format(ClockDateTime, format, formatProvider, Offset); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? formatProvider = null) { return DateTimeFormat.TryFormat(ClockDateTime, destination, out charsWritten, format, formatProvider, Offset); } public DateTimeOffset ToUniversalTime() { return new DateTimeOffset(UtcDateTime); } public static bool TryParse([NotNullWhen(true)] string? input, out DateTimeOffset result) { DateTime result2; TimeSpan offset; bool result3 = DateTimeParse.TryParse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out result2, out offset); result = new DateTimeOffset(result2.Ticks, offset); return result3; } public static bool TryParse(ReadOnlySpan input, out DateTimeOffset result) { DateTime result2; TimeSpan offset; bool result3 = DateTimeParse.TryParse(input, DateTimeFormatInfo.CurrentInfo, DateTimeStyles.None, out result2, out offset); result = new DateTimeOffset(result2.Ticks, offset); return result3; } public static bool TryParse([NotNullWhen(true)] string? input, IFormatProvider? formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, "styles"); if (input == null) { result = default(DateTimeOffset); return false; } DateTime result2; TimeSpan offset; bool result3 = DateTimeParse.TryParse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out result2, out offset); result = new DateTimeOffset(result2.Ticks, offset); return result3; } public static bool TryParse(ReadOnlySpan input, IFormatProvider? formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, "styles"); DateTime result2; TimeSpan offset; bool result3 = DateTimeParse.TryParse(input, DateTimeFormatInfo.GetInstance(formatProvider), styles, out result2, out offset); result = new DateTimeOffset(result2.Ticks, offset); return result3; } public static bool TryParseExact([NotNullWhen(true)] string? input, [NotNullWhen(true)] string? format, IFormatProvider? formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, "styles"); if (input == null || format == null) { result = default(DateTimeOffset); return false; } DateTime result2; TimeSpan offset; bool result3 = DateTimeParse.TryParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out result2, out offset); result = new DateTimeOffset(result2.Ticks, offset); return result3; } public static bool TryParseExact(ReadOnlySpan input, ReadOnlySpan format, IFormatProvider? formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, "styles"); DateTime result2; TimeSpan offset; bool result3 = DateTimeParse.TryParseExact(input, format, DateTimeFormatInfo.GetInstance(formatProvider), styles, out result2, out offset); result = new DateTimeOffset(result2.Ticks, offset); return result3; } public static bool TryParseExact([NotNullWhen(true)] string? input, [NotNullWhen(true)] string?[]? formats, IFormatProvider? formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, "styles"); if (input == null) { result = default(DateTimeOffset); return false; } DateTime result2; TimeSpan offset; bool result3 = DateTimeParse.TryParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out result2, out offset); result = new DateTimeOffset(result2.Ticks, offset); return result3; } public static bool TryParseExact(ReadOnlySpan input, [NotNullWhen(true)] string?[]? formats, IFormatProvider? formatProvider, DateTimeStyles styles, out DateTimeOffset result) { styles = ValidateStyles(styles, "styles"); DateTime result2; TimeSpan offset; bool result3 = DateTimeParse.TryParseExactMultiple(input, formats, DateTimeFormatInfo.GetInstance(formatProvider), styles, out result2, out offset); result = new DateTimeOffset(result2.Ticks, offset); return result3; } private static short ValidateOffset(TimeSpan offset) { long ticks = offset.Ticks; if (ticks % 600000000 != 0L) { throw new ArgumentException(SR.Argument_OffsetPrecision, "offset"); } if (ticks < -504000000000L || ticks > 504000000000L) { throw new ArgumentOutOfRangeException("offset", SR.Argument_OffsetOutOfRange); } return (short)(offset.Ticks / 600000000); } private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) { long num = dateTime.Ticks - offset.Ticks; if (num < 0 || num > 3155378975999999999L) { throw new ArgumentOutOfRangeException("offset", SR.Argument_UTCOutOfRange); } return new DateTime(num, DateTimeKind.Unspecified); } private static DateTimeStyles ValidateStyles(DateTimeStyles style, string parameterName) { if (((uint)style & 0xFFFFFF00u) != 0) { throw new ArgumentException(SR.Argument_InvalidDateTimeStyles, parameterName); } if ((style & DateTimeStyles.AssumeLocal) != 0 && (style & DateTimeStyles.AssumeUniversal) != 0) { throw new ArgumentException(SR.Argument_ConflictingDateTimeStyles, parameterName); } if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) { throw new ArgumentException(SR.Argument_DateTimeOffsetInvalidDateTimeStyles, parameterName); } style &= ~DateTimeStyles.RoundtripKind; style &= ~DateTimeStyles.AssumeLocal; return style; } public static implicit operator DateTimeOffset(DateTime dateTime) { return new DateTimeOffset(dateTime); } public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) { return new DateTimeOffset(dateTimeOffset.ClockDateTime + timeSpan, dateTimeOffset.Offset); } public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) { return new DateTimeOffset(dateTimeOffset.ClockDateTime - timeSpan, dateTimeOffset.Offset); } public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime - right.UtcDateTime; } public static bool operator ==(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime == right.UtcDateTime; } public static bool operator !=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime != right.UtcDateTime; } public static bool operator <(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime < right.UtcDateTime; } public static bool operator <=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime <= right.UtcDateTime; } public static bool operator >(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime > right.UtcDateTime; } public static bool operator >=(DateTimeOffset left, DateTimeOffset right) { return left.UtcDateTime >= right.UtcDateTime; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateTimeOffset IAdditionOperators.op_Addition(DateTimeOffset left, TimeSpan right) { return left + right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(DateTimeOffset left, DateTimeOffset right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(DateTimeOffset left, DateTimeOffset right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(DateTimeOffset left, DateTimeOffset right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(DateTimeOffset left, DateTimeOffset right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(DateTimeOffset left, DateTimeOffset right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(DateTimeOffset left, DateTimeOffset right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateTimeOffset IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out DateTimeOffset result) { return TryParse(s, provider, DateTimeStyles.None, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateTimeOffset ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out DateTimeOffset result) { return TryParse(s, provider, DateTimeStyles.None, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static DateTimeOffset ISubtractionOperators.op_Subtraction(DateTimeOffset left, TimeSpan right) { return left - right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan ISubtractionOperators.op_Subtraction(DateTimeOffset left, DateTimeOffset right) { return left - right; } } public enum DayOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } [Serializable] public sealed class DBNull : ISerializable, IConvertible { public static readonly DBNull Value = new DBNull(); private DBNull() { } private DBNull(SerializationInfo info, StreamingContext context) { throw new NotSupportedException(SR.NotSupported_DBNullSerial); } public void GetObjectData(SerializationInfo info, StreamingContext context) { UnitySerializationHolder.GetUnitySerializationInfo(info, 2); } public override string ToString() { return string.Empty; } public string ToString(IFormatProvider? provider) { return string.Empty; } public TypeCode GetTypeCode() { return TypeCode.DBNull; } bool IConvertible.ToBoolean(IFormatProvider provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } sbyte IConvertible.ToSByte(IFormatProvider provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } byte IConvertible.ToByte(IFormatProvider provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } short IConvertible.ToInt16(IFormatProvider provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } ushort IConvertible.ToUInt16(IFormatProvider provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } int IConvertible.ToInt32(IFormatProvider provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } uint IConvertible.ToUInt32(IFormatProvider provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } long IConvertible.ToInt64(IFormatProvider provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } ulong IConvertible.ToUInt64(IFormatProvider provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } float IConvertible.ToSingle(IFormatProvider provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } double IConvertible.ToDouble(IFormatProvider provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } decimal IConvertible.ToDecimal(IFormatProvider provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.InvalidCast_FromDBNull); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } } internal class DefaultBinder : Binder { [Flags] private enum Primitives { Boolean = 8, Char = 0x10, SByte = 0x20, Byte = 0x40, Int16 = 0x80, UInt16 = 0x100, Int32 = 0x200, UInt32 = 0x400, Int64 = 0x800, UInt64 = 0x1000, Single = 0x2000, Double = 0x4000, Decimal = 0x8000, DateTime = 0x10000, String = 0x40000 } internal sealed class BinderState { internal readonly int[] _argsMap; internal readonly int _originalSize; internal readonly bool _isParamArray; internal BinderState(int[] argsMap, int originalSize, bool isParamArray) { _argsMap = argsMap; _originalSize = originalSize; _isParamArray = isParamArray; } } private static readonly Primitives[] s_primitiveConversions = new Primitives[19] { (Primitives)0, (Primitives)0, (Primitives)0, Primitives.Boolean, Primitives.Char | Primitives.UInt16 | Primitives.Int32 | Primitives.UInt32 | Primitives.Int64 | Primitives.UInt64 | Primitives.Single | Primitives.Double, Primitives.SByte | Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, Primitives.Char | Primitives.Byte | Primitives.Int16 | Primitives.UInt16 | Primitives.Int32 | Primitives.UInt32 | Primitives.Int64 | Primitives.UInt64 | Primitives.Single | Primitives.Double, Primitives.Int16 | Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, Primitives.UInt16 | Primitives.Int32 | Primitives.UInt32 | Primitives.Int64 | Primitives.UInt64 | Primitives.Single | Primitives.Double, Primitives.Int32 | Primitives.Int64 | Primitives.Single | Primitives.Double, Primitives.UInt32 | Primitives.Int64 | Primitives.UInt64 | Primitives.Single | Primitives.Double, Primitives.Int64 | Primitives.Single | Primitives.Double, Primitives.UInt64 | Primitives.Single | Primitives.Double, Primitives.Single | Primitives.Double, Primitives.Double, Primitives.Decimal, Primitives.DateTime, (Primitives)0, Primitives.String }; public sealed override MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo cultureInfo, string[] names, out object state) { if (match == null || match.Length == 0) { throw new ArgumentException(SR.Arg_EmptyArray, "match"); } MethodBase[] array = (MethodBase[])match.Clone(); state = null; int[][] array2 = new int[array.Length][]; for (int i = 0; i < array.Length; i++) { ParameterInfo[] parametersNoCopy = array[i].GetParametersNoCopy(); array2[i] = new int[(parametersNoCopy.Length > args.Length) ? parametersNoCopy.Length : args.Length]; if (names == null) { for (int j = 0; j < args.Length; j++) { array2[i][j] = j; } } else if (!CreateParamOrder(array2[i], parametersNoCopy, names)) { array[i] = null; } } Type[] array3 = new Type[array.Length]; Type[] array4 = new Type[args.Length]; for (int i = 0; i < args.Length; i++) { if (args[i] != null) { array4[i] = args[i].GetType(); } } int num = 0; bool flag = (bindingAttr & BindingFlags.OptionalParamBinding) != 0; for (int i = 0; i < array.Length; i++) { Type type = null; if (array[i] == null) { continue; } ParameterInfo[] parametersNoCopy2 = array[i].GetParametersNoCopy(); if (parametersNoCopy2.Length == 0) { if (args.Length == 0 || (array[i].CallingConvention & CallingConventions.VarArgs) != 0) { array2[num] = array2[i]; array[num++] = array[i]; } continue; } int j; if (parametersNoCopy2.Length > args.Length) { for (j = args.Length; j < parametersNoCopy2.Length - 1 && parametersNoCopy2[j].DefaultValue != DBNull.Value; j++) { } if (j != parametersNoCopy2.Length - 1) { continue; } if (parametersNoCopy2[j].DefaultValue == DBNull.Value) { if (!parametersNoCopy2[j].ParameterType.IsArray || !parametersNoCopy2[j].IsDefined(typeof(ParamArrayAttribute), inherit: true)) { continue; } type = parametersNoCopy2[j].ParameterType.GetElementType(); } } else if (parametersNoCopy2.Length < args.Length) { int num2 = parametersNoCopy2.Length - 1; if (!parametersNoCopy2[num2].ParameterType.IsArray || !parametersNoCopy2[num2].IsDefined(typeof(ParamArrayAttribute), inherit: true) || array2[i][num2] != num2) { continue; } type = parametersNoCopy2[num2].ParameterType.GetElementType(); } else { int num3 = parametersNoCopy2.Length - 1; if (parametersNoCopy2[num3].ParameterType.IsArray && parametersNoCopy2[num3].IsDefined(typeof(ParamArrayAttribute), inherit: true) && array2[i][num3] == num3 && !parametersNoCopy2[num3].ParameterType.IsAssignableFrom(array4[num3])) { type = parametersNoCopy2[num3].ParameterType.GetElementType(); } } int num4 = ((type != null) ? (parametersNoCopy2.Length - 1) : args.Length); for (j = 0; j < num4; j++) { Type type2 = parametersNoCopy2[j].ParameterType; if (type2.IsByRef) { type2 = type2.GetElementType(); } if (type2 == array4[array2[i][j]] || (flag && args[array2[i][j]] == Type.Missing) || args[array2[i][j]] == null || type2 == typeof(object)) { continue; } if (type2.IsPrimitive) { if (array4[array2[i][j]] == null || !CanChangePrimitive(args[array2[i][j]]?.GetType(), type2)) { break; } } else if (!(array4[array2[i][j]] == null) && !type2.IsAssignableFrom(array4[array2[i][j]]) && (!array4[array2[i][j]].IsCOMObject || !type2.IsInstanceOfType(args[array2[i][j]]))) { break; } } if (type != null && j == parametersNoCopy2.Length - 1) { for (; j < args.Length; j++) { if (type.IsPrimitive) { if (array4[j] == null || !CanChangePrimitive(args[j]?.GetType(), type)) { break; } } else if (!(array4[j] == null) && !type.IsAssignableFrom(array4[j]) && (!array4[j].IsCOMObject || !type.IsInstanceOfType(args[j]))) { break; } } } if (j == args.Length) { array2[num] = array2[i]; array3[num] = type; array[num++] = array[i]; } } switch (num) { case 0: throw new MissingMethodException(SR.MissingMember); case 1: { if (names != null) { state = new BinderState((int[])array2[0].Clone(), args.Length, array3[0] != null); ReorderParams(array2[0], args); } ParameterInfo[] parametersNoCopy4 = array[0].GetParametersNoCopy(); if (parametersNoCopy4.Length == args.Length) { if (array3[0] != null) { object[] array8 = new object[parametersNoCopy4.Length]; int num8 = parametersNoCopy4.Length - 1; Array.Copy(args, array8, num8); array8[num8] = Array.CreateInstance(array3[0], 1); ((Array)array8[num8]).SetValue(args[num8], 0); args = array8; } } else if (parametersNoCopy4.Length > args.Length) { object[] array9 = new object[parametersNoCopy4.Length]; int i; for (i = 0; i < args.Length; i++) { array9[i] = args[i]; } for (; i < parametersNoCopy4.Length - 1; i++) { array9[i] = parametersNoCopy4[i].DefaultValue; } if (array3[0] != null) { array9[i] = Array.CreateInstance(array3[0], 0); } else { array9[i] = parametersNoCopy4[i].DefaultValue; } args = array9; } else if ((array[0].CallingConvention & CallingConventions.VarArgs) == 0) { object[] array10 = new object[parametersNoCopy4.Length]; int num9 = parametersNoCopy4.Length - 1; Array.Copy(args, array10, num9); array10[num9] = Array.CreateInstance(array3[0], args.Length - num9); Array.Copy(args, num9, (Array)array10[num9], 0, args.Length - num9); args = array10; } return array[0]; } default: { int num5 = 0; bool flag2 = false; for (int i = 1; i < num; i++) { switch (FindMostSpecificMethod(array[num5], array2[num5], array3[num5], array[i], array2[i], array3[i], array4, args)) { case 0: flag2 = true; break; case 2: num5 = i; flag2 = false; break; } } if (flag2) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } if (names != null) { state = new BinderState((int[])array2[num5].Clone(), args.Length, array3[num5] != null); ReorderParams(array2[num5], args); } ParameterInfo[] parametersNoCopy3 = array[num5].GetParametersNoCopy(); if (parametersNoCopy3.Length == args.Length) { if (array3[num5] != null) { object[] array5 = new object[parametersNoCopy3.Length]; int num6 = parametersNoCopy3.Length - 1; Array.Copy(args, array5, num6); array5[num6] = Array.CreateInstance(array3[num5], 1); ((Array)array5[num6]).SetValue(args[num6], 0); args = array5; } } else if (parametersNoCopy3.Length > args.Length) { object[] array6 = new object[parametersNoCopy3.Length]; int i; for (i = 0; i < args.Length; i++) { array6[i] = args[i]; } for (; i < parametersNoCopy3.Length - 1; i++) { array6[i] = parametersNoCopy3[i].DefaultValue; } if (array3[num5] != null) { array6[i] = Array.CreateInstance(array3[num5], 0); } else { array6[i] = parametersNoCopy3[i].DefaultValue; } args = array6; } else if ((array[num5].CallingConvention & CallingConventions.VarArgs) == 0) { object[] array7 = new object[parametersNoCopy3.Length]; int num7 = parametersNoCopy3.Length - 1; Array.Copy(args, array7, num7); array7[num7] = Array.CreateInstance(array3[num5], args.Length - num7); Array.Copy(args, num7, (Array)array7[num7], 0, args.Length - num7); args = array7; } return array[num5]; } } } public sealed override FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo cultureInfo) { if (match == null) { throw new ArgumentNullException("match"); } int num = 0; FieldInfo[] array = (FieldInfo[])match.Clone(); if ((bindingAttr & BindingFlags.SetField) != 0) { Type type = value.GetType(); for (int i = 0; i < array.Length; i++) { Type fieldType = array[i].FieldType; if (fieldType == type) { array[num++] = array[i]; } else if (value == Empty.Value && fieldType.IsClass) { array[num++] = array[i]; } else if (fieldType == typeof(object)) { array[num++] = array[i]; } else if (fieldType.IsPrimitive) { if (CanChangePrimitive(type, fieldType)) { array[num++] = array[i]; } } else if (fieldType.IsAssignableFrom(type)) { array[num++] = array[i]; } } switch (num) { case 0: throw new MissingFieldException(SR.MissingField); case 1: return array[0]; } } int num2 = 0; bool flag = false; for (int i = 1; i < num; i++) { switch (FindMostSpecificField(array[num2], array[i])) { case 0: flag = true; break; case 2: num2 = i; flag = false; break; } } if (flag) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } return array[num2]; } public sealed override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers) { Type[] array = new Type[types.Length]; for (int i = 0; i < types.Length; i++) { array[i] = types[i].UnderlyingSystemType; if (!array[i].IsRuntimeImplemented() && !(array[i] is SignatureType)) { throw new ArgumentException(SR.Arg_MustBeType, "types"); } } types = array; if (match == null || match.Length == 0) { throw new ArgumentException(SR.Arg_EmptyArray, "match"); } MethodBase[] array2 = (MethodBase[])match.Clone(); int num = 0; for (int i = 0; i < array2.Length; i++) { ParameterInfo[] parametersNoCopy = array2[i].GetParametersNoCopy(); if (parametersNoCopy.Length != types.Length) { continue; } int j; for (j = 0; j < types.Length; j++) { Type parameterType = parametersNoCopy[j].ParameterType; if (types[j].MatchesParameterTypeExactly(parametersNoCopy[j]) || parameterType == typeof(object)) { continue; } Type type = types[j]; if (type is SignatureType signatureType) { if (!(array2[i] is MethodInfo genericMethod)) { break; } type = signatureType.TryResolveAgainstGenericMethod(genericMethod); if (type == null) { break; } } if (parameterType.IsPrimitive) { if (!type.UnderlyingSystemType.IsRuntimeImplemented() || !CanChangePrimitive(type.UnderlyingSystemType, parameterType.UnderlyingSystemType)) { break; } } else if (!parameterType.IsAssignableFrom(type)) { break; } } if (j == types.Length) { array2[num++] = array2[i]; } } switch (num) { case 0: return null; case 1: return array2[0]; default: { int num2 = 0; bool flag = false; int[] array3 = new int[types.Length]; for (int i = 0; i < types.Length; i++) { array3[i] = i; } for (int i = 1; i < num; i++) { switch (FindMostSpecificMethod(array2[num2], array3, null, array2[i], array3, null, types, null)) { case 0: flag = true; break; case 2: flag = false; num2 = i; break; } } if (flag) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } return array2[num2]; } } } public sealed override PropertyInfo SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers) { if (indexes != null) { foreach (Type type in indexes) { if (type == null) { throw new ArgumentNullException("indexes"); } } } if (match == null || match.Length == 0) { throw new ArgumentException(SR.Arg_EmptyArray, "match"); } PropertyInfo[] array = (PropertyInfo[])match.Clone(); int j = 0; int num = 0; int num2 = ((indexes != null) ? indexes.Length : 0); for (int k = 0; k < array.Length; k++) { if (indexes != null) { ParameterInfo[] indexParameters = array[k].GetIndexParameters(); if (indexParameters.Length != num2) { continue; } for (j = 0; j < num2; j++) { Type parameterType = indexParameters[j].ParameterType; if (parameterType == indexes[j] || parameterType == typeof(object)) { continue; } if (parameterType.IsPrimitive) { if (!indexes[j].UnderlyingSystemType.IsRuntimeImplemented() || !CanChangePrimitive(indexes[j].UnderlyingSystemType, parameterType.UnderlyingSystemType)) { break; } } else if (!parameterType.IsAssignableFrom(indexes[j])) { break; } } } if (j != num2) { continue; } if (returnType != null) { if (array[k].PropertyType.IsPrimitive) { if (!returnType.UnderlyingSystemType.IsRuntimeImplemented() || !CanChangePrimitive(returnType.UnderlyingSystemType, array[k].PropertyType.UnderlyingSystemType)) { continue; } } else if (!array[k].PropertyType.IsAssignableFrom(returnType)) { continue; } } array[num++] = array[k]; } switch (num) { case 0: return null; case 1: return array[0]; default: { int num3 = 0; bool flag = false; int[] array2 = new int[num2]; for (int k = 0; k < num2; k++) { array2[k] = k; } for (int k = 1; k < num; k++) { int num4 = FindMostSpecificType(array[num3].PropertyType, array[k].PropertyType, returnType); if (num4 == 0 && indexes != null) { num4 = FindMostSpecific(array[num3].GetIndexParameters(), array2, null, array[k].GetIndexParameters(), array2, null, indexes, null); } if (num4 == 0) { num4 = FindMostSpecificProperty(array[num3], array[k]); if (num4 == 0) { flag = true; } } if (num4 == 2) { flag = false; num3 = k; } } if (flag) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } return array[num3]; } } } public override object ChangeType(object value, Type type, CultureInfo cultureInfo) { throw new NotSupportedException(SR.NotSupported_ChangeType); } public sealed override void ReorderArgumentArray(ref object[] args, object state) { BinderState binderState = (BinderState)state; ReorderParams(binderState._argsMap, args); if (binderState._isParamArray) { int num = args.Length - 1; if (args.Length == binderState._originalSize) { args[num] = ((object[])args[num])[0]; return; } object[] array = new object[args.Length]; Array.Copy(args, array, num); int num2 = num; int num3 = 0; while (num2 < array.Length) { array[num2] = ((object[])args[num])[num3]; num2++; num3++; } args = array; } else if (args.Length > binderState._originalSize) { object[] array2 = new object[binderState._originalSize]; Array.Copy(args, array2, binderState._originalSize); args = array2; } } public static MethodBase ExactBinding(MethodBase[] match, Type[] types, ParameterModifier[] modifiers) { if (match == null) { throw new ArgumentNullException("match"); } MethodBase[] array = new MethodBase[match.Length]; int num = 0; for (int i = 0; i < match.Length; i++) { ParameterInfo[] parametersNoCopy = match[i].GetParametersNoCopy(); if (parametersNoCopy.Length == 0) { continue; } int j; for (j = 0; j < types.Length; j++) { Type parameterType = parametersNoCopy[j].ParameterType; if (!parameterType.Equals(types[j])) { break; } } if (j >= types.Length) { array[num] = match[i]; num++; } } return num switch { 0 => null, 1 => array[0], _ => FindMostDerivedNewSlotMeth(array, num), }; } public static PropertyInfo ExactPropertyBinding(PropertyInfo[] match, Type returnType, Type[] types, ParameterModifier[] modifiers) { if (match == null) { throw new ArgumentNullException("match"); } PropertyInfo propertyInfo = null; int num = ((types != null) ? types.Length : 0); for (int i = 0; i < match.Length; i++) { ParameterInfo[] indexParameters = match[i].GetIndexParameters(); int j; for (j = 0; j < num; j++) { Type parameterType = indexParameters[j].ParameterType; if (parameterType != types[j]) { break; } } if (j >= num && (!(returnType != null) || !(returnType != match[i].PropertyType))) { if (propertyInfo != null) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } propertyInfo = match[i]; } } return propertyInfo; } private static int FindMostSpecific(ParameterInfo[] p1, int[] paramOrder1, Type paramArrayType1, ParameterInfo[] p2, int[] paramOrder2, Type paramArrayType2, Type[] types, object[] args) { if (paramArrayType1 != null && paramArrayType2 == null) { return 2; } if (paramArrayType2 != null && paramArrayType1 == null) { return 1; } bool flag = false; bool flag2 = false; for (int i = 0; i < types.Length; i++) { if (args != null && args[i] == Type.Missing) { continue; } Type type = ((!(paramArrayType1 != null) || paramOrder1[i] < p1.Length - 1) ? p1[paramOrder1[i]].ParameterType : paramArrayType1); Type type2 = ((!(paramArrayType2 != null) || paramOrder2[i] < p2.Length - 1) ? p2[paramOrder2[i]].ParameterType : paramArrayType2); if (!(type == type2)) { switch (FindMostSpecificType(type, type2, types[i])) { case 0: return 0; case 1: flag = true; break; case 2: flag2 = true; break; } } } if (flag == flag2) { if (!flag && args != null) { if (p1.Length > p2.Length) { return 1; } if (p2.Length > p1.Length) { return 2; } } return 0; } if (!flag) { return 2; } return 1; } private static int FindMostSpecificType(Type c1, Type c2, Type t) { if (c1 == c2) { return 0; } if (t is SignatureType pattern) { if (pattern.MatchesExactly(c1)) { return 1; } if (pattern.MatchesExactly(c2)) { return 2; } } else { if (c1 == t) { return 1; } if (c2 == t) { return 2; } } if (c1.IsByRef || c2.IsByRef) { if (c1.IsByRef && c2.IsByRef) { c1 = c1.GetElementType(); c2 = c2.GetElementType(); } else if (c1.IsByRef) { if (c1.GetElementType() == c2) { return 2; } c1 = c1.GetElementType(); } else { if (c2.GetElementType() == c1) { return 1; } c2 = c2.GetElementType(); } } bool flag; bool flag2; if (c1.IsPrimitive && c2.IsPrimitive) { flag = CanChangePrimitive(c2, c1); flag2 = CanChangePrimitive(c1, c2); } else { flag = c1.IsAssignableFrom(c2); flag2 = c2.IsAssignableFrom(c1); } if (flag == flag2) { return 0; } if (flag) { return 2; } return 1; } private static int FindMostSpecificMethod(MethodBase m1, int[] paramOrder1, Type paramArrayType1, MethodBase m2, int[] paramOrder2, Type paramArrayType2, Type[] types, object[] args) { int num = FindMostSpecific(m1.GetParametersNoCopy(), paramOrder1, paramArrayType1, m2.GetParametersNoCopy(), paramOrder2, paramArrayType2, types, args); if (num != 0) { return num; } if (CompareMethodSig(m1, m2)) { int hierarchyDepth = GetHierarchyDepth(m1.DeclaringType); int hierarchyDepth2 = GetHierarchyDepth(m2.DeclaringType); if (hierarchyDepth == hierarchyDepth2) { return 0; } if (hierarchyDepth < hierarchyDepth2) { return 2; } return 1; } return 0; } private static int FindMostSpecificField(FieldInfo cur1, FieldInfo cur2) { if (cur1.Name == cur2.Name) { int hierarchyDepth = GetHierarchyDepth(cur1.DeclaringType); int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType); if (hierarchyDepth == hierarchyDepth2) { return 0; } if (hierarchyDepth < hierarchyDepth2) { return 2; } return 1; } return 0; } private static int FindMostSpecificProperty(PropertyInfo cur1, PropertyInfo cur2) { if (cur1.Name == cur2.Name) { int hierarchyDepth = GetHierarchyDepth(cur1.DeclaringType); int hierarchyDepth2 = GetHierarchyDepth(cur2.DeclaringType); if (hierarchyDepth == hierarchyDepth2) { return 0; } if (hierarchyDepth < hierarchyDepth2) { return 2; } return 1; } return 0; } public static bool CompareMethodSig(MethodBase m1, MethodBase m2) { ParameterInfo[] parametersNoCopy = m1.GetParametersNoCopy(); ParameterInfo[] parametersNoCopy2 = m2.GetParametersNoCopy(); if (parametersNoCopy.Length != parametersNoCopy2.Length) { return false; } int num = parametersNoCopy.Length; for (int i = 0; i < num; i++) { if (parametersNoCopy[i].ParameterType != parametersNoCopy2[i].ParameterType) { return false; } } return true; } private static int GetHierarchyDepth(Type t) { int num = 0; Type type = t; do { num++; type = type.BaseType; } while (type != null); return num; } internal static MethodBase FindMostDerivedNewSlotMeth(MethodBase[] match, int cMatches) { int num = 0; MethodBase result = null; for (int i = 0; i < cMatches; i++) { int hierarchyDepth = GetHierarchyDepth(match[i].DeclaringType); if (hierarchyDepth == num) { throw new AmbiguousMatchException(SR.Arg_AmbiguousMatchException); } if (hierarchyDepth > num) { num = hierarchyDepth; result = match[i]; } } return result; } private static void ReorderParams(int[] paramOrder, object[] vars) { object[] array = new object[vars.Length]; for (int i = 0; i < vars.Length; i++) { array[i] = vars[i]; } for (int j = 0; j < vars.Length; j++) { vars[j] = array[paramOrder[j]]; } } private static bool CreateParamOrder(int[] paramOrder, ParameterInfo[] pars, string[] names) { bool[] array = new bool[pars.Length]; for (int i = 0; i < pars.Length; i++) { paramOrder[i] = -1; } for (int j = 0; j < names.Length; j++) { int k; for (k = 0; k < pars.Length; k++) { if (names[j].Equals(pars[k].Name)) { paramOrder[k] = j; array[j] = true; break; } } if (k == pars.Length) { return false; } } int l = 0; for (int m = 0; m < pars.Length; m++) { if (paramOrder[m] != -1) { continue; } for (; l < pars.Length; l++) { if (!array[l]) { paramOrder[m] = l; l++; break; } } } return true; } internal static bool CanChangePrimitive(Type source, Type target) { if ((source == typeof(IntPtr) && target == typeof(IntPtr)) || (source == typeof(UIntPtr) && target == typeof(UIntPtr))) { return true; } Primitives primitives = s_primitiveConversions[(int)Type.GetTypeCode(source)]; Primitives primitives2 = (Primitives)(1 << (int)Type.GetTypeCode(target)); return (primitives & primitives2) != 0; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class DivideByZeroException : ArithmeticException { public DivideByZeroException() : base(SR.Arg_DivideByZero) { base.HResult = -2147352558; } public DivideByZeroException(string? message) : base(message) { base.HResult = -2147352558; } public DivideByZeroException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2147352558; } protected DivideByZeroException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class DllNotFoundException : TypeLoadException { public DllNotFoundException() : base(SR.Arg_DllNotFoundException) { base.HResult = -2146233052; } public DllNotFoundException(string? message) : base(message) { base.HResult = -2146233052; } public DllNotFoundException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233052; } protected DllNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Double : IComparable, IConvertible, ISpanFormattable, IFormattable, IComparable, IEquatable, IBinaryFloatingPoint, IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IFloatingPoint, ISignedNumber, IMinMaxValue { private readonly double m_value; public const double MinValue = -1.7976931348623157E+308; public const double MaxValue = 1.7976931348623157E+308; public const double Epsilon = 5E-324; public const double NegativeInfinity = -1.0 / 0.0; public const double PositiveInfinity = 1.0 / 0.0; public const double NaN = 0.0 / 0.0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IAdditiveIdentity.AdditiveIdentity => 0.0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.E => Math.E; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Epsilon => double.Epsilon; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.NaN => double.NaN; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.NegativeInfinity => double.NegativeInfinity; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.NegativeZero => -0.0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Pi => Math.PI; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.PositiveInfinity => double.PositiveInfinity; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Tau => Math.PI * 2.0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IMinMaxValue.MinValue => double.MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IMinMaxValue.MaxValue => double.MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IMultiplicativeIdentity.MultiplicativeIdentity => 1.0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double INumber.One => 1.0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double INumber.Zero => 0.0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double ISignedNumber.NegativeOne => -1.0; [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsFinite(double d) { long num = BitConverter.DoubleToInt64Bits(d); return (num & 0x7FFFFFFFFFFFFFFFL) < 9218868437227405312L; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsInfinity(double d) { long num = BitConverter.DoubleToInt64Bits(d); return (num & 0x7FFFFFFFFFFFFFFFL) == 9218868437227405312L; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsNaN(double d) { return d != d; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsNegative(double d) { return BitConverter.DoubleToInt64Bits(d) < 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsNegativeInfinity(double d) { return d == double.NegativeInfinity; } [NonVersionable] public static bool IsNormal(double d) { long num = BitConverter.DoubleToInt64Bits(d); num &= 0x7FFFFFFFFFFFFFFFL; if (num < 9218868437227405312L && num != 0L) { return (num & 0x7FF0000000000000L) != 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsPositiveInfinity(double d) { return d == double.PositiveInfinity; } [NonVersionable] public static bool IsSubnormal(double d) { long num = BitConverter.DoubleToInt64Bits(d); num &= 0x7FFFFFFFFFFFFFFFL; if (num < 9218868437227405312L && num != 0L) { return (num & 0x7FF0000000000000L) == 0; } return false; } internal static int ExtractExponentFromBits(ulong bits) { return (int)(bits >> 52) & 0x7FF; } internal static ulong ExtractSignificandFromBits(ulong bits) { return bits & 0xFFFFFFFFFFFFFuL; } public int CompareTo(object? value) { if (value == null) { return 1; } if (value is double num) { if (this < num) { return -1; } if (this > num) { return 1; } if (this == num) { return 0; } if (IsNaN(this)) { if (!IsNaN(num)) { return -1; } return 0; } return 1; } throw new ArgumentException(SR.Arg_MustBeDouble); } public int CompareTo(double value) { if (this < value) { return -1; } if (this > value) { return 1; } if (this == value) { return 0; } if (IsNaN(this)) { if (!IsNaN(value)) { return -1; } return 0; } return 1; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is double num)) { return false; } if (num == this) { return true; } if (IsNaN(num)) { return IsNaN(this); } return false; } [NonVersionable] public static bool operator ==(double left, double right) { return left == right; } [NonVersionable] public static bool operator !=(double left, double right) { return left != right; } [NonVersionable] public static bool operator <(double left, double right) { return left < right; } [NonVersionable] public static bool operator >(double left, double right) { return left > right; } [NonVersionable] public static bool operator <=(double left, double right) { return left <= right; } [NonVersionable] public static bool operator >=(double left, double right) { return left >= right; } public bool Equals(double obj) { if (obj == this) { return true; } if (IsNaN(obj)) { return IsNaN(this); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { long num = Unsafe.As(ref Unsafe.AsRef(in m_value)); if (((num - 1) & 0x7FFFFFFFFFFFFFFFL) >= 9218868437227405312L) { num &= 0x7FF0000000000000L; } return (int)num ^ (int)(num >> 32); } public override string ToString() { return Number.FormatDouble(this, null, NumberFormatInfo.CurrentInfo); } public string ToString(string? format) { return Number.FormatDouble(this, format, NumberFormatInfo.CurrentInfo); } public string ToString(IFormatProvider? provider) { return Number.FormatDouble(this, null, NumberFormatInfo.GetInstance(provider)); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatDouble(this, format, NumberFormatInfo.GetInstance(provider)); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return Number.TryFormatDouble(this, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten); } public static double Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseDouble(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } public static double Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseDouble(s, style, NumberFormatInfo.CurrentInfo); } public static double Parse(string s, IFormatProvider? provider) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseDouble(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } public static double Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseDouble(s, style, NumberFormatInfo.GetInstance(provider)); } public static double Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Float | NumberStyles.AllowThousands, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.ParseDouble(s, style, NumberFormatInfo.GetInstance(provider)); } public static bool TryParse([NotNullWhen(true)] string? s, out double result) { if (s == null) { result = 0.0; return false; } return TryParse((ReadOnlySpan)s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan s, out double result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out double result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { result = 0.0; return false; } return TryParse((ReadOnlySpan)s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out double result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out double result) { return Number.TryParseDouble(s, style, info, out result); } public TypeCode GetTypeCode() { return TypeCode.Double; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(this); } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Double", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this); } double IConvertible.ToDouble(IFormatProvider provider) { return this; } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Double", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IAdditionOperators.op_Addition(double left, double right) { return left + right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IBinaryNumber.IsPow2(double value) { ulong num = BitConverter.DoubleToUInt64Bits(value); uint num2 = (uint)(int)(num >> 52) & 0x7FFu; ulong num3 = num & 0xFFFFFFFFFFFFFuL; if (value > 0.0 && num2 != 0 && num2 != 2047) { return num3 == 0; } return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IBinaryNumber.Log2(double value) { return Math.Log2(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IBitwiseOperators.op_BitwiseAnd(double left, double right) { ulong value = BitConverter.DoubleToUInt64Bits(left) & BitConverter.DoubleToUInt64Bits(right); return BitConverter.UInt64BitsToDouble(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IBitwiseOperators.op_BitwiseOr(double left, double right) { ulong value = BitConverter.DoubleToUInt64Bits(left) | BitConverter.DoubleToUInt64Bits(right); return BitConverter.UInt64BitsToDouble(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IBitwiseOperators.op_ExclusiveOr(double left, double right) { ulong value = BitConverter.DoubleToUInt64Bits(left) ^ BitConverter.DoubleToUInt64Bits(right); return BitConverter.UInt64BitsToDouble(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IBitwiseOperators.op_OnesComplement(double value) { ulong value2 = ~BitConverter.DoubleToUInt64Bits(value); return BitConverter.UInt64BitsToDouble(value2); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(double left, double right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(double left, double right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(double left, double right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(double left, double right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IDecrementOperators.op_Decrement(double value) { return value -= 1.0; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IDivisionOperators.op_Division(double left, double right) { return left / right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(double left, double right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(double left, double right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Acos(double x) { return Math.Acos(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Acosh(double x) { return Math.Acosh(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Asin(double x) { return Math.Asin(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Asinh(double x) { return Math.Asinh(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Atan(double x) { return Math.Atan(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Atan2(double y, double x) { return Math.Atan2(y, x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Atanh(double x) { return Math.Atanh(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.BitIncrement(double x) { return Math.BitIncrement(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.BitDecrement(double x) { return Math.BitDecrement(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Cbrt(double x) { return Math.Cbrt(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Ceiling(double x) { return Math.Ceiling(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.CopySign(double x, double y) { return Math.CopySign(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Cos(double x) { return Math.Cos(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Cosh(double x) { return Math.Cosh(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Exp(double x) { return Math.Exp(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Floor(double x) { return Math.Floor(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.FusedMultiplyAdd(double left, double right, double addend) { return Math.FusedMultiplyAdd(left, right, addend); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.IEEERemainder(double left, double right) { return Math.IEEERemainder(left, right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TInteger IFloatingPoint.ILogB(double x) { return TInteger.Create(Math.ILogB(x)); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Log(double x) { return Math.Log(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Log(double x, double newBase) { return Math.Log(x, newBase); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Log2(double x) { return Math.Log2(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Log10(double x) { return Math.Log10(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.MaxMagnitude(double x, double y) { return Math.MaxMagnitude(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.MinMagnitude(double x, double y) { return Math.MinMagnitude(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Pow(double x, double y) { return Math.Pow(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Round(double x) { return Math.Round(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Round(double x, TInteger digits) { return Math.Round(x, int.Create(digits)); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Round(double x, MidpointRounding mode) { return Math.Round(x, mode); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Round(double x, TInteger digits, MidpointRounding mode) { return Math.Round(x, int.Create(digits), mode); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.ScaleB(double x, TInteger n) { return Math.ScaleB(x, int.Create(n)); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Sin(double x) { return Math.Sin(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Sinh(double x) { return Math.Sinh(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Sqrt(double x) { return Math.Sqrt(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Tan(double x) { return Math.Tan(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Tanh(double x) { return Math.Tanh(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IFloatingPoint.Truncate(double x) { return Math.Truncate(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsFinite(double d) { return IsFinite(d); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsInfinity(double d) { return IsInfinity(d); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsNaN(double d) { return IsNaN(d); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsNegative(double d) { return IsNegative(d); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsNegativeInfinity(double d) { return IsNegativeInfinity(d); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsNormal(double d) { return IsNormal(d); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsPositiveInfinity(double d) { return IsPositiveInfinity(d); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsSubnormal(double d) { return IsSubnormal(d); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IIncrementOperators.op_Increment(double value) { return value += 1.0; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IModulusOperators.op_Modulus(double left, double right) { return left % right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IMultiplyOperators.op_Multiply(double left, double right) { return left * right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double INumber.Abs(double value) { return Math.Abs(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double INumber.Clamp(double value, double min, double max) { return Math.Clamp(value, min, max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double INumber.Create(TOther value) { if (typeof(TOther) == typeof(byte)) { return (int)(byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (int)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (double)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (int)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (nint)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0.0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (int)(byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (int)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (double)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (int)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (nint)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0.0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (int)(byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (int)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (double)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (int)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (nint)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0.0; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (double Quotient, double Remainder) INumber.DivRem(double left, double right) { return (left / right, left % right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double INumber.Max(double x, double y) { return Math.Max(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double INumber.Min(double x, double y) { return Math.Min(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double INumber.Sign(double value) { return Math.Sign(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out double result) { if (typeof(TOther) == typeof(byte)) { result = (int)(byte)(object)value; return true; } if (typeof(TOther) == typeof(char)) { result = (int)(char)(object)value; return true; } if (typeof(TOther) == typeof(decimal)) { result = (double)(decimal)(object)value; return true; } if (typeof(TOther) == typeof(double)) { result = (double)(object)value; return true; } if (typeof(TOther) == typeof(short)) { result = (short)(object)value; return true; } if (typeof(TOther) == typeof(int)) { result = (int)(object)value; return true; } if (typeof(TOther) == typeof(long)) { result = (long)(object)value; return true; } if (typeof(TOther) == typeof(IntPtr)) { result = (nint)(IntPtr)(object)value; return true; } if (typeof(TOther) == typeof(sbyte)) { result = (sbyte)(object)value; return true; } if (typeof(TOther) == typeof(float)) { result = (float)(object)value; return true; } if (typeof(TOther) == typeof(ushort)) { result = (int)(ushort)(object)value; return true; } if (typeof(TOther) == typeof(uint)) { result = (uint)(object)value; return true; } if (typeof(TOther) == typeof(ulong)) { result = (ulong)(object)value; return true; } if (typeof(TOther) == typeof(UIntPtr)) { result = (nint)(nuint)(UIntPtr)(object)value; return true; } ThrowHelper.ThrowNotSupportedException(); result = 0.0; return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out double result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out double result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out double result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out double result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double ISubtractionOperators.op_Subtraction(double left, double right) { return left - right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IUnaryNegationOperators.op_UnaryNegation(double value) { return 0.0 - value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IUnaryPlusOperators.op_UnaryPlus(double value) { return value; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class DuplicateWaitObjectException : ArgumentException { public DuplicateWaitObjectException() : base(SR.Arg_DuplicateWaitObjectException) { base.HResult = -2146233047; } public DuplicateWaitObjectException(string? parameterName) : base(SR.Arg_DuplicateWaitObjectException, parameterName) { base.HResult = -2146233047; } public DuplicateWaitObjectException(string? parameterName, string? message) : base(message, parameterName) { base.HResult = -2146233047; } public DuplicateWaitObjectException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233047; } protected DuplicateWaitObjectException(SerializationInfo info, StreamingContext context) : base(info, context) { } } internal sealed class Empty { public static readonly Empty Value = new Empty(); private Empty() { } public override string ToString() { return string.Empty; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class EntryPointNotFoundException : TypeLoadException { public EntryPointNotFoundException() : base(SR.Arg_EntryPointNotFoundException) { base.HResult = -2146233053; } public EntryPointNotFoundException(string? message) : base(message) { base.HResult = -2146233053; } public EntryPointNotFoundException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233053; } protected EntryPointNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public enum EnvironmentVariableTarget { Process, User, Machine } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class EventArgs { public static readonly EventArgs Empty = new EventArgs(); } public delegate void EventHandler(object? sender, EventArgs e); public delegate void EventHandler(object? sender, TEventArgs e); [Serializable] [Obsolete("ExecutionEngineException previously indicated an unspecified fatal error in the runtime. The runtime no longer raises this exception so this type is obsolete.")] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class ExecutionEngineException : SystemException { public ExecutionEngineException() : base(SR.Arg_ExecutionEngineException) { base.HResult = -2146233082; } public ExecutionEngineException(string? message) : base(message) { base.HResult = -2146233082; } public ExecutionEngineException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233082; } private ExecutionEngineException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class FieldAccessException : MemberAccessException { public FieldAccessException() : base(SR.Arg_FieldAccessException) { base.HResult = -2146233081; } public FieldAccessException(string? message) : base(message) { base.HResult = -2146233081; } public FieldAccessException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233081; } protected FieldAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [AttributeUsage(AttributeTargets.Enum, Inherited = false)] public class FlagsAttribute : Attribute { } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class FormatException : SystemException { public FormatException() : base(SR.Arg_FormatException) { base.HResult = -2146233033; } public FormatException(string? message) : base(message) { base.HResult = -2146233033; } public FormatException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233033; } protected FormatException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public abstract class FormattableString : IFormattable { public abstract string Format { get; } public abstract int ArgumentCount { get; } public abstract object?[] GetArguments(); public abstract object? GetArgument(int index); public abstract string ToString(IFormatProvider? formatProvider); string IFormattable.ToString(string ignored, IFormatProvider formatProvider) { return ToString(formatProvider); } public static string Invariant(FormattableString formattable) { if (formattable == null) { throw new ArgumentNullException("formattable"); } return formattable.ToString(CultureInfo.InvariantCulture); } public static string CurrentCulture(FormattableString formattable) { if (formattable == null) { throw new ArgumentNullException("formattable"); } return formattable.ToString(CultureInfo.CurrentCulture); } public override string ToString() { return ToString(CultureInfo.CurrentCulture); } } public delegate TResult Func(); public delegate TResult Func(T arg); public delegate TResult Func(T1 arg1, T2 arg2); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15); public delegate TResult Func(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16); public readonly struct GCGenerationInfo { public long SizeBeforeBytes { get; } public long FragmentationBeforeBytes { get; } public long SizeAfterBytes { get; } public long FragmentationAfterBytes { get; } } public enum GCKind { Any, Ephemeral, FullBlocking, Background } [StructLayout(LayoutKind.Sequential)] internal sealed class GCMemoryInfoData { internal long _highMemoryLoadThresholdBytes; internal long _totalAvailableMemoryBytes; internal long _memoryLoadBytes; internal long _heapSizeBytes; internal long _fragmentedBytes; internal long _totalCommittedBytes; internal long _promotedBytes; internal long _pinnedObjectsCount; internal long _finalizationPendingCount; internal long _index; internal int _generation; internal int _pauseTimePercentage; internal bool _compacted; internal bool _concurrent; private GCGenerationInfo _generationInfo0; private GCGenerationInfo _generationInfo1; private GCGenerationInfo _generationInfo2; private GCGenerationInfo _generationInfo3; private GCGenerationInfo _generationInfo4; private TimeSpan _pauseDuration0; private TimeSpan _pauseDuration1; internal ReadOnlySpan GenerationInfoAsSpan => MemoryMarshal.CreateReadOnlySpan(ref _generationInfo0, 5); internal ReadOnlySpan PauseDurationsAsSpan => MemoryMarshal.CreateReadOnlySpan(ref _pauseDuration0, 2); } public readonly struct GCMemoryInfo { private readonly GCMemoryInfoData _data; public long HighMemoryLoadThresholdBytes => _data._highMemoryLoadThresholdBytes; public long MemoryLoadBytes => _data._memoryLoadBytes; public long TotalAvailableMemoryBytes => _data._totalAvailableMemoryBytes; public long HeapSizeBytes => _data._heapSizeBytes; public long FragmentedBytes => _data._fragmentedBytes; public long Index => _data._index; public int Generation => _data._generation; public bool Compacted => _data._compacted; public bool Concurrent => _data._concurrent; public long TotalCommittedBytes => _data._totalCommittedBytes; public long PromotedBytes => _data._promotedBytes; public long PinnedObjectsCount => _data._pinnedObjectsCount; public long FinalizationPendingCount => _data._finalizationPendingCount; public ReadOnlySpan PauseDurations => _data.PauseDurationsAsSpan; public double PauseTimePercentage => (double)_data._pauseTimePercentage / 100.0; public ReadOnlySpan GenerationInfo => _data.GenerationInfoAsSpan; internal GCMemoryInfo(GCMemoryInfoData data) { _data = data; } } internal sealed class Gen2GcCallback : CriticalFinalizerObject { private readonly Func _callback0; private readonly Func _callback1; private GCHandle _weakTargetObj; private Gen2GcCallback(Func callback) { _callback0 = callback; } private Gen2GcCallback(Func callback, object targetObj) { _callback1 = callback; _weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak); } public static void Register(Func callback) { new Gen2GcCallback(callback); } public static void Register(Func callback, object targetObj) { new Gen2GcCallback(callback, targetObj); } ~Gen2GcCallback() { if (_weakTargetObj.IsAllocated) { object target = _weakTargetObj.Target; if (target == null) { _weakTargetObj.Free(); return; } try { if (!_callback1(target)) { _weakTargetObj.Free(); return; } } catch { } } else { try { if (!_callback0()) { return; } } catch { } } GC.ReRegisterForFinalize(this); } } internal static class DateTimeFormat { internal static char[] allStandardFormats = new char[19] { 'd', 'D', 'f', 'F', 'g', 'G', 'm', 'M', 'o', 'O', 'r', 'R', 's', 't', 'T', 'u', 'U', 'y', 'Y' }; internal static readonly DateTimeFormatInfo InvariantFormatInfo = CultureInfo.InvariantCulture.DateTimeFormat; internal static readonly string[] InvariantAbbreviatedMonthNames = InvariantFormatInfo.AbbreviatedMonthNames; internal static readonly string[] InvariantAbbreviatedDayNames = InvariantFormatInfo.AbbreviatedDayNames; internal static string[] fixedNumberFormats = new string[7] { "0", "00", "000", "0000", "00000", "000000", "0000000" }; internal static void FormatDigits(StringBuilder outputBuffer, int value, int len) { FormatDigits(outputBuffer, value, len, overrideLengthLimit: false); } internal unsafe static void FormatDigits(StringBuilder outputBuffer, int value, int len, bool overrideLengthLimit) { if (!overrideLengthLimit && len > 2) { len = 2; } char* ptr = stackalloc char[16]; char* ptr2 = ptr + 16; int num = value; do { *(--ptr2) = (char)(num % 10 + 48); num /= 10; } while (num != 0 && ptr2 > ptr); int i; for (i = (int)(ptr + 16 - ptr2); i < len; i++) { if (ptr2 <= ptr) { break; } *(--ptr2) = '0'; } outputBuffer.Append(ptr2, i); } private static void HebrewFormatDigits(StringBuilder outputBuffer, int digits) { HebrewNumber.Append(outputBuffer, digits); } internal static int ParseRepeatPattern(ReadOnlySpan format, int pos, char patternChar) { int length = format.Length; int i; for (i = pos + 1; i < length && format[i] == patternChar; i++) { } return i - pos; } private static string FormatDayOfWeek(int dayOfWeek, int repeat, DateTimeFormatInfo dtfi) { if (repeat == 3) { return dtfi.GetAbbreviatedDayName((DayOfWeek)dayOfWeek); } return dtfi.GetDayName((DayOfWeek)dayOfWeek); } private static string FormatMonth(int month, int repeatCount, DateTimeFormatInfo dtfi) { if (repeatCount == 3) { return dtfi.GetAbbreviatedMonthName(month); } return dtfi.GetMonthName(month); } private static string FormatHebrewMonthName(DateTime time, int month, int repeatCount, DateTimeFormatInfo dtfi) { if (dtfi.Calendar.IsLeapYear(dtfi.Calendar.GetYear(time))) { return dtfi.InternalGetMonthName(month, MonthNameStyles.LeapYear, repeatCount == 3); } if (month >= 7) { month++; } if (repeatCount == 3) { return dtfi.GetAbbreviatedMonthName(month); } return dtfi.GetMonthName(month); } internal static int ParseQuoteString(ReadOnlySpan format, int pos, StringBuilder result) { int length = format.Length; int num = pos; char c = format[pos++]; bool flag = false; while (pos < length) { char c2 = format[pos++]; if (c2 == c) { flag = true; break; } if (c2 == '\\') { if (pos >= length) { throw new FormatException(SR.Format_InvalidString); } result.Append(format[pos++]); } else { result.Append(c2); } } if (!flag) { throw new FormatException(SR.Format(SR.Format_BadQuote, c)); } return pos - num; } internal static int ParseNextChar(ReadOnlySpan format, int pos) { if (pos >= format.Length - 1) { return -1; } return format[pos + 1]; } private static bool IsUseGenitiveForm(ReadOnlySpan format, int index, int tokenLen, char patternToMatch) { int num = 0; int num2 = index - 1; while (num2 >= 0 && format[num2] != patternToMatch) { num2--; } if (num2 >= 0) { while (--num2 >= 0 && format[num2] == patternToMatch) { num++; } if (num <= 1) { return true; } } for (num2 = index + tokenLen; num2 < format.Length && format[num2] != patternToMatch; num2++) { } if (num2 < format.Length) { num = 0; while (++num2 < format.Length && format[num2] == patternToMatch) { num++; } if (num <= 1) { return true; } } return false; } private static StringBuilder FormatCustomized(DateTime dateTime, ReadOnlySpan format, DateTimeFormatInfo dtfi, TimeSpan offset, StringBuilder result) { Calendar calendar = dtfi.Calendar; bool flag = false; if (result == null) { flag = true; result = StringBuilderCache.Acquire(); } bool flag2 = calendar.ID == CalendarId.HEBREW; bool flag3 = calendar.ID == CalendarId.JAPAN; bool timeOnly = true; int num; for (int i = 0; i < format.Length; i += num) { char c = format[i]; switch (c) { case 'g': num = ParseRepeatPattern(format, i, c); result.Append(dtfi.GetEraName(calendar.GetEra(dateTime))); break; case 'h': { num = ParseRepeatPattern(format, i, c); int num3 = dateTime.Hour % 12; if (num3 == 0) { num3 = 12; } FormatDigits(result, num3, num); break; } case 'H': num = ParseRepeatPattern(format, i, c); FormatDigits(result, dateTime.Hour, num); break; case 'm': num = ParseRepeatPattern(format, i, c); FormatDigits(result, dateTime.Minute, num); break; case 's': num = ParseRepeatPattern(format, i, c); FormatDigits(result, dateTime.Second, num); break; case 'F': case 'f': num = ParseRepeatPattern(format, i, c); if (num <= 7) { long num4 = dateTime.Ticks % 10000000; num4 /= (long)Math.Pow(10.0, 7 - num); if (c == 'f') { result.AppendSpanFormattable((int)num4, fixedNumberFormats[num - 1], CultureInfo.InvariantCulture); break; } int num5 = num; while (num5 > 0 && num4 % 10 == 0L) { num4 /= 10; num5--; } if (num5 > 0) { result.AppendSpanFormattable((int)num4, fixedNumberFormats[num5 - 1], CultureInfo.InvariantCulture); } else if (result.Length > 0 && result[result.Length - 1] == '.') { result.Remove(result.Length - 1, 1); } break; } if (flag) { StringBuilderCache.Release(result); } throw new FormatException(SR.Format_InvalidString); case 't': num = ParseRepeatPattern(format, i, c); if (num == 1) { if (dateTime.Hour < 12) { if (dtfi.AMDesignator.Length >= 1) { result.Append(dtfi.AMDesignator[0]); } } else if (dtfi.PMDesignator.Length >= 1) { result.Append(dtfi.PMDesignator[0]); } } else { result.Append((dateTime.Hour < 12) ? dtfi.AMDesignator : dtfi.PMDesignator); } break; case 'd': num = ParseRepeatPattern(format, i, c); if (num <= 2) { int dayOfMonth = calendar.GetDayOfMonth(dateTime); if (flag2) { HebrewFormatDigits(result, dayOfMonth); } else { FormatDigits(result, dayOfMonth, num); } } else { int dayOfWeek = (int)calendar.GetDayOfWeek(dateTime); result.Append(FormatDayOfWeek(dayOfWeek, num, dtfi)); } timeOnly = false; break; case 'M': { num = ParseRepeatPattern(format, i, c); int month = calendar.GetMonth(dateTime); if (num <= 2) { if (flag2) { HebrewFormatDigits(result, month); } else { FormatDigits(result, month, num); } } else if (flag2) { result.Append(FormatHebrewMonthName(dateTime, month, num, dtfi)); } else if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0) { result.Append(dtfi.InternalGetMonthName(month, IsUseGenitiveForm(format, i, num, 'd') ? MonthNameStyles.Genitive : MonthNameStyles.Regular, num == 3)); } else { result.Append(FormatMonth(month, num, dtfi)); } timeOnly = false; break; } case 'y': { int year = calendar.GetYear(dateTime); num = ParseRepeatPattern(format, i, c); if (flag3 && !LocalAppContextSwitches.FormatJapaneseFirstYearAsANumber && year == 1 && ((i + num < format.Length && format[i + num] == '年') || (i + num < format.Length - 1 && format[i + num] == '\'' && format[i + num + 1] == '年'))) { result.Append("元"[0]); } else if (dtfi.HasForceTwoDigitYears) { FormatDigits(result, year, (num <= 2) ? num : 2); } else if (calendar.ID == CalendarId.HEBREW) { HebrewFormatDigits(result, year); } else if (num <= 2) { FormatDigits(result, year % 100, num); } else if (num <= 16) { FormatDigits(result, year, num, overrideLengthLimit: true); } else { result.Append(year.ToString("D" + num.ToString(CultureInfo.InvariantCulture), CultureInfo.InvariantCulture)); } timeOnly = false; break; } case 'z': num = ParseRepeatPattern(format, i, c); FormatCustomizedTimeZone(dateTime, offset, num, timeOnly, result); break; case 'K': num = 1; FormatCustomizedRoundripTimeZone(dateTime, offset, result); break; case ':': result.Append(dtfi.TimeSeparator); num = 1; break; case '/': result.Append(dtfi.DateSeparator); num = 1; break; case '"': case '\'': num = ParseQuoteString(format, i, result); break; case '%': { int num2 = ParseNextChar(format, i); if (num2 >= 0 && num2 != 37) { char reference = (char)num2; StringBuilder stringBuilder = FormatCustomized(dateTime, MemoryMarshal.CreateReadOnlySpan(ref reference, 1), dtfi, offset, result); num = 2; break; } if (flag) { StringBuilderCache.Release(result); } throw new FormatException(SR.Format_InvalidString); } case '\\': { int num2 = ParseNextChar(format, i); if (num2 >= 0) { result.Append((char)num2); num = 2; break; } if (flag) { StringBuilderCache.Release(result); } throw new FormatException(SR.Format_InvalidString); } default: result.Append(c); num = 1; break; } } return result; } private static void FormatCustomizedTimeZone(DateTime dateTime, TimeSpan offset, int tokenLen, bool timeOnly, StringBuilder result) { if (offset.Ticks == long.MinValue) { offset = ((timeOnly && dateTime.Ticks < 864000000000L) ? TimeZoneInfo.GetLocalUtcOffset(DateTime.Now, TimeZoneInfoOptions.NoThrowOnInvalidTime) : ((dateTime.Kind != DateTimeKind.Utc) ? TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime) : default(TimeSpan))); } if (offset.Ticks >= 0) { result.Append('+'); } else { result.Append('-'); offset = offset.Negate(); } StringBuilder stringBuilder; IFormatProvider invariantCulture; if (tokenLen <= 1) { stringBuilder = result; StringBuilder stringBuilder2 = stringBuilder; invariantCulture = CultureInfo.InvariantCulture; IFormatProvider provider = invariantCulture; StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(0, 1, stringBuilder, invariantCulture); handler.AppendFormatted(offset.Hours, "0"); stringBuilder2.Append(provider, ref handler); return; } stringBuilder = result; StringBuilder stringBuilder3 = stringBuilder; invariantCulture = CultureInfo.InvariantCulture; IFormatProvider provider2 = invariantCulture; StringBuilder.AppendInterpolatedStringHandler handler2 = new StringBuilder.AppendInterpolatedStringHandler(0, 1, stringBuilder, invariantCulture); handler2.AppendFormatted(offset.Hours, "00"); stringBuilder3.Append(provider2, ref handler2); if (tokenLen >= 3) { stringBuilder = result; StringBuilder stringBuilder4 = stringBuilder; invariantCulture = CultureInfo.InvariantCulture; IFormatProvider provider3 = invariantCulture; StringBuilder.AppendInterpolatedStringHandler handler3 = new StringBuilder.AppendInterpolatedStringHandler(1, 1, stringBuilder, invariantCulture); handler3.AppendLiteral(":"); handler3.AppendFormatted(offset.Minutes, "00"); stringBuilder4.Append(provider3, ref handler3); } } private static void FormatCustomizedRoundripTimeZone(DateTime dateTime, TimeSpan offset, StringBuilder result) { if (offset.Ticks == long.MinValue) { switch (dateTime.Kind) { case DateTimeKind.Local: break; case DateTimeKind.Utc: result.Append('Z'); return; default: return; } offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); } if (offset.Ticks >= 0) { result.Append('+'); } else { result.Append('-'); offset = offset.Negate(); } Append2DigitNumber(result, offset.Hours); result.Append(':'); Append2DigitNumber(result, offset.Minutes); } private static void Append2DigitNumber(StringBuilder result, int val) { result.Append((char)(48 + val / 10)); result.Append((char)(48 + val % 10)); } internal static string GetRealFormat(ReadOnlySpan format, DateTimeFormatInfo dtfi) { switch (format[0]) { case 'd': return dtfi.ShortDatePattern; case 'D': return dtfi.LongDatePattern; case 'f': return dtfi.LongDatePattern + " " + dtfi.ShortTimePattern; case 'F': return dtfi.FullDateTimePattern; case 'g': return dtfi.GeneralShortTimePattern; case 'G': return dtfi.GeneralLongTimePattern; case 'M': case 'm': return dtfi.MonthDayPattern; case 'O': case 'o': return "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"; case 'R': case 'r': return dtfi.RFC1123Pattern; case 's': return dtfi.SortableDateTimePattern; case 't': return dtfi.ShortTimePattern; case 'T': return dtfi.LongTimePattern; case 'u': return dtfi.UniversalSortableDateTimePattern; case 'U': return dtfi.FullDateTimePattern; case 'Y': case 'y': return dtfi.YearMonthPattern; default: throw new FormatException(SR.Format_InvalidString); } } private static string ExpandPredefinedFormat(ReadOnlySpan format, ref DateTime dateTime, ref DateTimeFormatInfo dtfi, TimeSpan offset) { switch (format[0]) { case 'O': case 'o': dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'R': case 'r': case 'u': if (offset.Ticks != long.MinValue) { dateTime -= offset; } dtfi = DateTimeFormatInfo.InvariantInfo; break; case 's': dtfi = DateTimeFormatInfo.InvariantInfo; break; case 'U': if (offset.Ticks != long.MinValue) { throw new FormatException(SR.Format_InvalidString); } dtfi = (DateTimeFormatInfo)dtfi.Clone(); if (dtfi.Calendar.GetType() != typeof(GregorianCalendar)) { dtfi.Calendar = GregorianCalendar.GetDefaultInstance(); } dateTime = dateTime.ToUniversalTime(); break; } return GetRealFormat(format, dtfi); } internal static string Format(DateTime dateTime, string format, IFormatProvider provider) { return Format(dateTime, format, provider, new TimeSpan(long.MinValue)); } internal static string Format(DateTime dateTime, string format, IFormatProvider provider, TimeSpan offset) { if (format != null && format.Length == 1) { switch (format[0]) { case 'O': case 'o': { Span destination = stackalloc char[33]; TryFormatO(dateTime, offset, destination, out var charsWritten2); return destination.Slice(0, charsWritten2).ToString(); } case 'R': case 'r': { string text = string.FastAllocateString(29); TryFormatR(dateTime, offset, new Span(ref text.GetRawStringData(), text.Length), out var _); return text; } } } DateTimeFormatInfo instance = DateTimeFormatInfo.GetInstance(provider); return StringBuilderCache.GetStringAndRelease(FormatStringBuilder(dateTime, format, instance, offset)); } internal static bool TryFormat(DateTime dateTime, Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider provider) { return TryFormat(dateTime, destination, out charsWritten, format, provider, new TimeSpan(long.MinValue)); } internal static bool TryFormat(DateTime dateTime, Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider provider, TimeSpan offset) { if (format.Length == 1) { switch (format[0]) { case 'O': case 'o': return TryFormatO(dateTime, offset, destination, out charsWritten); case 'R': case 'r': return TryFormatR(dateTime, offset, destination, out charsWritten); } } DateTimeFormatInfo instance = DateTimeFormatInfo.GetInstance(provider); StringBuilder stringBuilder = FormatStringBuilder(dateTime, format, instance, offset); bool flag = stringBuilder.Length <= destination.Length; if (flag) { stringBuilder.CopyTo(0, destination, stringBuilder.Length); charsWritten = stringBuilder.Length; } else { charsWritten = 0; } StringBuilderCache.Release(stringBuilder); return flag; } private static StringBuilder FormatStringBuilder(DateTime dateTime, ReadOnlySpan format, DateTimeFormatInfo dtfi, TimeSpan offset) { if (format.Length == 0) { bool flag = false; if (dateTime.Ticks < 864000000000L) { switch (dtfi.Calendar.ID) { case CalendarId.JAPAN: case CalendarId.TAIWAN: case CalendarId.HIJRI: case CalendarId.HEBREW: case CalendarId.JULIAN: case CalendarId.PERSIAN: case CalendarId.UMALQURA: flag = true; dtfi = DateTimeFormatInfo.InvariantInfo; break; } } format = ((offset.Ticks != long.MinValue) ? ((ReadOnlySpan)(flag ? "yyyy'-'MM'-'ddTHH':'mm':'ss zzz" : dtfi.DateTimeOffsetPattern)) : ((ReadOnlySpan)(flag ? "s" : "G"))); } if (format.Length == 1) { format = ExpandPredefinedFormat(format, ref dateTime, ref dtfi, offset); } return FormatCustomized(dateTime, format, dtfi, offset, null); } internal static bool IsValidCustomDateFormat(ReadOnlySpan format, bool throwOnError) { int i = 0; while (i < format.Length) { switch (format[i]) { case '\\': if (i == format.Length - 1) { if (throwOnError) { throw new FormatException(SR.Format_InvalidString); } return false; } i += 2; break; case '"': case '\'': { char c; for (c = format[i++]; i < format.Length && format[i] != c; i++) { } if (i >= format.Length) { if (throwOnError) { throw new FormatException(SR.Format(SR.Format_BadQuote, c)); } return false; } i++; break; } case ':': case 'F': case 'H': case 'K': case 'f': case 'h': case 'm': case 's': case 't': case 'z': if (throwOnError) { throw new FormatException(SR.Format_InvalidString); } return false; default: i++; break; } } return true; } internal static bool IsValidCustomTimeFormat(ReadOnlySpan format, bool throwOnError) { int length = format.Length; int i = 0; while (i < length) { switch (format[i]) { case '\\': if (i == length - 1) { if (throwOnError) { throw new FormatException(SR.Format_InvalidString); } return false; } i += 2; break; case '"': case '\'': { char c; for (c = format[i++]; i < length && format[i] != c; i++) { } if (i >= length) { if (throwOnError) { throw new FormatException(SR.Format(SR.Format_BadQuote, c)); } return false; } i++; break; } case '/': case 'M': case 'd': case 'k': case 'y': case 'z': if (throwOnError) { throw new FormatException(SR.Format_InvalidString); } return false; default: i++; break; } } return true; } internal static bool TryFormatTimeOnlyO(int hour, int minute, int second, long fraction, Span destination) { if (destination.Length < 16) { return false; } WriteTwoDecimalDigits((uint)hour, destination, 0); destination[2] = ':'; WriteTwoDecimalDigits((uint)minute, destination, 3); destination[5] = ':'; WriteTwoDecimalDigits((uint)second, destination, 6); destination[8] = '.'; WriteDigits((uint)fraction, destination.Slice(9, 7)); return true; } internal static bool TryFormatTimeOnlyR(int hour, int minute, int second, Span destination) { if (destination.Length < 8) { return false; } WriteTwoDecimalDigits((uint)hour, destination, 0); destination[2] = ':'; WriteTwoDecimalDigits((uint)minute, destination, 3); destination[5] = ':'; WriteTwoDecimalDigits((uint)second, destination, 6); return true; } internal static bool TryFormatDateOnlyO(int year, int month, int day, Span destination) { if (destination.Length < 10) { return false; } WriteFourDecimalDigits((uint)year, destination); destination[4] = '-'; WriteTwoDecimalDigits((uint)month, destination, 5); destination[7] = '-'; WriteTwoDecimalDigits((uint)day, destination, 8); return true; } internal static bool TryFormatDateOnlyR(DayOfWeek dayOfWeek, int year, int month, int day, Span destination) { if (destination.Length < 16) { return false; } string text = InvariantAbbreviatedDayNames[(int)dayOfWeek]; string text2 = InvariantAbbreviatedMonthNames[month - 1]; destination[0] = text[0]; destination[1] = text[1]; destination[2] = text[2]; destination[3] = ','; destination[4] = ' '; WriteTwoDecimalDigits((uint)day, destination, 5); destination[7] = ' '; destination[8] = text2[0]; destination[9] = text2[1]; destination[10] = text2[2]; destination[11] = ' '; WriteFourDecimalDigits((uint)year, destination, 12); return true; } private static bool TryFormatO(DateTime dateTime, TimeSpan offset, Span destination, out int charsWritten) { int num = 27; DateTimeKind dateTimeKind = DateTimeKind.Local; if (offset.Ticks == long.MinValue) { dateTimeKind = dateTime.Kind; switch (dateTimeKind) { case DateTimeKind.Local: offset = TimeZoneInfo.Local.GetUtcOffset(dateTime); num += 6; break; case DateTimeKind.Utc: num++; break; } } else { num += 6; } if (destination.Length < num) { charsWritten = 0; return false; } charsWritten = num; _ = ref destination[26]; dateTime.GetDate(out var year, out var month, out var day); dateTime.GetTimePrecise(out var hour, out var minute, out var second, out var tick); WriteFourDecimalDigits((uint)year, destination); destination[4] = '-'; WriteTwoDecimalDigits((uint)month, destination, 5); destination[7] = '-'; WriteTwoDecimalDigits((uint)day, destination, 8); destination[10] = 'T'; WriteTwoDecimalDigits((uint)hour, destination, 11); destination[13] = ':'; WriteTwoDecimalDigits((uint)minute, destination, 14); destination[16] = ':'; WriteTwoDecimalDigits((uint)second, destination, 17); destination[19] = '.'; WriteDigits((uint)tick, destination.Slice(20, 7)); switch (dateTimeKind) { case DateTimeKind.Local: { int num2 = (int)(offset.Ticks / 600000000); char c; if (num2 < 0) { c = '-'; num2 = -num2; } else { c = '+'; } int result; int value = Math.DivRem(num2, 60, out result); WriteTwoDecimalDigits((uint)result, destination, 31); destination[30] = ':'; WriteTwoDecimalDigits((uint)value, destination, 28); destination[27] = c; break; } case DateTimeKind.Utc: destination[27] = 'Z'; break; } return true; } private static bool TryFormatR(DateTime dateTime, TimeSpan offset, Span destination, out int charsWritten) { if (destination.Length <= 28) { charsWritten = 0; return false; } if (offset.Ticks != long.MinValue) { dateTime -= offset; } dateTime.GetDate(out var year, out var month, out var day); dateTime.GetTime(out var hour, out var minute, out var second); string text = InvariantAbbreviatedDayNames[(int)dateTime.DayOfWeek]; string text2 = InvariantAbbreviatedMonthNames[month - 1]; destination[0] = text[0]; destination[1] = text[1]; destination[2] = text[2]; destination[3] = ','; destination[4] = ' '; WriteTwoDecimalDigits((uint)day, destination, 5); destination[7] = ' '; destination[8] = text2[0]; destination[9] = text2[1]; destination[10] = text2[2]; destination[11] = ' '; WriteFourDecimalDigits((uint)year, destination, 12); destination[16] = ' '; WriteTwoDecimalDigits((uint)hour, destination, 17); destination[19] = ':'; WriteTwoDecimalDigits((uint)minute, destination, 20); destination[22] = ':'; WriteTwoDecimalDigits((uint)second, destination, 23); destination[25] = ' '; destination[26] = 'G'; destination[27] = 'M'; destination[28] = 'T'; charsWritten = 29; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteTwoDecimalDigits(uint value, Span destination, int offset) { uint num = 48 + value; value /= 10; destination[offset + 1] = (char)(num - value * 10); destination[offset] = (char)(48 + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteFourDecimalDigits(uint value, Span buffer, int startingIndex = 0) { uint num = 48 + value; value /= 10; buffer[startingIndex + 3] = (char)(num - value * 10); num = 48 + value; value /= 10; buffer[startingIndex + 2] = (char)(num - value * 10); num = 48 + value; value /= 10; buffer[startingIndex + 1] = (char)(num - value * 10); buffer[startingIndex] = (char)(48 + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteDigits(ulong value, Span buffer) { for (int num = buffer.Length - 1; num >= 1; num--) { ulong num2 = 48 + value; value /= 10; buffer[num] = (char)(num2 - value * 10); } buffer[0] = (char)(48 + value); } internal static string[] GetAllDateTimes(DateTime dateTime, char format, DateTimeFormatInfo dtfi) { string[] array; switch (format) { case 'D': case 'F': case 'G': case 'M': case 'T': case 'Y': case 'd': case 'f': case 'g': case 'm': case 't': case 'y': { string[] allDateTimePatterns = dtfi.GetAllDateTimePatterns(format); array = new string[allDateTimePatterns.Length]; for (int j = 0; j < allDateTimePatterns.Length; j++) { array[j] = Format(dateTime, allDateTimePatterns[j], dtfi); } break; } case 'U': { DateTime dateTime2 = dateTime.ToUniversalTime(); string[] allDateTimePatterns = dtfi.GetAllDateTimePatterns(format); array = new string[allDateTimePatterns.Length]; for (int i = 0; i < allDateTimePatterns.Length; i++) { array[i] = Format(dateTime2, allDateTimePatterns[i], dtfi); } break; } case 'O': case 'R': case 'o': case 'r': case 's': case 'u': array = new string[1] { Format(dateTime, char.ToString(format), dtfi) }; break; default: throw new FormatException(SR.Format_InvalidString); } return array; } internal static string[] GetAllDateTimes(DateTime dateTime, DateTimeFormatInfo dtfi) { List list = new List(132); for (int i = 0; i < allStandardFormats.Length; i++) { string[] allDateTimes = GetAllDateTimes(dateTime, allStandardFormats[i], dtfi); for (int j = 0; j < allDateTimes.Length; j++) { list.Add(allDateTimes[j]); } } return list.ToArray(); } } internal static class DateTimeParse { internal delegate bool MatchNumberDelegate(ref __DTString str, int digitLen, out int result); internal enum DTT { End, NumEnd, NumAmpm, NumSpace, NumDatesep, NumTimesep, MonthEnd, MonthSpace, MonthDatesep, NumDatesuff, NumTimesuff, DayOfWeek, YearSpace, YearDateSep, YearEnd, TimeZone, Era, NumUTCTimeMark, Unk, NumLocalTimeMark, Max } internal enum TM { NotSet = -1, AM, PM } internal enum DS { BEGIN, N, NN, D_Nd, D_NN, D_NNd, D_M, D_MN, D_NM, D_MNd, D_NDS, D_Y, D_YN, D_YNd, D_YM, D_YMd, D_S, T_S, T_Nt, T_NNt, ERROR, DX_NN, DX_NNN, DX_MN, DX_NM, DX_MNN, DX_DS, DX_DSN, DX_NDS, DX_NNDS, DX_YNN, DX_YMN, DX_YN, DX_YM, TX_N, TX_NN, TX_NNN, TX_TS, DX_NNY } private static readonly MatchNumberDelegate s_hebrewNumberParser = MatchHebrewDigits; private static readonly DS[][] s_dateParsingStates = new DS[20][] { new DS[18] { DS.BEGIN, DS.ERROR, DS.TX_N, DS.N, DS.D_Nd, DS.T_Nt, DS.ERROR, DS.D_M, DS.D_M, DS.D_S, DS.T_S, DS.BEGIN, DS.D_Y, DS.D_Y, DS.ERROR, DS.BEGIN, DS.BEGIN, DS.ERROR }, new DS[18] { DS.ERROR, DS.DX_NN, DS.ERROR, DS.NN, DS.D_NNd, DS.ERROR, DS.DX_NM, DS.D_NM, DS.D_MNd, DS.D_NDS, DS.ERROR, DS.N, DS.D_YN, DS.D_YNd, DS.DX_YN, DS.N, DS.N, DS.ERROR }, new DS[18] { DS.DX_NN, DS.DX_NNN, DS.TX_N, DS.DX_NNN, DS.ERROR, DS.T_Nt, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.ERROR, DS.T_S, DS.NN, DS.DX_NNY, DS.ERROR, DS.DX_NNY, DS.NN, DS.NN, DS.ERROR }, new DS[18] { DS.ERROR, DS.DX_NN, DS.ERROR, DS.D_NN, DS.D_NNd, DS.ERROR, DS.DX_NM, DS.D_MN, DS.D_MNd, DS.ERROR, DS.ERROR, DS.D_Nd, DS.D_YN, DS.D_YNd, DS.DX_YN, DS.ERROR, DS.D_Nd, DS.ERROR }, new DS[18] { DS.DX_NN, DS.DX_NNN, DS.TX_N, DS.DX_NNN, DS.ERROR, DS.T_Nt, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.DX_DS, DS.T_S, DS.D_NN, DS.DX_NNY, DS.ERROR, DS.DX_NNY, DS.ERROR, DS.D_NN, DS.ERROR }, new DS[18] { DS.ERROR, DS.DX_NNN, DS.DX_NNN, DS.DX_NNN, DS.ERROR, DS.ERROR, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.DX_DS, DS.ERROR, DS.D_NNd, DS.DX_NNY, DS.ERROR, DS.DX_NNY, DS.ERROR, DS.D_NNd, DS.ERROR }, new DS[18] { DS.ERROR, DS.DX_MN, DS.ERROR, DS.D_MN, DS.D_MNd, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_M, DS.D_YM, DS.D_YMd, DS.DX_YM, DS.ERROR, DS.D_M, DS.ERROR }, new DS[18] { DS.DX_MN, DS.DX_MNN, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.DX_DS, DS.T_S, DS.D_MN, DS.DX_YMN, DS.ERROR, DS.DX_YMN, DS.ERROR, DS.D_MN, DS.ERROR }, new DS[18] { DS.DX_NM, DS.DX_MNN, DS.DX_MNN, DS.DX_MNN, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.DX_DS, DS.T_S, DS.D_NM, DS.DX_YMN, DS.ERROR, DS.DX_YMN, DS.ERROR, DS.D_NM, DS.ERROR }, new DS[18] { DS.ERROR, DS.DX_MNN, DS.ERROR, DS.DX_MNN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_MNd, DS.DX_YMN, DS.ERROR, DS.DX_YMN, DS.ERROR, DS.D_MNd, DS.ERROR }, new DS[18] { DS.DX_NDS, DS.DX_NNDS, DS.DX_NNDS, DS.DX_NNDS, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_NDS, DS.T_S, DS.D_NDS, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_NDS, DS.ERROR }, new DS[18] { DS.ERROR, DS.DX_YN, DS.ERROR, DS.D_YN, DS.D_YNd, DS.ERROR, DS.DX_YM, DS.D_YM, DS.D_YMd, DS.D_YM, DS.ERROR, DS.D_Y, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_Y, DS.ERROR }, new DS[18] { DS.DX_YN, DS.DX_YNN, DS.DX_YNN, DS.DX_YNN, DS.ERROR, DS.ERROR, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR }, new DS[18] { DS.ERROR, DS.DX_YNN, DS.DX_YNN, DS.DX_YNN, DS.ERROR, DS.ERROR, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YN, DS.ERROR }, new DS[18] { DS.DX_YM, DS.DX_YMN, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR }, new DS[18] { DS.ERROR, DS.DX_YMN, DS.DX_YMN, DS.DX_YMN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_YM, DS.ERROR }, new DS[18] { DS.DX_DS, DS.DX_DSN, DS.TX_N, DS.T_Nt, DS.ERROR, DS.T_Nt, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_S, DS.T_S, DS.D_S, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_S, DS.ERROR }, new DS[18] { DS.TX_TS, DS.TX_TS, DS.TX_TS, DS.T_Nt, DS.D_Nd, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.D_S, DS.T_S, DS.T_S, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_S, DS.T_S, DS.ERROR }, new DS[18] { DS.ERROR, DS.TX_NN, DS.TX_NN, DS.TX_NN, DS.ERROR, DS.T_NNt, DS.DX_NM, DS.D_NM, DS.ERROR, DS.ERROR, DS.T_S, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_Nt, DS.T_Nt, DS.TX_NN }, new DS[18] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_S, DS.T_NNt, DS.ERROR, DS.ERROR, DS.ERROR, DS.T_NNt, DS.T_NNt, DS.TX_NNN } }; internal static DateTime ParseExact(ReadOnlySpan s, ReadOnlySpan format, DateTimeFormatInfo dtfi, DateTimeStyles style) { DateTimeResult result = default(DateTimeResult); result.Init(s); if (TryParseExact(s, format, dtfi, style, ref result)) { return result.parsedDate; } throw GetDateTimeParseException(ref result); } internal static DateTime ParseExact(ReadOnlySpan s, ReadOnlySpan format, DateTimeFormatInfo dtfi, DateTimeStyles style, out TimeSpan offset) { DateTimeResult result = default(DateTimeResult); result.Init(s); result.flags |= ParseFlags.CaptureOffset; if (TryParseExact(s, format, dtfi, style, ref result)) { offset = result.timeZoneOffset; return result.parsedDate; } throw GetDateTimeParseException(ref result); } internal static bool TryParseExact(ReadOnlySpan s, ReadOnlySpan format, DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result) { DateTimeResult result2 = default(DateTimeResult); result2.Init(s); if (TryParseExact(s, format, dtfi, style, ref result2)) { result = result2.parsedDate; return true; } result = DateTime.MinValue; return false; } internal static bool TryParseExact(ReadOnlySpan s, ReadOnlySpan format, DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result, out TimeSpan offset) { DateTimeResult result2 = default(DateTimeResult); result2.Init(s); result2.flags |= ParseFlags.CaptureOffset; if (TryParseExact(s, format, dtfi, style, ref result2)) { result = result2.parsedDate; offset = result2.timeZoneOffset; return true; } result = DateTime.MinValue; offset = TimeSpan.Zero; return false; } internal static bool TryParseExact(ReadOnlySpan s, ReadOnlySpan format, DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result) { if (s.Length == 0) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDateTime"); return false; } if (format.Length == 0) { result.SetBadFormatSpecifierFailure(); return false; } return DoStrictParse(s, format, style, dtfi, ref result); } internal static DateTime ParseExactMultiple(ReadOnlySpan s, string[] formats, DateTimeFormatInfo dtfi, DateTimeStyles style) { DateTimeResult result = default(DateTimeResult); result.Init(s); if (TryParseExactMultiple(s, formats, dtfi, style, ref result)) { return result.parsedDate; } throw GetDateTimeParseException(ref result); } internal static DateTime ParseExactMultiple(ReadOnlySpan s, string[] formats, DateTimeFormatInfo dtfi, DateTimeStyles style, out TimeSpan offset) { DateTimeResult result = default(DateTimeResult); result.Init(s); result.flags |= ParseFlags.CaptureOffset; if (TryParseExactMultiple(s, formats, dtfi, style, ref result)) { offset = result.timeZoneOffset; return result.parsedDate; } throw GetDateTimeParseException(ref result); } internal static bool TryParseExactMultiple(ReadOnlySpan s, string[] formats, DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result, out TimeSpan offset) { DateTimeResult result2 = default(DateTimeResult); result2.Init(s); result2.flags |= ParseFlags.CaptureOffset; if (TryParseExactMultiple(s, formats, dtfi, style, ref result2)) { result = result2.parsedDate; offset = result2.timeZoneOffset; return true; } result = DateTime.MinValue; offset = TimeSpan.Zero; return false; } internal static bool TryParseExactMultiple(ReadOnlySpan s, string[] formats, DateTimeFormatInfo dtfi, DateTimeStyles style, out DateTime result) { DateTimeResult result2 = default(DateTimeResult); result2.Init(s); if (TryParseExactMultiple(s, formats, dtfi, style, ref result2)) { result = result2.parsedDate; return true; } result = DateTime.MinValue; return false; } internal static bool TryParseExactMultiple(ReadOnlySpan s, string[] formats, DateTimeFormatInfo dtfi, DateTimeStyles style, ref DateTimeResult result) { if (formats == null) { result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, "formats"); return false; } if (s.Length == 0) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDateTime"); return false; } if (formats.Length == 0) { result.SetFailure(ParseFailureKind.Format, "Format_NoFormatSpecifier"); return false; } foreach (string text in formats) { if (string.IsNullOrEmpty(text)) { result.SetBadFormatSpecifierFailure(); return false; } DateTimeResult result2 = default(DateTimeResult); result2.Init(s); result2.flags = result.flags; if (TryParseExact(s, text, dtfi, style, ref result2)) { result.parsedDate = result2.parsedDate; result.timeZoneOffset = result2.timeZoneOffset; return true; } } result.SetBadDateTimeFailure(); return false; } private static bool MatchWord(ref __DTString str, string target) { if (target.Length > str.Value.Length - str.Index) { return false; } if (str.CompareInfo.Compare(str.Value.Slice(str.Index, target.Length), target, CompareOptions.IgnoreCase) != 0) { return false; } int num = str.Index + target.Length; if (num < str.Value.Length) { char c = str.Value[num]; if (char.IsLetter(c)) { return false; } } str.Index = num; if (str.Index < str.Length) { str.m_current = str.Value[str.Index]; } return true; } private static bool GetTimeZoneName(ref __DTString str) { if (MatchWord(ref str, "GMT")) { return true; } if (MatchWord(ref str, "Z")) { return true; } return false; } internal static bool IsDigit(char ch) { return (uint)(ch - 48) <= 9u; } private static bool ParseFraction(ref __DTString str, out double result) { result = 0.0; double num = 0.1; int num2 = 0; char current; while (str.GetNext() && IsDigit(current = str.m_current)) { result += (double)(current - 48) * num; num *= 0.1; num2++; } return num2 > 0; } private static bool ParseTimeZone(ref __DTString str, ref TimeSpan result) { int num = 0; DTSubString subString = str.GetSubString(); if (subString.length != 1) { return false; } char c = subString[0]; if (c != '+' && c != '-') { return false; } str.ConsumeSubString(subString); subString = str.GetSubString(); if (subString.type != DTSubStringType.Number) { return false; } int value = subString.value; int hours; switch (subString.length) { case 1: case 2: hours = value; str.ConsumeSubString(subString); subString = str.GetSubString(); if (subString.length == 1 && subString[0] == ':') { str.ConsumeSubString(subString); subString = str.GetSubString(); if (subString.type != DTSubStringType.Number || subString.length < 1 || subString.length > 2) { return false; } num = subString.value; str.ConsumeSubString(subString); } break; case 3: case 4: hours = value / 100; num = value % 100; str.ConsumeSubString(subString); break; default: return false; } if (num < 0 || num >= 60) { return false; } result = new TimeSpan(hours, num, 0); if (c == '-') { result = result.Negate(); } return true; } private static bool HandleTimeZone(ref __DTString str, ref DateTimeResult result) { if (str.Index < str.Length - 1) { char c = str.Value[str.Index]; int num = 0; while (char.IsWhiteSpace(c) && str.Index + num < str.Length - 1) { num++; c = str.Value[str.Index + num]; } if (c == '+' || c == '-') { str.Index += num; if ((result.flags & ParseFlags.TimeZoneUsed) != 0) { result.SetBadDateTimeFailure(); return false; } result.flags |= ParseFlags.TimeZoneUsed; if (!ParseTimeZone(ref str, ref result.timeZoneOffset)) { result.SetBadDateTimeFailure(); return false; } } } return true; } private static bool Lex(DS dps, ref __DTString str, ref DateTimeToken dtok, ref DateTimeRawInfo raw, ref DateTimeResult result, ref DateTimeFormatInfo dtfi, DateTimeStyles styles) { dtok.dtt = DTT.Unk; str.GetRegularToken(out var tokenType, out var tokenValue, dtfi); int indexBeforeSeparator; char charBeforeSeparator; switch (tokenType) { case TokenType.NumberToken: case TokenType.YearNumberToken: { if (raw.numCount == 3 || tokenValue == -1) { result.SetBadDateTimeFailure(); return false; } if (dps == DS.T_NNt && str.Index < str.Length - 1) { char c = str.Value[str.Index]; if (c == '.') { ParseFraction(ref str, out raw.fraction); } } if ((dps == DS.T_NNt || dps == DS.T_Nt) && str.Index < str.Length - 1 && !HandleTimeZone(ref str, ref result)) { return false; } dtok.num = tokenValue; TokenType separatorToken; if (tokenType == TokenType.YearNumberToken) { if (raw.year == -1) { raw.year = tokenValue; switch (separatorToken = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator)) { case TokenType.SEP_End: dtok.dtt = DTT.YearEnd; break; case TokenType.SEP_Am: case TokenType.SEP_Pm: if (raw.timeMark == TM.NotSet) { raw.timeMark = ((separatorToken != TokenType.SEP_Am) ? TM.PM : TM.AM); dtok.dtt = DTT.YearSpace; } else { result.SetBadDateTimeFailure(); } break; case TokenType.SEP_Space: dtok.dtt = DTT.YearSpace; break; case TokenType.SEP_Date: dtok.dtt = DTT.YearDateSep; break; case TokenType.SEP_Time: if (!raw.hasSameDateAndTimeSeparators) { result.SetBadDateTimeFailure(); return false; } dtok.dtt = DTT.YearDateSep; break; case TokenType.SEP_DateOrOffset: if (s_dateParsingStates[(int)dps][13] == DS.ERROR && s_dateParsingStates[(int)dps][12] > DS.ERROR) { str.Index = indexBeforeSeparator; str.m_current = charBeforeSeparator; dtok.dtt = DTT.YearSpace; } else { dtok.dtt = DTT.YearDateSep; } break; case TokenType.SEP_YearSuff: case TokenType.SEP_MonthSuff: case TokenType.SEP_DaySuff: dtok.dtt = DTT.NumDatesuff; dtok.suffix = separatorToken; break; case TokenType.SEP_HourSuff: case TokenType.SEP_MinuteSuff: case TokenType.SEP_SecondSuff: dtok.dtt = DTT.NumTimesuff; dtok.suffix = separatorToken; break; default: result.SetBadDateTimeFailure(); return false; } return true; } result.SetBadDateTimeFailure(); return false; } switch (separatorToken = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator)) { case TokenType.SEP_End: dtok.dtt = DTT.NumEnd; raw.AddNumber(dtok.num); break; case TokenType.SEP_Am: case TokenType.SEP_Pm: if (raw.timeMark == TM.NotSet) { raw.timeMark = ((separatorToken != TokenType.SEP_Am) ? TM.PM : TM.AM); dtok.dtt = DTT.NumAmpm; if (dps == DS.D_NN && !ProcessTerminalState(DS.DX_NN, ref result, ref styles, ref raw, dtfi)) { return false; } raw.AddNumber(dtok.num); if ((dps == DS.T_NNt || dps == DS.T_Nt) && !HandleTimeZone(ref str, ref result)) { return false; } } else { result.SetBadDateTimeFailure(); } break; case TokenType.SEP_Space: dtok.dtt = DTT.NumSpace; raw.AddNumber(dtok.num); break; case TokenType.SEP_Date: dtok.dtt = DTT.NumDatesep; raw.AddNumber(dtok.num); break; case TokenType.SEP_DateOrOffset: if (s_dateParsingStates[(int)dps][4] == DS.ERROR && s_dateParsingStates[(int)dps][3] > DS.ERROR) { str.Index = indexBeforeSeparator; str.m_current = charBeforeSeparator; dtok.dtt = DTT.NumSpace; } else { dtok.dtt = DTT.NumDatesep; } raw.AddNumber(dtok.num); break; case TokenType.SEP_Time: if (raw.hasSameDateAndTimeSeparators && (dps == DS.D_Y || dps == DS.D_YN || dps == DS.D_YNd || dps == DS.D_YM || dps == DS.D_YMd)) { dtok.dtt = DTT.NumDatesep; raw.AddNumber(dtok.num); } else { dtok.dtt = DTT.NumTimesep; raw.AddNumber(dtok.num); } break; case TokenType.SEP_YearSuff: try { dtok.num = dtfi.Calendar.ToFourDigitYear(tokenValue); } catch (ArgumentOutOfRangeException) { result.SetBadDateTimeFailure(); return false; } dtok.dtt = DTT.NumDatesuff; dtok.suffix = separatorToken; break; case TokenType.SEP_MonthSuff: case TokenType.SEP_DaySuff: dtok.dtt = DTT.NumDatesuff; dtok.suffix = separatorToken; break; case TokenType.SEP_HourSuff: case TokenType.SEP_MinuteSuff: case TokenType.SEP_SecondSuff: dtok.dtt = DTT.NumTimesuff; dtok.suffix = separatorToken; break; case TokenType.SEP_LocalTimeMark: dtok.dtt = DTT.NumLocalTimeMark; raw.AddNumber(dtok.num); break; default: result.SetBadDateTimeFailure(); return false; } break; } case TokenType.HebrewNumber: { TokenType separatorToken; if (tokenValue >= 100) { if (raw.year == -1) { raw.year = tokenValue; TokenType tokenType2 = (separatorToken = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator)); if (tokenType2 != TokenType.SEP_End) { if (tokenType2 != TokenType.SEP_Space) { if (tokenType2 != TokenType.SEP_DateOrOffset || s_dateParsingStates[(int)dps][12] <= DS.ERROR) { result.SetBadDateTimeFailure(); return false; } str.Index = indexBeforeSeparator; str.m_current = charBeforeSeparator; dtok.dtt = DTT.YearSpace; } else { dtok.dtt = DTT.YearSpace; } } else { dtok.dtt = DTT.YearEnd; } break; } result.SetBadDateTimeFailure(); return false; } dtok.num = tokenValue; raw.AddNumber(dtok.num); switch (separatorToken = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator)) { case TokenType.SEP_End: dtok.dtt = DTT.NumEnd; break; case TokenType.SEP_Space: case TokenType.SEP_Date: dtok.dtt = DTT.NumDatesep; break; case TokenType.SEP_DateOrOffset: if (s_dateParsingStates[(int)dps][4] == DS.ERROR && s_dateParsingStates[(int)dps][3] > DS.ERROR) { str.Index = indexBeforeSeparator; str.m_current = charBeforeSeparator; dtok.dtt = DTT.NumSpace; } else { dtok.dtt = DTT.NumDatesep; } break; default: result.SetBadDateTimeFailure(); return false; } break; } case TokenType.DayOfWeekToken: if (raw.dayOfWeek == -1) { raw.dayOfWeek = tokenValue; dtok.dtt = DTT.DayOfWeek; break; } result.SetBadDateTimeFailure(); return false; case TokenType.MonthToken: if (raw.month == -1) { TokenType separatorToken; switch (separatorToken = str.GetSeparatorToken(dtfi, out indexBeforeSeparator, out charBeforeSeparator)) { case TokenType.SEP_End: dtok.dtt = DTT.MonthEnd; break; case TokenType.SEP_Space: dtok.dtt = DTT.MonthSpace; break; case TokenType.SEP_Date: dtok.dtt = DTT.MonthDatesep; break; case TokenType.SEP_Time: if (!raw.hasSameDateAndTimeSeparators) { result.SetBadDateTimeFailure(); return false; } dtok.dtt = DTT.MonthDatesep; break; case TokenType.SEP_DateOrOffset: if (s_dateParsingStates[(int)dps][8] == DS.ERROR && s_dateParsingStates[(int)dps][7] > DS.ERROR) { str.Index = indexBeforeSeparator; str.m_current = charBeforeSeparator; dtok.dtt = DTT.MonthSpace; } else { dtok.dtt = DTT.MonthDatesep; } break; default: result.SetBadDateTimeFailure(); return false; } raw.month = tokenValue; break; } result.SetBadDateTimeFailure(); return false; case TokenType.EraToken: if (result.era != -1) { result.era = tokenValue; dtok.dtt = DTT.Era; break; } result.SetBadDateTimeFailure(); return false; case TokenType.JapaneseEraToken: if (GlobalizationMode.Invariant) { return false; } result.calendar = JapaneseCalendar.GetDefaultInstance(); dtfi = DateTimeFormatInfo.GetJapaneseCalendarDTFI(); if (result.era != -1) { result.era = tokenValue; dtok.dtt = DTT.Era; break; } result.SetBadDateTimeFailure(); return false; case TokenType.TEraToken: if (GlobalizationMode.Invariant) { return false; } result.calendar = TaiwanCalendar.GetDefaultInstance(); dtfi = DateTimeFormatInfo.GetTaiwanCalendarDTFI(); if (result.era != -1) { result.era = tokenValue; dtok.dtt = DTT.Era; break; } result.SetBadDateTimeFailure(); return false; case TokenType.TimeZoneToken: if ((result.flags & ParseFlags.TimeZoneUsed) != 0) { result.SetBadDateTimeFailure(); return false; } dtok.dtt = DTT.TimeZone; result.flags |= ParseFlags.TimeZoneUsed; result.timeZoneOffset = new TimeSpan(0L); result.flags |= ParseFlags.TimeZoneUtc; break; case TokenType.EndOfString: dtok.dtt = DTT.End; break; case TokenType.Am: case TokenType.Pm: if (raw.timeMark == TM.NotSet) { raw.timeMark = (TM)tokenValue; break; } result.SetBadDateTimeFailure(); return false; case TokenType.UnknownToken: if (char.IsLetter(str.m_current)) { result.SetFailure(ParseFailureKind.FormatWithOriginalDateTimeAndParameter, "Format_UnknownDateTimeWord", str.Index); return false; } if ((str.m_current == '-' || str.m_current == '+') && (result.flags & ParseFlags.TimeZoneUsed) == 0) { int index = str.Index; if (ParseTimeZone(ref str, ref result.timeZoneOffset)) { result.flags |= ParseFlags.TimeZoneUsed; return true; } str.Index = index; } if (VerifyValidPunctuation(ref str)) { return true; } result.SetBadDateTimeFailure(); return false; } return true; } private static bool VerifyValidPunctuation(ref __DTString str) { switch (str.Value[str.Index]) { case '#': { bool flag = false; bool flag2 = false; for (int j = 0; j < str.Length; j++) { char c = str.Value[j]; switch (c) { case '#': if (flag) { if (flag2) { return false; } flag2 = true; } else { flag = true; } break; case '\0': if (!flag2) { return false; } break; default: if (!char.IsWhiteSpace(c) && (!flag || flag2)) { return false; } break; } } if (!flag2) { return false; } str.GetNext(); return true; } case '\0': { for (int i = str.Index; i < str.Length; i++) { if (str.Value[i] != 0) { return false; } } str.Index = str.Length; return true; } default: return false; } } private static bool GetYearMonthDayOrder(string datePattern, out int order) { int num = -1; int num2 = -1; int num3 = -1; int num4 = 0; bool flag = false; for (int i = 0; i < datePattern.Length && num4 < 3; i++) { char c = datePattern[i]; switch (c) { case '%': case '\\': i++; continue; case '"': case '\'': flag = !flag; break; } if (flag) { continue; } switch (c) { case 'y': num = num4++; for (; i + 1 < datePattern.Length && datePattern[i + 1] == 'y'; i++) { } break; case 'M': num2 = num4++; for (; i + 1 < datePattern.Length && datePattern[i + 1] == 'M'; i++) { } break; case 'd': { int num5 = 1; for (; i + 1 < datePattern.Length && datePattern[i + 1] == 'd'; i++) { num5++; } if (num5 <= 2) { num3 = num4++; } break; } } } if (num == 0 && num2 == 1 && num3 == 2) { order = 0; return true; } if (num2 == 0 && num3 == 1 && num == 2) { order = 1; return true; } if (num3 == 0 && num2 == 1 && num == 2) { order = 2; return true; } if (num == 0 && num3 == 1 && num2 == 2) { order = 3; return true; } order = -1; return false; } private static bool GetYearMonthOrder(string pattern, out int order) { int num = -1; int num2 = -1; int num3 = 0; bool flag = false; for (int i = 0; i < pattern.Length && num3 < 2; i++) { char c = pattern[i]; switch (c) { case '%': case '\\': i++; continue; case '"': case '\'': flag = !flag; break; } if (flag) { continue; } switch (c) { case 'y': num = num3++; for (; i + 1 < pattern.Length && pattern[i + 1] == 'y'; i++) { } break; case 'M': num2 = num3++; for (; i + 1 < pattern.Length && pattern[i + 1] == 'M'; i++) { } break; } } if (num == 0 && num2 == 1) { order = 4; return true; } if (num2 == 0 && num == 1) { order = 5; return true; } order = -1; return false; } private static bool GetMonthDayOrder(string pattern, out int order) { int num = -1; int num2 = -1; int num3 = 0; bool flag = false; for (int i = 0; i < pattern.Length && num3 < 2; i++) { char c = pattern[i]; switch (c) { case '%': case '\\': i++; continue; case '"': case '\'': flag = !flag; break; } if (flag) { continue; } switch (c) { case 'd': { int num4 = 1; for (; i + 1 < pattern.Length && pattern[i + 1] == 'd'; i++) { num4++; } if (num4 <= 2) { num2 = num3++; } break; } case 'M': num = num3++; for (; i + 1 < pattern.Length && pattern[i + 1] == 'M'; i++) { } break; } } if (num == 0 && num2 == 1) { order = 6; return true; } if (num2 == 0 && num == 1) { order = 7; return true; } order = -1; return false; } private static bool TryAdjustYear(ref DateTimeResult result, int year, out int adjustedYear) { if (year < 100) { try { year = result.calendar.ToFourDigitYear(year); } catch (ArgumentOutOfRangeException) { adjustedYear = -1; return false; } } adjustedYear = year; return true; } private static bool SetDateYMD(ref DateTimeResult result, int year, int month, int day) { if (result.calendar.IsValidDay(year, month, day, result.era)) { result.SetDate(year, month, day); return true; } return false; } private static bool SetDateMDY(ref DateTimeResult result, int month, int day, int year) { return SetDateYMD(ref result, year, month, day); } private static bool SetDateDMY(ref DateTimeResult result, int day, int month, int year) { return SetDateYMD(ref result, year, month, day); } private static bool SetDateYDM(ref DateTimeResult result, int year, int day, int month) { return SetDateYMD(ref result, year, month, day); } private static void GetDefaultYear(ref DateTimeResult result, ref DateTimeStyles styles) { result.Year = result.calendar.GetYear(GetDateTimeNow(ref result, ref styles)); result.flags |= ParseFlags.YearDefault; } private static bool GetDayOfNN(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveDate) != 0) { result.SetBadDateTimeFailure(); return false; } int number = raw.GetNumber(0); int number2 = raw.GetNumber(1); GetDefaultYear(ref result, ref styles); if (!GetMonthDayOrder(dtfi.MonthDayPattern, out var order)) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern); return false; } if (order == 6) { if (SetDateYMD(ref result, result.Year, number, number2)) { result.flags |= ParseFlags.HaveDate; return true; } } else if (SetDateYMD(ref result, result.Year, number2, number)) { result.flags |= ParseFlags.HaveDate; return true; } result.SetBadDateTimeFailure(); return false; } private static bool GetDayOfNNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveDate) != 0) { result.SetBadDateTimeFailure(); return false; } int number = raw.GetNumber(0); int number2 = raw.GetNumber(1); int number3 = raw.GetNumber(2); if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, out var order)) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern); return false; } int adjustedYear; switch (order) { case 0: if (TryAdjustYear(ref result, number, out adjustedYear) && SetDateYMD(ref result, adjustedYear, number2, number3)) { result.flags |= ParseFlags.HaveDate; return true; } break; case 1: if (TryAdjustYear(ref result, number3, out adjustedYear) && SetDateMDY(ref result, number, number2, adjustedYear)) { result.flags |= ParseFlags.HaveDate; return true; } break; case 2: if (TryAdjustYear(ref result, number3, out adjustedYear) && SetDateDMY(ref result, number, number2, adjustedYear)) { result.flags |= ParseFlags.HaveDate; return true; } break; case 3: if (TryAdjustYear(ref result, number, out adjustedYear) && SetDateYDM(ref result, adjustedYear, number2, number3)) { result.flags |= ParseFlags.HaveDate; return true; } break; } result.SetBadDateTimeFailure(); return false; } private static bool GetDayOfMN(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveDate) != 0) { result.SetBadDateTimeFailure(); return false; } if (!GetMonthDayOrder(dtfi.MonthDayPattern, out var order)) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern); return false; } if (order == 7) { if (!GetYearMonthOrder(dtfi.YearMonthPattern, out var order2)) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.YearMonthPattern); return false; } if (order2 == 5) { if (!TryAdjustYear(ref result, raw.GetNumber(0), out var adjustedYear) || !SetDateYMD(ref result, adjustedYear, raw.month, 1)) { result.SetBadDateTimeFailure(); return false; } return true; } } GetDefaultYear(ref result, ref styles); if (!SetDateYMD(ref result, result.Year, raw.month, raw.GetNumber(0))) { result.SetBadDateTimeFailure(); return false; } return true; } private static bool GetHebrewDayOfNM(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if (!GetMonthDayOrder(dtfi.MonthDayPattern, out var order)) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern); return false; } result.Month = raw.month; if ((order == 7 || order == 6) && result.calendar.IsValidDay(result.Year, result.Month, raw.GetNumber(0), result.era)) { result.Day = raw.GetNumber(0); return true; } result.SetBadDateTimeFailure(); return false; } private static bool GetDayOfNM(ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveDate) != 0) { result.SetBadDateTimeFailure(); return false; } if (!GetMonthDayOrder(dtfi.MonthDayPattern, out var order)) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern); return false; } if (order == 6) { if (!GetYearMonthOrder(dtfi.YearMonthPattern, out var order2)) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.YearMonthPattern); return false; } if (order2 == 4) { if (!TryAdjustYear(ref result, raw.GetNumber(0), out var adjustedYear) || !SetDateYMD(ref result, adjustedYear, raw.month, 1)) { result.SetBadDateTimeFailure(); return false; } return true; } } GetDefaultYear(ref result, ref styles); if (!SetDateYMD(ref result, result.Year, raw.month, raw.GetNumber(0))) { result.SetBadDateTimeFailure(); return false; } return true; } private static bool GetDayOfMNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveDate) != 0) { result.SetBadDateTimeFailure(); return false; } int number = raw.GetNumber(0); int number2 = raw.GetNumber(1); if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, out var order)) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern); return false; } int adjustedYear; switch (order) { case 1: if (TryAdjustYear(ref result, number2, out adjustedYear) && result.calendar.IsValidDay(adjustedYear, raw.month, number, result.era)) { result.SetDate(adjustedYear, raw.month, number); result.flags |= ParseFlags.HaveDate; return true; } if (TryAdjustYear(ref result, number, out adjustedYear) && result.calendar.IsValidDay(adjustedYear, raw.month, number2, result.era)) { result.SetDate(adjustedYear, raw.month, number2); result.flags |= ParseFlags.HaveDate; return true; } break; case 0: if (TryAdjustYear(ref result, number, out adjustedYear) && result.calendar.IsValidDay(adjustedYear, raw.month, number2, result.era)) { result.SetDate(adjustedYear, raw.month, number2); result.flags |= ParseFlags.HaveDate; return true; } if (TryAdjustYear(ref result, number2, out adjustedYear) && result.calendar.IsValidDay(adjustedYear, raw.month, number, result.era)) { result.SetDate(adjustedYear, raw.month, number); result.flags |= ParseFlags.HaveDate; return true; } break; case 2: if (TryAdjustYear(ref result, number2, out adjustedYear) && result.calendar.IsValidDay(adjustedYear, raw.month, number, result.era)) { result.SetDate(adjustedYear, raw.month, number); result.flags |= ParseFlags.HaveDate; return true; } if (TryAdjustYear(ref result, number, out adjustedYear) && result.calendar.IsValidDay(adjustedYear, raw.month, number2, result.era)) { result.SetDate(adjustedYear, raw.month, number2); result.flags |= ParseFlags.HaveDate; return true; } break; } result.SetBadDateTimeFailure(); return false; } private static bool GetDayOfYNN(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveDate) != 0) { result.SetBadDateTimeFailure(); return false; } int number = raw.GetNumber(0); int number2 = raw.GetNumber(1); string shortDatePattern = dtfi.ShortDatePattern; if (GetYearMonthDayOrder(shortDatePattern, out var order) && order == 3) { if (SetDateYMD(ref result, raw.year, number2, number)) { result.flags |= ParseFlags.HaveDate; return true; } } else if (SetDateYMD(ref result, raw.year, number, number2)) { result.flags |= ParseFlags.HaveDate; return true; } result.SetBadDateTimeFailure(); return false; } private static bool GetDayOfNNY(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveDate) != 0) { result.SetBadDateTimeFailure(); return false; } int number = raw.GetNumber(0); int number2 = raw.GetNumber(1); if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, out var order)) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern); return false; } if (order == 1 || order == 0) { if (SetDateYMD(ref result, raw.year, number, number2)) { result.flags |= ParseFlags.HaveDate; return true; } } else if (SetDateYMD(ref result, raw.year, number2, number)) { result.flags |= ParseFlags.HaveDate; return true; } result.SetBadDateTimeFailure(); return false; } private static bool GetDayOfYMN(ref DateTimeResult result, ref DateTimeRawInfo raw) { if ((result.flags & ParseFlags.HaveDate) != 0) { result.SetBadDateTimeFailure(); return false; } if (SetDateYMD(ref result, raw.year, raw.month, raw.GetNumber(0))) { result.flags |= ParseFlags.HaveDate; return true; } result.SetBadDateTimeFailure(); return false; } private static bool GetDayOfYN(ref DateTimeResult result, ref DateTimeRawInfo raw) { if ((result.flags & ParseFlags.HaveDate) != 0) { result.SetBadDateTimeFailure(); return false; } if (SetDateYMD(ref result, raw.year, raw.GetNumber(0), 1)) { result.flags |= ParseFlags.HaveDate; return true; } result.SetBadDateTimeFailure(); return false; } private static bool GetDayOfYM(ref DateTimeResult result, ref DateTimeRawInfo raw) { if ((result.flags & ParseFlags.HaveDate) != 0) { result.SetBadDateTimeFailure(); return false; } if (SetDateYMD(ref result, raw.year, raw.month, 1)) { result.flags |= ParseFlags.HaveDate; return true; } result.SetBadDateTimeFailure(); return false; } private static void AdjustTimeMark(DateTimeFormatInfo dtfi, ref DateTimeRawInfo raw) { if (raw.timeMark == TM.NotSet && dtfi.AMDesignator != null && dtfi.PMDesignator != null) { if (dtfi.AMDesignator.Length == 0 && dtfi.PMDesignator.Length != 0) { raw.timeMark = TM.AM; } if (dtfi.PMDesignator.Length == 0 && dtfi.AMDesignator.Length != 0) { raw.timeMark = TM.PM; } } } private static bool AdjustHour(ref int hour, TM timeMark) { switch (timeMark) { case TM.AM: if (hour < 0 || hour > 12) { return false; } hour = ((hour != 12) ? hour : 0); break; default: if (hour < 0 || hour > 23) { return false; } if (hour < 12) { hour += 12; } break; case TM.NotSet: break; } return true; } private static bool GetTimeOfN(ref DateTimeResult result, ref DateTimeRawInfo raw) { if ((result.flags & ParseFlags.HaveTime) != 0) { result.SetBadDateTimeFailure(); return false; } if (raw.timeMark == TM.NotSet) { result.SetBadDateTimeFailure(); return false; } result.Hour = raw.GetNumber(0); result.flags |= ParseFlags.HaveTime; return true; } private static bool GetTimeOfNN(ref DateTimeResult result, ref DateTimeRawInfo raw) { if ((result.flags & ParseFlags.HaveTime) != 0) { result.SetBadDateTimeFailure(); return false; } result.Hour = raw.GetNumber(0); result.Minute = raw.GetNumber(1); result.flags |= ParseFlags.HaveTime; return true; } private static bool GetTimeOfNNN(ref DateTimeResult result, ref DateTimeRawInfo raw) { if ((result.flags & ParseFlags.HaveTime) != 0) { result.SetBadDateTimeFailure(); return false; } result.Hour = raw.GetNumber(0); result.Minute = raw.GetNumber(1); result.Second = raw.GetNumber(2); result.flags |= ParseFlags.HaveTime; return true; } private static bool GetDateOfDSN(ref DateTimeResult result, ref DateTimeRawInfo raw) { if (raw.numCount != 1 || result.Day != -1) { result.SetBadDateTimeFailure(); return false; } result.Day = raw.GetNumber(0); return true; } private static bool GetDateOfNDS(ref DateTimeResult result, ref DateTimeRawInfo raw) { if (result.Month == -1) { result.SetBadDateTimeFailure(); return false; } if (result.Year != -1) { result.SetBadDateTimeFailure(); return false; } if (!TryAdjustYear(ref result, raw.GetNumber(0), out result.Year)) { result.SetBadDateTimeFailure(); return false; } result.Day = 1; return true; } private static bool GetDateOfNNDS(ref DateTimeResult result, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { if ((result.flags & ParseFlags.HaveYear) != 0) { if ((result.flags & ParseFlags.HaveMonth) == 0 && (result.flags & ParseFlags.HaveDay) == 0 && TryAdjustYear(ref result, raw.year, out result.Year) && SetDateYMD(ref result, result.Year, raw.GetNumber(0), raw.GetNumber(1))) { return true; } } else if ((result.flags & ParseFlags.HaveMonth) != 0 && (result.flags & ParseFlags.HaveYear) == 0 && (result.flags & ParseFlags.HaveDay) == 0) { if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, out var order)) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern); return false; } int adjustedYear; if (order == 0) { if (TryAdjustYear(ref result, raw.GetNumber(0), out adjustedYear) && SetDateYMD(ref result, adjustedYear, result.Month, raw.GetNumber(1))) { return true; } } else if (TryAdjustYear(ref result, raw.GetNumber(1), out adjustedYear) && SetDateYMD(ref result, adjustedYear, result.Month, raw.GetNumber(0))) { return true; } } result.SetBadDateTimeFailure(); return false; } private static bool ProcessDateTimeSuffix(ref DateTimeResult result, ref DateTimeRawInfo raw, ref DateTimeToken dtok) { switch (dtok.suffix) { case TokenType.SEP_YearSuff: if ((result.flags & ParseFlags.HaveYear) != 0) { return false; } result.flags |= ParseFlags.HaveYear; result.Year = (raw.year = dtok.num); break; case TokenType.SEP_MonthSuff: if ((result.flags & ParseFlags.HaveMonth) != 0) { return false; } result.flags |= ParseFlags.HaveMonth; result.Month = (raw.month = dtok.num); break; case TokenType.SEP_DaySuff: if ((result.flags & ParseFlags.HaveDay) != 0) { return false; } result.flags |= ParseFlags.HaveDay; result.Day = dtok.num; break; case TokenType.SEP_HourSuff: if ((result.flags & ParseFlags.HaveHour) != 0) { return false; } result.flags |= ParseFlags.HaveHour; result.Hour = dtok.num; break; case TokenType.SEP_MinuteSuff: if ((result.flags & ParseFlags.HaveMinute) != 0) { return false; } result.flags |= ParseFlags.HaveMinute; result.Minute = dtok.num; break; case TokenType.SEP_SecondSuff: if ((result.flags & ParseFlags.HaveSecond) != 0) { return false; } result.flags |= ParseFlags.HaveSecond; result.Second = dtok.num; break; } return true; } internal static bool ProcessHebrewTerminalState(DS dps, ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { switch (dps) { case DS.DX_MNN: raw.year = raw.GetNumber(1); if (!dtfi.YearMonthAdjustment(ref raw.year, ref raw.month, parsedMonthName: true)) { result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar"); return false; } if (!GetDayOfMNN(ref result, ref raw, dtfi)) { return false; } break; case DS.DX_YMN: if (!dtfi.YearMonthAdjustment(ref raw.year, ref raw.month, parsedMonthName: true)) { result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar"); return false; } if (!GetDayOfYMN(ref result, ref raw)) { return false; } break; case DS.DX_NNY: if (raw.year < 1000) { raw.year += 5000; } if (!GetDayOfNNY(ref result, ref raw, dtfi)) { return false; } if (!dtfi.YearMonthAdjustment(ref result.Year, ref raw.month, parsedMonthName: true)) { result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar"); return false; } break; case DS.DX_MN: case DS.DX_NM: GetDefaultYear(ref result, ref styles); if (!dtfi.YearMonthAdjustment(ref result.Year, ref raw.month, parsedMonthName: true)) { result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar"); return false; } if (!GetHebrewDayOfNM(ref result, ref raw, dtfi)) { return false; } break; case DS.DX_YM: if (!dtfi.YearMonthAdjustment(ref raw.year, ref raw.month, parsedMonthName: true)) { result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar"); return false; } if (!GetDayOfYM(ref result, ref raw)) { return false; } break; case DS.TX_N: if (!GetTimeOfN(ref result, ref raw)) { return false; } break; case DS.TX_NN: if (!GetTimeOfNN(ref result, ref raw)) { return false; } break; case DS.TX_NNN: if (!GetTimeOfNNN(ref result, ref raw)) { return false; } break; default: result.SetBadDateTimeFailure(); return false; } if (dps > DS.ERROR) { raw.numCount = 0; } return true; } internal static bool ProcessTerminalState(DS dps, ref DateTimeResult result, ref DateTimeStyles styles, ref DateTimeRawInfo raw, DateTimeFormatInfo dtfi) { bool flag = true; switch (dps) { case DS.DX_NN: flag = GetDayOfNN(ref result, ref styles, ref raw, dtfi); break; case DS.DX_NNN: flag = GetDayOfNNN(ref result, ref raw, dtfi); break; case DS.DX_MN: flag = GetDayOfMN(ref result, ref styles, ref raw, dtfi); break; case DS.DX_NM: flag = GetDayOfNM(ref result, ref styles, ref raw, dtfi); break; case DS.DX_MNN: flag = GetDayOfMNN(ref result, ref raw, dtfi); break; case DS.DX_DS: flag = true; break; case DS.DX_YNN: flag = GetDayOfYNN(ref result, ref raw, dtfi); break; case DS.DX_NNY: flag = GetDayOfNNY(ref result, ref raw, dtfi); break; case DS.DX_YMN: flag = GetDayOfYMN(ref result, ref raw); break; case DS.DX_YN: flag = GetDayOfYN(ref result, ref raw); break; case DS.DX_YM: flag = GetDayOfYM(ref result, ref raw); break; case DS.TX_N: flag = GetTimeOfN(ref result, ref raw); break; case DS.TX_NN: flag = GetTimeOfNN(ref result, ref raw); break; case DS.TX_NNN: flag = GetTimeOfNNN(ref result, ref raw); break; case DS.TX_TS: flag = true; break; case DS.DX_DSN: flag = GetDateOfDSN(ref result, ref raw); break; case DS.DX_NDS: flag = GetDateOfNDS(ref result, ref raw); break; case DS.DX_NNDS: flag = GetDateOfNNDS(ref result, ref raw, dtfi); break; } if (!flag) { return false; } if (dps > DS.ERROR) { raw.numCount = 0; } return true; } internal static DateTime Parse(ReadOnlySpan s, DateTimeFormatInfo dtfi, DateTimeStyles styles) { DateTimeResult result = default(DateTimeResult); result.Init(s); if (TryParse(s, dtfi, styles, ref result)) { return result.parsedDate; } throw GetDateTimeParseException(ref result); } internal static DateTime Parse(ReadOnlySpan s, DateTimeFormatInfo dtfi, DateTimeStyles styles, out TimeSpan offset) { DateTimeResult result = default(DateTimeResult); result.Init(s); result.flags |= ParseFlags.CaptureOffset; if (TryParse(s, dtfi, styles, ref result)) { offset = result.timeZoneOffset; return result.parsedDate; } throw GetDateTimeParseException(ref result); } internal static bool TryParse(ReadOnlySpan s, DateTimeFormatInfo dtfi, DateTimeStyles styles, out DateTime result) { DateTimeResult result2 = default(DateTimeResult); result2.Init(s); if (TryParse(s, dtfi, styles, ref result2)) { result = result2.parsedDate; return true; } result = DateTime.MinValue; return false; } internal static bool TryParse(ReadOnlySpan s, DateTimeFormatInfo dtfi, DateTimeStyles styles, out DateTime result, out TimeSpan offset) { DateTimeResult result2 = default(DateTimeResult); result2.Init(s); result2.flags |= ParseFlags.CaptureOffset; if (TryParse(s, dtfi, styles, ref result2)) { result = result2.parsedDate; offset = result2.timeZoneOffset; return true; } result = DateTime.MinValue; offset = TimeSpan.Zero; return false; } internal unsafe static bool TryParse(ReadOnlySpan s, DateTimeFormatInfo dtfi, DateTimeStyles styles, ref DateTimeResult result) { if (s.Length == 0) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDateTime"); return false; } DS dS = DS.BEGIN; bool flag = false; DateTimeToken dtok = default(DateTimeToken); dtok.suffix = TokenType.SEP_Unk; DateTimeRawInfo raw = default(DateTimeRawInfo); int* numberBuffer = stackalloc int[3]; raw.Init(numberBuffer); raw.hasSameDateAndTimeSeparators = dtfi.DateSeparator.Equals(dtfi.TimeSeparator, StringComparison.Ordinal); result.calendar = dtfi.Calendar; result.era = 0; __DTString str = new __DTString(s, dtfi); str.GetNext(); do { if (!Lex(dS, ref str, ref dtok, ref raw, ref result, ref dtfi, styles)) { return false; } if (dtok.dtt == DTT.Unk) { continue; } if (dtok.suffix != TokenType.SEP_Unk) { if (!ProcessDateTimeSuffix(ref result, ref raw, ref dtok)) { result.SetBadDateTimeFailure(); return false; } dtok.suffix = TokenType.SEP_Unk; } if (dtok.dtt == DTT.NumLocalTimeMark) { if (dS == DS.D_YNd || dS == DS.D_YN) { return ParseISO8601(ref raw, ref str, styles, ref result); } result.SetBadDateTimeFailure(); return false; } if (raw.hasSameDateAndTimeSeparators) { if (dtok.dtt == DTT.YearEnd || dtok.dtt == DTT.YearSpace || dtok.dtt == DTT.YearDateSep) { if (dS == DS.T_Nt) { dS = DS.D_Nd; } if (dS == DS.T_NNt) { dS = DS.D_NNd; } } bool flag2 = str.AtEnd(); if (s_dateParsingStates[(int)dS][(int)dtok.dtt] == DS.ERROR || flag2) { switch (dtok.dtt) { case DTT.YearDateSep: dtok.dtt = (flag2 ? DTT.YearEnd : DTT.YearSpace); break; case DTT.NumDatesep: dtok.dtt = (flag2 ? DTT.NumEnd : DTT.NumSpace); break; case DTT.NumTimesep: dtok.dtt = (flag2 ? DTT.NumEnd : DTT.NumSpace); break; case DTT.MonthDatesep: dtok.dtt = (flag2 ? DTT.MonthEnd : DTT.MonthSpace); break; } } } dS = s_dateParsingStates[(int)dS][(int)dtok.dtt]; if (dS == DS.ERROR) { result.SetBadDateTimeFailure(); return false; } if (dS <= DS.ERROR) { continue; } if ((dtfi.FormatFlags & DateTimeFormatFlags.UseHebrewRule) != 0) { if (!ProcessHebrewTerminalState(dS, ref result, ref styles, ref raw, dtfi)) { return false; } } else if (!ProcessTerminalState(dS, ref result, ref styles, ref raw, dtfi)) { return false; } flag = true; dS = DS.BEGIN; } while (dtok.dtt != 0 && dtok.dtt != DTT.NumEnd && dtok.dtt != DTT.MonthEnd); if (!flag) { result.SetBadDateTimeFailure(); return false; } AdjustTimeMark(dtfi, ref raw); if (!AdjustHour(ref result.Hour, raw.timeMark)) { result.SetBadDateTimeFailure(); return false; } bool bTimeOnly = result.Year == -1 && result.Month == -1 && result.Day == -1; if (!CheckDefaultDateTime(ref result, ref result.calendar, styles)) { return false; } if (!result.calendar.TryToDateTime(result.Year, result.Month, result.Day, result.Hour, result.Minute, result.Second, 0, result.era, out var result2)) { result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar"); return false; } if (raw.fraction > 0.0 && !result2.TryAddTicks((long)Math.Round(raw.fraction * 10000000.0), out result2)) { result.SetBadDateTimeFailure(); return false; } if (raw.dayOfWeek != -1 && raw.dayOfWeek != (int)result.calendar.GetDayOfWeek(result2)) { result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, "Format_BadDayOfWeek"); return false; } result.parsedDate = result2; if (!DetermineTimeZoneAdjustments(ref result, styles, bTimeOnly)) { return false; } return true; } private static bool DetermineTimeZoneAdjustments(ref DateTimeResult result, DateTimeStyles styles, bool bTimeOnly) { if ((result.flags & ParseFlags.CaptureOffset) != 0) { return DateTimeOffsetTimeZonePostProcessing(ref result, styles); } long ticks = result.timeZoneOffset.Ticks; if (ticks < -504000000000L || ticks > 504000000000L) { result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, "Format_OffsetOutOfRange"); return false; } if ((result.flags & ParseFlags.TimeZoneUsed) == 0) { if ((styles & DateTimeStyles.AssumeLocal) != 0) { if ((styles & DateTimeStyles.AdjustToUniversal) == 0) { result.parsedDate = DateTime.SpecifyKind(result.parsedDate, DateTimeKind.Local); return true; } result.flags |= ParseFlags.TimeZoneUsed; result.timeZoneOffset = TimeZoneInfo.GetLocalUtcOffset(result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime); } else { if ((styles & DateTimeStyles.AssumeUniversal) == 0) { return true; } if ((styles & DateTimeStyles.AdjustToUniversal) != 0) { result.parsedDate = DateTime.SpecifyKind(result.parsedDate, DateTimeKind.Utc); return true; } result.flags |= ParseFlags.TimeZoneUsed; result.timeZoneOffset = TimeSpan.Zero; } } if ((styles & DateTimeStyles.RoundtripKind) != 0 && (result.flags & ParseFlags.TimeZoneUtc) != 0) { result.parsedDate = DateTime.SpecifyKind(result.parsedDate, DateTimeKind.Utc); return true; } if ((styles & DateTimeStyles.AdjustToUniversal) != 0) { return AdjustTimeZoneToUniversal(ref result); } return AdjustTimeZoneToLocal(ref result, bTimeOnly); } private static bool DateTimeOffsetTimeZonePostProcessing(ref DateTimeResult result, DateTimeStyles styles) { if ((result.flags & ParseFlags.TimeZoneUsed) == 0) { if ((styles & DateTimeStyles.AssumeUniversal) != 0) { result.timeZoneOffset = TimeSpan.Zero; } else { result.timeZoneOffset = TimeZoneInfo.GetLocalUtcOffset(result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime); } } long ticks = result.timeZoneOffset.Ticks; long num = result.parsedDate.Ticks - ticks; if (num < 0 || num > 3155378975999999999L) { result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, "Format_UTCOutOfRange"); return false; } if (ticks < -504000000000L || ticks > 504000000000L) { result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, "Format_OffsetOutOfRange"); return false; } if ((styles & DateTimeStyles.AdjustToUniversal) != 0) { if ((result.flags & ParseFlags.TimeZoneUsed) == 0 && (styles & DateTimeStyles.AssumeUniversal) == 0) { bool result2 = AdjustTimeZoneToUniversal(ref result); result.timeZoneOffset = TimeSpan.Zero; return result2; } result.parsedDate = new DateTime(num, DateTimeKind.Utc); result.timeZoneOffset = TimeSpan.Zero; } return true; } private static bool AdjustTimeZoneToUniversal(ref DateTimeResult result) { long ticks = result.parsedDate.Ticks; ticks -= result.timeZoneOffset.Ticks; if (ticks < 0) { ticks += 864000000000L; } if (ticks < 0 || ticks > 3155378975999999999L) { result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, "Format_DateOutOfRange"); return false; } result.parsedDate = new DateTime(ticks, DateTimeKind.Utc); return true; } private static bool AdjustTimeZoneToLocal(ref DateTimeResult result, bool bTimeOnly) { long ticks = result.parsedDate.Ticks; TimeZoneInfo local = TimeZoneInfo.Local; bool isAmbiguousLocalDst = false; if (ticks < 864000000000L) { ticks -= result.timeZoneOffset.Ticks; ticks += local.GetUtcOffset(bTimeOnly ? DateTime.Now : result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks; if (ticks < 0) { ticks += 864000000000L; } } else { ticks -= result.timeZoneOffset.Ticks; if (ticks < 0 || ticks > 3155378975999999999L) { ticks += local.GetUtcOffset(result.parsedDate, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks; } else { DateTime time = new DateTime(ticks, DateTimeKind.Utc); ticks += TimeZoneInfo.GetUtcOffsetFromUtc(time, TimeZoneInfo.Local, out var _, out isAmbiguousLocalDst).Ticks; } } if (ticks < 0 || ticks > 3155378975999999999L) { result.parsedDate = DateTime.MinValue; result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, "Format_DateOutOfRange"); return false; } result.parsedDate = new DateTime(ticks, DateTimeKind.Local, isAmbiguousLocalDst); return true; } private static bool ParseISO8601(ref DateTimeRawInfo raw, ref __DTString str, DateTimeStyles styles, ref DateTimeResult result) { if (raw.year >= 0 && raw.GetNumber(0) >= 0) { raw.GetNumber(1); _ = 0; } str.Index--; int result2 = 0; double result3 = 0.0; str.SkipWhiteSpaces(); if (!ParseDigits(ref str, 2, out var result4)) { result.SetBadDateTimeFailure(); return false; } str.SkipWhiteSpaces(); if (!str.Match(':')) { result.SetBadDateTimeFailure(); return false; } str.SkipWhiteSpaces(); if (!ParseDigits(ref str, 2, out var result5)) { result.SetBadDateTimeFailure(); return false; } str.SkipWhiteSpaces(); if (str.Match(':')) { str.SkipWhiteSpaces(); if (!ParseDigits(ref str, 2, out result2)) { result.SetBadDateTimeFailure(); return false; } if (str.Match('.')) { if (!ParseFraction(ref str, out result3)) { result.SetBadDateTimeFailure(); return false; } str.Index--; } str.SkipWhiteSpaces(); } if (str.GetNext()) { switch (str.GetChar()) { case '+': case '-': result.flags |= ParseFlags.TimeZoneUsed; if (!ParseTimeZone(ref str, ref result.timeZoneOffset)) { result.SetBadDateTimeFailure(); return false; } str.Index--; break; case 'Z': case 'z': result.flags |= ParseFlags.TimeZoneUsed; result.timeZoneOffset = TimeSpan.Zero; result.flags |= ParseFlags.TimeZoneUtc; break; default: str.Index--; break; } str.SkipWhiteSpaces(); if (str.Match('#')) { if (!VerifyValidPunctuation(ref str)) { result.SetBadDateTimeFailure(); return false; } str.SkipWhiteSpaces(); } if (str.Match('\0') && !VerifyValidPunctuation(ref str)) { result.SetBadDateTimeFailure(); return false; } if (str.GetNext()) { result.SetBadDateTimeFailure(); return false; } } Calendar defaultInstance = GregorianCalendar.GetDefaultInstance(); if (!defaultInstance.TryToDateTime(raw.year, raw.GetNumber(0), raw.GetNumber(1), result4, result5, result2, 0, result.era, out var result6)) { result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar"); return false; } if (!result6.TryAddTicks((long)Math.Round(result3 * 10000000.0), out result6)) { result.SetBadDateTimeFailure(); return false; } result.parsedDate = result6; return DetermineTimeZoneAdjustments(ref result, styles, bTimeOnly: false); } internal static bool MatchHebrewDigits(ref __DTString str, int digitLen, out int number) { number = 0; HebrewNumberParsingContext context = new HebrewNumberParsingContext(0); HebrewNumberParsingState hebrewNumberParsingState = HebrewNumberParsingState.ContinueParsing; while (hebrewNumberParsingState == HebrewNumberParsingState.ContinueParsing && str.GetNext()) { hebrewNumberParsingState = HebrewNumber.ParseByChar(str.GetChar(), ref context); } if (hebrewNumberParsingState == HebrewNumberParsingState.FoundEndOfHebrewNumber) { number = context.result; return true; } return false; } internal static bool ParseDigits(ref __DTString str, int digitLen, out int result) { if (digitLen == 1) { return ParseDigits(ref str, 1, 2, out result); } return ParseDigits(ref str, digitLen, digitLen, out result); } internal static bool ParseDigits(ref __DTString str, int minDigitLen, int maxDigitLen, out int result) { int num = 0; int index = str.Index; int i; for (i = 0; i < maxDigitLen; i++) { if (!str.GetNextDigit()) { str.Index--; break; } num = num * 10 + str.GetDigit(); } result = num; if (i < minDigitLen) { str.Index = index; return false; } return true; } private static bool ParseFractionExact(ref __DTString str, int maxDigitLen, ref double result) { if (!str.GetNextDigit()) { str.Index--; return false; } result = str.GetDigit(); int i; for (i = 1; i < maxDigitLen; i++) { if (!str.GetNextDigit()) { str.Index--; break; } result = result * 10.0 + (double)str.GetDigit(); } result /= TimeSpanParse.Pow10(i); return i == maxDigitLen; } private static bool ParseSign(ref __DTString str, ref bool result) { if (!str.GetNext()) { return false; } switch (str.GetChar()) { case '+': result = true; return true; case '-': result = false; return true; default: return false; } } private static bool ParseTimeZoneOffset(ref __DTString str, int len, ref TimeSpan result) { bool result2 = true; int result3 = 0; int result4; if ((uint)(len - 1) <= 1u) { if (!ParseSign(ref str, ref result2)) { return false; } if (!ParseDigits(ref str, len, out result4)) { return false; } } else { if (!ParseSign(ref str, ref result2)) { return false; } if (!ParseDigits(ref str, 1, out result4)) { return false; } if (str.Match(":")) { if (!ParseDigits(ref str, 2, out result3)) { return false; } } else { str.Index--; if (!ParseDigits(ref str, 2, out result3)) { return false; } } } if (result3 < 0 || result3 >= 60) { return false; } result = new TimeSpan(result4, result3, 0); if (!result2) { result = result.Negate(); } return true; } private static bool MatchAbbreviatedMonthName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result) { int maxMatchStrLen = 0; result = -1; if (str.GetNext()) { int num = ((dtfi.GetMonthName(13).Length == 0) ? 12 : 13); for (int i = 1; i <= num; i++) { string abbreviatedMonthName = dtfi.GetAbbreviatedMonthName(i); int matchLength = abbreviatedMonthName.Length; if ((dtfi.HasSpacesInMonthNames ? str.MatchSpecifiedWords(abbreviatedMonthName, checkWordBoundary: false, ref matchLength) : str.MatchSpecifiedWord(abbreviatedMonthName)) && matchLength > maxMatchStrLen) { maxMatchStrLen = matchLength; result = i; } } if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0) { int num2 = str.MatchLongestWords(dtfi.AbbreviatedMonthGenitiveNames, ref maxMatchStrLen); if (num2 >= 0) { result = num2 + 1; } } if ((dtfi.FormatFlags & DateTimeFormatFlags.UseLeapYearMonth) != 0) { int num3 = str.MatchLongestWords(dtfi.InternalGetLeapYearMonthNames(), ref maxMatchStrLen); if (num3 >= 0) { result = num3 + 1; } } } if (result > 0) { str.Index += maxMatchStrLen - 1; return true; } return false; } private static bool MatchMonthName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result) { int maxMatchStrLen = 0; result = -1; if (str.GetNext()) { int num = ((dtfi.GetMonthName(13).Length == 0) ? 12 : 13); for (int i = 1; i <= num; i++) { string monthName = dtfi.GetMonthName(i); int matchLength = monthName.Length; if ((dtfi.HasSpacesInMonthNames ? str.MatchSpecifiedWords(monthName, checkWordBoundary: false, ref matchLength) : str.MatchSpecifiedWord(monthName)) && matchLength > maxMatchStrLen) { maxMatchStrLen = matchLength; result = i; } } if ((dtfi.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0) { int num2 = str.MatchLongestWords(dtfi.MonthGenitiveNames, ref maxMatchStrLen); if (num2 >= 0) { result = num2 + 1; } } if ((dtfi.FormatFlags & DateTimeFormatFlags.UseLeapYearMonth) != 0) { int num3 = str.MatchLongestWords(dtfi.InternalGetLeapYearMonthNames(), ref maxMatchStrLen); if (num3 >= 0) { result = num3 + 1; } } } if (result > 0) { str.Index += maxMatchStrLen - 1; return true; } return false; } private static bool MatchAbbreviatedDayName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result) { int num = 0; result = -1; if (str.GetNext()) { for (DayOfWeek dayOfWeek = DayOfWeek.Sunday; dayOfWeek <= DayOfWeek.Saturday; dayOfWeek++) { string abbreviatedDayName = dtfi.GetAbbreviatedDayName(dayOfWeek); int matchLength = abbreviatedDayName.Length; if ((dtfi.HasSpacesInDayNames ? str.MatchSpecifiedWords(abbreviatedDayName, checkWordBoundary: false, ref matchLength) : str.MatchSpecifiedWord(abbreviatedDayName)) && matchLength > num) { num = matchLength; result = (int)dayOfWeek; } } } if (result >= 0) { str.Index += num - 1; return true; } return false; } private static bool MatchDayName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result) { int num = 0; result = -1; if (str.GetNext()) { for (DayOfWeek dayOfWeek = DayOfWeek.Sunday; dayOfWeek <= DayOfWeek.Saturday; dayOfWeek++) { string dayName = dtfi.GetDayName(dayOfWeek); int matchLength = dayName.Length; if ((dtfi.HasSpacesInDayNames ? str.MatchSpecifiedWords(dayName, checkWordBoundary: false, ref matchLength) : str.MatchSpecifiedWord(dayName)) && matchLength > num) { num = matchLength; result = (int)dayOfWeek; } } } if (result >= 0) { str.Index += num - 1; return true; } return false; } private static bool MatchEraName(ref __DTString str, DateTimeFormatInfo dtfi, ref int result) { if (str.GetNext()) { int[] eras = dtfi.Calendar.Eras; if (eras != null) { for (int i = 0; i < eras.Length; i++) { string eraName = dtfi.GetEraName(eras[i]); if (str.MatchSpecifiedWord(eraName)) { str.Index += eraName.Length - 1; result = eras[i]; return true; } eraName = dtfi.GetAbbreviatedEraName(eras[i]); if (str.MatchSpecifiedWord(eraName)) { str.Index += eraName.Length - 1; result = eras[i]; return true; } } } } return false; } private static bool MatchTimeMark(ref __DTString str, DateTimeFormatInfo dtfi, ref TM result) { result = TM.NotSet; if (dtfi.AMDesignator.Length == 0) { result = TM.AM; } if (dtfi.PMDesignator.Length == 0) { result = TM.PM; } if (str.GetNext()) { string aMDesignator = dtfi.AMDesignator; if (aMDesignator.Length > 0 && str.MatchSpecifiedWord(aMDesignator)) { str.Index += aMDesignator.Length - 1; result = TM.AM; return true; } aMDesignator = dtfi.PMDesignator; if (aMDesignator.Length > 0 && str.MatchSpecifiedWord(aMDesignator)) { str.Index += aMDesignator.Length - 1; result = TM.PM; return true; } str.Index--; } if (result != TM.NotSet) { return true; } return false; } private static bool MatchAbbreviatedTimeMark(ref __DTString str, DateTimeFormatInfo dtfi, ref TM result) { if (str.GetNext()) { string aMDesignator = dtfi.AMDesignator; if (aMDesignator.Length > 0 && str.GetChar() == aMDesignator[0]) { result = TM.AM; return true; } string pMDesignator = dtfi.PMDesignator; if (pMDesignator.Length > 0 && str.GetChar() == pMDesignator[0]) { result = TM.PM; return true; } } return false; } private static bool CheckNewValue(ref int currentValue, int newValue, char patternChar, ref DateTimeResult result) { if (currentValue == -1) { currentValue = newValue; return true; } if (newValue != currentValue) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", patternChar); return false; } return true; } private static DateTime GetDateTimeNow(ref DateTimeResult result, ref DateTimeStyles styles) { if ((result.flags & ParseFlags.CaptureOffset) != 0) { if ((result.flags & ParseFlags.TimeZoneUsed) != 0) { return new DateTime(DateTime.UtcNow.Ticks + result.timeZoneOffset.Ticks, DateTimeKind.Unspecified); } if ((styles & DateTimeStyles.AssumeUniversal) != 0) { return DateTime.UtcNow; } } return DateTime.Now; } private static bool CheckDefaultDateTime(ref DateTimeResult result, ref Calendar cal, DateTimeStyles styles) { if ((result.flags & ParseFlags.CaptureOffset) != 0 && (result.Month != -1 || result.Day != -1) && (result.Year == -1 || (result.flags & ParseFlags.YearDefault) != 0) && (result.flags & ParseFlags.TimeZoneUsed) != 0) { result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, "Format_MissingIncompleteDate"); return false; } if (result.Year == -1 || result.Month == -1 || result.Day == -1) { DateTime dateTimeNow = GetDateTimeNow(ref result, ref styles); if (result.Month == -1 && result.Day == -1) { if (result.Year == -1) { if ((styles & DateTimeStyles.NoCurrentDateDefault) != 0) { cal = GregorianCalendar.GetDefaultInstance(); result.Year = (result.Month = (result.Day = 1)); } else { result.Year = cal.GetYear(dateTimeNow); result.Month = cal.GetMonth(dateTimeNow); result.Day = cal.GetDayOfMonth(dateTimeNow); } } else { result.Month = 1; result.Day = 1; } } else { if (result.Year == -1) { result.Year = cal.GetYear(dateTimeNow); } if (result.Month == -1) { result.Month = 1; } if (result.Day == -1) { result.Day = 1; } } } if (result.Hour == -1) { result.Hour = 0; } if (result.Minute == -1) { result.Minute = 0; } if (result.Second == -1) { result.Second = 0; } if (result.era == -1) { result.era = 0; } return true; } private static string ExpandPredefinedFormat(ReadOnlySpan format, ref DateTimeFormatInfo dtfi, ref ParsingInfo parseInfo, ref DateTimeResult result) { switch (format[0]) { case 'O': case 'o': case 's': ConfigureFormatOS(ref dtfi, ref parseInfo); break; case 'R': case 'r': ConfigureFormatR(ref dtfi, ref parseInfo, ref result); break; case 'u': parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); dtfi = DateTimeFormatInfo.InvariantInfo; if ((result.flags & ParseFlags.CaptureOffset) != 0) { result.flags |= ParseFlags.UtcSortPattern; } break; case 'U': parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); result.flags |= ParseFlags.TimeZoneUsed; result.timeZoneOffset = new TimeSpan(0L); result.flags |= ParseFlags.TimeZoneUtc; if (dtfi.Calendar.GetType() != typeof(GregorianCalendar)) { dtfi = (DateTimeFormatInfo)dtfi.Clone(); dtfi.Calendar = GregorianCalendar.GetDefaultInstance(); } break; } return DateTimeFormat.GetRealFormat(format, dtfi); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool ParseJapaneseEraStart(ref __DTString str, DateTimeFormatInfo dtfi) { if (LocalAppContextSwitches.EnforceLegacyJapaneseDateParsing || dtfi.Calendar.ID != CalendarId.JAPAN || !str.GetNext()) { return false; } if (str.m_current != "元"[0]) { str.Index--; return false; } return true; } private static void ConfigureFormatR(ref DateTimeFormatInfo dtfi, ref ParsingInfo parseInfo, ref DateTimeResult result) { parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); dtfi = DateTimeFormatInfo.InvariantInfo; if ((result.flags & ParseFlags.CaptureOffset) != 0) { result.flags |= ParseFlags.Rfc1123Pattern; } } private static void ConfigureFormatOS(ref DateTimeFormatInfo dtfi, ref ParsingInfo parseInfo) { parseInfo.calendar = GregorianCalendar.GetDefaultInstance(); dtfi = DateTimeFormatInfo.InvariantInfo; } private static bool ParseByFormat(ref __DTString str, ref __DTString format, ref ParsingInfo parseInfo, DateTimeFormatInfo dtfi, ref DateTimeResult result) { int result2 = 0; int result3 = 0; int result4 = 0; int result5 = 0; int result6 = 0; int result7 = 0; int result8 = 0; double result9 = 0.0; TM result10 = TM.AM; char @char = format.GetChar(); switch (@char) { case 'y': { int repeatCount = format.GetRepeatCount(); bool flag; if (ParseJapaneseEraStart(ref str, dtfi)) { result2 = 1; flag = true; } else if (dtfi.HasForceTwoDigitYears) { flag = ParseDigits(ref str, 1, 4, out result2); } else { if (repeatCount <= 2) { parseInfo.fUseTwoDigitYear = true; } flag = ParseDigits(ref str, repeatCount, out result2); } if (!flag && parseInfo.fCustomNumberParser) { flag = parseInfo.parseNumberDelegate(ref str, repeatCount, out result2); } if (!flag) { result.SetBadDateTimeFailure(); return false; } if (!CheckNewValue(ref result.Year, result2, @char, ref result)) { return false; } break; } case 'M': { int repeatCount = format.GetRepeatCount(); if (repeatCount <= 2) { if (!ParseDigits(ref str, repeatCount, out result3) && (!parseInfo.fCustomNumberParser || !parseInfo.parseNumberDelegate(ref str, repeatCount, out result3))) { result.SetBadDateTimeFailure(); return false; } } else { if (repeatCount == 3) { if (!MatchAbbreviatedMonthName(ref str, dtfi, ref result3)) { result.SetBadDateTimeFailure(); return false; } } else if (!MatchMonthName(ref str, dtfi, ref result3)) { result.SetBadDateTimeFailure(); return false; } result.flags |= ParseFlags.ParsedMonthName; } if (!CheckNewValue(ref result.Month, result3, @char, ref result)) { return false; } break; } case 'd': { int repeatCount = format.GetRepeatCount(); if (repeatCount <= 2) { if (!ParseDigits(ref str, repeatCount, out result4) && (!parseInfo.fCustomNumberParser || !parseInfo.parseNumberDelegate(ref str, repeatCount, out result4))) { result.SetBadDateTimeFailure(); return false; } if (!CheckNewValue(ref result.Day, result4, @char, ref result)) { return false; } break; } if (repeatCount == 3) { if (!MatchAbbreviatedDayName(ref str, dtfi, ref result5)) { result.SetBadDateTimeFailure(); return false; } } else if (!MatchDayName(ref str, dtfi, ref result5)) { result.SetBadDateTimeFailure(); return false; } if (!CheckNewValue(ref parseInfo.dayOfWeek, result5, @char, ref result)) { return false; } break; } case 'g': format.GetRepeatCount(); if (!MatchEraName(ref str, dtfi, ref result.era)) { result.SetBadDateTimeFailure(); return false; } break; case 'h': { parseInfo.fUseHour12 = true; int repeatCount = format.GetRepeatCount(); if (!ParseDigits(ref str, (repeatCount < 2) ? 1 : 2, out result6)) { result.SetBadDateTimeFailure(); return false; } if (!CheckNewValue(ref result.Hour, result6, @char, ref result)) { return false; } break; } case 'H': { int repeatCount = format.GetRepeatCount(); if (!ParseDigits(ref str, (repeatCount < 2) ? 1 : 2, out result6)) { result.SetBadDateTimeFailure(); return false; } if (!CheckNewValue(ref result.Hour, result6, @char, ref result)) { return false; } break; } case 'm': { int repeatCount = format.GetRepeatCount(); if (!ParseDigits(ref str, (repeatCount < 2) ? 1 : 2, out result7)) { result.SetBadDateTimeFailure(); return false; } if (!CheckNewValue(ref result.Minute, result7, @char, ref result)) { return false; } break; } case 's': { int repeatCount = format.GetRepeatCount(); if (!ParseDigits(ref str, (repeatCount < 2) ? 1 : 2, out result8)) { result.SetBadDateTimeFailure(); return false; } if (!CheckNewValue(ref result.Second, result8, @char, ref result)) { return false; } break; } case 'F': case 'f': { int repeatCount = format.GetRepeatCount(); if (repeatCount <= 7) { if (!ParseFractionExact(ref str, repeatCount, ref result9) && @char == 'f') { result.SetBadDateTimeFailure(); return false; } if (result.fraction < 0.0) { result.fraction = result9; } else if (result9 != result.fraction) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", @char); return false; } break; } result.SetBadDateTimeFailure(); return false; } case 't': { int repeatCount = format.GetRepeatCount(); if (repeatCount == 1) { if (!MatchAbbreviatedTimeMark(ref str, dtfi, ref result10)) { result.SetBadDateTimeFailure(); return false; } } else if (!MatchTimeMark(ref str, dtfi, ref result10)) { result.SetBadDateTimeFailure(); return false; } if (parseInfo.timeMark == TM.NotSet) { parseInfo.timeMark = result10; } else if (parseInfo.timeMark != result10) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", @char); return false; } break; } case 'z': { int repeatCount = format.GetRepeatCount(); TimeSpan result11 = new TimeSpan(0L); if (!ParseTimeZoneOffset(ref str, repeatCount, ref result11)) { result.SetBadDateTimeFailure(); return false; } if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && result11 != result.timeZoneOffset) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'z'); return false; } result.timeZoneOffset = result11; result.flags |= ParseFlags.TimeZoneUsed; break; } case 'Z': if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && result.timeZoneOffset != TimeSpan.Zero) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'Z'); return false; } result.flags |= ParseFlags.TimeZoneUsed; result.timeZoneOffset = new TimeSpan(0L); result.flags |= ParseFlags.TimeZoneUtc; str.Index++; if (!GetTimeZoneName(ref str)) { result.SetBadDateTimeFailure(); return false; } str.Index--; break; case 'K': if (str.Match('Z')) { if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && result.timeZoneOffset != TimeSpan.Zero) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'K'); return false; } result.flags |= ParseFlags.TimeZoneUsed; result.timeZoneOffset = new TimeSpan(0L); result.flags |= ParseFlags.TimeZoneUtc; } else if (str.Match('+') || str.Match('-')) { str.Index--; TimeSpan result12 = new TimeSpan(0L); if (!ParseTimeZoneOffset(ref str, 3, ref result12)) { result.SetBadDateTimeFailure(); return false; } if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && result12 != result.timeZoneOffset) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'K'); return false; } result.timeZoneOffset = result12; result.flags |= ParseFlags.TimeZoneUsed; } break; case ':': if (((dtfi.TimeSeparator.Length > 1 && dtfi.TimeSeparator[0] == ':') || !str.Match(':')) && !str.Match(dtfi.TimeSeparator)) { result.SetBadDateTimeFailure(); return false; } break; case '/': if (((dtfi.DateSeparator.Length > 1 && dtfi.DateSeparator[0] == '/') || !str.Match('/')) && !str.Match(dtfi.DateSeparator)) { result.SetBadDateTimeFailure(); return false; } break; case '"': case '\'': { StringBuilder stringBuilder = StringBuilderCache.Acquire(); if (!TryParseQuoteString(format.Value, format.Index, stringBuilder, out var repeatCount)) { result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadQuote", @char); StringBuilderCache.Release(stringBuilder); return false; } format.Index += repeatCount - 1; string stringAndRelease = StringBuilderCache.GetStringAndRelease(stringBuilder); for (int i = 0; i < stringAndRelease.Length; i++) { if (stringAndRelease[i] == ' ' && parseInfo.fAllowInnerWhite) { str.SkipWhiteSpaces(); } else if (!str.Match(stringAndRelease[i])) { result.SetBadDateTimeFailure(); return false; } } if ((result.flags & ParseFlags.CaptureOffset) != 0 && (((result.flags & ParseFlags.Rfc1123Pattern) != 0 && stringAndRelease == "GMT") || ((result.flags & ParseFlags.UtcSortPattern) != 0 && stringAndRelease == "Z"))) { result.flags |= ParseFlags.TimeZoneUsed; result.timeZoneOffset = TimeSpan.Zero; } break; } case '%': if (format.Index >= format.Value.Length - 1 || format.Value[format.Index + 1] == '%') { result.SetBadFormatSpecifierFailure(format.Value); return false; } break; case '\\': if (format.GetNext()) { if (!str.Match(format.GetChar())) { result.SetBadDateTimeFailure(); return false; } break; } result.SetBadFormatSpecifierFailure(format.Value); return false; case '.': if (!str.Match(@char)) { if (!format.GetNext() || !format.Match('F')) { result.SetBadDateTimeFailure(); return false; } format.GetRepeatCount(); } break; default: if (@char == ' ') { if (!parseInfo.fAllowInnerWhite && !str.Match(@char)) { if (parseInfo.fAllowTrailingWhite && format.GetNext() && ParseByFormat(ref str, ref format, ref parseInfo, dtfi, ref result)) { return true; } result.SetBadDateTimeFailure(); return false; } } else if (format.MatchSpecifiedWord("GMT")) { format.Index += "GMT".Length - 1; result.flags |= ParseFlags.TimeZoneUsed; result.timeZoneOffset = TimeSpan.Zero; if (!str.Match("GMT")) { result.SetBadDateTimeFailure(); return false; } } else if (!str.Match(@char)) { result.SetBadDateTimeFailure(); return false; } break; } return true; } internal static bool TryParseQuoteString(ReadOnlySpan format, int pos, StringBuilder result, out int returnValue) { returnValue = 0; int length = format.Length; int num = pos; char c = format[pos++]; bool flag = false; while (pos < length) { char c2 = format[pos++]; if (c2 == c) { flag = true; break; } if (c2 == '\\') { if (pos >= length) { return false; } result.Append(format[pos++]); } else { result.Append(c2); } } if (!flag) { return false; } returnValue = pos - num; return true; } private static bool DoStrictParse(ReadOnlySpan s, ReadOnlySpan formatParam, DateTimeStyles styles, DateTimeFormatInfo dtfi, ref DateTimeResult result) { ParsingInfo parseInfo = default(ParsingInfo); parseInfo.Init(); parseInfo.calendar = dtfi.Calendar; parseInfo.fAllowInnerWhite = (styles & DateTimeStyles.AllowInnerWhite) != 0; parseInfo.fAllowTrailingWhite = (styles & DateTimeStyles.AllowTrailingWhite) != 0; if (formatParam.Length == 1) { char c = formatParam[0]; if (styles == DateTimeStyles.None) { switch (c) { case 'R': case 'r': ConfigureFormatR(ref dtfi, ref parseInfo, ref result); return ParseFormatR(s, ref parseInfo, ref result); case 'O': case 'o': ConfigureFormatOS(ref dtfi, ref parseInfo); return ParseFormatO(s, ref result); } } if ((result.flags & ParseFlags.CaptureOffset) != 0 && c == 'U') { result.SetBadFormatSpecifierFailure(formatParam); return false; } formatParam = ExpandPredefinedFormat(formatParam, ref dtfi, ref parseInfo, ref result); } result.calendar = parseInfo.calendar; if (parseInfo.calendar.ID == CalendarId.HEBREW) { parseInfo.parseNumberDelegate = s_hebrewNumberParser; parseInfo.fCustomNumberParser = true; } result.Hour = (result.Minute = (result.Second = -1)); __DTString format = new __DTString(formatParam, dtfi, checkDigitToken: false); __DTString str = new __DTString(s, dtfi, checkDigitToken: false); if (parseInfo.fAllowTrailingWhite) { format.TrimTail(); format.RemoveTrailingInQuoteSpaces(); str.TrimTail(); } if ((styles & DateTimeStyles.AllowLeadingWhite) != 0) { format.SkipWhiteSpaces(); format.RemoveLeadingInQuoteSpaces(); str.SkipWhiteSpaces(); } while (format.GetNext()) { if (parseInfo.fAllowInnerWhite) { str.SkipWhiteSpaces(); } if (!ParseByFormat(ref str, ref format, ref parseInfo, dtfi, ref result)) { return false; } } if (str.Index < str.Value.Length - 1) { result.SetBadDateTimeFailure(); return false; } if (parseInfo.fUseTwoDigitYear && (dtfi.FormatFlags & DateTimeFormatFlags.UseHebrewRule) == 0) { if (result.Year >= 100) { result.SetBadDateTimeFailure(); return false; } try { result.Year = parseInfo.calendar.ToFourDigitYear(result.Year); } catch (ArgumentOutOfRangeException) { result.SetBadDateTimeFailure(); return false; } } if (parseInfo.fUseHour12) { if (parseInfo.timeMark == TM.NotSet) { parseInfo.timeMark = TM.AM; } if (result.Hour > 12) { result.SetBadDateTimeFailure(); return false; } if (parseInfo.timeMark == TM.AM) { if (result.Hour == 12) { result.Hour = 0; } } else { result.Hour = ((result.Hour == 12) ? 12 : (result.Hour + 12)); } } else if ((parseInfo.timeMark == TM.AM && result.Hour >= 12) || (parseInfo.timeMark == TM.PM && result.Hour < 12)) { result.SetBadDateTimeFailure(); return false; } bool flag = result.Year == -1 && result.Month == -1 && result.Day == -1; if (!CheckDefaultDateTime(ref result, ref parseInfo.calendar, styles)) { return false; } if (!flag && dtfi.HasYearMonthAdjustment && !dtfi.YearMonthAdjustment(ref result.Year, ref result.Month, (result.flags & ParseFlags.ParsedMonthName) != 0)) { result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar"); return false; } if (!parseInfo.calendar.TryToDateTime(result.Year, result.Month, result.Day, result.Hour, result.Minute, result.Second, 0, result.era, out result.parsedDate)) { result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar"); return false; } if (result.fraction > 0.0 && !result.parsedDate.TryAddTicks((long)Math.Round(result.fraction * 10000000.0), out result.parsedDate)) { result.SetBadDateTimeFailure(); return false; } if (parseInfo.dayOfWeek != -1 && parseInfo.dayOfWeek != (int)parseInfo.calendar.GetDayOfWeek(result.parsedDate)) { result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, "Format_BadDayOfWeek"); return false; } return DetermineTimeZoneAdjustments(ref result, styles, flag); } private static bool ParseFormatR(ReadOnlySpan source, ref ParsingInfo parseInfo, ref DateTimeResult result) { if (source.Length != 29) { result.SetBadDateTimeFailure(); return false; } uint num = source[0]; uint num2 = source[1]; uint num3 = source[2]; uint num4 = source[3]; if ((num | num2 | num3 | num4) > 127) { result.SetBadDateTimeFailure(); return false; } DayOfWeek dayOfWeek; switch ((num << 24) | (num2 << 16) | (num3 << 8) | num4 | 0x20202000) { case 1937075756u: dayOfWeek = DayOfWeek.Sunday; break; case 1836019244u: dayOfWeek = DayOfWeek.Monday; break; case 1953850668u: dayOfWeek = DayOfWeek.Tuesday; break; case 2003133484u: dayOfWeek = DayOfWeek.Wednesday; break; case 1953002796u: dayOfWeek = DayOfWeek.Thursday; break; case 1718774060u: dayOfWeek = DayOfWeek.Friday; break; case 1935766572u: dayOfWeek = DayOfWeek.Saturday; break; default: result.SetBadDateTimeFailure(); return false; } if (source[4] != ' ') { result.SetBadDateTimeFailure(); return false; } uint num5 = (uint)(source[5] - 48); uint num6 = (uint)(source[6] - 48); if (num5 > 9 || num6 > 9) { result.SetBadDateTimeFailure(); return false; } int day = (int)(num5 * 10 + num6); if (source[7] != ' ') { result.SetBadDateTimeFailure(); return false; } uint num7 = source[8]; uint num8 = source[9]; uint num9 = source[10]; uint num10 = source[11]; if ((num7 | num8 | num9 | num10) > 127) { result.SetBadDateTimeFailure(); return false; } int month; switch ((num7 << 24) | (num8 << 16) | (num9 << 8) | num10 | 0x20202000) { case 1784770080u: month = 1; break; case 1717920288u: month = 2; break; case 1835102752u: month = 3; break; case 1634759200u: month = 4; break; case 1835104544u: month = 5; break; case 1786080800u: month = 6; break; case 1786080288u: month = 7; break; case 1635084064u: month = 8; break; case 1936027680u: month = 9; break; case 1868788768u: month = 10; break; case 1852798496u: month = 11; break; case 1684366112u: month = 12; break; default: result.SetBadDateTimeFailure(); return false; } uint num11 = (uint)(source[12] - 48); uint num12 = (uint)(source[13] - 48); uint num13 = (uint)(source[14] - 48); uint num14 = (uint)(source[15] - 48); if (num11 > 9 || num12 > 9 || num13 > 9 || num14 > 9) { result.SetBadDateTimeFailure(); return false; } int year = (int)(num11 * 1000 + num12 * 100 + num13 * 10 + num14); if (source[16] != ' ') { result.SetBadDateTimeFailure(); return false; } uint num15 = (uint)(source[17] - 48); uint num16 = (uint)(source[18] - 48); if (num15 > 9 || num16 > 9) { result.SetBadDateTimeFailure(); return false; } int hour = (int)(num15 * 10 + num16); if (source[19] != ':') { result.SetBadDateTimeFailure(); return false; } uint num17 = (uint)(source[20] - 48); uint num18 = (uint)(source[21] - 48); if (num17 > 9 || num18 > 9) { result.SetBadDateTimeFailure(); return false; } int minute = (int)(num17 * 10 + num18); if (source[22] != ':') { result.SetBadDateTimeFailure(); return false; } uint num19 = (uint)(source[23] - 48); uint num20 = (uint)(source[24] - 48); if (num19 > 9 || num20 > 9) { result.SetBadDateTimeFailure(); return false; } int second = (int)(num19 * 10 + num20); if (source[25] != ' ' || source[26] != 'G' || source[27] != 'M' || source[28] != 'T') { result.SetBadDateTimeFailure(); return false; } if (!parseInfo.calendar.TryToDateTime(year, month, day, hour, minute, second, 0, 0, out result.parsedDate)) { result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar"); return false; } if (dayOfWeek != result.parsedDate.DayOfWeek) { result.SetFailure(ParseFailureKind.FormatWithOriginalDateTime, "Format_BadDayOfWeek"); return false; } return true; } private static bool ParseFormatO(ReadOnlySpan source, ref DateTimeResult result) { if ((uint)source.Length < 27u || source[4] != '-' || source[7] != '-' || source[10] != 'T' || source[13] != ':' || source[16] != ':' || source[19] != '.') { result.SetBadDateTimeFailure(); return false; } uint num = (uint)(source[0] - 48); uint num2 = (uint)(source[1] - 48); uint num3 = (uint)(source[2] - 48); uint num4 = (uint)(source[3] - 48); if (num > 9 || num2 > 9 || num3 > 9 || num4 > 9) { result.SetBadDateTimeFailure(); return false; } int year = (int)(num * 1000 + num2 * 100 + num3 * 10 + num4); uint num5 = (uint)(source[5] - 48); uint num6 = (uint)(source[6] - 48); if (num5 > 9 || num6 > 9) { result.SetBadDateTimeFailure(); return false; } int month = (int)(num5 * 10 + num6); uint num7 = (uint)(source[8] - 48); uint num8 = (uint)(source[9] - 48); if (num7 > 9 || num8 > 9) { result.SetBadDateTimeFailure(); return false; } int day = (int)(num7 * 10 + num8); uint num9 = (uint)(source[11] - 48); uint num10 = (uint)(source[12] - 48); if (num9 > 9 || num10 > 9) { result.SetBadDateTimeFailure(); return false; } int hour = (int)(num9 * 10 + num10); uint num11 = (uint)(source[14] - 48); uint num12 = (uint)(source[15] - 48); if (num11 > 9 || num12 > 9) { result.SetBadDateTimeFailure(); return false; } int minute = (int)(num11 * 10 + num12); uint num13 = (uint)(source[17] - 48); uint num14 = (uint)(source[18] - 48); if (num13 > 9 || num14 > 9) { result.SetBadDateTimeFailure(); return false; } int second = (int)(num13 * 10 + num14); uint num15 = (uint)(source[20] - 48); uint num16 = (uint)(source[21] - 48); uint num17 = (uint)(source[22] - 48); uint num18 = (uint)(source[23] - 48); uint num19 = (uint)(source[24] - 48); uint num20 = (uint)(source[25] - 48); uint num21 = (uint)(source[26] - 48); if (num15 > 9 || num16 > 9 || num17 > 9 || num18 > 9 || num19 > 9 || num20 > 9 || num21 > 9) { result.SetBadDateTimeFailure(); return false; } double num22 = (double)(num15 * 1000000 + num16 * 100000 + num17 * 10000 + num18 * 1000 + num19 * 100 + num20 * 10 + num21) / 10000000.0; if (!DateTime.TryCreate(year, month, day, hour, minute, second, 0, out var result2)) { result.SetBadDateTimeFailure(); return false; } if (!result2.TryAddTicks((long)Math.Round(num22 * 10000000.0), out result.parsedDate)) { result.SetBadDateTimeFailure(); return false; } if ((uint)source.Length > 27u) { char c = source[27]; switch (c) { case 'Z': if (source.Length != 28) { result.SetBadDateTimeFailure(); return false; } result.flags |= ParseFlags.TimeZoneUsed | ParseFlags.TimeZoneUtc; break; case '+': case '-': { int num25; int num26; if (source.Length == 33) { uint num23 = (uint)(source[28] - 48); uint num24 = (uint)(source[29] - 48); if (num23 > 9 || num24 > 9) { result.SetBadDateTimeFailure(); return false; } num25 = (int)(num23 * 10 + num24); num26 = 30; } else { if (source.Length != 32) { result.SetBadDateTimeFailure(); return false; } num25 = source[28] - 48; if ((uint)num25 > 9u) { result.SetBadDateTimeFailure(); return false; } num26 = 29; } if (source[num26] != ':') { result.SetBadDateTimeFailure(); return false; } uint num27 = (uint)(source[num26 + 1] - 48); uint num28 = (uint)(source[num26 + 2] - 48); if (num27 > 9 || num28 > 9) { result.SetBadDateTimeFailure(); return false; } int minutes = (int)(num27 * 10 + num28); result.flags |= ParseFlags.TimeZoneUsed; result.timeZoneOffset = new TimeSpan(num25, minutes, 0); if (c == '-') { result.timeZoneOffset = result.timeZoneOffset.Negate(); } break; } default: result.SetBadDateTimeFailure(); return false; } } return DetermineTimeZoneAdjustments(ref result, DateTimeStyles.None, bTimeOnly: false); } private static Exception GetDateTimeParseException(ref DateTimeResult result) { return result.failure switch { ParseFailureKind.ArgumentNull => new ArgumentNullException(result.failureArgumentName, SR.GetResourceString(result.failureMessageID)), ParseFailureKind.Format => new FormatException(SR.GetResourceString(result.failureMessageID)), ParseFailureKind.FormatWithParameter => new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), result.failureMessageFormatArgument)), ParseFailureKind.FormatBadDateTimeCalendar => new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), new string(result.originalDateTimeString), result.calendar)), ParseFailureKind.FormatWithOriginalDateTime => new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), new string(result.originalDateTimeString))), ParseFailureKind.FormatWithFormatSpecifier => new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), new string(result.failedFormatSpecifier))), ParseFailureKind.FormatWithOriginalDateTimeAndParameter => new FormatException(SR.Format(SR.GetResourceString(result.failureMessageID), new string(result.originalDateTimeString), result.failureMessageFormatArgument)), _ => null, }; } } internal ref struct __DTString { internal ReadOnlySpan Value; internal int Index; internal char m_current; private readonly CompareInfo m_info; private readonly bool m_checkDigitToken; private static readonly char[] WhiteSpaceChecks = new char[2] { ' ', '\u00a0' }; internal int Length => Value.Length; internal CompareInfo CompareInfo => m_info; internal __DTString(ReadOnlySpan str, DateTimeFormatInfo dtfi, bool checkDigitToken) : this(str, dtfi) { m_checkDigitToken = checkDigitToken; } internal __DTString(ReadOnlySpan str, DateTimeFormatInfo dtfi) { Index = -1; Value = str; m_current = '\0'; m_info = dtfi.CompareInfo; m_checkDigitToken = (dtfi.FormatFlags & DateTimeFormatFlags.UseDigitPrefixInTokens) != 0; } internal bool GetNext() { Index++; if (Index < Length) { m_current = Value[Index]; return true; } return false; } internal bool AtEnd() { if (Index >= Length) { return true; } return false; } internal bool Advance(int count) { Index += count; if (Index < Length) { m_current = Value[Index]; return true; } return false; } internal void GetRegularToken(out TokenType tokenType, out int tokenValue, DateTimeFormatInfo dtfi) { tokenValue = 0; if (Index >= Length) { tokenType = TokenType.EndOfString; return; } while (true) { if (DateTimeParse.IsDigit(m_current)) { tokenValue = m_current - 48; int index = Index; while (++Index < Length) { m_current = Value[Index]; int num = m_current - 48; if (num < 0 || num > 9) { break; } tokenValue = tokenValue * 10 + num; } if (Index - index > 8) { tokenType = TokenType.NumberToken; tokenValue = -1; } else if (Index - index < 3) { tokenType = TokenType.NumberToken; } else { tokenType = TokenType.YearNumberToken; } if (m_checkDigitToken) { int index2 = Index; char current = m_current; Index = index; m_current = Value[Index]; if (dtfi.Tokenize(TokenType.RegularTokenMask, out var tokenType2, out var tokenValue2, ref this)) { tokenType = tokenType2; tokenValue = tokenValue2; } else { Index = index2; m_current = current; } } break; } if (char.IsWhiteSpace(m_current)) { do { if (++Index < Length) { m_current = Value[Index]; continue; } tokenType = TokenType.EndOfString; return; } while (char.IsWhiteSpace(m_current)); continue; } dtfi.Tokenize(TokenType.RegularTokenMask, out tokenType, out tokenValue, ref this); break; } } internal TokenType GetSeparatorToken(DateTimeFormatInfo dtfi, out int indexBeforeSeparator, out char charBeforeSeparator) { indexBeforeSeparator = Index; charBeforeSeparator = m_current; if (!SkipWhiteSpaceCurrent()) { return TokenType.SEP_End; } TokenType tokenType; if (!DateTimeParse.IsDigit(m_current)) { if (!dtfi.Tokenize(TokenType.SeparatorTokenMask, out tokenType, out var _, ref this)) { tokenType = TokenType.SEP_Space; return tokenType; } return tokenType; } tokenType = TokenType.SEP_Space; return tokenType; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool MatchSpecifiedWord(string target) { if (Index + target.Length <= Length) { return m_info.Compare(Value.Slice(Index, target.Length), target, CompareOptions.IgnoreCase) == 0; } return false; } internal bool MatchSpecifiedWords(string target, bool checkWordBoundary, ref int matchLength) { int num = Value.Length - Index; matchLength = target.Length; if (matchLength > num || m_info.Compare(Value.Slice(Index, matchLength), target, CompareOptions.IgnoreCase) != 0) { int num2 = 0; int num3 = Index; int num4 = target.IndexOfAny(WhiteSpaceChecks, num2); if (num4 == -1) { return false; } do { int num5 = num4 - num2; if (num3 >= Value.Length - num5) { return false; } if (num5 == 0) { matchLength--; } else { if (!char.IsWhiteSpace(Value[num3 + num5])) { return false; } if (m_info.CompareOptionIgnoreCase(Value.Slice(num3, num5), target.AsSpan(num2, num5)) != 0) { return false; } num3 = num3 + num5 + 1; } num2 = num4 + 1; while (num3 < Value.Length && char.IsWhiteSpace(Value[num3])) { num3++; matchLength++; } } while ((num4 = target.IndexOfAny(WhiteSpaceChecks, num2)) >= 0); if (num2 < target.Length) { int num6 = target.Length - num2; if (num3 > Value.Length - num6) { return false; } if (m_info.CompareOptionIgnoreCase(Value.Slice(num3, num6), target.AsSpan(num2, num6)) != 0) { return false; } } } if (checkWordBoundary) { int num7 = Index + matchLength; if (num7 < Value.Length && char.IsLetter(Value[num7])) { return false; } } return true; } internal bool Match(string str) { if (++Index >= Length) { return false; } if (str.Length > Value.Length - Index) { return false; } if (m_info.Compare(Value.Slice(Index, str.Length), str, CompareOptions.Ordinal) == 0) { Index += str.Length - 1; return true; } return false; } internal bool Match(char ch) { if (++Index >= Length) { return false; } if (Value[Index] == ch) { m_current = ch; return true; } Index--; return false; } internal int MatchLongestWords(string[] words, ref int maxMatchStrLen) { int result = -1; for (int i = 0; i < words.Length; i++) { string text = words[i]; int matchLength = text.Length; if (MatchSpecifiedWords(text, checkWordBoundary: false, ref matchLength) && matchLength > maxMatchStrLen) { maxMatchStrLen = matchLength; result = i; } } return result; } internal int GetRepeatCount() { char c = Value[Index]; int i; for (i = Index + 1; i < Length && Value[i] == c; i++) { } int result = i - Index; Index = i - 1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool GetNextDigit() { if (++Index < Length) { return DateTimeParse.IsDigit(Value[Index]); } return false; } internal char GetChar() { return Value[Index]; } internal int GetDigit() { return Value[Index] - 48; } internal void SkipWhiteSpaces() { while (Index + 1 < Length) { char c = Value[Index + 1]; if (!char.IsWhiteSpace(c)) { break; } Index++; } } internal bool SkipWhiteSpaceCurrent() { if (Index >= Length) { return false; } if (!char.IsWhiteSpace(m_current)) { return true; } while (++Index < Length) { m_current = Value[Index]; if (!char.IsWhiteSpace(m_current)) { return true; } } return false; } internal void TrimTail() { int num = Length - 1; while (num >= 0 && char.IsWhiteSpace(Value[num])) { num--; } Value = Value.Slice(0, num + 1); } internal void RemoveTrailingInQuoteSpaces() { int num = Length - 1; if (num <= 1) { return; } char c = Value[num]; if ((c == '\'' || c == '"') && char.IsWhiteSpace(Value[num - 1])) { num--; while (num >= 1 && char.IsWhiteSpace(Value[num - 1])) { num--; } Span span = new char[num + 1]; span[num] = c; Value.Slice(0, num).CopyTo(span); Value = span; } } internal void RemoveLeadingInQuoteSpaces() { if (Length <= 2) { return; } int i = 0; char c = Value[i]; if (c == '\'' || c == '"') { for (; i + 1 < Length && char.IsWhiteSpace(Value[i + 1]); i++) { } if (i != 0) { Span span = new char[Value.Length - i]; span[0] = c; Value.Slice(i + 1).CopyTo(span.Slice(1)); Value = span; } } } internal DTSubString GetSubString() { DTSubString result = default(DTSubString); result.index = Index; result.s = Value; while (Index + result.length < Length) { char c = Value[Index + result.length]; DTSubStringType dTSubStringType = ((c < '0' || c > '9') ? DTSubStringType.Other : DTSubStringType.Number); if (result.length == 0) { result.type = dTSubStringType; } else if (result.type != dTSubStringType) { break; } result.length++; if (dTSubStringType != DTSubStringType.Number) { break; } if (result.length > 8) { result.type = DTSubStringType.Invalid; return result; } int num = c - 48; result.value = result.value * 10 + num; } if (result.length == 0) { result.type = DTSubStringType.End; return result; } return result; } internal void ConsumeSubString(DTSubString sub) { Index = sub.index + sub.length; if (Index < Length) { m_current = Value[Index]; } } } internal enum DTSubStringType { Unknown, Invalid, Number, End, Other } internal ref struct DTSubString { internal ReadOnlySpan s; internal int index; internal int length; internal DTSubStringType type; internal int value; internal char this[int relativeIndex] => s[index + relativeIndex]; } internal struct DateTimeToken { internal DateTimeParse.DTT dtt; internal TokenType suffix; internal int num; } internal struct DateTimeRawInfo { private unsafe int* num; internal int numCount; internal int month; internal int year; internal int dayOfWeek; internal int era; internal DateTimeParse.TM timeMark; internal double fraction; internal bool hasSameDateAndTimeSeparators; internal unsafe void Init(int* numberBuffer) { month = -1; year = -1; dayOfWeek = -1; era = -1; timeMark = DateTimeParse.TM.NotSet; fraction = -1.0; num = numberBuffer; } internal unsafe void AddNumber(int value) { num[numCount++] = value; } internal unsafe int GetNumber(int index) { return num[index]; } } internal enum ParseFailureKind { None, ArgumentNull, Format, FormatWithParameter, FormatWithOriginalDateTime, FormatWithFormatSpecifier, FormatWithOriginalDateTimeAndParameter, FormatBadDateTimeCalendar, WrongParts } [Flags] internal enum ParseFlags { HaveYear = 1, HaveMonth = 2, HaveDay = 4, HaveHour = 8, HaveMinute = 0x10, HaveSecond = 0x20, HaveTime = 0x40, HaveDate = 0x80, TimeZoneUsed = 0x100, TimeZoneUtc = 0x200, ParsedMonthName = 0x400, CaptureOffset = 0x800, YearDefault = 0x1000, Rfc1123Pattern = 0x2000, UtcSortPattern = 0x4000 } internal ref struct DateTimeResult { internal int Year; internal int Month; internal int Day; internal int Hour; internal int Minute; internal int Second; internal double fraction; internal int era; internal ParseFlags flags; internal TimeSpan timeZoneOffset; internal Calendar calendar; internal DateTime parsedDate; internal ParseFailureKind failure; internal string failureMessageID; internal object failureMessageFormatArgument; internal string failureArgumentName; internal ReadOnlySpan originalDateTimeString; internal ReadOnlySpan failedFormatSpecifier; internal void Init(ReadOnlySpan originalDateTimeString) { this.originalDateTimeString = originalDateTimeString; Year = -1; Month = -1; Day = -1; fraction = -1.0; era = -1; } internal void SetDate(int year, int month, int day) { Year = year; Month = month; Day = day; } internal void SetBadFormatSpecifierFailure() { SetBadFormatSpecifierFailure(ReadOnlySpan.Empty); } internal void SetBadFormatSpecifierFailure(ReadOnlySpan failedFormatSpecifier) { failure = ParseFailureKind.FormatWithFormatSpecifier; failureMessageID = "Format_BadFormatSpecifier"; this.failedFormatSpecifier = failedFormatSpecifier; } internal void SetBadDateTimeFailure() { failure = ParseFailureKind.FormatWithOriginalDateTime; failureMessageID = "Format_BadDateTime"; failureMessageFormatArgument = null; } internal void SetFailure(ParseFailureKind failure, string failureMessageID) { this.failure = failure; this.failureMessageID = failureMessageID; failureMessageFormatArgument = null; } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) { this.failure = failure; this.failureMessageID = failureMessageID; this.failureMessageFormatArgument = failureMessageFormatArgument; } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument, string failureArgumentName) { this.failure = failure; this.failureMessageID = failureMessageID; this.failureMessageFormatArgument = failureMessageFormatArgument; this.failureArgumentName = failureArgumentName; } } internal struct ParsingInfo { internal Calendar calendar; internal int dayOfWeek; internal DateTimeParse.TM timeMark; internal bool fUseHour12; internal bool fUseTwoDigitYear; internal bool fAllowInnerWhite; internal bool fAllowTrailingWhite; internal bool fCustomNumberParser; internal DateTimeParse.MatchNumberDelegate parseNumberDelegate; internal void Init() { dayOfWeek = -1; timeMark = DateTimeParse.TM.NotSet; } } internal enum TokenType { NumberToken = 1, YearNumberToken = 2, Am = 3, Pm = 4, MonthToken = 5, EndOfString = 6, DayOfWeekToken = 7, TimeZoneToken = 8, EraToken = 9, DateWordToken = 10, UnknownToken = 11, HebrewNumber = 12, JapaneseEraToken = 13, TEraToken = 14, IgnorableSymbol = 15, SEP_Unk = 256, SEP_End = 512, SEP_Space = 768, SEP_Am = 1024, SEP_Pm = 1280, SEP_Date = 1536, SEP_Time = 1792, SEP_YearSuff = 2048, SEP_MonthSuff = 2304, SEP_DaySuff = 2560, SEP_HourSuff = 2816, SEP_MinuteSuff = 3072, SEP_SecondSuff = 3328, SEP_LocalTimeMark = 3584, SEP_DateOrOffset = 3840, RegularTokenMask = 255, SeparatorTokenMask = 65280 } [Serializable] [NonVersionable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Guid : ISpanFormattable, IFormattable, IComparable, IComparable, IEquatable, IComparisonOperators, IEqualityOperators, ISpanParseable, IParseable { private enum GuidParseThrowStyle : byte { None, All, AllButOverflow } [StructLayout(LayoutKind.Explicit)] private struct GuidResult { [FieldOffset(0)] internal uint _a; [FieldOffset(4)] internal uint _bc; [FieldOffset(4)] internal ushort _b; [FieldOffset(6)] internal ushort _c; [FieldOffset(8)] internal uint _defg; [FieldOffset(8)] internal ushort _de; [FieldOffset(8)] internal byte _d; [FieldOffset(10)] internal ushort _fg; [FieldOffset(12)] internal uint _hijk; [FieldOffset(16)] private readonly GuidParseThrowStyle _throwStyle; internal GuidResult(GuidParseThrowStyle canThrow) { this = default(GuidResult); _throwStyle = canThrow; } internal readonly void SetFailure(bool overflow, string failureMessageID) { if (_throwStyle == GuidParseThrowStyle.None) { return; } if (overflow) { if (_throwStyle == GuidParseThrowStyle.All) { throw new OverflowException(SR.GetResourceString(failureMessageID)); } throw new FormatException(SR.Format_GuidUnrecognized); } throw new FormatException(SR.GetResourceString(failureMessageID)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly Guid ToGuid() { return Unsafe.As(ref Unsafe.AsRef(in this)); } } public static readonly Guid Empty; private readonly int _a; private readonly short _b; private readonly short _c; private readonly byte _d; private readonly byte _e; private readonly byte _f; private readonly byte _g; private readonly byte _h; private readonly byte _i; private readonly byte _j; private readonly byte _k; public Guid(byte[] b) : this(new ReadOnlySpan(b ?? throw new ArgumentNullException("b"))) { } public Guid(ReadOnlySpan b) { if (b.Length != 16) { throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "16"), "b"); } _ = BitConverter.IsLittleEndian; this = MemoryMarshal.Read(b); } [CLSCompliant(false)] public Guid(uint a, ushort b, ushort c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = (int)a; _b = (short)b; _c = (short)c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } public Guid(int a, short b, short c, byte[] d) { if (d == null) { throw new ArgumentNullException("d"); } if (d.Length != 8) { throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "8"), "d"); } _a = a; _b = b; _c = c; _k = d[7]; _d = d[0]; _e = d[1]; _f = d[2]; _g = d[3]; _h = d[4]; _i = d[5]; _j = d[6]; } public Guid(int a, short b, short c, byte d, byte e, byte f, byte g, byte h, byte i, byte j, byte k) { _a = a; _b = b; _c = c; _d = d; _e = e; _f = f; _g = g; _h = h; _i = i; _j = j; _k = k; } public Guid(string g) { if (g == null) { throw new ArgumentNullException("g"); } GuidResult result = new GuidResult(GuidParseThrowStyle.All); bool flag = TryParseGuid(g, ref result); this = result.ToGuid(); } public static Guid Parse(string input) { if (input == null) { throw new ArgumentNullException("input"); } return Parse((ReadOnlySpan)input); } public static Guid Parse(ReadOnlySpan input) { GuidResult result = new GuidResult(GuidParseThrowStyle.AllButOverflow); bool flag = TryParseGuid(input, ref result); return result.ToGuid(); } public static bool TryParse([NotNullWhen(true)] string? input, out Guid result) { if (input == null) { result = default(Guid); return false; } return TryParse((ReadOnlySpan)input, out result); } public static bool TryParse(ReadOnlySpan input, out Guid result) { GuidResult result2 = new GuidResult(GuidParseThrowStyle.None); if (TryParseGuid(input, ref result2)) { result = result2.ToGuid(); return true; } result = default(Guid); return false; } public static Guid ParseExact(string input, string format) { if (input == null) { throw new ArgumentNullException("input"); } ReadOnlySpan input2 = input; if (format == null) { throw new ArgumentNullException("format"); } return ParseExact(input2, format); } public static Guid ParseExact(ReadOnlySpan input, ReadOnlySpan format) { if (format.Length != 1) { throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } input = input.Trim(); GuidResult result = new GuidResult(GuidParseThrowStyle.AllButOverflow); bool flag = (char)(ushort)(format[0] | 0x20) switch { 'd' => TryParseExactD(input, ref result), 'n' => TryParseExactN(input, ref result), 'b' => TryParseExactB(input, ref result), 'p' => TryParseExactP(input, ref result), 'x' => TryParseExactX(input, ref result), _ => throw new FormatException(SR.Format_InvalidGuidFormatSpecification), }; return result.ToGuid(); } public static bool TryParseExact([NotNullWhen(true)] string? input, [NotNullWhen(true)] string? format, out Guid result) { if (input == null) { result = default(Guid); return false; } return TryParseExact((ReadOnlySpan)input, (ReadOnlySpan)format, out result); } public static bool TryParseExact(ReadOnlySpan input, ReadOnlySpan format, out Guid result) { if (format.Length != 1) { result = default(Guid); return false; } input = input.Trim(); GuidResult result2 = new GuidResult(GuidParseThrowStyle.None); bool flag = false; switch ((char)(ushort)(format[0] | 0x20)) { case 'd': flag = TryParseExactD(input, ref result2); break; case 'n': flag = TryParseExactN(input, ref result2); break; case 'b': flag = TryParseExactB(input, ref result2); break; case 'p': flag = TryParseExactP(input, ref result2); break; case 'x': flag = TryParseExactX(input, ref result2); break; } if (flag) { result = result2.ToGuid(); return true; } result = default(Guid); return false; } private static bool TryParseGuid(ReadOnlySpan guidString, ref GuidResult result) { guidString = guidString.Trim(); if (guidString.Length == 0) { result.SetFailure(overflow: false, "Format_GuidUnrecognized"); return false; } return guidString[0] switch { '(' => TryParseExactP(guidString, ref result), '{' => guidString.Contains('-') ? TryParseExactB(guidString, ref result) : TryParseExactX(guidString, ref result), _ => guidString.Contains('-') ? TryParseExactD(guidString, ref result) : TryParseExactN(guidString, ref result), }; } private static bool TryParseExactB(ReadOnlySpan guidString, ref GuidResult result) { if (guidString.Length != 38 || guidString[0] != '{' || guidString[37] != '}') { result.SetFailure(overflow: false, "Format_GuidInvLen"); return false; } return TryParseExactD(guidString.Slice(1, 36), ref result); } private static bool TryParseExactD(ReadOnlySpan guidString, ref GuidResult result) { if (guidString.Length != 36 || guidString[8] != '-' || guidString[13] != '-' || guidString[18] != '-' || guidString[23] != '-') { result.SetFailure(overflow: false, (guidString.Length != 36) ? "Format_GuidInvLen" : "Format_GuidDashes"); return false; } Span span = MemoryMarshal.AsBytes(new Span(ref result, 1)); int invalidIfNegative = 0; span[0] = DecodeByte(guidString[6], guidString[7], ref invalidIfNegative); span[1] = DecodeByte(guidString[4], guidString[5], ref invalidIfNegative); span[2] = DecodeByte(guidString[2], guidString[3], ref invalidIfNegative); span[3] = DecodeByte(guidString[0], guidString[1], ref invalidIfNegative); span[4] = DecodeByte(guidString[11], guidString[12], ref invalidIfNegative); span[5] = DecodeByte(guidString[9], guidString[10], ref invalidIfNegative); span[6] = DecodeByte(guidString[16], guidString[17], ref invalidIfNegative); span[7] = DecodeByte(guidString[14], guidString[15], ref invalidIfNegative); span[8] = DecodeByte(guidString[19], guidString[20], ref invalidIfNegative); span[9] = DecodeByte(guidString[21], guidString[22], ref invalidIfNegative); span[10] = DecodeByte(guidString[24], guidString[25], ref invalidIfNegative); span[11] = DecodeByte(guidString[26], guidString[27], ref invalidIfNegative); span[12] = DecodeByte(guidString[28], guidString[29], ref invalidIfNegative); span[13] = DecodeByte(guidString[30], guidString[31], ref invalidIfNegative); span[14] = DecodeByte(guidString[32], guidString[33], ref invalidIfNegative); span[15] = DecodeByte(guidString[34], guidString[35], ref invalidIfNegative); if (invalidIfNegative >= 0) { if (!BitConverter.IsLittleEndian) { } return true; } if (guidString.IndexOfAny('X', 'x', '+') != -1 && TryCompatParsing(guidString, ref result)) { return true; } result.SetFailure(overflow: false, "Format_GuidInvalidChar"); return false; static bool TryCompatParsing(ReadOnlySpan guidString, ref GuidResult result) { if (TryParseHex(guidString.Slice(0, 8), out result._a) && TryParseHex(guidString.Slice(9, 4), out var result2)) { result._b = (ushort)result2; if (TryParseHex(guidString.Slice(14, 4), out result2)) { result._c = (ushort)result2; if (TryParseHex(guidString.Slice(19, 4), out result2)) { if (!BitConverter.IsLittleEndian) { } result._de = BinaryPrimitives.ReverseEndianness((ushort)result2); if (TryParseHex(guidString.Slice(24, 4), out result2)) { if (!BitConverter.IsLittleEndian) { } result._fg = BinaryPrimitives.ReverseEndianness((ushort)result2); if (Number.TryParseUInt32HexNumberStyle(guidString.Slice(28, 8), NumberStyles.AllowHexSpecifier, out result2) == Number.ParsingStatus.OK) { if (!BitConverter.IsLittleEndian) { } result._hijk = BinaryPrimitives.ReverseEndianness(result2); return true; } } } } } return false; } } private static bool TryParseExactN(ReadOnlySpan guidString, ref GuidResult result) { if (guidString.Length != 32) { result.SetFailure(overflow: false, "Format_GuidInvLen"); return false; } Span span = MemoryMarshal.AsBytes(new Span(ref result, 1)); int invalidIfNegative = 0; span[0] = DecodeByte(guidString[6], guidString[7], ref invalidIfNegative); span[1] = DecodeByte(guidString[4], guidString[5], ref invalidIfNegative); span[2] = DecodeByte(guidString[2], guidString[3], ref invalidIfNegative); span[3] = DecodeByte(guidString[0], guidString[1], ref invalidIfNegative); span[4] = DecodeByte(guidString[10], guidString[11], ref invalidIfNegative); span[5] = DecodeByte(guidString[8], guidString[9], ref invalidIfNegative); span[6] = DecodeByte(guidString[14], guidString[15], ref invalidIfNegative); span[7] = DecodeByte(guidString[12], guidString[13], ref invalidIfNegative); span[8] = DecodeByte(guidString[16], guidString[17], ref invalidIfNegative); span[9] = DecodeByte(guidString[18], guidString[19], ref invalidIfNegative); span[10] = DecodeByte(guidString[20], guidString[21], ref invalidIfNegative); span[11] = DecodeByte(guidString[22], guidString[23], ref invalidIfNegative); span[12] = DecodeByte(guidString[24], guidString[25], ref invalidIfNegative); span[13] = DecodeByte(guidString[26], guidString[27], ref invalidIfNegative); span[14] = DecodeByte(guidString[28], guidString[29], ref invalidIfNegative); span[15] = DecodeByte(guidString[30], guidString[31], ref invalidIfNegative); if (invalidIfNegative >= 0) { if (!BitConverter.IsLittleEndian) { } return true; } result.SetFailure(overflow: false, "Format_GuidInvalidChar"); return false; } private static bool TryParseExactP(ReadOnlySpan guidString, ref GuidResult result) { if (guidString.Length != 38 || guidString[0] != '(' || guidString[37] != ')') { result.SetFailure(overflow: false, "Format_GuidInvLen"); return false; } return TryParseExactD(guidString.Slice(1, 36), ref result); } private static bool TryParseExactX(ReadOnlySpan guidString, ref GuidResult result) { guidString = EatAllWhitespace(guidString); if (guidString.Length == 0 || guidString[0] != '{') { result.SetFailure(overflow: false, "Format_GuidBrace"); return false; } if (!IsHexPrefix(guidString, 1)) { result.SetFailure(overflow: false, "Format_GuidHexPrefix"); return false; } int num = 3; int num2 = guidString.Slice(num).IndexOf(','); if (num2 <= 0) { result.SetFailure(overflow: false, "Format_GuidComma"); return false; } bool overflow = false; if (!TryParseHex(guidString.Slice(num, num2), out result._a, ref overflow) || overflow) { result.SetFailure(overflow, overflow ? "Overflow_UInt32" : "Format_GuidInvalidChar"); return false; } if (!IsHexPrefix(guidString, num + num2 + 1)) { result.SetFailure(overflow: false, "Format_GuidHexPrefix"); return false; } num = num + num2 + 3; num2 = guidString.Slice(num).IndexOf(','); if (num2 <= 0) { result.SetFailure(overflow: false, "Format_GuidComma"); return false; } if (!TryParseHex(guidString.Slice(num, num2), out result._b, ref overflow) || overflow) { result.SetFailure(overflow, overflow ? "Overflow_UInt32" : "Format_GuidInvalidChar"); return false; } if (!IsHexPrefix(guidString, num + num2 + 1)) { result.SetFailure(overflow: false, "Format_GuidHexPrefix"); return false; } num = num + num2 + 3; num2 = guidString.Slice(num).IndexOf(','); if (num2 <= 0) { result.SetFailure(overflow: false, "Format_GuidComma"); return false; } if (!TryParseHex(guidString.Slice(num, num2), out result._c, ref overflow) || overflow) { result.SetFailure(overflow, overflow ? "Overflow_UInt32" : "Format_GuidInvalidChar"); return false; } if ((uint)guidString.Length <= (uint)(num + num2 + 1) || guidString[num + num2 + 1] != '{') { result.SetFailure(overflow: false, "Format_GuidBrace"); return false; } num2++; for (int i = 0; i < 8; i++) { if (!IsHexPrefix(guidString, num + num2 + 1)) { result.SetFailure(overflow: false, "Format_GuidHexPrefix"); return false; } num = num + num2 + 3; if (i < 7) { num2 = guidString.Slice(num).IndexOf(','); if (num2 <= 0) { result.SetFailure(overflow: false, "Format_GuidComma"); return false; } } else { num2 = guidString.Slice(num).IndexOf('}'); if (num2 <= 0) { result.SetFailure(overflow: false, "Format_GuidBraceAfterLastNumber"); return false; } } if (!TryParseHex(guidString.Slice(num, num2), out uint result2, ref overflow) || overflow || result2 > 255) { result.SetFailure(overflow, overflow ? "Overflow_UInt32" : ((result2 > 255) ? "Overflow_Byte" : "Format_GuidInvalidChar")); return false; } Unsafe.Add(ref result._d, i) = (byte)result2; } if (num + num2 + 1 >= guidString.Length || guidString[num + num2 + 1] != '}') { result.SetFailure(overflow: false, "Format_GuidEndBrace"); return false; } if (num + num2 + 1 != guidString.Length - 1) { result.SetFailure(overflow: false, "Format_ExtraJunkAtEnd"); return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static byte DecodeByte(nuint ch1, nuint ch2, ref int invalidIfNegative) { ReadOnlySpan charToHexLookup = HexConverter.CharToHexLookup; int num = -1; if (ch1 < (nuint)charToHexLookup.Length) { num = (sbyte)Unsafe.Add(ref MemoryMarshal.GetReference(charToHexLookup), (nint)ch1); } num <<= 4; int num2 = -1; if (ch2 < (nuint)charToHexLookup.Length) { num2 = (sbyte)Unsafe.Add(ref MemoryMarshal.GetReference(charToHexLookup), (nint)ch2); } int num3 = num | num2; invalidIfNegative |= num3; return (byte)num3; } private static bool TryParseHex(ReadOnlySpan guidString, out ushort result, ref bool overflow) { uint result2; bool result3 = TryParseHex(guidString, out result2, ref overflow); result = (ushort)result2; return result3; } private static bool TryParseHex(ReadOnlySpan guidString, out uint result) { bool overflow = false; return TryParseHex(guidString, out result, ref overflow); } private static bool TryParseHex(ReadOnlySpan guidString, out uint result, ref bool overflow) { if (guidString.Length != 0) { if (guidString[0] == '+') { guidString = guidString.Slice(1); } if ((uint)guidString.Length > 1u && guidString[0] == '0' && (guidString[1] | 0x20) == 120) { guidString = guidString.Slice(2); } } int i; for (i = 0; i < guidString.Length && guidString[i] == '0'; i++) { } int num = 0; uint num2 = 0u; for (; i < guidString.Length; i++) { char c = guidString[i]; int num3 = HexConverter.FromChar(c); if (num3 == 255) { if (num > 8) { overflow = true; } result = 0u; return false; } num2 = num2 * 16 + (uint)num3; num++; } if (num > 8) { overflow = true; } result = num2; return true; } private static ReadOnlySpan EatAllWhitespace(ReadOnlySpan str) { int i; for (i = 0; i < str.Length && !char.IsWhiteSpace(str[i]); i++) { } if (i == str.Length) { return str; } char[] array = new char[str.Length]; int length = 0; if (i > 0) { length = i; str.Slice(0, i).CopyTo(array); } for (; i < str.Length; i++) { char c = str[i]; if (!char.IsWhiteSpace(c)) { array[length++] = c; } } return new ReadOnlySpan(array, 0, length); } private static bool IsHexPrefix(ReadOnlySpan str, int i) { if (i + 1 < str.Length && str[i] == '0') { return (str[i + 1] | 0x20) == 120; } return false; } public byte[] ToByteArray() { byte[] array = new byte[16]; _ = BitConverter.IsLittleEndian; MemoryMarshal.TryWrite(array, ref Unsafe.AsRef(in this)); return array; } public bool TryWriteBytes(Span destination) { _ = BitConverter.IsLittleEndian; return MemoryMarshal.TryWrite(destination, ref Unsafe.AsRef(in this)); } public override string ToString() { return ToString("D", null); } public override int GetHashCode() { ref int reference = ref Unsafe.AsRef(in _a); return reference ^ Unsafe.Add(ref reference, 1) ^ Unsafe.Add(ref reference, 2) ^ Unsafe.Add(ref reference, 3); } public override bool Equals([NotNullWhen(true)] object? o) { if (o is Guid right) { return EqualsCore(in this, in right); } return false; } public bool Equals(Guid g) { return EqualsCore(in this, in g); } private static bool EqualsCore(in Guid left, in Guid right) { ref int reference = ref Unsafe.AsRef(in left._a); ref int reference2 = ref Unsafe.AsRef(in right._a); if (reference == reference2 && Unsafe.Add(ref reference, 1) == Unsafe.Add(ref reference2, 1) && Unsafe.Add(ref reference, 2) == Unsafe.Add(ref reference2, 2)) { return Unsafe.Add(ref reference, 3) == Unsafe.Add(ref reference2, 3); } return false; } private static int GetResult(uint me, uint them) { if (me >= them) { return 1; } return -1; } public int CompareTo(object? value) { if (value == null) { return 1; } if (!(value is Guid guid)) { throw new ArgumentException(SR.Arg_MustBeGuid, "value"); } if (guid._a != _a) { return GetResult((uint)_a, (uint)guid._a); } if (guid._b != _b) { return GetResult((uint)_b, (uint)guid._b); } if (guid._c != _c) { return GetResult((uint)_c, (uint)guid._c); } if (guid._d != _d) { return GetResult(_d, guid._d); } if (guid._e != _e) { return GetResult(_e, guid._e); } if (guid._f != _f) { return GetResult(_f, guid._f); } if (guid._g != _g) { return GetResult(_g, guid._g); } if (guid._h != _h) { return GetResult(_h, guid._h); } if (guid._i != _i) { return GetResult(_i, guid._i); } if (guid._j != _j) { return GetResult(_j, guid._j); } if (guid._k != _k) { return GetResult(_k, guid._k); } return 0; } public int CompareTo(Guid value) { if (value._a != _a) { return GetResult((uint)_a, (uint)value._a); } if (value._b != _b) { return GetResult((uint)_b, (uint)value._b); } if (value._c != _c) { return GetResult((uint)_c, (uint)value._c); } if (value._d != _d) { return GetResult(_d, value._d); } if (value._e != _e) { return GetResult(_e, value._e); } if (value._f != _f) { return GetResult(_f, value._f); } if (value._g != _g) { return GetResult(_g, value._g); } if (value._h != _h) { return GetResult(_h, value._h); } if (value._i != _i) { return GetResult(_i, value._i); } if (value._j != _j) { return GetResult(_j, value._j); } if (value._k != _k) { return GetResult(_k, value._k); } return 0; } public static bool operator ==(Guid a, Guid b) { return EqualsCore(in a, in b); } public static bool operator !=(Guid a, Guid b) { return !EqualsCore(in a, in b); } public string ToString(string? format) { return ToString(format, null); } private unsafe static int HexsToChars(char* guidChars, int a, int b) { *guidChars = HexConverter.ToCharLower(a >> 4); guidChars[1] = HexConverter.ToCharLower(a); guidChars[2] = HexConverter.ToCharLower(b >> 4); guidChars[3] = HexConverter.ToCharLower(b); return 4; } private unsafe static int HexsToCharsHexOutput(char* guidChars, int a, int b) { *guidChars = '0'; guidChars[1] = 'x'; guidChars[2] = HexConverter.ToCharLower(a >> 4); guidChars[3] = HexConverter.ToCharLower(a); guidChars[4] = ','; guidChars[5] = '0'; guidChars[6] = 'x'; guidChars[7] = HexConverter.ToCharLower(b >> 4); guidChars[8] = HexConverter.ToCharLower(b); return 9; } public string ToString(string? format, IFormatProvider? provider) { if (string.IsNullOrEmpty(format)) { format = "D"; } if (format.Length != 1) { throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } int length; switch (format[0]) { case 'D': case 'd': length = 36; break; case 'N': case 'n': length = 32; break; case 'B': case 'P': case 'b': case 'p': length = 38; break; case 'X': case 'x': length = 68; break; default: throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } string text = string.FastAllocateString(length); int charsWritten; bool flag = TryFormat(new Span(ref text.GetRawStringData(), text.Length), out charsWritten, format); return text; } public unsafe bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan)) { if (format.Length == 0) { format = "D"; } if (format.Length != 1) { throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } bool flag = true; bool flag2 = false; int num = 0; int num2; switch (format[0]) { case 'D': case 'd': num2 = 36; break; case 'N': case 'n': flag = false; num2 = 32; break; case 'B': case 'b': num = 8192123; num2 = 38; break; case 'P': case 'p': num = 2687016; num2 = 38; break; case 'X': case 'x': num = 8192123; flag = false; flag2 = true; num2 = 68; break; default: throw new FormatException(SR.Format_InvalidGuidFormatSpecification); } if (destination.Length < num2) { charsWritten = 0; return false; } fixed (char* ptr = &MemoryMarshal.GetReference(destination)) { char* ptr2 = ptr; if (num != 0) { *(ptr2++) = (char)num; } if (flag2) { *(ptr2++) = '0'; *(ptr2++) = 'x'; ptr2 += HexsToChars(ptr2, _a >> 24, _a >> 16); ptr2 += HexsToChars(ptr2, _a >> 8, _a); *(ptr2++) = ','; *(ptr2++) = '0'; *(ptr2++) = 'x'; ptr2 += HexsToChars(ptr2, _b >> 8, _b); *(ptr2++) = ','; *(ptr2++) = '0'; *(ptr2++) = 'x'; ptr2 += HexsToChars(ptr2, _c >> 8, _c); *(ptr2++) = ','; *(ptr2++) = '{'; ptr2 += HexsToCharsHexOutput(ptr2, _d, _e); *(ptr2++) = ','; ptr2 += HexsToCharsHexOutput(ptr2, _f, _g); *(ptr2++) = ','; ptr2 += HexsToCharsHexOutput(ptr2, _h, _i); *(ptr2++) = ','; ptr2 += HexsToCharsHexOutput(ptr2, _j, _k); *(ptr2++) = '}'; } else { ptr2 += HexsToChars(ptr2, _a >> 24, _a >> 16); ptr2 += HexsToChars(ptr2, _a >> 8, _a); if (flag) { *(ptr2++) = '-'; } ptr2 += HexsToChars(ptr2, _b >> 8, _b); if (flag) { *(ptr2++) = '-'; } ptr2 += HexsToChars(ptr2, _c >> 8, _c); if (flag) { *(ptr2++) = '-'; } ptr2 += HexsToChars(ptr2, _d, _e); if (flag) { *(ptr2++) = '-'; } ptr2 += HexsToChars(ptr2, _f, _g); ptr2 += HexsToChars(ptr2, _h, _i); ptr2 += HexsToChars(ptr2, _j, _k); } if (num != 0) { *(ptr2++) = (char)(num >> 16); } } charsWritten = num2; return true; } bool ISpanFormattable.TryFormat(Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider provider) { return TryFormat(destination, out charsWritten, format); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(Guid left, Guid right) { if (left._a != right._a) { return (uint)left._a < (uint)right._a; } if (left._b != right._b) { return (uint)left._b < (uint)right._b; } if (left._c != right._c) { return (uint)left._c < (uint)right._c; } if (left._d != right._d) { return left._d < right._d; } if (left._e != right._e) { return left._e < right._e; } if (left._f != right._f) { return left._f < right._f; } if (left._g != right._g) { return left._g < right._g; } if (left._h != right._h) { return left._h < right._h; } if (left._i != right._i) { return left._i < right._i; } if (left._j != right._j) { return left._j < right._j; } if (left._k != right._k) { return left._k < right._k; } return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(Guid left, Guid right) { if (left._a != right._a) { return (uint)left._a < (uint)right._a; } if (left._b != right._b) { return (uint)left._b < (uint)right._b; } if (left._c != right._c) { return (uint)left._c < (uint)right._c; } if (left._d != right._d) { return left._d < right._d; } if (left._e != right._e) { return left._e < right._e; } if (left._f != right._f) { return left._f < right._f; } if (left._g != right._g) { return left._g < right._g; } if (left._h != right._h) { return left._h < right._h; } if (left._i != right._i) { return left._i < right._i; } if (left._j != right._j) { return left._j < right._j; } if (left._k != right._k) { return left._k < right._k; } return true; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(Guid left, Guid right) { if (left._a != right._a) { return (uint)left._a > (uint)right._a; } if (left._b != right._b) { return (uint)left._b > (uint)right._b; } if (left._c != right._c) { return (uint)left._c > (uint)right._c; } if (left._d != right._d) { return left._d > right._d; } if (left._e != right._e) { return left._e > right._e; } if (left._f != right._f) { return left._f > right._f; } if (left._g != right._g) { return left._g > right._g; } if (left._h != right._h) { return left._h > right._h; } if (left._i != right._i) { return left._i > right._i; } if (left._j != right._j) { return left._j > right._j; } if (left._k != right._k) { return left._k > right._k; } return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(Guid left, Guid right) { if (left._a != right._a) { return (uint)left._a > (uint)right._a; } if (left._b != right._b) { return (uint)left._b > (uint)right._b; } if (left._c != right._c) { return (uint)left._c > (uint)right._c; } if (left._d != right._d) { return left._d > right._d; } if (left._e != right._e) { return left._e > right._e; } if (left._f != right._f) { return left._f > right._f; } if (left._g != right._g) { return left._g > right._g; } if (left._h != right._h) { return left._h > right._h; } if (left._i != right._i) { return left._i > right._i; } if (left._j != right._j) { return left._j > right._j; } if (left._k != right._k) { return left._k > right._k; } return true; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(Guid left, Guid right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(Guid left, Guid right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Guid IParseable.Parse(string s, IFormatProvider provider) { return Parse(s); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out Guid result) { return TryParse(s, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Guid ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out Guid result) { return TryParse(s, out result); } public static Guid NewGuid() { Guid guid; int num = Interop.Ole32.CoCreateGuid(out guid); if (num != 0) { Exception ex = new Exception(); ex.HResult = num; throw ex; } return guid; } } public readonly struct Half : IComparable, ISpanFormattable, IFormattable, IComparable, IEquatable, IBinaryFloatingPoint, IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IFloatingPoint, ISignedNumber, IMinMaxValue { private static readonly Half PositiveZero = new Half(0); private static readonly Half NegativeZero = new Half(32768); private readonly ushort _value; public static Half Epsilon => new Half(1); public static Half PositiveInfinity => new Half(31744); public static Half NegativeInfinity => new Half(64512); public static Half NaN => new Half(65024); public static Half MinValue => new Half(64511); public static Half MaxValue => new Half(31743); private sbyte Exponent => (sbyte)((_value & 0x7C00) >> 10); private ushort Significand => (ushort)(_value & 0x3FFu); [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IAdditiveIdentity.AdditiveIdentity => PositiveZero; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.E => (Half)(float)Math.E; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Epsilon => Epsilon; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.NaN => NaN; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.NegativeInfinity => NegativeInfinity; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.NegativeZero => NegativeZero; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Pi => (Half)(float)Math.PI; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.PositiveInfinity => PositiveInfinity; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Tau => (Half)((float)Math.PI * 2f); [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IMinMaxValue.MinValue => MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IMinMaxValue.MaxValue => MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IMultiplicativeIdentity.MultiplicativeIdentity => (Half)1f; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half INumber.One => (Half)1f; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half INumber.Zero => PositiveZero; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half ISignedNumber.NegativeOne => (Half)(-1f); internal Half(ushort value) { _value = value; } private Half(bool sign, ushort exp, ushort sig) { _value = (ushort)(((sign ? 1 : 0) << 15) + (exp << 10) + sig); } public static bool operator <(Half left, Half right) { if (IsNaN(left) || IsNaN(right)) { return false; } bool flag = IsNegative(left); if (flag != IsNegative(right)) { if (flag) { return !AreZero(left, right); } return false; } if (left._value != right._value) { return (left._value < right._value) ^ flag; } return false; } public static bool operator >(Half left, Half right) { return right < left; } public static bool operator <=(Half left, Half right) { if (IsNaN(left) || IsNaN(right)) { return false; } bool flag = IsNegative(left); if (flag != IsNegative(right)) { if (!flag) { return AreZero(left, right); } return true; } if (left._value != right._value) { return (left._value < right._value) ^ flag; } return true; } public static bool operator >=(Half left, Half right) { return right <= left; } public static bool operator ==(Half left, Half right) { if (IsNaN(left) || IsNaN(right)) { return false; } if (left._value != right._value) { return AreZero(left, right); } return true; } public static bool operator !=(Half left, Half right) { return !(left == right); } public static bool IsFinite(Half value) { return StripSign(value) < 31744; } public static bool IsInfinity(Half value) { return StripSign(value) == 31744; } public static bool IsNaN(Half value) { return StripSign(value) > 31744; } public static bool IsNegative(Half value) { return (short)value._value < 0; } public static bool IsNegativeInfinity(Half value) { return value._value == 64512; } public static bool IsNormal(Half value) { uint num = StripSign(value); if (num < 31744 && num != 0) { return (num & 0x7C00) != 0; } return false; } public static bool IsPositiveInfinity(Half value) { return value._value == 31744; } public static bool IsSubnormal(Half value) { uint num = StripSign(value); if (num < 31744 && num != 0) { return (num & 0x7C00) == 0; } return false; } public static Half Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseHalf(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } public static Half Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseHalf(s, style, NumberFormatInfo.CurrentInfo); } public static Half Parse(string s, IFormatProvider? provider) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseHalf(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } public static Half Parse(string s, NumberStyles style = NumberStyles.Float | NumberStyles.AllowThousands, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseHalf(s, style, NumberFormatInfo.GetInstance(provider)); } public static Half Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Float | NumberStyles.AllowThousands, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.ParseHalf(s, style, NumberFormatInfo.GetInstance(provider)); } public static bool TryParse([NotNullWhen(true)] string? s, out Half result) { if (s == null) { result = default(Half); return false; } return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, null, out result); } public static bool TryParse(ReadOnlySpan s, out Half result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, null, out result); } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out Half result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { result = default(Half); return false; } return TryParse(s.AsSpan(), style, provider, out result); } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out Half result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.TryParseHalf(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool AreZero(Half left, Half right) { return (ushort)((left._value | right._value) & -32769) == 0; } private static bool IsNaNOrZero(Half value) { return ((value._value - 1) & -32769) >= 31744; } private static uint StripSign(Half value) { return (ushort)(value._value & 0xFFFF7FFFu); } public int CompareTo(object? obj) { if (!(obj is Half)) { if (obj != null) { throw new ArgumentException(SR.Arg_MustBeHalf); } return 1; } return CompareTo((Half)obj); } public int CompareTo(Half other) { if (this < other) { return -1; } if (this > other) { return 1; } if (this == other) { return 0; } if (IsNaN(this)) { if (!IsNaN(other)) { return -1; } return 0; } return 1; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is Half other) { return Equals(other); } return false; } public bool Equals(Half other) { if (_value != other._value && !AreZero(this, other)) { if (IsNaN(this)) { return IsNaN(other); } return false; } return true; } public override int GetHashCode() { if (IsNaNOrZero(this)) { return _value & 0x7C00; } return _value; } public override string ToString() { return Number.FormatHalf(this, null, NumberFormatInfo.CurrentInfo); } public string ToString(string? format) { return Number.FormatHalf(this, format, NumberFormatInfo.CurrentInfo); } public string ToString(IFormatProvider? provider) { return Number.FormatHalf(this, null, NumberFormatInfo.GetInstance(provider)); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatHalf(this, format, NumberFormatInfo.GetInstance(provider)); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return Number.TryFormatHalf(this, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten); } public static explicit operator Half(float value) { uint num = BitConverter.SingleToUInt32Bits(value); bool flag = (num & 0x80000000u) >> 31 != 0; int num2 = (int)(num & 0x7F800000) >> 23; uint num3 = num & 0x7FFFFFu; if (num2 == 255) { if (num3 != 0) { return CreateHalfNaN(flag, (ulong)num3 << 41); } if (!flag) { return PositiveInfinity; } return NegativeInfinity; } uint num4 = (num3 >> 9) | (((num3 & 0x1FFu) != 0) ? 1u : 0u); if (((uint)num2 | num4) == 0) { return new Half(flag, 0, 0); } return new Half(RoundPackToHalf(flag, (short)(num2 - 113), (ushort)(num4 | 0x4000u))); } public static explicit operator Half(double value) { ulong num = BitConverter.DoubleToUInt64Bits(value); bool flag = (num & 0x8000000000000000uL) >> 63 != 0; int num2 = (int)((num & 0x7FF0000000000000L) >> 52); ulong num3 = num & 0xFFFFFFFFFFFFFuL; if (num2 == 2047) { if (num3 != 0L) { return CreateHalfNaN(flag, num3 << 12); } if (!flag) { return PositiveInfinity; } return NegativeInfinity; } uint num4 = (uint)ShiftRightJam(num3, 38); if (((uint)num2 | num4) == 0) { return new Half(flag, 0, 0); } return new Half(RoundPackToHalf(flag, (short)(num2 - 1009), (ushort)(num4 | 0x4000u))); } public static explicit operator float(Half value) { bool flag = IsNegative(value); int num = value.Exponent; uint num2 = value.Significand; switch (num) { case 31: if (num2 != 0) { return CreateSingleNaN(flag, (ulong)num2 << 54); } if (!flag) { return float.PositiveInfinity; } return float.NegativeInfinity; case 0: { if (num2 == 0) { return BitConverter.UInt32BitsToSingle(flag ? 2147483648u : 0u); } (int Exp, uint Sig) tuple = NormSubnormalF16Sig(num2); num = tuple.Exp; num2 = tuple.Sig; num--; break; } } return CreateSingle(flag, (byte)(num + 112), num2 << 13); } public static explicit operator double(Half value) { bool flag = IsNegative(value); int num = value.Exponent; uint num2 = value.Significand; switch (num) { case 31: if (num2 != 0) { return CreateDoubleNaN(flag, (ulong)num2 << 54); } if (!flag) { return double.PositiveInfinity; } return double.NegativeInfinity; case 0: { if (num2 == 0) { return BitConverter.UInt64BitsToDouble(flag ? 9223372036854775808uL : 0); } (int Exp, uint Sig) tuple = NormSubnormalF16Sig(num2); num = tuple.Exp; num2 = tuple.Sig; num--; break; } } return CreateDouble(flag, (ushort)(num + 1008), (ulong)num2 << 42); } internal static Half Negate(Half value) { if (!IsNaN(value)) { return new Half((ushort)(value._value ^ 0x8000u)); } return value; } private static (int Exp, uint Sig) NormSubnormalF16Sig(uint sig) { int num = BitOperations.LeadingZeroCount(sig) - 16 - 5; return (1 - num, sig << num); } private static Half CreateHalfNaN(bool sign, ulong significand) { uint num = (uint)((sign ? 1 : 0) << 15); uint num2 = (uint)(significand >> 54); return BitConverter.UInt16BitsToHalf((ushort)(num | 0x7E00u | num2)); } private static ushort RoundPackToHalf(bool sign, short exp, ushort sig) { int num = sig & 0xF; if ((uint)exp >= 29u) { if (exp < 0) { sig = (ushort)ShiftRightJam(sig, -exp); exp = 0; num = sig & 0xF; } else if (exp > 29 || sig + 8 >= 32768) { if (!sign) { return 31744; } return 64512; } } sig = (ushort)(sig + 8 >> 4); sig &= (ushort)(~((((num ^ 8) == 0) ? 1 : 0) & 1)); if (sig == 0) { exp = 0; } return new Half(sign, (ushort)exp, sig)._value; } private static uint ShiftRightJam(uint i, int dist) { if (dist >= 31) { if (i == 0) { return 0u; } return 1u; } return (i >> dist) | ((i << -dist != 0) ? 1u : 0u); } private static ulong ShiftRightJam(ulong l, int dist) { if (dist >= 63) { if (l == 0L) { return 0uL; } return 1uL; } return (l >> dist) | (ulong)((l << -dist != 0L) ? 1 : 0); } private static float CreateSingleNaN(bool sign, ulong significand) { uint num = (uint)((sign ? 1 : 0) << 31); uint num2 = (uint)(significand >> 41); return BitConverter.UInt32BitsToSingle(num | 0x7FC00000u | num2); } private static double CreateDoubleNaN(bool sign, ulong significand) { ulong num = (ulong)((long)(sign ? 1 : 0) << 63); ulong num2 = significand >> 12; return BitConverter.UInt64BitsToDouble(num | 0x7FF8000000000000uL | num2); } private static float CreateSingle(bool sign, byte exp, uint sig) { return BitConverter.UInt32BitsToSingle((uint)(((sign ? 1 : 0) << 31) + (exp << 23)) + sig); } private static double CreateDouble(bool sign, ushort exp, ulong sig) { return BitConverter.UInt64BitsToDouble((ulong)(((long)(sign ? 1 : 0) << 63) + (long)((ulong)exp << 52)) + sig); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IAdditionOperators.op_Addition(Half left, Half right) { return (Half)((float)left + (float)right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IBinaryNumber.IsPow2(Half value) { uint num = BitConverter.HalfToUInt16Bits(value); uint num2 = (num >> 10) & 0x1Fu; uint num3 = num & 0x3FFu; if (value > PositiveZero && num2 != 0 && num2 != 31) { return num3 == 0; } return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IBinaryNumber.Log2(Half value) { return (Half)MathF.Log2((float)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IBitwiseOperators.op_BitwiseAnd(Half left, Half right) { ushort value = (ushort)(BitConverter.HalfToUInt16Bits(left) & BitConverter.HalfToUInt16Bits(right)); return BitConverter.UInt16BitsToHalf(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IBitwiseOperators.op_BitwiseOr(Half left, Half right) { ushort value = (ushort)(BitConverter.HalfToUInt16Bits(left) | BitConverter.HalfToUInt16Bits(right)); return BitConverter.UInt16BitsToHalf(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IBitwiseOperators.op_ExclusiveOr(Half left, Half right) { ushort value = (ushort)(BitConverter.HalfToUInt16Bits(left) ^ BitConverter.HalfToUInt16Bits(right)); return BitConverter.UInt16BitsToHalf(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IBitwiseOperators.op_OnesComplement(Half value) { ushort value2 = (ushort)(~BitConverter.HalfToUInt16Bits(value)); return BitConverter.UInt16BitsToHalf(value2); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(Half left, Half right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(Half left, Half right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(Half left, Half right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(Half left, Half right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IDecrementOperators.op_Decrement(Half value) { float num = (float)value; num -= 1f; return (Half)num; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(Half left, Half right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(Half left, Half right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IDivisionOperators.op_Division(Half left, Half right) { return (Half)((float)left / (float)right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Acos(Half x) { return (Half)MathF.Acos((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Acosh(Half x) { return (Half)MathF.Acosh((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Asin(Half x) { return (Half)MathF.Asin((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Asinh(Half x) { return (Half)MathF.Asinh((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Atan(Half x) { return (Half)MathF.Atan((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Atan2(Half y, Half x) { return (Half)MathF.Atan2((float)y, (float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Atanh(Half x) { return (Half)MathF.Atanh((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.BitIncrement(Half x) { ushort num = BitConverter.HalfToUInt16Bits(x); if ((num & 0x7C00) >= 31744) { if (num != 64512) { return x; } return MinValue; } if (num == 32768) { return Epsilon; } num += (ushort)((num >= 0) ? 1 : (-1)); return BitConverter.UInt16BitsToHalf(num); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.BitDecrement(Half x) { ushort num = BitConverter.HalfToUInt16Bits(x); if ((num & 0x7C00) >= 31744) { if (num != 31744) { return x; } return MaxValue; } if (num == 0) { return new Half(32769); } num += (ushort)((num < 0) ? 1 : (-1)); return BitConverter.UInt16BitsToHalf(num); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Cbrt(Half x) { return (Half)MathF.Cbrt((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Ceiling(Half x) { return (Half)MathF.Ceiling((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.CopySign(Half x, Half y) { return (Half)MathF.CopySign((float)x, (float)y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Cos(Half x) { return (Half)MathF.Cos((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Cosh(Half x) { return (Half)MathF.Cosh((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Exp(Half x) { return (Half)MathF.Exp((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Floor(Half x) { return (Half)MathF.Floor((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.FusedMultiplyAdd(Half left, Half right, Half addend) { return (Half)MathF.FusedMultiplyAdd((float)left, (float)right, (float)addend); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.IEEERemainder(Half left, Half right) { return (Half)MathF.IEEERemainder((float)left, (float)right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TInteger IFloatingPoint.ILogB(Half x) { return TInteger.Create(MathF.ILogB((float)x)); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Log(Half x) { return (Half)MathF.Log((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Log(Half x, Half newBase) { return (Half)MathF.Log((float)x, (float)newBase); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Log2(Half x) { return (Half)MathF.Log2((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Log10(Half x) { return (Half)MathF.Log10((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.MaxMagnitude(Half x, Half y) { return (Half)MathF.MaxMagnitude((float)x, (float)y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.MinMagnitude(Half x, Half y) { return (Half)MathF.MinMagnitude((float)x, (float)y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Pow(Half x, Half y) { return (Half)MathF.Pow((float)x, (float)y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Round(Half x) { return (Half)MathF.Round((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Round(Half x, TInteger digits) { return (Half)MathF.Round((float)x, int.Create(digits)); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Round(Half x, MidpointRounding mode) { return (Half)MathF.Round((float)x, mode); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Round(Half x, TInteger digits, MidpointRounding mode) { return (Half)MathF.Round((float)x, int.Create(digits), mode); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.ScaleB(Half x, TInteger n) { return (Half)MathF.ScaleB((float)x, int.Create(n)); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Sin(Half x) { return (Half)MathF.Sin((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Sinh(Half x) { return (Half)MathF.Sinh((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Sqrt(Half x) { return (Half)MathF.Sqrt((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Tan(Half x) { return (Half)MathF.Tan((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Tanh(Half x) { return (Half)MathF.Tanh((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IFloatingPoint.Truncate(Half x) { return (Half)MathF.Truncate((float)x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsFinite(Half x) { return IsFinite(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsInfinity(Half x) { return IsInfinity(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsNaN(Half x) { return IsNaN(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsNegative(Half x) { return IsNegative(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsNegativeInfinity(Half x) { return IsNegativeInfinity(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsNormal(Half x) { return IsNormal(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsPositiveInfinity(Half x) { return IsPositiveInfinity(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsSubnormal(Half x) { return IsSubnormal(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IIncrementOperators.op_Increment(Half value) { float num = (float)value; num += 1f; return (Half)num; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IModulusOperators.op_Modulus(Half left, Half right) { return (Half)((float)left % (float)right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IMultiplyOperators.op_Multiply(Half left, Half right) { return (Half)((float)left * (float)right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half INumber.Abs(Half value) { return (Half)MathF.Abs((float)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half INumber.Clamp(Half value, Half min, Half max) { return (Half)Math.Clamp((float)value, (float)min, (float)max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half INumber.Create(TOther value) { if (typeof(TOther) == typeof(byte)) { return (Half)(int)(byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (Half)(int)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (Half)(float)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (Half)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (Half)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (Half)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (Half)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (Half)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (Half)(sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (Half)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (Half)(int)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (Half)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (Half)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (Half)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return default(Half); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (Half)(int)(byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (Half)(int)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (Half)(float)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (Half)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (Half)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (Half)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (Half)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (Half)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (Half)(sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (Half)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (Half)(int)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (Half)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (Half)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (Half)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return default(Half); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (Half)(int)(byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (Half)(int)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (Half)(float)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (Half)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (Half)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (Half)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (Half)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (Half)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (Half)(sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (Half)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (Half)(int)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (Half)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (Half)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (Half)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return default(Half); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (Half Quotient, Half Remainder) INumber.DivRem(Half left, Half right) { return ((Half)((float)left / (float)right), (Half)((float)left % (float)right)); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half INumber.Max(Half x, Half y) { return (Half)MathF.Max((float)x, (float)y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half INumber.Min(Half x, Half y) { return (Half)MathF.Min((float)x, (float)y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half INumber.Sign(Half value) { return (Half)MathF.Sign((float)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out Half result) { if (typeof(TOther) == typeof(byte)) { result = (Half)(int)(byte)(object)value; return true; } if (typeof(TOther) == typeof(char)) { result = (Half)(int)(char)(object)value; return true; } if (typeof(TOther) == typeof(decimal)) { result = (Half)(float)(decimal)(object)value; return true; } if (typeof(TOther) == typeof(double)) { result = (Half)(double)(object)value; return true; } if (typeof(TOther) == typeof(short)) { result = (Half)(short)(object)value; return true; } if (typeof(TOther) == typeof(int)) { result = (Half)(int)(object)value; return true; } if (typeof(TOther) == typeof(long)) { result = (Half)(long)(object)value; return true; } if (typeof(TOther) == typeof(IntPtr)) { result = (Half)(nint)(IntPtr)(object)value; return true; } if (typeof(TOther) == typeof(sbyte)) { result = (Half)(sbyte)(object)value; return true; } if (typeof(TOther) == typeof(float)) { result = (Half)(float)(object)value; return true; } if (typeof(TOther) == typeof(ushort)) { result = (Half)(int)(ushort)(object)value; return true; } if (typeof(TOther) == typeof(uint)) { result = (Half)(uint)(object)value; return true; } if (typeof(TOther) == typeof(ulong)) { result = (Half)(ulong)(object)value; return true; } if (typeof(TOther) == typeof(UIntPtr)) { result = (Half)(nuint)(UIntPtr)(object)value; return true; } ThrowHelper.ThrowNotSupportedException(); result = default(Half); return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out Half result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out Half result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out Half result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out Half result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half ISubtractionOperators.op_Subtraction(Half left, Half right) { return (Half)((float)left - (float)right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IUnaryNegationOperators.op_UnaryNegation(Half value) { return (Half)(0f - (float)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static Half IUnaryPlusOperators.op_UnaryPlus(Half value) { return value; } } public struct HashCode { private static readonly uint s_seed = GenerateGlobalSeed(); private uint _v1; private uint _v2; private uint _v3; private uint _v4; private uint _queue1; private uint _queue2; private uint _queue3; private uint _length; private unsafe static uint GenerateGlobalSeed() { System.Runtime.CompilerServices.Unsafe.SkipInit(out uint result); Interop.GetRandomBytes((byte*)(&result), 4); return result; } public static int Combine(T1 value1) { uint queuedValue = (uint)(value1?.GetHashCode() ?? 0); uint num = MixEmptyState(); num += 4; num = QueueRound(num, queuedValue); return (int)MixFinal(num); } public static int Combine(T1 value1, T2 value2) { uint queuedValue = (uint)(value1?.GetHashCode() ?? 0); uint queuedValue2 = (uint)(value2?.GetHashCode() ?? 0); uint num = MixEmptyState(); num += 8; num = QueueRound(num, queuedValue); num = QueueRound(num, queuedValue2); return (int)MixFinal(num); } public static int Combine(T1 value1, T2 value2, T3 value3) { uint queuedValue = (uint)(value1?.GetHashCode() ?? 0); uint queuedValue2 = (uint)(value2?.GetHashCode() ?? 0); uint queuedValue3 = (uint)(value3?.GetHashCode() ?? 0); uint num = MixEmptyState(); num += 12; num = QueueRound(num, queuedValue); num = QueueRound(num, queuedValue2); num = QueueRound(num, queuedValue3); return (int)MixFinal(num); } public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4) { uint input = (uint)(value1?.GetHashCode() ?? 0); uint input2 = (uint)(value2?.GetHashCode() ?? 0); uint input3 = (uint)(value3?.GetHashCode() ?? 0); uint input4 = (uint)(value4?.GetHashCode() ?? 0); Initialize(out var v, out var v2, out var v3, out var v4); v = Round(v, input); v2 = Round(v2, input2); v3 = Round(v3, input3); v4 = Round(v4, input4); uint num = MixState(v, v2, v3, v4); num += 16; return (int)MixFinal(num); } public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5) { uint input = (uint)(value1?.GetHashCode() ?? 0); uint input2 = (uint)(value2?.GetHashCode() ?? 0); uint input3 = (uint)(value3?.GetHashCode() ?? 0); uint input4 = (uint)(value4?.GetHashCode() ?? 0); uint queuedValue = (uint)(value5?.GetHashCode() ?? 0); Initialize(out var v, out var v2, out var v3, out var v4); v = Round(v, input); v2 = Round(v2, input2); v3 = Round(v3, input3); v4 = Round(v4, input4); uint num = MixState(v, v2, v3, v4); num += 20; num = QueueRound(num, queuedValue); return (int)MixFinal(num); } public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6) { uint input = (uint)(value1?.GetHashCode() ?? 0); uint input2 = (uint)(value2?.GetHashCode() ?? 0); uint input3 = (uint)(value3?.GetHashCode() ?? 0); uint input4 = (uint)(value4?.GetHashCode() ?? 0); uint queuedValue = (uint)(value5?.GetHashCode() ?? 0); uint queuedValue2 = (uint)(value6?.GetHashCode() ?? 0); Initialize(out var v, out var v2, out var v3, out var v4); v = Round(v, input); v2 = Round(v2, input2); v3 = Round(v3, input3); v4 = Round(v4, input4); uint num = MixState(v, v2, v3, v4); num += 24; num = QueueRound(num, queuedValue); num = QueueRound(num, queuedValue2); return (int)MixFinal(num); } public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7) { uint input = (uint)(value1?.GetHashCode() ?? 0); uint input2 = (uint)(value2?.GetHashCode() ?? 0); uint input3 = (uint)(value3?.GetHashCode() ?? 0); uint input4 = (uint)(value4?.GetHashCode() ?? 0); uint queuedValue = (uint)(value5?.GetHashCode() ?? 0); uint queuedValue2 = (uint)(value6?.GetHashCode() ?? 0); uint queuedValue3 = (uint)(value7?.GetHashCode() ?? 0); Initialize(out var v, out var v2, out var v3, out var v4); v = Round(v, input); v2 = Round(v2, input2); v3 = Round(v3, input3); v4 = Round(v4, input4); uint num = MixState(v, v2, v3, v4); num += 28; num = QueueRound(num, queuedValue); num = QueueRound(num, queuedValue2); num = QueueRound(num, queuedValue3); return (int)MixFinal(num); } public static int Combine(T1 value1, T2 value2, T3 value3, T4 value4, T5 value5, T6 value6, T7 value7, T8 value8) { uint input = (uint)(value1?.GetHashCode() ?? 0); uint input2 = (uint)(value2?.GetHashCode() ?? 0); uint input3 = (uint)(value3?.GetHashCode() ?? 0); uint input4 = (uint)(value4?.GetHashCode() ?? 0); uint input5 = (uint)(value5?.GetHashCode() ?? 0); uint input6 = (uint)(value6?.GetHashCode() ?? 0); uint input7 = (uint)(value7?.GetHashCode() ?? 0); uint input8 = (uint)(value8?.GetHashCode() ?? 0); Initialize(out var v, out var v2, out var v3, out var v4); v = Round(v, input); v2 = Round(v2, input2); v3 = Round(v3, input3); v4 = Round(v4, input4); v = Round(v, input5); v2 = Round(v2, input6); v3 = Round(v3, input7); v4 = Round(v4, input8); uint num = MixState(v, v2, v3, v4); num += 32; return (int)MixFinal(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Initialize(out uint v1, out uint v2, out uint v3, out uint v4) { v1 = (uint)((int)s_seed + -1640531535 + -2048144777); v2 = s_seed + 2246822519u; v3 = s_seed; v4 = s_seed - 2654435761u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint Round(uint hash, uint input) { return BitOperations.RotateLeft(hash + (uint)((int)input * -2048144777), 13) * 2654435761u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint QueueRound(uint hash, uint queuedValue) { return BitOperations.RotateLeft(hash + (uint)((int)queuedValue * -1028477379), 17) * 668265263; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint MixState(uint v1, uint v2, uint v3, uint v4) { return BitOperations.RotateLeft(v1, 1) + BitOperations.RotateLeft(v2, 7) + BitOperations.RotateLeft(v3, 12) + BitOperations.RotateLeft(v4, 18); } private static uint MixEmptyState() { return s_seed + 374761393; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint MixFinal(uint hash) { hash ^= hash >> 15; hash *= 2246822519u; hash ^= hash >> 13; hash *= 3266489917u; hash ^= hash >> 16; return hash; } public void Add(T value) { Add(value?.GetHashCode() ?? 0); } public void Add(T value, IEqualityComparer? comparer) { Add((value != null) ? (comparer?.GetHashCode(value) ?? value.GetHashCode()) : 0); } public void AddBytes(ReadOnlySpan value) { ref byte reference = ref MemoryMarshal.GetReference(value); ref byte reference2 = ref Unsafe.Add(ref reference, value.Length); while ((nint)Unsafe.ByteOffset(ref reference, ref reference2) >= 4) { Add(Unsafe.ReadUnaligned(ref reference)); reference = ref Unsafe.Add(ref reference, 4); } while (Unsafe.IsAddressLessThan(ref reference, ref reference2)) { Add((int)reference); reference = ref Unsafe.Add(ref reference, 1); } } private void Add(int value) { uint num = _length++; switch (num % 4) { case 0u: _queue1 = (uint)value; return; case 1u: _queue2 = (uint)value; return; case 2u: _queue3 = (uint)value; return; } if (num == 3) { Initialize(out _v1, out _v2, out _v3, out _v4); } _v1 = Round(_v1, _queue1); _v2 = Round(_v2, _queue2); _v3 = Round(_v3, _queue3); _v4 = Round(_v4, (uint)value); } public int ToHashCode() { uint length = _length; uint num = length % 4; uint num2 = ((length < 4) ? MixEmptyState() : MixState(_v1, _v2, _v3, _v4)); num2 += length * 4; if (num != 0) { num2 = QueueRound(num2, _queue1); if (num > 1) { num2 = QueueRound(num2, _queue2); if (num > 2) { num2 = QueueRound(num2, _queue3); } } } return (int)MixFinal(num2); } [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code.", true)] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(SR.HashCode_HashCodeNotSupported); } [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes.", true)] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw new NotSupportedException(SR.HashCode_EqualityNotSupported); } } public interface IAsyncDisposable { ValueTask DisposeAsync(); } public interface IAsyncResult { bool IsCompleted { get; } WaitHandle AsyncWaitHandle { get; } object? AsyncState { get; } bool CompletedSynchronously { get; } } public interface ICloneable { object Clone(); } public interface IComparable { int CompareTo(object? obj); } public interface IComparable { int CompareTo(T? other); } [CLSCompliant(false)] public interface IConvertible { TypeCode GetTypeCode(); bool ToBoolean(IFormatProvider? provider); char ToChar(IFormatProvider? provider); sbyte ToSByte(IFormatProvider? provider); byte ToByte(IFormatProvider? provider); short ToInt16(IFormatProvider? provider); ushort ToUInt16(IFormatProvider? provider); int ToInt32(IFormatProvider? provider); uint ToUInt32(IFormatProvider? provider); long ToInt64(IFormatProvider? provider); ulong ToUInt64(IFormatProvider? provider); float ToSingle(IFormatProvider? provider); double ToDouble(IFormatProvider? provider); decimal ToDecimal(IFormatProvider? provider); DateTime ToDateTime(IFormatProvider? provider); string ToString(IFormatProvider? provider); object ToType(Type conversionType, IFormatProvider? provider); } public interface ICustomFormatter { string Format(string? format, object? arg, IFormatProvider? formatProvider); } public interface IDisposable { void Dispose(); } public interface IEquatable { bool Equals(T? other); } public interface IFormatProvider { object? GetFormat(Type? formatType); } public interface IFormattable { string ToString(string? format, IFormatProvider? formatProvider); } public readonly struct Index : IEquatable { private readonly int _value; public static Index Start => new Index(0); public static Index End => new Index(-1); public int Value { get { if (_value < 0) { return ~_value; } return _value; } } public bool IsFromEnd => _value < 0; [MethodImpl(MethodImplOptions.AggressiveInlining)] public Index(int value, bool fromEnd = false) { if (value < 0) { ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } if (fromEnd) { _value = ~value; } else { _value = value; } } private Index(int value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Index FromStart(int value) { if (value < 0) { ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } return new Index(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Index FromEnd(int value) { if (value < 0) { ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } return new Index(~value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public int GetOffset(int length) { int num = _value; if (IsFromEnd) { num += length + 1; } return num; } public override bool Equals([NotNullWhen(true)] object? value) { if (value is Index) { return _value == ((Index)value)._value; } return false; } public bool Equals(Index other) { return _value == other._value; } public override int GetHashCode() { return _value; } public static implicit operator Index(int value) { return FromStart(value); } public override string ToString() { if (IsFromEnd) { return ToStringFromEnd(); } return ((uint)Value).ToString(); } private string ToStringFromEnd() { Span span = stackalloc char[11]; int charsWritten; bool flag = ((uint)Value).TryFormat(span.Slice(1), out charsWritten); span[0] = '^'; return new string(span.Slice(0, charsWritten + 1)); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class IndexOutOfRangeException : SystemException { public IndexOutOfRangeException() : base(SR.Arg_IndexOutOfRangeException) { base.HResult = -2146233080; } public IndexOutOfRangeException(string? message) : base(message) { base.HResult = -2146233080; } public IndexOutOfRangeException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233080; } private IndexOutOfRangeException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class InsufficientExecutionStackException : SystemException { public InsufficientExecutionStackException() : base(SR.Arg_InsufficientExecutionStackException) { base.HResult = -2146232968; } public InsufficientExecutionStackException(string? message) : base(message) { base.HResult = -2146232968; } public InsufficientExecutionStackException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146232968; } private InsufficientExecutionStackException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class InsufficientMemoryException : OutOfMemoryException { public InsufficientMemoryException() : base(Exception.GetMessageFromNativeResources(ExceptionMessageKind.OutOfMemory)) { base.HResult = -2146233027; } public InsufficientMemoryException(string? message) : base(message) { base.HResult = -2146233027; } public InsufficientMemoryException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233027; } private InsufficientMemoryException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Int16 : IComparable, IConvertible, ISpanFormattable, IFormattable, IComparable, IEquatable, IBinaryInteger, IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IShiftOperators, IMinMaxValue, ISignedNumber { private readonly short m_value; public const short MaxValue = 32767; public const short MinValue = -32768; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IAdditiveIdentity.AdditiveIdentity => 0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IMinMaxValue.MinValue => short.MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IMinMaxValue.MaxValue => short.MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IMultiplicativeIdentity.MultiplicativeIdentity => 1; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short INumber.One => 1; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short INumber.Zero => 0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short ISignedNumber.NegativeOne => -1; public int CompareTo(object? value) { if (value == null) { return 1; } if (value is short) { return this - (short)value; } throw new ArgumentException(SR.Arg_MustBeInt16); } public int CompareTo(short value) { return this - value; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is short)) { return false; } return this == (short)obj; } [NonVersionable] public bool Equals(short obj) { return this == obj; } public override int GetHashCode() { return this; } public override string ToString() { return Number.Int32ToDecStr(this); } public string ToString(IFormatProvider? provider) { return Number.FormatInt32(this, 0, null, provider); } public string ToString(string? format) { return ToString(format, null); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatInt32(this, 65535, format, provider); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return Number.TryFormatInt32(this, 65535, format, provider, destination, out charsWritten); } public static short Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static short Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, style, NumberFormatInfo.CurrentInfo); } public static short Parse(string s, IFormatProvider? provider) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static short Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, style, NumberFormatInfo.GetInstance(provider)); } public static short Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static short Parse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info) { int result; Number.ParsingStatus parsingStatus = Number.TryParseInt32(s, style, info, out result); if (parsingStatus != 0) { Number.ThrowOverflowOrFormatException(parsingStatus, TypeCode.Int16); } if ((uint)(result - -32768 - ((int)(style & NumberStyles.AllowHexSpecifier) << 6)) > 65535u) { Number.ThrowOverflowException(TypeCode.Int16); } return (short)result; } public static bool TryParse([NotNullWhen(true)] string? s, out short result) { if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan s, out short result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out short result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan)s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out short result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out short result) { if (Number.TryParseInt32(s, style, info, out var result2) != 0 || (uint)(result2 - -32768 - ((int)(style & NumberStyles.AllowHexSpecifier) << 6)) > 65535u) { result = 0; return false; } result = (short)result2; return true; } public TypeCode GetTypeCode() { return TypeCode.Int16; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(this); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(this); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return this; } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int16", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IAdditionOperators.op_Addition(short left, short right) { return (short)(left + right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IBinaryInteger.LeadingZeroCount(short value) { return (short)(BitOperations.LeadingZeroCount((ushort)value) - 16); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IBinaryInteger.PopCount(short value) { return (short)BitOperations.PopCount((ushort)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IBinaryInteger.RotateLeft(short value, int rotateAmount) { return (short)((value << (rotateAmount & 0xF)) | ((ushort)value >> ((16 - rotateAmount) & 0xF))); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IBinaryInteger.RotateRight(short value, int rotateAmount) { return (short)(((ushort)value >> (rotateAmount & 0xF)) | (value << ((16 - rotateAmount) & 0xF))); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IBinaryInteger.TrailingZeroCount(short value) { return (byte)(BitOperations.TrailingZeroCount(value << 16) - 16); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IBinaryNumber.IsPow2(short value) { return BitOperations.IsPow2(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IBinaryNumber.Log2(short value) { if (value < 0) { ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } return (short)BitOperations.Log2((ushort)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IBitwiseOperators.op_BitwiseAnd(short left, short right) { return (short)(left & right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IBitwiseOperators.op_BitwiseOr(short left, short right) { return (short)(left | right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IBitwiseOperators.op_ExclusiveOr(short left, short right) { return (short)(left ^ right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IBitwiseOperators.op_OnesComplement(short value) { return (short)(~value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(short left, short right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(short left, short right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(short left, short right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(short left, short right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IDecrementOperators.op_Decrement(short value) { return --value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IDivisionOperators.op_Division(short left, short right) { return (short)(left / right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(short left, short right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(short left, short right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IIncrementOperators.op_Increment(short value) { return ++value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IModulusOperators.op_Modulus(short left, short right) { return (short)(left % right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IMultiplyOperators.op_Multiply(short left, short right) { return (short)(left * right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short INumber.Abs(short value) { return Math.Abs(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short INumber.Clamp(short value, short min, short max) { return Math.Clamp(value, min, max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short INumber.Create(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } checked { if (typeof(TOther) == typeof(char)) { return (short)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (short)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (short)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (short)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (short)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (short)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (short)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (short)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (short)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (short)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (short)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { char c = (char)(object)value; if (c <= '翿') { return (short)c; } return short.MaxValue; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (!(num > 32767m)) { if (!(num < -32768m)) { return (short)num; } return short.MinValue; } return short.MaxValue; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (!(num2 > 32767.0)) { if (!(num2 < -32768.0)) { return (short)num2; } return short.MinValue; } return short.MaxValue; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { int num3 = (int)(object)value; if (num3 <= 32767) { if (num3 >= -32768) { return (short)num3; } return short.MinValue; } return short.MaxValue; } if (typeof(TOther) == typeof(long)) { long num4 = (long)(object)value; if (num4 <= 32767) { if (num4 >= -32768) { return (short)num4; } return short.MinValue; } return short.MaxValue; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr <= 32767) { if ((nint)intPtr >= -32768) { return (short)(nint)intPtr; } return short.MinValue; } return short.MaxValue; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { float num5 = (float)(object)value; if (!(num5 > 32767f)) { if (!(num5 < -32768f)) { return (short)num5; } return short.MinValue; } return short.MaxValue; } if (typeof(TOther) == typeof(ushort)) { ushort num6 = (ushort)(object)value; if (num6 <= 32767) { return (short)num6; } return short.MaxValue; } if (typeof(TOther) == typeof(uint)) { uint num7 = (uint)(object)value; if ((long)num7 <= 32767L) { return (short)num7; } return short.MaxValue; } if (typeof(TOther) == typeof(ulong)) { ulong num8 = (ulong)(object)value; if (num8 <= 32767) { return (short)num8; } return short.MaxValue; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr <= 32767) { return (short)(nuint)uIntPtr; } return short.MaxValue; } ThrowHelper.ThrowNotSupportedException(); return 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (short)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (short)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (short)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (short)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (short)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (short)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (short)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (short)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (short)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (short)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (short)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (short Quotient, short Remainder) INumber.DivRem(short left, short right) { return Math.DivRem(left, right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short INumber.Max(short x, short y) { return Math.Max(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short INumber.Min(short x, short y) { return Math.Min(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short INumber.Sign(short value) { return (short)Math.Sign(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out short result) { if (typeof(TOther) == typeof(byte)) { result = (byte)(object)value; return true; } if (typeof(TOther) == typeof(char)) { char c = (char)(object)value; if (c > '翿') { result = 0; return false; } result = (short)c; return true; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (num < -32768m || num > 32767m) { result = 0; return false; } result = (short)num; return true; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (num2 < -32768.0 || num2 > 32767.0) { result = 0; return false; } result = (short)num2; return true; } if (typeof(TOther) == typeof(short)) { result = (short)(object)value; return true; } if (typeof(TOther) == typeof(int)) { int num3 = (int)(object)value; if (num3 < -32768 || num3 > 32767) { result = 0; return false; } result = (short)num3; return true; } if (typeof(TOther) == typeof(long)) { long num4 = (long)(object)value; if (num4 < -32768 || num4 > 32767) { result = 0; return false; } result = (short)num4; return true; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr < -32768 || (nint)intPtr > 32767) { result = 0; return false; } result = (short)(nint)intPtr; return true; } if (typeof(TOther) == typeof(sbyte)) { result = (sbyte)(object)value; return true; } if (typeof(TOther) == typeof(float)) { float num5 = (float)(object)value; if (num5 < -32768f || num5 > 32767f) { result = 0; return false; } result = (short)num5; return true; } if (typeof(TOther) == typeof(ushort)) { ushort num6 = (ushort)(object)value; if (num6 > 32767) { result = 0; return false; } result = (short)num6; return true; } if (typeof(TOther) == typeof(uint)) { uint num7 = (uint)(object)value; if ((long)num7 > 32767L) { result = 0; return false; } result = (short)num7; return true; } if (typeof(TOther) == typeof(ulong)) { ulong num8 = (ulong)(object)value; if (num8 > 32767) { result = 0; return false; } result = (short)num8; return true; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr > 32767) { result = 0; return false; } result = (short)(nuint)uIntPtr; return true; } ThrowHelper.ThrowNotSupportedException(); result = 0; return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out short result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out short result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out short result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IShiftOperators.op_LeftShift(short value, int shiftAmount) { return (short)(value << shiftAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IShiftOperators.op_RightShift(short value, int shiftAmount) { return (short)(value >> shiftAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out short result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short ISubtractionOperators.op_Subtraction(short left, short right) { return (short)(left - right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IUnaryNegationOperators.op_UnaryNegation(short value) { return (short)(-value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static short IUnaryPlusOperators.op_UnaryPlus(short value) { return value; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Int32 : IComparable, IConvertible, ISpanFormattable, IFormattable, IComparable, IEquatable, IBinaryInteger, IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IShiftOperators, IMinMaxValue, ISignedNumber { private readonly int m_value; public const int MaxValue = 2147483647; public const int MinValue = -2147483648; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IAdditiveIdentity.AdditiveIdentity => 0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IMinMaxValue.MinValue => int.MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IMinMaxValue.MaxValue => int.MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IMultiplicativeIdentity.MultiplicativeIdentity => 1; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int INumber.One => 1; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int INumber.Zero => 0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int ISignedNumber.NegativeOne => -1; public int CompareTo(object? value) { if (value == null) { return 1; } if (value is int num) { if (this < num) { return -1; } if (this > num) { return 1; } return 0; } throw new ArgumentException(SR.Arg_MustBeInt32); } public int CompareTo(int value) { if (this < value) { return -1; } if (this > value) { return 1; } return 0; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is int)) { return false; } return this == (int)obj; } [NonVersionable] public bool Equals(int obj) { return this == obj; } public override int GetHashCode() { return this; } public override string ToString() { return Number.Int32ToDecStr(this); } public string ToString(string? format) { return ToString(format, null); } public string ToString(IFormatProvider? provider) { return Number.FormatInt32(this, 0, null, provider); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatInt32(this, -1, format, provider); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return Number.TryFormatInt32(this, -1, format, provider, destination, out charsWritten); } public static int Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static int Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseInt32(s, style, NumberFormatInfo.CurrentInfo); } public static int Parse(string s, IFormatProvider? provider) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static int Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider)); } public static int Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider)); } public static bool TryParse([NotNullWhen(true)] string? s, out int result) { if (s == null) { result = 0; return false; } return Number.TryParseInt32IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } public static bool TryParse(ReadOnlySpan s, out int result) { return Number.TryParseInt32IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out int result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out int result) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } public TypeCode GetTypeCode() { return TypeCode.Int32; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(this); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(this); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return this; } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int32", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IAdditionOperators.op_Addition(int left, int right) { return left + right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IBinaryInteger.LeadingZeroCount(int value) { return BitOperations.LeadingZeroCount((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IBinaryInteger.PopCount(int value) { return BitOperations.PopCount((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IBinaryInteger.RotateLeft(int value, int rotateAmount) { return (int)BitOperations.RotateLeft((uint)value, rotateAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IBinaryInteger.RotateRight(int value, int rotateAmount) { return (int)BitOperations.RotateRight((uint)value, rotateAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IBinaryInteger.TrailingZeroCount(int value) { return BitOperations.TrailingZeroCount(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IBinaryNumber.IsPow2(int value) { return BitOperations.IsPow2(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IBinaryNumber.Log2(int value) { if (value < 0) { ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } return BitOperations.Log2((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IBitwiseOperators.op_BitwiseAnd(int left, int right) { return left & right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IBitwiseOperators.op_BitwiseOr(int left, int right) { return left | right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IBitwiseOperators.op_ExclusiveOr(int left, int right) { return left ^ right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IBitwiseOperators.op_OnesComplement(int value) { return ~value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(int left, int right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(int left, int right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(int left, int right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(int left, int right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IDecrementOperators.op_Decrement(int value) { return --value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IDivisionOperators.op_Division(int left, int right) { return left / right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(int left, int right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(int left, int right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IIncrementOperators.op_Increment(int value) { return ++value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IModulusOperators.op_Modulus(int left, int right) { return left % right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IMultiplyOperators.op_Multiply(int left, int right) { return left * right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int INumber.Abs(int value) { return Math.Abs(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int INumber.Clamp(int value, int min, int max) { return Math.Clamp(value, min, max); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] internal static int Create(TOther value) where TOther : INumber { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (int)(decimal)(object)value; } checked { if (typeof(TOther) == typeof(double)) { return (int)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (int)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (int)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (int)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (int)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (int)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (int)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int INumber.Create(TOther value) { return Create(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (!(num > 2147483647m)) { if (!(num < -2147483648m)) { return (int)num; } return int.MinValue; } return int.MaxValue; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (!(num2 > 2147483647.0)) { if (!(num2 < -2147483648.0)) { return (int)num2; } return int.MinValue; } return int.MaxValue; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { long num3 = (long)(object)value; if (num3 <= int.MaxValue) { if (num3 >= int.MinValue) { return (int)num3; } return int.MinValue; } return int.MaxValue; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr <= int.MaxValue) { if ((nint)intPtr >= int.MinValue) { return (int)(nint)intPtr; } return int.MinValue; } return int.MaxValue; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { float num4 = (float)(object)value; if (!(num4 > 2.1474836E+09f)) { if (!(num4 < -2.1474836E+09f)) { return (int)num4; } return int.MinValue; } return int.MaxValue; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { uint num5 = (uint)(object)value; if (num5 <= int.MaxValue) { return (int)num5; } return int.MaxValue; } if (typeof(TOther) == typeof(ulong)) { ulong num6 = (ulong)(object)value; if (num6 <= int.MaxValue) { return (int)num6; } return int.MaxValue; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr <= int.MaxValue) { return (int)(nuint)uIntPtr; } return int.MaxValue; } ThrowHelper.ThrowNotSupportedException(); return 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (int)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (int)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (int)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (int)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (int)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (int)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (int)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (int)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (int Quotient, int Remainder) INumber.DivRem(int left, int right) { return Math.DivRem(left, right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int INumber.Max(int x, int y) { return Math.Max(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int INumber.Min(int x, int y) { return Math.Min(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int INumber.Sign(int value) { return Math.Sign(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out int result) { if (typeof(TOther) == typeof(byte)) { result = (byte)(object)value; return true; } if (typeof(TOther) == typeof(char)) { result = (char)(object)value; return true; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (num < -2147483648m || num > 2147483647m) { result = 0; return false; } result = (int)num; return true; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (num2 < -2147483648.0 || num2 > 2147483647.0) { result = 0; return false; } result = (int)num2; return true; } if (typeof(TOther) == typeof(short)) { result = (short)(object)value; return true; } if (typeof(TOther) == typeof(int)) { result = (int)(object)value; return true; } if (typeof(TOther) == typeof(long)) { long num3 = (long)(object)value; if (num3 < int.MinValue || num3 > int.MaxValue) { result = 0; return false; } result = (int)num3; return true; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr < int.MinValue || (nint)intPtr > int.MaxValue) { result = 0; return false; } result = (int)(nint)intPtr; return true; } if (typeof(TOther) == typeof(sbyte)) { result = (sbyte)(object)value; return true; } if (typeof(TOther) == typeof(float)) { float num4 = (float)(object)value; if (num4 < -2.1474836E+09f || num4 > 2.1474836E+09f) { result = 0; return false; } result = (int)num4; return true; } if (typeof(TOther) == typeof(ushort)) { result = (ushort)(object)value; return true; } if (typeof(TOther) == typeof(uint)) { uint num5 = (uint)(object)value; if (num5 > int.MaxValue) { result = 0; return false; } result = (int)num5; return true; } if (typeof(TOther) == typeof(ulong)) { ulong num6 = (ulong)(object)value; if (num6 > int.MaxValue) { result = 0; return false; } result = (int)num6; return true; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr > int.MaxValue) { result = 0; return false; } result = (int)(nuint)uIntPtr; return true; } ThrowHelper.ThrowNotSupportedException(); result = 0; return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out int result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out int result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out int result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IShiftOperators.op_LeftShift(int value, int shiftAmount) { return value << shiftAmount; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IShiftOperators.op_RightShift(int value, int shiftAmount) { return value >> shiftAmount; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out int result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int ISubtractionOperators.op_Subtraction(int left, int right) { return left - right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IUnaryNegationOperators.op_UnaryNegation(int value) { return -value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static int IUnaryPlusOperators.op_UnaryPlus(int value) { return value; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Int64 : IComparable, IConvertible, ISpanFormattable, IFormattable, IComparable, IEquatable, IBinaryInteger, IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IShiftOperators, IMinMaxValue, ISignedNumber { private readonly long m_value; public const long MaxValue = 9223372036854775807L; public const long MinValue = -9223372036854775808L; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IAdditiveIdentity.AdditiveIdentity => 0L; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IMinMaxValue.MinValue => long.MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IMinMaxValue.MaxValue => long.MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IMultiplicativeIdentity.MultiplicativeIdentity => 1L; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long INumber.One => 1L; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long INumber.Zero => 0L; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long ISignedNumber.NegativeOne => -1L; public int CompareTo(object? value) { if (value == null) { return 1; } if (value is long num) { if (this < num) { return -1; } if (this > num) { return 1; } return 0; } throw new ArgumentException(SR.Arg_MustBeInt64); } public int CompareTo(long value) { if (this < value) { return -1; } if (this > value) { return 1; } return 0; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is long)) { return false; } return this == (long)obj; } [NonVersionable] public bool Equals(long obj) { return this == obj; } public override int GetHashCode() { return (int)this ^ (int)(this >> 32); } public override string ToString() { return Number.Int64ToDecStr(this); } public string ToString(IFormatProvider? provider) { return Number.FormatInt64(this, null, provider); } public string ToString(string? format) { return Number.FormatInt64(this, format, null); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatInt64(this, format, provider); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return Number.TryFormatInt64(this, format, provider, destination, out charsWritten); } public static long Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static long Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseInt64(s, style, NumberFormatInfo.CurrentInfo); } public static long Parse(string s, IFormatProvider? provider) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static long Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseInt64(s, style, NumberFormatInfo.GetInstance(provider)); } public static long Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseInt64(s, style, NumberFormatInfo.GetInstance(provider)); } public static bool TryParse([NotNullWhen(true)] string? s, out long result) { if (s == null) { result = 0L; return false; } return Number.TryParseInt64IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } public static bool TryParse(ReadOnlySpan s, out long result) { return Number.TryParseInt64IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out long result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0L; return false; } return Number.TryParseInt64(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out long result) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseInt64(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } public TypeCode GetTypeCode() { return TypeCode.Int64; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(this); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(this); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return this; } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int64", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IAdditionOperators.op_Addition(long left, long right) { return left + right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IBinaryInteger.LeadingZeroCount(long value) { return BitOperations.LeadingZeroCount((ulong)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IBinaryInteger.PopCount(long value) { return BitOperations.PopCount((ulong)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IBinaryInteger.RotateLeft(long value, int rotateAmount) { return (long)BitOperations.RotateLeft((ulong)value, rotateAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IBinaryInteger.RotateRight(long value, int rotateAmount) { return (long)BitOperations.RotateRight((ulong)value, rotateAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IBinaryInteger.TrailingZeroCount(long value) { return BitOperations.TrailingZeroCount(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IBinaryNumber.IsPow2(long value) { return BitOperations.IsPow2(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IBinaryNumber.Log2(long value) { if (value < 0) { ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } return BitOperations.Log2((ulong)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IBitwiseOperators.op_BitwiseAnd(long left, long right) { return left & right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IBitwiseOperators.op_BitwiseOr(long left, long right) { return left | right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IBitwiseOperators.op_ExclusiveOr(long left, long right) { return left ^ right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IBitwiseOperators.op_OnesComplement(long value) { return ~value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(long left, long right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(long left, long right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(long left, long right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(long left, long right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IDecrementOperators.op_Decrement(long value) { return --value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IDivisionOperators.op_Division(long left, long right) { return left / right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(long left, long right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(long left, long right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IIncrementOperators.op_Increment(long value) { return ++value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IModulusOperators.op_Modulus(long left, long right) { return left % right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IMultiplyOperators.op_Multiply(long left, long right) { return left * right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long INumber.Abs(long value) { return Math.Abs(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long INumber.Clamp(long value, long min, long max) { return Math.Clamp(value, min, max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long INumber.Create(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (long)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return checked((long)(double)(object)value); } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (long)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } checked { if (typeof(TOther) == typeof(float)) { return (long)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (long)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (long)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0L; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (!(num > 9223372036854775807m)) { if (!(num < -9223372036854775808m)) { return (long)num; } return long.MinValue; } return long.MaxValue; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (!(num2 > 9.223372036854776E+18)) { if (!(num2 < -9.223372036854776E+18)) { return (long)num2; } return long.MinValue; } return long.MaxValue; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (long)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { float num3 = (float)(object)value; if (!(num3 > 9.223372E+18f)) { if (!(num3 < -9.223372E+18f)) { return (long)num3; } return long.MinValue; } return long.MaxValue; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { ulong num4 = (ulong)(object)value; if (num4 <= long.MaxValue) { return (long)num4; } return long.MaxValue; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((ulong)(nuint)uIntPtr <= 9223372036854775807uL) { return (long)(nuint)uIntPtr; } return long.MaxValue; } ThrowHelper.ThrowNotSupportedException(); return 0L; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (long)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (long)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (long)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (long)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (long)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (long)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0L; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (long Quotient, long Remainder) INumber.DivRem(long left, long right) { return Math.DivRem(left, right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long INumber.Max(long x, long y) { return Math.Max(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long INumber.Min(long x, long y) { return Math.Min(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long INumber.Sign(long value) { return Math.Sign(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out long result) { if (typeof(TOther) == typeof(byte)) { result = (byte)(object)value; return true; } if (typeof(TOther) == typeof(char)) { result = (char)(object)value; return true; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (num < -9223372036854775808m || num > 9223372036854775807m) { result = 0L; return false; } result = (long)num; return true; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (num2 < -9.223372036854776E+18 || num2 > 9.223372036854776E+18) { result = 0L; return false; } result = (long)num2; return true; } if (typeof(TOther) == typeof(short)) { result = (short)(object)value; return true; } if (typeof(TOther) == typeof(int)) { result = (int)(object)value; return true; } if (typeof(TOther) == typeof(long)) { result = (long)(object)value; return true; } if (typeof(TOther) == typeof(IntPtr)) { result = (long)(IntPtr)(object)value; return true; } if (typeof(TOther) == typeof(sbyte)) { result = (sbyte)(object)value; return true; } if (typeof(TOther) == typeof(float)) { float num3 = (float)(object)value; if (num3 < -9.223372E+18f || num3 > 9.223372E+18f) { result = 0L; return false; } result = (long)num3; return true; } if (typeof(TOther) == typeof(ushort)) { result = (ushort)(object)value; return true; } if (typeof(TOther) == typeof(uint)) { result = (uint)(object)value; return true; } if (typeof(TOther) == typeof(ulong)) { ulong num4 = (ulong)(object)value; if (num4 > long.MaxValue) { result = 0L; return false; } result = (long)num4; return true; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((ulong)(nuint)uIntPtr > 9223372036854775807uL) { result = 0L; return false; } result = (long)(nuint)uIntPtr; return true; } ThrowHelper.ThrowNotSupportedException(); result = 0L; return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out long result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out long result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out long result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IShiftOperators.op_LeftShift(long value, int shiftAmount) { return value << shiftAmount; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IShiftOperators.op_RightShift(long value, int shiftAmount) { return value >> shiftAmount; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out long result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long ISubtractionOperators.op_Subtraction(long left, long right) { return left - right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IUnaryNegationOperators.op_UnaryNegation(long value) { return -value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static long IUnaryPlusOperators.op_UnaryPlus(long value) { return value; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct IntPtr : IEquatable, IComparable, IComparable, ISpanFormattable, IFormattable, ISerializable, IBinaryInteger, IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IShiftOperators, IMinMaxValue, ISignedNumber { private unsafe readonly void* _value; [Intrinsic] public static readonly IntPtr Zero; public static int Size { [NonVersionable] get { return 4; } } public static IntPtr MaxValue { [NonVersionable] get { return (IntPtr)int.MaxValue; } } public static IntPtr MinValue { [NonVersionable] get { return (IntPtr)int.MinValue; } } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IAdditiveIdentity.AdditiveIdentity => 0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IMinMaxValue.MinValue => MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IMinMaxValue.MaxValue => MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IMultiplicativeIdentity.MultiplicativeIdentity => 1; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint INumber.One => 1; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint INumber.Zero => 0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint ISignedNumber.NegativeOne => -1; [NonVersionable] public unsafe IntPtr(int value) { _value = (void*)value; } [NonVersionable] public unsafe IntPtr(long value) { _value = (void*)checked((int)value); } [CLSCompliant(false)] [NonVersionable] public unsafe IntPtr(void* value) { _value = value; } private unsafe IntPtr(SerializationInfo info, StreamingContext context) { long @int = info.GetInt64("value"); _ = Size; if (@int > int.MaxValue || @int < int.MinValue) { throw new ArgumentException(SR.Serialization_InvalidPtrValue); } _value = (void*)@int; } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("value", ToInt64()); } public unsafe override bool Equals([NotNullWhen(true)] object? obj) { if (obj is IntPtr intPtr) { return _value == intPtr._value; } return false; } public unsafe override int GetHashCode() { return (int)_value; } [NonVersionable] public unsafe int ToInt32() { return (int)_value; } [NonVersionable] public unsafe long ToInt64() { return (nint)_value; } [NonVersionable] public static explicit operator IntPtr(int value) { return new IntPtr(value); } [NonVersionable] public static explicit operator IntPtr(long value) { return new IntPtr(value); } [CLSCompliant(false)] [NonVersionable] public unsafe static explicit operator IntPtr(void* value) { return new IntPtr(value); } [CLSCompliant(false)] [NonVersionable] public unsafe static explicit operator void*(IntPtr value) { return value._value; } [NonVersionable] public unsafe static explicit operator int(IntPtr value) { return (int)value._value; } [NonVersionable] public unsafe static explicit operator long(IntPtr value) { return (nint)value._value; } [NonVersionable] public unsafe static bool operator ==(IntPtr value1, IntPtr value2) { return value1._value == value2._value; } [NonVersionable] public unsafe static bool operator !=(IntPtr value1, IntPtr value2) { return value1._value != value2._value; } [NonVersionable] public static IntPtr Add(IntPtr pointer, int offset) { return pointer + offset; } [NonVersionable] public unsafe static IntPtr operator +(IntPtr pointer, int offset) { return (nint)((byte*)pointer._value + offset); } [NonVersionable] public static IntPtr Subtract(IntPtr pointer, int offset) { return pointer - offset; } [NonVersionable] public unsafe static IntPtr operator -(IntPtr pointer, int offset) { return (nint)((byte*)pointer._value - offset); } [CLSCompliant(false)] [NonVersionable] public unsafe void* ToPointer() { return _value; } public unsafe int CompareTo(object? value) { if (value == null) { return 1; } if (value is IntPtr intPtr) { if ((nint)_value < (nint)intPtr) { return -1; } if ((nint)_value > (nint)intPtr) { return 1; } return 0; } throw new ArgumentException(SR.Arg_MustBeIntPtr); } public unsafe int CompareTo(IntPtr value) { return ((int)_value).CompareTo((int)value); } [NonVersionable] public unsafe bool Equals(IntPtr other) { return (int)_value == (int)other; } public unsafe override string ToString() { return ((int)_value).ToString(); } public unsafe string ToString(string? format) { return ((int)_value).ToString(format); } public unsafe string ToString(IFormatProvider? provider) { return ((int)_value).ToString(provider); } public unsafe string ToString(string? format, IFormatProvider? provider) { return ((int)_value).ToString(format, provider); } public unsafe bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return ((int)_value).TryFormat(destination, out charsWritten, format, provider); } public static IntPtr Parse(string s) { return (IntPtr)int.Parse(s); } public static IntPtr Parse(string s, NumberStyles style) { return (IntPtr)int.Parse(s, style); } public static IntPtr Parse(string s, IFormatProvider? provider) { return (IntPtr)int.Parse(s, provider); } public static IntPtr Parse(string s, NumberStyles style, IFormatProvider? provider) { return (IntPtr)int.Parse(s, style, provider); } public static IntPtr Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { return (IntPtr)int.Parse(s, style, provider); } public static bool TryParse([NotNullWhen(true)] string? s, out IntPtr result) { Unsafe.SkipInit(out result); return int.TryParse(s, out Unsafe.As(ref result)); } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out IntPtr result) { Unsafe.SkipInit(out result); return int.TryParse(s, style, provider, out Unsafe.As(ref result)); } public static bool TryParse(ReadOnlySpan s, out IntPtr result) { Unsafe.SkipInit(out result); return int.TryParse(s, out Unsafe.As(ref result)); } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out IntPtr result) { Unsafe.SkipInit(out result); return int.TryParse(s, style, provider, out Unsafe.As(ref result)); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IAdditionOperators.op_Addition(nint left, nint right) { return left + right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IBinaryInteger.LeadingZeroCount(nint value) { if (Environment.Is64BitProcess) { } return BitOperations.LeadingZeroCount((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IBinaryInteger.PopCount(nint value) { if (Environment.Is64BitProcess) { } return BitOperations.PopCount((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IBinaryInteger.RotateLeft(nint value, int rotateAmount) { if (Environment.Is64BitProcess) { } return (nint)BitOperations.RotateLeft((uint)value, rotateAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IBinaryInteger.RotateRight(nint value, int rotateAmount) { if (Environment.Is64BitProcess) { } return (nint)BitOperations.RotateRight((uint)value, rotateAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IBinaryInteger.TrailingZeroCount(nint value) { if (Environment.Is64BitProcess) { } return BitOperations.TrailingZeroCount((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IBinaryNumber.IsPow2(nint value) { return BitOperations.IsPow2(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IBinaryNumber.Log2(nint value) { if (value < 0) { ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } if (Environment.Is64BitProcess) { } return BitOperations.Log2((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IBitwiseOperators.op_BitwiseAnd(nint left, nint right) { return left & right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IBitwiseOperators.op_BitwiseOr(nint left, nint right) { return left | right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IBitwiseOperators.op_ExclusiveOr(nint left, nint right) { return left ^ right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IBitwiseOperators.op_OnesComplement(nint value) { return ~value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(nint left, nint right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(nint left, nint right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(nint left, nint right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(nint left, nint right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IDecrementOperators.op_Decrement(nint value) { return --value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IDivisionOperators.op_Division(nint left, nint right) { return left / right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(nint left, nint right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(nint left, nint right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IIncrementOperators.op_Increment(nint value) { return ++value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IModulusOperators.op_Modulus(nint left, nint right) { return left % right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IMultiplyOperators.op_Multiply(nint left, nint right) { return left * right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint INumber.Abs(nint value) { return Math.Abs(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint INumber.Clamp(nint value, nint min, nint max) { return Math.Clamp(value, min, max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint INumber.Create(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } checked { if (typeof(TOther) == typeof(decimal)) { return (nint)(long)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (nint)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (nint)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (nint)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (nint)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (nint)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (nint)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (!(num > (decimal)(long)MaxValue)) { if (!(num < (decimal)(long)MinValue)) { return (nint)(long)num; } return MinValue; } return MaxValue; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (!(num2 > (double)(nint)MaxValue)) { if (!(num2 < (double)(nint)MinValue)) { return (nint)num2; } return MinValue; } return MaxValue; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { long num3 = (long)(object)value; if (num3 <= (nint)MaxValue) { if (num3 >= (nint)MinValue) { return (nint)num3; } return MinValue; } return MaxValue; } if (typeof(TOther) == typeof(IntPtr)) { return (IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { float num4 = (float)(object)value; if (!(num4 > (float)(nint)MaxValue)) { if (!(num4 < (float)(nint)MinValue)) { return (nint)num4; } return MinValue; } return MaxValue; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { uint num5 = (uint)(object)value; if (num5 <= (nint)MaxValue) { return (nint)num5; } return MaxValue; } if (typeof(TOther) == typeof(ulong)) { ulong num6 = (ulong)(object)value; if (num6 <= (nuint)(nint)MaxValue) { return (nint)num6; } return MaxValue; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr <= (nuint)(nint)MaxValue) { return (nint)(nuint)uIntPtr; } return MaxValue; } ThrowHelper.ThrowNotSupportedException(); return 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (nint)(long)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (nint)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (nint)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (nint)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (nint)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (nint)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (nint)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (nint Quotient, nint Remainder) INumber.DivRem(nint left, nint right) { return Math.DivRem(left, right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint INumber.Max(nint x, nint y) { return Math.Max(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint INumber.Min(nint x, nint y) { return Math.Min(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint INumber.Sign(nint value) { return Math.Sign(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out nint result) { if (typeof(TOther) == typeof(byte)) { result = (byte)(object)value; return true; } if (typeof(TOther) == typeof(char)) { result = (char)(object)value; return true; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (num < (decimal)(long)MinValue || num > (decimal)(long)MaxValue) { result = 0; return false; } result = (nint)(long)num; return true; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (num2 < (double)(nint)MinValue || num2 > (double)(nint)MaxValue) { result = 0; return false; } result = (nint)num2; return true; } if (typeof(TOther) == typeof(short)) { result = (short)(object)value; return true; } if (typeof(TOther) == typeof(int)) { result = (int)(object)value; return true; } if (typeof(TOther) == typeof(long)) { long num3 = (long)(object)value; if (num3 < (nint)MinValue || num3 > (nint)MaxValue) { result = 0; return false; } result = (nint)num3; return true; } if (typeof(TOther) == typeof(IntPtr)) { result = (IntPtr)(object)value; return true; } if (typeof(TOther) == typeof(sbyte)) { result = (sbyte)(object)value; return true; } if (typeof(TOther) == typeof(float)) { float num4 = (float)(object)value; if (num4 < (float)(nint)MinValue || num4 > (float)(nint)MaxValue) { result = 0; return false; } result = (nint)num4; return true; } if (typeof(TOther) == typeof(ushort)) { result = (ushort)(object)value; return true; } if (typeof(TOther) == typeof(uint)) { uint num5 = (uint)(object)value; if (num5 > (nint)MaxValue) { result = 0; return false; } result = (nint)num5; return true; } if (typeof(TOther) == typeof(ulong)) { ulong num6 = (ulong)(object)value; if (num6 > (nuint)(nint)MaxValue) { result = 0; return false; } result = (nint)num6; return true; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr > (nuint)(nint)MaxValue) { result = 0; return false; } result = (nint)(nuint)uIntPtr; return true; } ThrowHelper.ThrowNotSupportedException(); result = 0; return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out nint result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out nint result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out nint result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IShiftOperators.op_LeftShift(nint value, int shiftAmount) { return value << shiftAmount; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IShiftOperators.op_RightShift(nint value, int shiftAmount) { return value >> shiftAmount; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out nint result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint ISubtractionOperators.op_Subtraction(nint left, nint right) { return left - right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IUnaryNegationOperators.op_UnaryNegation(nint value) { return -value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nint IUnaryPlusOperators.op_UnaryPlus(nint value) { return value; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class InvalidCastException : SystemException { public InvalidCastException() : base(SR.Arg_InvalidCastException) { base.HResult = -2147467262; } public InvalidCastException(string? message) : base(message) { base.HResult = -2147467262; } public InvalidCastException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2147467262; } public InvalidCastException(string? message, int errorCode) : base(message) { base.HResult = errorCode; } protected InvalidCastException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class InvalidOperationException : SystemException { public InvalidOperationException() : base(SR.Arg_InvalidOperationException) { base.HResult = -2146233079; } public InvalidOperationException(string? message) : base(message) { base.HResult = -2146233079; } public InvalidOperationException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233079; } protected InvalidOperationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class InvalidProgramException : SystemException { public InvalidProgramException() : base(SR.InvalidProgram_Default) { base.HResult = -2146233030; } public InvalidProgramException(string? message) : base(message) { base.HResult = -2146233030; } public InvalidProgramException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233030; } private InvalidProgramException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class InvalidTimeZoneException : Exception { public InvalidTimeZoneException() { } public InvalidTimeZoneException(string? message) : base(message) { } public InvalidTimeZoneException(string? message, Exception? innerException) : base(message, innerException) { } protected InvalidTimeZoneException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public interface IObservable { IDisposable Subscribe(IObserver observer); } public interface IObserver { void OnNext(T value); void OnError(Exception error); void OnCompleted(); } public interface IProgress { void Report(T value); } public interface ISpanFormattable : IFormattable { bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider? provider); } internal enum LazyState { NoneViaConstructor, NoneViaFactory, NoneException, PublicationOnlyViaConstructor, PublicationOnlyViaFactory, PublicationOnlyWait, PublicationOnlyException, ExecutionAndPublicationViaConstructor, ExecutionAndPublicationViaFactory, ExecutionAndPublicationException } internal sealed class LazyHelper { internal static readonly LazyHelper NoneViaConstructor = new LazyHelper(LazyState.NoneViaConstructor); internal static readonly LazyHelper NoneViaFactory = new LazyHelper(LazyState.NoneViaFactory); internal static readonly LazyHelper PublicationOnlyViaConstructor = new LazyHelper(LazyState.PublicationOnlyViaConstructor); internal static readonly LazyHelper PublicationOnlyViaFactory = new LazyHelper(LazyState.PublicationOnlyViaFactory); internal static readonly LazyHelper PublicationOnlyWaitForOtherThreadToPublish = new LazyHelper(LazyState.PublicationOnlyWait); private readonly ExceptionDispatchInfo _exceptionDispatch; internal LazyState State { get; } internal LazyHelper(LazyState state) { State = state; } internal LazyHelper(LazyThreadSafetyMode mode, Exception exception) { switch (mode) { case LazyThreadSafetyMode.ExecutionAndPublication: State = LazyState.ExecutionAndPublicationException; break; case LazyThreadSafetyMode.None: State = LazyState.NoneException; break; case LazyThreadSafetyMode.PublicationOnly: State = LazyState.PublicationOnlyException; break; } _exceptionDispatch = ExceptionDispatchInfo.Capture(exception); } [DoesNotReturn] internal void ThrowException() { _exceptionDispatch.Throw(); } private LazyThreadSafetyMode GetMode() { switch (State) { case LazyState.NoneViaConstructor: case LazyState.NoneViaFactory: case LazyState.NoneException: return LazyThreadSafetyMode.None; case LazyState.PublicationOnlyViaConstructor: case LazyState.PublicationOnlyViaFactory: case LazyState.PublicationOnlyWait: case LazyState.PublicationOnlyException: return LazyThreadSafetyMode.PublicationOnly; case LazyState.ExecutionAndPublicationViaConstructor: case LazyState.ExecutionAndPublicationViaFactory: case LazyState.ExecutionAndPublicationException: return LazyThreadSafetyMode.ExecutionAndPublication; default: return LazyThreadSafetyMode.None; } } internal static LazyThreadSafetyMode? GetMode(LazyHelper state) { return state?.GetMode(); } internal static bool GetIsValueFaulted(LazyHelper state) { return state?._exceptionDispatch != null; } internal static LazyHelper Create(LazyThreadSafetyMode mode, bool useDefaultConstructor) { switch (mode) { case LazyThreadSafetyMode.None: if (!useDefaultConstructor) { return NoneViaFactory; } return NoneViaConstructor; case LazyThreadSafetyMode.PublicationOnly: if (!useDefaultConstructor) { return PublicationOnlyViaFactory; } return PublicationOnlyViaConstructor; case LazyThreadSafetyMode.ExecutionAndPublication: { LazyState state = (useDefaultConstructor ? LazyState.ExecutionAndPublicationViaConstructor : LazyState.ExecutionAndPublicationViaFactory); return new LazyHelper(state); } default: throw new ArgumentOutOfRangeException("mode", SR.Lazy_ctor_ModeInvalid); } } internal static T CreateViaDefaultConstructor<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] T>() { try { return Activator.CreateInstance(); } catch (MissingMethodException) { throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT); } } internal static LazyThreadSafetyMode GetModeFromIsThreadSafe(bool isThreadSafe) { if (!isThreadSafe) { return LazyThreadSafetyMode.None; } return LazyThreadSafetyMode.ExecutionAndPublication; } } [DebuggerTypeProxy(typeof(LazyDebugView<>))] [DebuggerDisplay("ThreadSafetyMode={Mode}, IsValueCreated={IsValueCreated}, IsValueFaulted={IsValueFaulted}, Value={ValueForDebugDisplay}")] public class Lazy<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] T> { private volatile LazyHelper _state; private Func _factory; private T _value; internal T? ValueForDebugDisplay { get { if (!IsValueCreated) { return default(T); } return _value; } } internal LazyThreadSafetyMode? Mode => LazyHelper.GetMode(_state); internal bool IsValueFaulted => LazyHelper.GetIsValueFaulted(_state); public bool IsValueCreated => _state == null; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Value { get { if (_state != null) { return CreateValue(); } return _value; } } private static T CreateViaDefaultConstructor() { return LazyHelper.CreateViaDefaultConstructor(); } public Lazy() : this((Func)null, LazyThreadSafetyMode.ExecutionAndPublication, useDefaultConstructor: true) { } public Lazy(T value) { _value = value; } public Lazy(Func valueFactory) : this(valueFactory, LazyThreadSafetyMode.ExecutionAndPublication, useDefaultConstructor: false) { } public Lazy(bool isThreadSafe) : this((Func)null, LazyHelper.GetModeFromIsThreadSafe(isThreadSafe), useDefaultConstructor: true) { } public Lazy(LazyThreadSafetyMode mode) : this((Func)null, mode, useDefaultConstructor: true) { } public Lazy(Func valueFactory, bool isThreadSafe) : this(valueFactory, LazyHelper.GetModeFromIsThreadSafe(isThreadSafe), useDefaultConstructor: false) { } public Lazy(Func valueFactory, LazyThreadSafetyMode mode) : this(valueFactory, mode, useDefaultConstructor: false) { } private Lazy(Func valueFactory, LazyThreadSafetyMode mode, bool useDefaultConstructor) { if (valueFactory == null && !useDefaultConstructor) { throw new ArgumentNullException("valueFactory"); } _factory = valueFactory; _state = LazyHelper.Create(mode, useDefaultConstructor); } private void ViaConstructor() { _value = CreateViaDefaultConstructor(); _state = null; } private void ViaFactory(LazyThreadSafetyMode mode) { try { Func factory = _factory; if (factory == null) { throw new InvalidOperationException(SR.Lazy_Value_RecursiveCallsToValue); } _factory = null; _value = factory(); _state = null; } catch (Exception exception) { _state = new LazyHelper(mode, exception); throw; } } private void ExecutionAndPublication(LazyHelper executionAndPublication, bool useDefaultConstructor) { lock (executionAndPublication) { if (_state == executionAndPublication) { if (useDefaultConstructor) { ViaConstructor(); } else { ViaFactory(LazyThreadSafetyMode.ExecutionAndPublication); } } } } private void PublicationOnly(LazyHelper publicationOnly, T possibleValue) { LazyHelper lazyHelper = Interlocked.CompareExchange(ref _state, LazyHelper.PublicationOnlyWaitForOtherThreadToPublish, publicationOnly); if (lazyHelper == publicationOnly) { _factory = null; _value = possibleValue; _state = null; } } private void PublicationOnlyViaConstructor(LazyHelper initializer) { PublicationOnly(initializer, CreateViaDefaultConstructor()); } private void PublicationOnlyViaFactory(LazyHelper initializer) { Func factory = _factory; if (factory == null) { PublicationOnlyWaitForOtherThreadToPublish(); } else { PublicationOnly(initializer, factory()); } } private void PublicationOnlyWaitForOtherThreadToPublish() { SpinWait spinWait = default(SpinWait); while (_state != null) { spinWait.SpinOnce(); } } private T CreateValue() { LazyHelper state = _state; if (state != null) { switch (state.State) { case LazyState.NoneViaConstructor: ViaConstructor(); break; case LazyState.NoneViaFactory: ViaFactory(LazyThreadSafetyMode.None); break; case LazyState.PublicationOnlyViaConstructor: PublicationOnlyViaConstructor(state); break; case LazyState.PublicationOnlyViaFactory: PublicationOnlyViaFactory(state); break; case LazyState.PublicationOnlyWait: PublicationOnlyWaitForOtherThreadToPublish(); break; case LazyState.ExecutionAndPublicationViaConstructor: ExecutionAndPublication(state, useDefaultConstructor: true); break; case LazyState.ExecutionAndPublicationViaFactory: ExecutionAndPublication(state, useDefaultConstructor: false); break; default: state.ThrowException(); break; } } return Value; } public override string? ToString() { if (!IsValueCreated) { return SR.Lazy_ToString_ValueNotCreated; } return Value.ToString(); } } internal sealed class LazyDebugView<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] T> { private readonly Lazy _lazy; public bool IsValueCreated => _lazy.IsValueCreated; public T Value => _lazy.ValueForDebugDisplay; public LazyThreadSafetyMode? Mode => _lazy.Mode; public bool IsValueFaulted => _lazy.IsValueFaulted; public LazyDebugView(Lazy lazy) { _lazy = lazy; } } public class Lazy<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] T, TMetadata> : Lazy { private readonly TMetadata _metadata; public TMetadata Metadata => _metadata; public Lazy(Func valueFactory, TMetadata metadata) : base(valueFactory) { _metadata = metadata; } public Lazy(TMetadata metadata) { _metadata = metadata; } public Lazy(TMetadata metadata, bool isThreadSafe) : base(isThreadSafe) { _metadata = metadata; } public Lazy(Func valueFactory, TMetadata metadata, bool isThreadSafe) : base(valueFactory, isThreadSafe) { _metadata = metadata; } public Lazy(TMetadata metadata, LazyThreadSafetyMode mode) : base(mode) { _metadata = metadata; } public Lazy(Func valueFactory, TMetadata metadata, LazyThreadSafetyMode mode) : base(valueFactory, mode) { _metadata = metadata; } } public enum LoaderOptimization { [Obsolete("LoaderOptimization.DisallowBindings has been deprecated and is not supported.")] DisallowBindings = 4, [Obsolete("LoaderOptimization.DomainMask has been deprecated and is not supported.")] DomainMask = 3, MultiDomain = 2, MultiDomainHost = 3, NotSpecified = 0, SingleDomain = 1 } [AttributeUsage(AttributeTargets.Method)] public sealed class LoaderOptimizationAttribute : Attribute { private readonly byte _val; public LoaderOptimization Value => (LoaderOptimization)_val; public LoaderOptimizationAttribute(byte value) { _val = value; } public LoaderOptimizationAttribute(LoaderOptimization value) { _val = (byte)value; } } internal static class LocalAppContextSwitches { private static int s_enableUnsafeUTF7Encoding; private static int s_enforceJapaneseEraYearRanges; private static int s_formatJapaneseFirstYearAsANumber; private static int s_enforceLegacyJapaneseDateParsing; private static int s_preserveEventListnerObjectIdentity; private static int s_serializationGuard; private static int s_showILOffset; public static bool EnableUnsafeUTF7Encoding { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return GetCachedSwitchValue("System.Text.Encoding.EnableUnsafeUTF7Encoding", ref s_enableUnsafeUTF7Encoding); } } public static bool EnforceJapaneseEraYearRanges { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return GetCachedSwitchValue("Switch.System.Globalization.EnforceJapaneseEraYearRanges", ref s_enforceJapaneseEraYearRanges); } } public static bool FormatJapaneseFirstYearAsANumber { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return GetCachedSwitchValue("Switch.System.Globalization.FormatJapaneseFirstYearAsANumber", ref s_formatJapaneseFirstYearAsANumber); } } public static bool EnforceLegacyJapaneseDateParsing { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return GetCachedSwitchValue("Switch.System.Globalization.EnforceLegacyJapaneseDateParsing", ref s_enforceLegacyJapaneseDateParsing); } } public static bool PreserveEventListnerObjectIdentity { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return GetCachedSwitchValue("Switch.System.Diagnostics.EventSource.PreserveEventListnerObjectIdentity", ref s_preserveEventListnerObjectIdentity); } } public static bool SerializationGuard { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return GetCachedSwitchValue("Switch.System.Runtime.Serialization.SerializationGuard", ref s_serializationGuard); } } public static bool ShowILOffsets { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return GetDefaultShowILOffsetSetting(); } } private static bool GetDefaultShowILOffsetSetting() { if (s_showILOffset < 0) { return false; } if (s_showILOffset > 0) { return true; } bool booleanConfig = AppContextConfigHelper.GetBooleanConfig("Switch.System.Diagnostics.StackTrace.ShowILOffsets", defaultValue: false); s_showILOffset = (booleanConfig ? 1 : (-1)); return booleanConfig; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool GetCachedSwitchValue(string switchName, ref int cachedSwitchValue) { if (cachedSwitchValue < 0) { return false; } if (cachedSwitchValue > 0) { return true; } return GetCachedSwitchValueInternal(switchName, ref cachedSwitchValue); } private static bool GetCachedSwitchValueInternal(string switchName, ref int cachedSwitchValue) { if (!AppContext.TryGetSwitch(switchName, out var isEnabled)) { isEnabled = GetSwitchDefaultValue(switchName); } AppContext.TryGetSwitch("TestSwitch.LocalAppContext.DisableCaching", out var isEnabled2); if (!isEnabled2) { cachedSwitchValue = (isEnabled ? 1 : (-1)); } return isEnabled; } private static bool GetSwitchDefaultValue(string switchName) { if (switchName == "Switch.System.Runtime.Serialization.SerializationGuard") { return true; } if (switchName == "System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization") { return true; } return false; } } public sealed class LocalDataStoreSlot { internal ThreadLocal Data { get; private set; } internal LocalDataStoreSlot(ThreadLocal data) { Data = data; GC.SuppressFinalize(this); } ~LocalDataStoreSlot() { } } [ClassInterface(ClassInterfaceType.AutoDispatch)] [ComVisible(true)] public abstract class MarshalByRefObject { [Obsolete("This Remoting API is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0010", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public object GetLifetimeService() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Remoting); } [Obsolete("This Remoting API is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0010", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public virtual object InitializeLifetimeService() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_Remoting); } protected MarshalByRefObject MemberwiseClone(bool cloneIdentity) { return (MarshalByRefObject)MemberwiseClone(); } } internal static class Marvin { public static ulong DefaultSeed { get; } = GenerateSeed(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ComputeHash32(ReadOnlySpan data, ulong seed) { return ComputeHash32(ref MemoryMarshal.GetReference(data), (uint)data.Length, (uint)seed, (uint)(seed >> 32)); } public static int ComputeHash32(ref byte data, uint count, uint p0, uint p1) { uint num; if (count < 8) { if (count < 4) { _ = BitConverter.IsLittleEndian; num = 128u; if ((count & (true ? 1u : 0u)) != 0) { num = Unsafe.AddByteOffset(ref data, (nuint)count & (nuint)2u); _ = BitConverter.IsLittleEndian; num |= 0x8000u; } if ((count & 2u) != 0) { _ = BitConverter.IsLittleEndian; num <<= 16; num |= Unsafe.ReadUnaligned(ref data); } goto IL_00a6; } } else { uint num2 = count / 8; do { p0 += Unsafe.ReadUnaligned(ref data); uint num3 = Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref data, 4u)); Block(ref p0, ref p1); p0 += num3; Block(ref p0, ref p1); data = ref Unsafe.AddByteOffset(ref data, 8u); } while (--num2 != 0); if ((count & 4) == 0) { goto IL_006a; } } p0 += Unsafe.ReadUnaligned(ref data); Block(ref p0, ref p1); goto IL_006a; IL_006a: num = Unsafe.ReadUnaligned(ref Unsafe.Add(ref Unsafe.AddByteOffset(ref data, (nuint)count & (nuint)7u), -4)); count = ~count << 3; _ = BitConverter.IsLittleEndian; num >>= 8; num |= 0x80000000u; num >>= (int)(count & 0x1F); goto IL_00a6; IL_00a6: p0 += num; Block(ref p0, ref p1); Block(ref p0, ref p1); return (int)(p1 ^ p0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void Block(ref uint rp0, ref uint rp1) { uint num = rp0; uint num2 = rp1; num2 ^= num; num = BitOperations.RotateLeft(num, 20); num += num2; num2 = BitOperations.RotateLeft(num2, 9); num2 ^= num; num = BitOperations.RotateLeft(num, 27); num += num2; num2 = BitOperations.RotateLeft(num2, 19); rp0 = num; rp1 = num2; } private unsafe static ulong GenerateSeed() { System.Runtime.CompilerServices.Unsafe.SkipInit(out ulong result); Interop.GetRandomBytes((byte*)(&result), 8); return result; } public static int ComputeHash32OrdinalIgnoreCase(ref char data, int count, uint p0, uint p1) { uint num = (uint)count; nuint num2 = 0u; while (true) { if (num >= 2) { uint value = Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.AddByteOffset(ref data, num2))); if (!Utf16Utility.AllCharsInUInt32AreAscii(value)) { break; } p0 += Utf16Utility.ConvertAllAsciiCharsInUInt32ToUppercase(value); Block(ref p0, ref p1); num2 += 4; num -= 2; continue; } if (num != 0) { uint value = Unsafe.AddByteOffset(ref data, num2); if (value > 127) { break; } _ = BitConverter.IsLittleEndian; p0 += Utf16Utility.ConvertAllAsciiCharsInUInt32ToUppercase(value) + 8388480; } _ = BitConverter.IsLittleEndian; p0 += 128; Block(ref p0, ref p1); Block(ref p0, ref p1); return (int)(p1 ^ p0); } return ComputeHash32OrdinalIgnoreCaseSlow(ref Unsafe.AddByteOffset(ref data, num2), (int)num, p0, p1); } private static int ComputeHash32OrdinalIgnoreCaseSlow(ref char data, int count, uint p0, uint p1) { char[] array = null; Span span = (((uint)count > 64u) ? ((Span)(array = ArrayPool.Shared.Rent(count))) : stackalloc char[64]); Span span2 = span; int num = Ordinal.ToUpperOrdinal(new ReadOnlySpan(ref data, count), span2); int result = ComputeHash32(ref Unsafe.As(ref MemoryMarshal.GetReference(span2)), (uint)(num * 2), p0, p1); if (array != null) { ArrayPool.Shared.Return(array); } return result; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class MemberAccessException : SystemException { public MemberAccessException() : base(SR.Arg_AccessException) { base.HResult = -2146233062; } public MemberAccessException(string? message) : base(message) { base.HResult = -2146233062; } public MemberAccessException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233062; } protected MemberAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [DebuggerTypeProxy(typeof(MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly struct Memory : IEquatable> { private readonly object _object; private readonly int _index; private readonly int _length; public static Memory Empty => default(Memory); public int Length => _length; public bool IsEmpty => _length == 0; public unsafe Span Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { ref T ptr = ref Unsafe.NullRef(); int length = 0; object @object = _object; if (@object != null) { if (typeof(T) == typeof(char) && @object.GetType() == typeof(string)) { ptr = ref Unsafe.As(ref Unsafe.As(@object).GetRawStringData()); length = Unsafe.As(@object).Length; } else if (RuntimeHelpers.ObjectHasComponentSize(@object)) { ptr = ref MemoryMarshal.GetArrayDataReference(Unsafe.As(@object)); length = Unsafe.As(@object).Length; } else { Span span = Unsafe.As>(@object).GetSpan(); ptr = ref MemoryMarshal.GetReference(span); length = span.Length; } nuint num = (uint)_index & 0x7FFFFFFFu; int length2 = _length; if ((uint)num > (uint)length || (uint)length2 > (uint)(length - (int)num)) { ThrowHelper.ThrowArgumentOutOfRangeException(); } ptr = ref Unsafe.Add(ref ptr, (IntPtr)(void*)num); length = length2; } return new Span(ref ptr, length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory(T[]? array) { if (array == null) { this = default(Memory); return; } if (!typeof(T).IsValueType && array.GetType() != typeof(T[])) { ThrowHelper.ThrowArrayTypeMismatchException(); } _object = array; _index = 0; _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(T[] array, int start) { if (array == null) { if (start != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Memory); return; } if (!typeof(T).IsValueType && array.GetType() != typeof(T[])) { ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length) { 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) { ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Memory); return; } if (!typeof(T).IsValueType && array.GetType() != typeof(T[])) { ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = array; _index = start; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager manager, int length) { if (length < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = manager; _index = 0; _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Memory(MemoryManager manager, int start, int length) { if (length < 0 || start < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(); } _object = manager; _index = start; _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[]? array) { return new Memory(array); } public static implicit operator Memory(ArraySegment segment) { return new Memory(segment.Array, segment.Offset, segment.Count); } public static implicit operator ReadOnlyMemory(Memory memory) { return Unsafe.As, ReadOnlyMemory>(ref memory); } public override string ToString() { if (typeof(T) == typeof(char)) { if (!(_object is string text)) { return Span.ToString(); } return text.Substring(_index, _length); } return $"System.Memory<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory Slice(int start) { if ((uint)start > (uint)_length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return new Memory(_object, _index + start, _length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Memory Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return new Memory(_object, _index + start, length); } public void CopyTo(Memory destination) { Span.CopyTo(destination.Span); } public bool TryCopyTo(Memory destination) { return Span.TryCopyTo(destination.Span); } public unsafe MemoryHandle Pin() { object @object = _object; if (@object != null) { if (typeof(T) == typeof(char) && @object is string text) { GCHandle handle = GCHandle.Alloc(@object, GCHandleType.Pinned); return new MemoryHandle(Unsafe.AsPointer(ref Unsafe.Add(ref text.GetRawStringData(), _index)), handle); } if (RuntimeHelpers.ObjectHasComponentSize(@object)) { if (_index < 0) { void* pointer = Unsafe.Add(Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(@object))), _index & 0x7FFFFFFF); return new MemoryHandle(pointer); } GCHandle handle2 = GCHandle.Alloc(@object, GCHandleType.Pinned); void* pointer2 = Unsafe.Add(Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(@object))), _index); return new MemoryHandle(pointer2, handle2); } return Unsafe.As>(@object).Pin(_index); } return default(MemoryHandle); } public T[] ToArray() { return Span.ToArray(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ReadOnlyMemory readOnlyMemory) { return readOnlyMemory.Equals(this); } if (obj is Memory other) { return Equals(other); } return false; } public bool Equals(Memory 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; } return HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length); } } internal sealed class MemoryDebugView { private readonly ReadOnlyMemory _memory; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _memory.ToArray(); public MemoryDebugView(Memory memory) { _memory = memory; } public MemoryDebugView(ReadOnlyMemory memory) { _memory = memory; } } public static class MemoryExtensions { [EditorBrowsable(EditorBrowsableState.Never)] [InterpolatedStringHandler] public ref struct TryWriteInterpolatedStringHandler { private readonly Span _destination; private readonly IFormatProvider _provider; internal int _pos; internal bool _success; private readonly bool _hasCustomFormatter; public TryWriteInterpolatedStringHandler(int literalLength, int formattedCount, Span destination, out bool shouldAppend) { _destination = destination; _provider = null; _pos = 0; _success = (shouldAppend = destination.Length >= literalLength); _hasCustomFormatter = false; } public TryWriteInterpolatedStringHandler(int literalLength, int formattedCount, Span destination, IFormatProvider? provider, out bool shouldAppend) { _destination = destination; _provider = provider; _pos = 0; _success = (shouldAppend = destination.Length >= literalLength); _hasCustomFormatter = provider != null && DefaultInterpolatedStringHandler.HasCustomFormatter(provider); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool AppendLiteral(string value) { if (value.Length == 1) { Span destination = _destination; int pos = _pos; if ((uint)pos < (uint)destination.Length) { destination[pos] = value[0]; _pos = pos + 1; return true; } return Fail(); } if (value.Length == 2) { Span destination2 = _destination; int pos2 = _pos; if ((uint)pos2 < destination2.Length - 1) { Unsafe.WriteUnaligned(ref Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetReference(destination2), pos2)), Unsafe.ReadUnaligned(ref Unsafe.As(ref value.GetRawStringData()))); _pos = pos2 + 2; return true; } return Fail(); } return AppendStringDirect(value); } private bool AppendStringDirect(string value) { if (value.TryCopyTo(_destination.Slice(_pos))) { _pos += value.Length; return true; } return Fail(); } public bool AppendFormatted(T value) { if (_hasCustomFormatter) { return AppendCustomFormatter(value, null); } string text; if (value is IFormattable) { if (value is ISpanFormattable) { if (((ISpanFormattable)(object)value).TryFormat(_destination.Slice(_pos), out var charsWritten, default(ReadOnlySpan), _provider)) { _pos += charsWritten; return true; } return Fail(); } text = ((IFormattable)(object)value).ToString(null, _provider); } else { text = value?.ToString(); } if (text != null) { return AppendStringDirect(text); } return true; } public bool AppendFormatted(T value, string? format) { if (_hasCustomFormatter) { return AppendCustomFormatter(value, format); } string text; if (value is IFormattable) { if (value is ISpanFormattable) { if (((ISpanFormattable)(object)value).TryFormat(_destination.Slice(_pos), out var charsWritten, format, _provider)) { _pos += charsWritten; return true; } return Fail(); } text = ((IFormattable)(object)value).ToString(format, _provider); } else { text = value?.ToString(); } if (text != null) { return AppendStringDirect(text); } return true; } public bool AppendFormatted(T value, int alignment) { int pos = _pos; if (AppendFormatted(value)) { if (alignment != 0) { return TryAppendOrInsertAlignmentIfNeeded(pos, alignment); } return true; } return Fail(); } public bool AppendFormatted(T value, int alignment, string? format) { int pos = _pos; if (AppendFormatted(value, format)) { if (alignment != 0) { return TryAppendOrInsertAlignmentIfNeeded(pos, alignment); } return true; } return Fail(); } public bool AppendFormatted(ReadOnlySpan value) { if (value.TryCopyTo(_destination.Slice(_pos))) { _pos += value.Length; return true; } return Fail(); } public bool AppendFormatted(ReadOnlySpan value, int alignment = 0, string? format = null) { bool flag = false; if (alignment < 0) { flag = true; alignment = -alignment; } int num = alignment - value.Length; if (num <= 0) { return AppendFormatted(value); } if (alignment <= _destination.Length - _pos) { if (flag) { value.CopyTo(_destination.Slice(_pos)); _pos += value.Length; _destination.Slice(_pos, num).Fill(' '); _pos += num; } else { _destination.Slice(_pos, num).Fill(' '); _pos += num; value.CopyTo(_destination.Slice(_pos)); _pos += value.Length; } return true; } return Fail(); } public bool AppendFormatted(string? value) { if (_hasCustomFormatter) { return AppendCustomFormatter(value, null); } if (value == null) { return true; } if (value.TryCopyTo(_destination.Slice(_pos))) { _pos += value.Length; return true; } return Fail(); } public bool AppendFormatted(string? value, int alignment = 0, string? format = null) { return this.AppendFormatted(value, alignment, format); } public bool AppendFormatted(object? value, int alignment = 0, string? format = null) { return this.AppendFormatted(value, alignment, format); } [MethodImpl(MethodImplOptions.NoInlining)] private bool AppendCustomFormatter(T value, string format) { ICustomFormatter customFormatter = (ICustomFormatter)_provider.GetFormat(typeof(ICustomFormatter)); if (customFormatter != null) { string text = customFormatter.Format(format, value, _provider); if (text != null) { return AppendStringDirect(text); } } return true; } private bool TryAppendOrInsertAlignmentIfNeeded(int startingPos, int alignment) { int num = _pos - startingPos; bool flag = false; if (alignment < 0) { flag = true; alignment = -alignment; } int num2 = alignment - num; if (num2 <= 0) { return true; } if (num2 <= _destination.Length - _pos) { if (flag) { _destination.Slice(_pos, num2).Fill(' '); } else { _destination.Slice(startingPos, num).CopyTo(_destination.Slice(startingPos + num2)); _destination.Slice(startingPos, num2).Fill(' '); } _pos += num2; return true; } return Fail(); } private bool Fail() { _success = false; return false; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this T[]? array, int start) { if (array == null) { if (start != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return default(Span); } if (!typeof(T).IsValueType && array.GetType() != typeof(T[])) { ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return new Span(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), (nint)(uint)start), array.Length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this T[]? array, Index startIndex) { if (array == null) { if (!startIndex.Equals(Index.Start)) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return default(Span); } if (!typeof(T).IsValueType && array.GetType() != typeof(T[])) { ThrowHelper.ThrowArrayTypeMismatchException(); } int offset = startIndex.GetOffset(array.Length); if ((uint)offset > (uint)array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return new Span(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), (nint)(uint)offset), array.Length - offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this T[]? array, Range range) { if (array == null) { Index start = range.Start; Index end = range.End; if (!start.Equals(Index.Start) || !end.Equals(Index.Start)) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return default(Span); } if (!typeof(T).IsValueType && array.GetType() != typeof(T[])) { ThrowHelper.ThrowArrayTypeMismatchException(); } var (num, length) = range.GetOffsetAndLength(array.Length); return new Span(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), (nint)(uint)num), length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan AsSpan(this string? text) { if (text == null) { return default(ReadOnlySpan); } return new ReadOnlySpan(ref text.GetRawStringData(), text.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan AsSpan(this string? text, int start) { if (text == null) { if (start != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return default(ReadOnlySpan); } if ((uint)start > (uint)text.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return new ReadOnlySpan(ref Unsafe.Add(ref text.GetRawStringData(), (nint)(uint)start), text.Length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan AsSpan(this string? text, int start, int length) { if (text == null) { if (start != 0 || length != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return default(ReadOnlySpan); } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return new ReadOnlySpan(ref Unsafe.Add(ref text.GetRawStringData(), (nint)(uint)start), length); } public static ReadOnlyMemory AsMemory(this string? text) { if (text == null) { return default(ReadOnlyMemory); } return new ReadOnlyMemory(text, 0, text.Length); } public static ReadOnlyMemory AsMemory(this string? text, int start) { if (text == null) { if (start != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return default(ReadOnlyMemory); } if ((uint)start > (uint)text.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return new ReadOnlyMemory(text, start, text.Length - start); } public static ReadOnlyMemory AsMemory(this string? text, Index startIndex) { if (text == null) { if (!startIndex.Equals(Index.Start)) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); } return default(ReadOnlyMemory); } int offset = startIndex.GetOffset(text.Length); if ((uint)offset > (uint)text.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return new ReadOnlyMemory(text, offset, text.Length - offset); } public static ReadOnlyMemory AsMemory(this string? text, int start, int length) { if (text == null) { if (start != 0 || length != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return default(ReadOnlyMemory); } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return new ReadOnlyMemory(text, start, length); } public static ReadOnlyMemory AsMemory(this string? text, Range range) { if (text == null) { Index start = range.Start; Index end = range.End; if (!start.Equals(Index.Start) || !end.Equals(Index.Start)) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text); } return default(ReadOnlyMemory); } var (start2, length) = range.GetOffsetAndLength(text.Length); return new ReadOnlyMemory(text, start2, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Contains(this Span span, T value) where T : IEquatable { if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { return SpanHelpers.Contains(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } if (Unsafe.SizeOf() == 2) { return SpanHelpers.Contains(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } } return SpanHelpers.Contains(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Contains(this ReadOnlySpan span, T value) where T : IEquatable { if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { return SpanHelpers.Contains(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } if (Unsafe.SizeOf() == 2) { return SpanHelpers.Contains(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } } return SpanHelpers.Contains(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this Span span, T value) where T : IEquatable { if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { return SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } if (Unsafe.SizeOf() == 2) { return SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } } return SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this Span span, ReadOnlySpan value) where T : IEquatable { if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { return SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(value)), value.Length); } if (Unsafe.SizeOf() == 2) { return SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(value)), value.Length); } } return SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf(this Span span, T value) where T : IEquatable { if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { return SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } if (Unsafe.SizeOf() == 2) { return SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } } return SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf(this Span span, ReadOnlySpan value) where T : IEquatable { if (Unsafe.SizeOf() == 1 && RuntimeHelpers.IsBitwiseEquatable()) { return SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(value)), value.Length); } return SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual(this Span span, ReadOnlySpan other) where T : IEquatable { int length = span.Length; if (RuntimeHelpers.IsBitwiseEquatable()) { nuint num = (nuint)Unsafe.SizeOf(); if (length == other.Length) { return SpanHelpers.SequenceEqual(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(ref MemoryMarshal.GetReference(other)), (uint)length * num); } return false; } if (length == other.Length) { return SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); } return false; } public static int SequenceCompareTo(this Span span, ReadOnlySpan other) where T : IComparable { if (typeof(T) == typeof(byte)) { return SpanHelpers.SequenceCompareTo(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return SpanHelpers.SequenceCompareTo(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(other)), other.Length); } return SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this ReadOnlySpan span, T value) where T : IEquatable { if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { return SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } if (Unsafe.SizeOf() == 2) { return SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } } return SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this ReadOnlySpan span, ReadOnlySpan value) where T : IEquatable { if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { return SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(value)), value.Length); } if (Unsafe.SizeOf() == 2) { return SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(value)), value.Length); } } return SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf(this ReadOnlySpan span, T value) where T : IEquatable { if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { return SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } if (Unsafe.SizeOf() == 2) { return SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value), span.Length); } } return SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), value, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf(this ReadOnlySpan span, ReadOnlySpan value) where T : IEquatable { if (Unsafe.SizeOf() == 1 && RuntimeHelpers.IsBitwiseEquatable()) { return SpanHelpers.LastIndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(value)), value.Length); } return SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this Span span, T value0, T value1) where T : IEquatable { if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { return SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); } if (Unsafe.SizeOf() == 2) { return SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); } } return SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this Span span, T value0, T value1, T value2) where T : IEquatable { if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { return SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); } if (Unsafe.SizeOf() == 2) { return SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); } } return SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this Span span, ReadOnlySpan values) where T : IEquatable { return ((ReadOnlySpan)span).IndexOfAny(values); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this ReadOnlySpan span, T value0, T value1) where T : IEquatable { if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { return SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); } if (Unsafe.SizeOf() == 2) { return SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); } } return SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this ReadOnlySpan span, T value0, T value1, T value2) where T : IEquatable { if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { return SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); } if (Unsafe.SizeOf() == 2) { return SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); } } return SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOfAny(this ReadOnlySpan span, ReadOnlySpan values) where T : IEquatable { if (RuntimeHelpers.IsBitwiseEquatable()) { if (Unsafe.SizeOf() == 1) { ref byte reference = ref Unsafe.As(ref MemoryMarshal.GetReference(values)); if (values.Length == 2) { return SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), reference, Unsafe.Add(ref reference, 1), span.Length); } if (values.Length == 3) { return SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), reference, Unsafe.Add(ref reference, 1), Unsafe.Add(ref reference, 2), span.Length); } } if (Unsafe.SizeOf() == 2) { ref char reference2 = ref Unsafe.As(ref MemoryMarshal.GetReference(values)); if (values.Length == 5) { return SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), reference2, Unsafe.Add(ref reference2, 1), Unsafe.Add(ref reference2, 2), Unsafe.Add(ref reference2, 3), Unsafe.Add(ref reference2, 4), span.Length); } if (values.Length == 2) { return SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), reference2, Unsafe.Add(ref reference2, 1), span.Length); } if (values.Length == 4) { return SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), reference2, Unsafe.Add(ref reference2, 1), Unsafe.Add(ref reference2, 2), Unsafe.Add(ref reference2, 3), span.Length); } if (values.Length == 3) { return SpanHelpers.IndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), reference2, Unsafe.Add(ref reference2, 1), Unsafe.Add(ref reference2, 2), span.Length); } if (values.Length == 1) { return SpanHelpers.IndexOf(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), reference2, span.Length); } } } return SpanHelpers.IndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny(this Span span, T value0, T value1) where T : IEquatable { if (Unsafe.SizeOf() == 1 && RuntimeHelpers.IsBitwiseEquatable()) { return SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); } return SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny(this Span span, T value0, T value1, T value2) where T : IEquatable { if (Unsafe.SizeOf() == 1 && RuntimeHelpers.IsBitwiseEquatable()) { return SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); } return SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny(this Span span, ReadOnlySpan values) where T : IEquatable { if (Unsafe.SizeOf() == 1 && RuntimeHelpers.IsBitwiseEquatable()) { return SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(values)), values.Length); } return SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny(this ReadOnlySpan span, T value0, T value1) where T : IEquatable { if (Unsafe.SizeOf() == 1 && RuntimeHelpers.IsBitwiseEquatable()) { return SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), span.Length); } return SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny(this ReadOnlySpan span, T value0, T value1, T value2) where T : IEquatable { if (Unsafe.SizeOf() == 1 && RuntimeHelpers.IsBitwiseEquatable()) { return SpanHelpers.LastIndexOfAny(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), Unsafe.As(ref value0), Unsafe.As(ref value1), Unsafe.As(ref value2), span.Length); } return SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), value0, value1, value2, span.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOfAny(this ReadOnlySpan span, ReadOnlySpan values) where T : IEquatable { return SpanHelpers.LastIndexOfAny(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(values), values.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool SequenceEqual(this ReadOnlySpan span, ReadOnlySpan other) where T : IEquatable { int length = span.Length; if (RuntimeHelpers.IsBitwiseEquatable()) { nuint num = (nuint)Unsafe.SizeOf(); if (length == other.Length) { return SpanHelpers.SequenceEqual(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(ref MemoryMarshal.GetReference(other)), (uint)length * num); } return false; } if (length == other.Length) { return SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other), length); } return false; } public static bool SequenceEqual(this Span span, ReadOnlySpan other, IEqualityComparer? comparer = null) { return ((ReadOnlySpan)span).SequenceEqual(other, comparer); } public static bool SequenceEqual(this ReadOnlySpan span, ReadOnlySpan other, IEqualityComparer? comparer = null) { if (span.Length != other.Length) { return false; } if (typeof(T).IsValueType && (comparer == null || comparer == EqualityComparer.Default)) { if (RuntimeHelpers.IsBitwiseEquatable()) { nuint num = (nuint)Unsafe.SizeOf(); return SpanHelpers.SequenceEqual(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(ref MemoryMarshal.GetReference(other)), (uint)span.Length * num); } for (int i = 0; i < span.Length; i++) { if (!EqualityComparer.Default.Equals(span[i], other[i])) { return false; } } return true; } if (comparer == null) { comparer = EqualityComparer.Default; } for (int j = 0; j < span.Length; j++) { if (!comparer.Equals(span[j], other[j])) { return false; } } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int SequenceCompareTo(this ReadOnlySpan span, ReadOnlySpan other) where T : IComparable { if (typeof(T) == typeof(byte)) { return SpanHelpers.SequenceCompareTo(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(other)), other.Length); } if (typeof(T) == typeof(char)) { return SpanHelpers.SequenceCompareTo(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), span.Length, ref Unsafe.As(ref MemoryMarshal.GetReference(other)), other.Length); } return SpanHelpers.SequenceCompareTo(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith(this Span span, ReadOnlySpan value) where T : IEquatable { int length = value.Length; if (RuntimeHelpers.IsBitwiseEquatable()) { nuint num = (nuint)Unsafe.SizeOf(); if (length <= span.Length) { return SpanHelpers.SequenceEqual(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(ref MemoryMarshal.GetReference(value)), (uint)length * num); } return false; } if (length <= span.Length) { return SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith(this ReadOnlySpan span, ReadOnlySpan value) where T : IEquatable { int length = value.Length; if (RuntimeHelpers.IsBitwiseEquatable()) { nuint num = (nuint)Unsafe.SizeOf(); if (length <= span.Length) { return SpanHelpers.SequenceEqual(ref Unsafe.As(ref MemoryMarshal.GetReference(span)), ref Unsafe.As(ref MemoryMarshal.GetReference(value)), (uint)length * num); } return false; } if (length <= span.Length) { return SpanHelpers.SequenceEqual(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), length); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EndsWith(this Span span, ReadOnlySpan value) where T : IEquatable { int length = span.Length; int length2 = value.Length; if (RuntimeHelpers.IsBitwiseEquatable()) { nuint num = (nuint)Unsafe.SizeOf(); if (length2 <= length) { return SpanHelpers.SequenceEqual(ref Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), (nint)(uint)(length - length2))), ref Unsafe.As(ref MemoryMarshal.GetReference(value)), (uint)length2 * num); } return false; } if (length2 <= length) { return SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), (nint)(uint)(length - length2)), ref MemoryMarshal.GetReference(value), length2); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EndsWith(this ReadOnlySpan span, ReadOnlySpan value) where T : IEquatable { int length = span.Length; int length2 = value.Length; if (RuntimeHelpers.IsBitwiseEquatable()) { nuint num = (nuint)Unsafe.SizeOf(); if (length2 <= length) { return SpanHelpers.SequenceEqual(ref Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), (nint)(uint)(length - length2))), ref Unsafe.As(ref MemoryMarshal.GetReference(value)), (uint)length2 * num); } return false; } if (length2 <= length) { return SpanHelpers.SequenceEqual(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), (nint)(uint)(length - length2)), ref MemoryMarshal.GetReference(value), length2); } return false; } public static void Reverse(this Span span) { if (span.Length > 1) { ref T reference = ref MemoryMarshal.GetReference(span); ref T reference2 = ref Unsafe.Add(ref Unsafe.Add(ref reference, span.Length), -1); do { T val = reference; reference = reference2; reference2 = val; reference = ref Unsafe.Add(ref reference, 1); reference2 = ref Unsafe.Add(ref reference2, -1); } while (Unsafe.IsAddressLessThan(ref reference, ref reference2)); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this T[]? array) { return new Span(array); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this T[]? array, int start, int length) { return new Span(array, start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this ArraySegment segment) { return new Span(segment.Array, segment.Offset, segment.Count); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this ArraySegment segment, int start) { if ((uint)start > (uint)segment.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return new Span(segment.Array, segment.Offset + start, segment.Count - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this ArraySegment segment, Index startIndex) { int offset = startIndex.GetOffset(segment.Count); return segment.AsSpan(offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this ArraySegment segment, int start, int length) { if ((uint)start > (uint)segment.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } if ((uint)length > (uint)(segment.Count - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); } return new Span(segment.Array, segment.Offset + start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsSpan(this ArraySegment segment, Range range) { var (num, length) = range.GetOffsetAndLength(segment.Count); return new Span(segment.Array, segment.Offset + num, length); } public static Memory AsMemory(this T[]? array) { return new Memory(array); } public static Memory AsMemory(this T[]? array, int start) { return new Memory(array, start); } public static Memory AsMemory(this T[]? array, Index startIndex) { if (array == null) { if (!startIndex.Equals(Index.Start)) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return default(Memory); } int offset = startIndex.GetOffset(array.Length); return new Memory(array, offset); } public static Memory AsMemory(this T[]? array, int start, int length) { return new Memory(array, start, length); } public static Memory AsMemory(this T[]? array, Range range) { if (array == null) { Index start = range.Start; Index end = range.End; if (!start.Equals(Index.Start) || !end.Equals(Index.Start)) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } return default(Memory); } var (start2, length) = range.GetOffsetAndLength(array.Length); return new Memory(array, start2, length); } public static Memory AsMemory(this ArraySegment segment) { return new Memory(segment.Array, segment.Offset, segment.Count); } public static Memory AsMemory(this ArraySegment segment, int start) { if ((uint)start > (uint)segment.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return new Memory(segment.Array, segment.Offset + start, segment.Count - start); } public static Memory AsMemory(this ArraySegment segment, int start, int length) { if ((uint)start > (uint)segment.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } if ((uint)length > (uint)(segment.Count - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); } return new Memory(segment.Array, segment.Offset + start, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo(this T[]? source, Span destination) { new ReadOnlySpan(source).CopyTo(destination); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void CopyTo(this T[]? source, Memory destination) { source.CopyTo(destination.Span); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Overlaps(this Span span, ReadOnlySpan other) { return ((ReadOnlySpan)span).Overlaps(other); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Overlaps(this Span span, ReadOnlySpan other, out int elementOffset) { return ((ReadOnlySpan)span).Overlaps(other, out elementOffset); } public static bool Overlaps(this ReadOnlySpan span, ReadOnlySpan other) { if (span.IsEmpty || other.IsEmpty) { return false; } IntPtr intPtr = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (Unsafe.SizeOf() == 4) { if ((uint)(int)intPtr >= (uint)(span.Length * Unsafe.SizeOf())) { return (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf())); } return true; } if ((ulong)(long)intPtr >= (ulong)((long)span.Length * (long)Unsafe.SizeOf())) { return (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf())); } return true; } public static bool Overlaps(this ReadOnlySpan span, ReadOnlySpan other, out int elementOffset) { if (span.IsEmpty || other.IsEmpty) { elementOffset = 0; return false; } IntPtr intPtr = Unsafe.ByteOffset(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(other)); if (Unsafe.SizeOf() == 4) { if ((uint)(int)intPtr < (uint)(span.Length * Unsafe.SizeOf()) || (uint)(int)intPtr > (uint)(-(other.Length * Unsafe.SizeOf()))) { if ((int)intPtr % Unsafe.SizeOf() != 0) { ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)intPtr / Unsafe.SizeOf(); return true; } elementOffset = 0; return false; } if ((ulong)(long)intPtr < (ulong)((long)span.Length * (long)Unsafe.SizeOf()) || (ulong)(long)intPtr > (ulong)(-((long)other.Length * (long)Unsafe.SizeOf()))) { if ((long)intPtr % Unsafe.SizeOf() != 0L) { ThrowHelper.ThrowArgumentException_OverlapAlignmentMismatch(); } elementOffset = (int)((long)intPtr / Unsafe.SizeOf()); return true; } elementOffset = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch(this Span span, IComparable comparable) { return span.BinarySearch>(comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch(this Span span, TComparable comparable) where TComparable : IComparable { return BinarySearch((ReadOnlySpan)span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch(this Span span, T value, TComparer comparer) where TComparer : IComparer { return ((ReadOnlySpan)span).BinarySearch(value, comparer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch(this ReadOnlySpan span, IComparable comparable) { return MemoryExtensions.BinarySearch>(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch(this ReadOnlySpan span, TComparable comparable) where TComparable : IComparable { return SpanHelpers.BinarySearch(span, comparable); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch(this ReadOnlySpan span, T value, TComparer comparer) where TComparer : IComparer { if (comparer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer); } SpanHelpers.ComparerComparable comparable = new SpanHelpers.ComparerComparable(value, comparer); return BinarySearch(span, comparable); } public static void Sort(this Span span) { span.Sort((IComparer)null); } public static void Sort(this Span span, TComparer comparer) where TComparer : IComparer? { if (span.Length > 1) { ArraySortHelper.Default.Sort(span, comparer); } } public static void Sort(this Span span, Comparison comparison) { if (comparison == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } if (span.Length > 1) { ArraySortHelper.Sort(span, comparison); } } public static void Sort(this Span keys, Span items) { keys.Sort>(items, null); } public static void Sort(this Span keys, Span items, TComparer comparer) where TComparer : IComparer? { if (keys.Length != items.Length) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_SpansMustHaveSameLength); } if (keys.Length > 1) { ArraySortHelper.Default.Sort(keys, items, comparer); } } public static void Sort(this Span keys, Span items, Comparison comparison) { if (comparison == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparison); } if (keys.Length != items.Length) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_SpansMustHaveSameLength); } if (keys.Length > 1) { ArraySortHelper.Default.Sort(keys, items, new ComparisonComparer(comparison)); } } public static bool TryWrite(this Span destination, [InterpolatedStringHandlerArgument("destination")] ref TryWriteInterpolatedStringHandler handler, out int charsWritten) { if (handler._success) { charsWritten = handler._pos; return true; } charsWritten = 0; return false; } public static bool TryWrite(this Span destination, IFormatProvider? provider, [InterpolatedStringHandlerArgument(new string[] { "destination", "provider" })] ref TryWriteInterpolatedStringHandler handler, out int charsWritten) { return destination.TryWrite(ref handler, out charsWritten); } public static bool IsWhiteSpace(this ReadOnlySpan span) { for (int i = 0; i < span.Length; i++) { if (!char.IsWhiteSpace(span[i])) { return false; } } return true; } public static bool Contains(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) { return span.IndexOf(value, comparisonType) >= 0; } public static bool Equals(this ReadOnlySpan span, ReadOnlySpan other, StringComparison comparisonType) { string.CheckStringComparison(comparisonType); switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.Compare(span, other, string.GetCaseCompareOfComparisonCulture(comparisonType)) == 0; case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.Compare(span, other, string.GetCaseCompareOfComparisonCulture(comparisonType)) == 0; case StringComparison.Ordinal: return span.EqualsOrdinal(other); default: return span.EqualsOrdinalIgnoreCase(other); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool EqualsOrdinal(this ReadOnlySpan span, ReadOnlySpan value) { if (span.Length != value.Length) { return false; } if (value.Length == 0) { return true; } return span.SequenceEqual(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool EqualsOrdinalIgnoreCase(this ReadOnlySpan span, ReadOnlySpan value) { if (span.Length != value.Length) { return false; } if (value.Length == 0) { return true; } return Ordinal.EqualsIgnoreCase(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), span.Length); } public static int CompareTo(this ReadOnlySpan span, ReadOnlySpan other, StringComparison comparisonType) { string.CheckStringComparison(comparisonType); switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.Compare(span, other, string.GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.Compare(span, other, string.GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: if (span.Length == 0 || other.Length == 0) { return span.Length - other.Length; } return string.CompareOrdinal(span, other); default: return Ordinal.CompareStringIgnoreCase(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(other), other.Length); } } public static int IndexOf(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) { string.CheckStringComparison(comparisonType); switch (comparisonType) { case StringComparison.Ordinal: return SpanHelpers.IndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); default: return Ordinal.IndexOfOrdinalIgnoreCase(span, value); } } public static int LastIndexOf(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) { string.CheckStringComparison(comparisonType); switch (comparisonType) { case StringComparison.Ordinal: return SpanHelpers.LastIndexOf(ref MemoryMarshal.GetReference(span), span.Length, ref MemoryMarshal.GetReference(value), value.Length); case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.LastIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); default: return Ordinal.LastIndexOfOrdinalIgnoreCase(span, value); } } public static int ToLower(this ReadOnlySpan source, Span destination, CultureInfo? culture) { if (source.Overlaps(destination)) { throw new InvalidOperationException(SR.InvalidOperation_SpanOverlappedOperation); } if (culture == null) { culture = CultureInfo.CurrentCulture; } if (destination.Length < source.Length) { return -1; } if (GlobalizationMode.Invariant) { InvariantModeCasing.ToLower(source, destination); } else { culture.TextInfo.ChangeCaseToLower(source, destination); } return source.Length; } public static int ToLowerInvariant(this ReadOnlySpan source, Span destination) { if (source.Overlaps(destination)) { throw new InvalidOperationException(SR.InvalidOperation_SpanOverlappedOperation); } if (destination.Length < source.Length) { return -1; } if (GlobalizationMode.Invariant) { InvariantModeCasing.ToLower(source, destination); } else { TextInfo.Invariant.ChangeCaseToLower(source, destination); } return source.Length; } public static int ToUpper(this ReadOnlySpan source, Span destination, CultureInfo? culture) { if (source.Overlaps(destination)) { throw new InvalidOperationException(SR.InvalidOperation_SpanOverlappedOperation); } if (culture == null) { culture = CultureInfo.CurrentCulture; } if (destination.Length < source.Length) { return -1; } if (GlobalizationMode.Invariant) { InvariantModeCasing.ToUpper(source, destination); } else { culture.TextInfo.ChangeCaseToUpper(source, destination); } return source.Length; } public static int ToUpperInvariant(this ReadOnlySpan source, Span destination) { if (source.Overlaps(destination)) { throw new InvalidOperationException(SR.InvalidOperation_SpanOverlappedOperation); } if (destination.Length < source.Length) { return -1; } if (GlobalizationMode.Invariant) { InvariantModeCasing.ToUpper(source, destination); } else { TextInfo.Invariant.ChangeCaseToUpper(source, destination); } return source.Length; } public static bool EndsWith(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) { string.CheckStringComparison(comparisonType); switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IsSuffix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IsSuffix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: return span.EndsWith(value); default: return span.EndsWithOrdinalIgnoreCase(value); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool EndsWithOrdinalIgnoreCase(this ReadOnlySpan span, ReadOnlySpan value) { if (value.Length <= span.Length) { return Ordinal.EqualsIgnoreCase(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), span.Length - value.Length), ref MemoryMarshal.GetReference(value), value.Length); } return false; } public static bool StartsWith(this ReadOnlySpan span, ReadOnlySpan value, StringComparison comparisonType) { string.CheckStringComparison(comparisonType); switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IsPrefix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IsPrefix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.Ordinal: return span.StartsWith(value); default: return span.StartsWithOrdinalIgnoreCase(value); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool StartsWithOrdinalIgnoreCase(this ReadOnlySpan span, ReadOnlySpan value) { if (value.Length <= span.Length) { return Ordinal.EqualsIgnoreCase(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), value.Length); } return false; } public static SpanRuneEnumerator EnumerateRunes(this ReadOnlySpan span) { return new SpanRuneEnumerator(span); } public static SpanRuneEnumerator EnumerateRunes(this Span span) { return new SpanRuneEnumerator(span); } public static SpanLineEnumerator EnumerateLines(this ReadOnlySpan span) { return new SpanLineEnumerator(span); } public static SpanLineEnumerator EnumerateLines(this Span span) { return new SpanLineEnumerator(span); } public static Memory Trim(this Memory memory, T trimElement) where T : IEquatable { ReadOnlySpan span = memory.Span; int start = ClampStart(span, trimElement); int length = ClampEnd(span, start, trimElement); return memory.Slice(start, length); } public static Memory TrimStart(this Memory memory, T trimElement) where T : IEquatable { return memory.Slice(ClampStart(memory.Span, trimElement)); } public static Memory TrimEnd(this Memory memory, T trimElement) where T : IEquatable { return memory.Slice(0, ClampEnd(memory.Span, 0, trimElement)); } public static ReadOnlyMemory Trim(this ReadOnlyMemory memory, T trimElement) where T : IEquatable { ReadOnlySpan span = memory.Span; int start = ClampStart(span, trimElement); int length = ClampEnd(span, start, trimElement); return memory.Slice(start, length); } public static ReadOnlyMemory TrimStart(this ReadOnlyMemory memory, T trimElement) where T : IEquatable { return memory.Slice(ClampStart(memory.Span, trimElement)); } public static ReadOnlyMemory TrimEnd(this ReadOnlyMemory memory, T trimElement) where T : IEquatable { return memory.Slice(0, ClampEnd(memory.Span, 0, trimElement)); } public static Span Trim(this Span span, T trimElement) where T : IEquatable { int start = ClampStart(span, trimElement); int length = ClampEnd(span, start, trimElement); return span.Slice(start, length); } public static Span TrimStart(this Span span, T trimElement) where T : IEquatable { return span.Slice(ClampStart(span, trimElement)); } public static Span TrimEnd(this Span span, T trimElement) where T : IEquatable { return span.Slice(0, ClampEnd(span, 0, trimElement)); } public static ReadOnlySpan Trim(this ReadOnlySpan span, T trimElement) where T : IEquatable { int start = ClampStart(span, trimElement); int length = ClampEnd(span, start, trimElement); return span.Slice(start, length); } public static ReadOnlySpan TrimStart(this ReadOnlySpan span, T trimElement) where T : IEquatable { return span.Slice(ClampStart(span, trimElement)); } public static ReadOnlySpan TrimEnd(this ReadOnlySpan span, T trimElement) where T : IEquatable { return span.Slice(0, ClampEnd(span, 0, trimElement)); } private static int ClampStart(ReadOnlySpan span, T trimElement) where T : IEquatable { int i = 0; if (trimElement != null) { for (; i < span.Length && trimElement.Equals(span[i]); i++) { } } else { for (; i < span.Length && span[i] == null; i++) { } } return i; } private static int ClampEnd(ReadOnlySpan span, int start, T trimElement) where T : IEquatable { int num = span.Length - 1; if (trimElement != null) { while (num >= start && trimElement.Equals(span[num])) { num--; } } else { while (num >= start && span[num] == null) { num--; } } return num - start + 1; } public static Memory Trim(this Memory memory, ReadOnlySpan trimElements) where T : IEquatable { if (trimElements.Length > 1) { ReadOnlySpan span = memory.Span; int start = ClampStart(span, trimElements); int length = ClampEnd(span, start, trimElements); return memory.Slice(start, length); } if (trimElements.Length == 1) { return memory.Trim(trimElements[0]); } return memory; } public static Memory TrimStart(this Memory memory, ReadOnlySpan trimElements) where T : IEquatable { if (trimElements.Length > 1) { return memory.Slice(ClampStart(memory.Span, trimElements)); } if (trimElements.Length == 1) { return memory.TrimStart(trimElements[0]); } return memory; } public static Memory TrimEnd(this Memory memory, ReadOnlySpan trimElements) where T : IEquatable { if (trimElements.Length > 1) { return memory.Slice(0, ClampEnd(memory.Span, 0, trimElements)); } if (trimElements.Length == 1) { return memory.TrimEnd(trimElements[0]); } return memory; } public static ReadOnlyMemory Trim(this ReadOnlyMemory memory, ReadOnlySpan trimElements) where T : IEquatable { if (trimElements.Length > 1) { ReadOnlySpan span = memory.Span; int start = ClampStart(span, trimElements); int length = ClampEnd(span, start, trimElements); return memory.Slice(start, length); } if (trimElements.Length == 1) { return memory.Trim(trimElements[0]); } return memory; } public static ReadOnlyMemory TrimStart(this ReadOnlyMemory memory, ReadOnlySpan trimElements) where T : IEquatable { if (trimElements.Length > 1) { return memory.Slice(ClampStart(memory.Span, trimElements)); } if (trimElements.Length == 1) { return memory.TrimStart(trimElements[0]); } return memory; } public static ReadOnlyMemory TrimEnd(this ReadOnlyMemory memory, ReadOnlySpan trimElements) where T : IEquatable { if (trimElements.Length > 1) { return memory.Slice(0, ClampEnd(memory.Span, 0, trimElements)); } if (trimElements.Length == 1) { return memory.TrimEnd(trimElements[0]); } return memory; } public static Span Trim(this Span span, ReadOnlySpan trimElements) where T : IEquatable { if (trimElements.Length > 1) { int start = ClampStart(span, trimElements); int length = ClampEnd(span, start, trimElements); return span.Slice(start, length); } if (trimElements.Length == 1) { return span.Trim(trimElements[0]); } return span; } public static Span TrimStart(this Span span, ReadOnlySpan trimElements) where T : IEquatable { if (trimElements.Length > 1) { return span.Slice(ClampStart(span, trimElements)); } if (trimElements.Length == 1) { return span.TrimStart(trimElements[0]); } return span; } public static Span TrimEnd(this Span span, ReadOnlySpan trimElements) where T : IEquatable { if (trimElements.Length > 1) { return span.Slice(0, ClampEnd(span, 0, trimElements)); } if (trimElements.Length == 1) { return span.TrimEnd(trimElements[0]); } return span; } public static ReadOnlySpan Trim(this ReadOnlySpan span, ReadOnlySpan trimElements) where T : IEquatable { if (trimElements.Length > 1) { int start = ClampStart(span, trimElements); int length = ClampEnd(span, start, trimElements); return span.Slice(start, length); } if (trimElements.Length == 1) { return span.Trim(trimElements[0]); } return span; } public static ReadOnlySpan TrimStart(this ReadOnlySpan span, ReadOnlySpan trimElements) where T : IEquatable { if (trimElements.Length > 1) { return span.Slice(ClampStart(span, trimElements)); } if (trimElements.Length == 1) { return span.TrimStart(trimElements[0]); } return span; } public static ReadOnlySpan TrimEnd(this ReadOnlySpan span, ReadOnlySpan trimElements) where T : IEquatable { if (trimElements.Length > 1) { return span.Slice(0, ClampEnd(span, 0, trimElements)); } if (trimElements.Length == 1) { return span.TrimEnd(trimElements[0]); } return span; } private static int ClampStart(ReadOnlySpan span, ReadOnlySpan trimElements) where T : IEquatable { int i; for (i = 0; i < span.Length && trimElements.Contains(span[i]); i++) { } return i; } private static int ClampEnd(ReadOnlySpan span, int start, ReadOnlySpan trimElements) where T : IEquatable { int num = span.Length - 1; while (num >= start && trimElements.Contains(span[num])) { num--; } return num - start + 1; } public static Memory Trim(this Memory memory) { ReadOnlySpan span = memory.Span; int start = ClampStart(span); int length = ClampEnd(span, start); return memory.Slice(start, length); } public static Memory TrimStart(this Memory memory) { return memory.Slice(ClampStart(memory.Span)); } public static Memory TrimEnd(this Memory memory) { return memory.Slice(0, ClampEnd(memory.Span, 0)); } public static ReadOnlyMemory Trim(this ReadOnlyMemory memory) { ReadOnlySpan span = memory.Span; int start = ClampStart(span); int length = ClampEnd(span, start); return memory.Slice(start, length); } public static ReadOnlyMemory TrimStart(this ReadOnlyMemory memory) { return memory.Slice(ClampStart(memory.Span)); } public static ReadOnlyMemory TrimEnd(this ReadOnlyMemory memory) { return memory.Slice(0, ClampEnd(memory.Span, 0)); } public static ReadOnlySpan Trim(this ReadOnlySpan span) { int i; for (i = 0; i < span.Length && char.IsWhiteSpace(span[i]); i++) { } int num = span.Length - 1; while (num > i && char.IsWhiteSpace(span[num])) { num--; } return span.Slice(i, num - i + 1); } public static ReadOnlySpan TrimStart(this ReadOnlySpan span) { int i; for (i = 0; i < span.Length && char.IsWhiteSpace(span[i]); i++) { } return span.Slice(i); } public static ReadOnlySpan TrimEnd(this ReadOnlySpan span) { int num = span.Length - 1; while (num >= 0 && char.IsWhiteSpace(span[num])) { num--; } return span.Slice(0, num + 1); } public static ReadOnlySpan Trim(this ReadOnlySpan span, char trimChar) { int i; for (i = 0; i < span.Length && span[i] == trimChar; i++) { } int num = span.Length - 1; while (num > i && span[num] == trimChar) { num--; } return span.Slice(i, num - i + 1); } public static ReadOnlySpan TrimStart(this ReadOnlySpan span, char trimChar) { int i; for (i = 0; i < span.Length && span[i] == trimChar; i++) { } return span.Slice(i); } public static ReadOnlySpan TrimEnd(this ReadOnlySpan span, char trimChar) { int num = span.Length - 1; while (num >= 0 && span[num] == trimChar) { num--; } return span.Slice(0, num + 1); } public static ReadOnlySpan Trim(this ReadOnlySpan span, ReadOnlySpan trimChars) { return span.TrimStart(trimChars).TrimEnd(trimChars); } public static ReadOnlySpan TrimStart(this ReadOnlySpan span, ReadOnlySpan 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 TrimEnd(this ReadOnlySpan span, ReadOnlySpan 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 Span Trim(this Span span) { int start = ClampStart(span); int length = ClampEnd(span, start); return span.Slice(start, length); } public static Span TrimStart(this Span span) { return span.Slice(ClampStart(span)); } public static Span TrimEnd(this Span span) { return span.Slice(0, ClampEnd(span, 0)); } private static int ClampStart(ReadOnlySpan span) { int i; for (i = 0; i < span.Length && char.IsWhiteSpace(span[i]); i++) { } return i; } private static int ClampEnd(ReadOnlySpan span, int start) { int num = span.Length - 1; while (num >= start && char.IsWhiteSpace(span[num])) { num--; } return num - start + 1; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class MethodAccessException : MemberAccessException { public MethodAccessException() : base(SR.Arg_MethodAccessException) { base.HResult = -2146233072; } public MethodAccessException(string? message) : base(message) { base.HResult = -2146233072; } public MethodAccessException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233072; } protected MethodAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public enum MidpointRounding { ToEven, AwayFromZero, ToZero, ToNegativeInfinity, ToPositiveInfinity } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class MissingFieldException : MissingMemberException, ISerializable { public override string Message { get { if (ClassName == null) { return base.Message; } return SR.Format(SR.MissingField_Name, ((Signature != null) ? (MissingMemberException.FormatSignature(Signature) + " ") : "") + ClassName + "." + MemberName); } } public MissingFieldException() : base(SR.Arg_MissingFieldException) { base.HResult = -2146233071; } public MissingFieldException(string? message) : base(message) { base.HResult = -2146233071; } public MissingFieldException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233071; } public MissingFieldException(string? className, string? fieldName) { ClassName = className; MemberName = fieldName; } protected MissingFieldException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class MissingMethodException : MissingMemberException { public override string Message { get { if (ClassName != null) { return SR.Format(SR.MissingMethod_Name, ClassName + "." + MemberName + ((Signature != null) ? (" " + MissingMemberException.FormatSignature(Signature)) : string.Empty)); } return base.Message; } } public MissingMethodException() : base(SR.Arg_MissingMethodException) { base.HResult = -2146233069; } public MissingMethodException(string? message) : base(message) { base.HResult = -2146233069; } public MissingMethodException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233069; } public MissingMethodException(string? className, string? methodName) { ClassName = className; MemberName = methodName; } protected MissingMethodException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class MulticastNotSupportedException : SystemException { public MulticastNotSupportedException() : base(SR.Arg_MulticastNotSupportedException) { base.HResult = -2146233068; } public MulticastNotSupportedException(string? message) : base(message) { base.HResult = -2146233068; } public MulticastNotSupportedException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233068; } private MulticastNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [AttributeUsage(AttributeTargets.Field, Inherited = false)] public sealed class NonSerializedAttribute : Attribute { } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class NotFiniteNumberException : ArithmeticException { private readonly double _offendingNumber; public double OffendingNumber => _offendingNumber; public NotFiniteNumberException() : base(SR.Arg_NotFiniteNumberException) { _offendingNumber = 0.0; base.HResult = -2146233048; } public NotFiniteNumberException(double offendingNumber) { _offendingNumber = offendingNumber; base.HResult = -2146233048; } public NotFiniteNumberException(string? message) : base(message) { _offendingNumber = 0.0; base.HResult = -2146233048; } public NotFiniteNumberException(string? message, double offendingNumber) : base(message) { _offendingNumber = offendingNumber; base.HResult = -2146233048; } public NotFiniteNumberException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233048; } public NotFiniteNumberException(string? message, double offendingNumber, Exception? innerException) : base(message, innerException) { _offendingNumber = offendingNumber; base.HResult = -2146233048; } protected NotFiniteNumberException(SerializationInfo info, StreamingContext context) : base(info, context) { _offendingNumber = info.GetDouble("OffendingNumber"); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("OffendingNumber", _offendingNumber, typeof(double)); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class NotImplementedException : SystemException { public NotImplementedException() : base(SR.Arg_NotImplementedException) { base.HResult = -2147467263; } public NotImplementedException(string? message) : base(message) { base.HResult = -2147467263; } public NotImplementedException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2147467263; } protected NotImplementedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class NotSupportedException : SystemException { public NotSupportedException() : base(SR.Arg_NotSupportedException) { base.HResult = -2146233067; } public NotSupportedException(string? message) : base(message) { base.HResult = -2146233067; } public NotSupportedException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233067; } protected NotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [NonVersionable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct Nullable where T : struct { private readonly bool hasValue; internal T value; public readonly bool HasValue { [NonVersionable] get { return hasValue; } } public readonly T Value { get { if (!hasValue) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_NoValue(); } return value; } } [NonVersionable] public Nullable(T value) { this.value = value; hasValue = true; } [NonVersionable] public readonly T GetValueOrDefault() { return value; } [NonVersionable] public readonly T GetValueOrDefault(T defaultValue) { if (!hasValue) { return defaultValue; } return value; } public override bool Equals(object? other) { if (!hasValue) { return other == null; } if (other == null) { return false; } return value.Equals(other); } public override int GetHashCode() { if (!hasValue) { return 0; } return value.GetHashCode(); } public override string? ToString() { if (!hasValue) { return ""; } return value.ToString(); } [NonVersionable] public static implicit operator T?(T value) { return value; } [NonVersionable] public static explicit operator T(T? value) { return value.Value; } } public static class Nullable { public static int Compare(T? n1, T? n2) where T : struct { if (n1.HasValue) { if (n2.HasValue) { return Comparer.Default.Compare(n1.value, n2.value); } return 1; } if (n2.HasValue) { return -1; } return 0; } public static bool Equals(T? n1, T? n2) where T : struct { if (n1.HasValue) { if (n2.HasValue) { return EqualityComparer.Default.Equals(n1.value, n2.value); } return false; } if (n2.HasValue) { return false; } return true; } public static Type? GetUnderlyingType(Type nullableType) { if ((object)nullableType == null) { throw new ArgumentNullException("nullableType"); } if (nullableType.IsGenericType && !nullableType.IsGenericTypeDefinition) { Type genericTypeDefinition = nullableType.GetGenericTypeDefinition(); if ((object)genericTypeDefinition == typeof(Nullable<>)) { return nullableType.GetGenericArguments()[0]; } } return null; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class NullReferenceException : SystemException { public NullReferenceException() : base(SR.Arg_NullReferenceException) { base.HResult = -2147467261; } public NullReferenceException(string? message) : base(message) { base.HResult = -2147467261; } public NullReferenceException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2147467261; } protected NullReferenceException(SerializationInfo info, StreamingContext context) : base(info, context) { } } internal static class Number { [StructLayout(LayoutKind.Sequential, Pack = 1)] internal ref struct BigInteger { private static readonly uint[] s_Pow10UInt32Table = new uint[10] { 1u, 10u, 100u, 1000u, 10000u, 100000u, 1000000u, 10000000u, 100000000u, 1000000000u }; private static readonly int[] s_Pow10BigNumTableIndices = new int[8] { 0, 2, 5, 10, 18, 33, 61, 116 }; private static readonly uint[] s_Pow10BigNumTable = new uint[234] { 1u, 100000000u, 2u, 1874919424u, 2328306u, 4u, 0u, 2242703233u, 762134875u, 1262u, 7u, 0u, 0u, 3211403009u, 1849224548u, 3668416493u, 3913284084u, 1593091u, 14u, 0u, 0u, 0u, 0u, 781532673u, 64985353u, 253049085u, 594863151u, 3553621484u, 3288652808u, 3167596762u, 2788392729u, 3911132675u, 590u, 27u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 2553183233u, 3201533787u, 3638140786u, 303378311u, 1809731782u, 3477761648u, 3583367183u, 649228654u, 2915460784u, 487929380u, 1011012442u, 1677677582u, 3428152256u, 1710878487u, 1438394610u, 2161952759u, 4100910556u, 1608314830u, 349175u, 54u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 4234999809u, 2012377703u, 2408924892u, 1570150255u, 3090844311u, 3273530073u, 1187251475u, 2498123591u, 3364452033u, 1148564857u, 687371067u, 2854068671u, 1883165473u, 505794538u, 2988060450u, 3159489326u, 2531348317u, 3215191468u, 849106862u, 3892080979u, 3288073877u, 2242451748u, 4183778142u, 2995818208u, 2477501924u, 325481258u, 2487842652u, 1774082830u, 1933815724u, 2962865281u, 1168579910u, 2724829000u, 2360374019u, 2315984659u, 2360052375u, 3251779801u, 1664357844u, 28u, 107u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 689565697u, 4116392818u, 1853628763u, 516071302u, 2568769159u, 365238920u, 336250165u, 1283268122u, 3425490969u, 248595470u, 2305176814u, 2111925499u, 507770399u, 2681111421u, 589114268u, 591287751u, 1708941527u, 4098957707u, 475844916u, 3378731398u, 2452339615u, 2817037361u, 2678008327u, 1656645978u, 2383430340u, 73103988u, 448667107u, 2329420453u, 3124020241u, 3625235717u, 3208634035u, 2412059158u, 2981664444u, 4117622508u, 838560765u, 3069470027u, 270153238u, 1802868219u, 3692709886u, 2161737865u, 2159912357u, 2585798786u, 837488486u, 4237238160u, 2540319504u, 3798629246u, 3748148874u, 1021550776u, 2386715342u, 1973637538u, 1823520457u, 1146713475u, 833971519u, 3277251466u, 905620390u, 26278816u, 2680483154u, 2294040859u, 373297482u, 5996609u, 4109575006u, 512575049u, 917036550u, 1942311753u, 2816916778u, 3248920332u, 1192784020u, 3537586671u, 2456567643u, 2925660628u, 759380297u, 888447942u, 3559939476u, 3654687237u, 805u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u }; private int _length; private unsafe fixed uint _blocks[116]; public unsafe static void Add(ref BigInteger lhs, ref BigInteger rhs, out BigInteger result) { ref BigInteger reference = ref lhs._length < rhs._length ? ref rhs : ref lhs; ref BigInteger reference2 = ref lhs._length < rhs._length ? ref lhs : ref rhs; int length = reference._length; int length2 = reference2._length; result._length = length; ulong num = 0uL; int num2 = 0; int num3 = 0; int num4 = 0; while (num3 < length2) { ulong num5 = num + reference._blocks[num2] + reference2._blocks[num3]; num = num5 >> 32; result._blocks[num4] = (uint)num5; num2++; num3++; num4++; } while (num2 < length) { ulong num6 = num + reference._blocks[num2]; num = num6 >> 32; result._blocks[num4] = (uint)num6; num2++; num4++; } int num7 = length; if (num != 0L) { if ((uint)num7 >= 116u) { SetZero(out result); return; } result._blocks[num4] = 1u; result._length++; } } public unsafe static int Compare(ref BigInteger lhs, ref BigInteger rhs) { int length = lhs._length; int length2 = rhs._length; int num = length - length2; if (num != 0) { return num; } if (length == 0) { return 0; } for (int num2 = length - 1; num2 >= 0; num2--) { long num3 = (long)lhs._blocks[num2] - (long)rhs._blocks[num2]; if (num3 != 0L) { if (num3 <= 0) { return -1; } return 1; } } return 0; } public static uint CountSignificantBits(uint value) { return (uint)(32 - BitOperations.LeadingZeroCount(value)); } public static uint CountSignificantBits(ulong value) { return (uint)(64 - BitOperations.LeadingZeroCount(value)); } public unsafe static uint CountSignificantBits(ref BigInteger value) { if (value.IsZero()) { return 0u; } uint num = (uint)(value._length - 1); return num * 32 + CountSignificantBits(value._blocks[num]); } public unsafe static void DivRem(ref BigInteger lhs, ref BigInteger rhs, out BigInteger quo, out BigInteger rem) { if (lhs.IsZero()) { SetZero(out quo); SetZero(out rem); return; } int length = lhs._length; int length2 = rhs._length; if (length == 1 && length2 == 1) { var (value, value2) = Math.DivRem(lhs._blocks[0], rhs._blocks[0]); SetUInt32(out quo, value); SetUInt32(out rem, value2); return; } if (length2 == 1) { int num = length; ulong right = rhs._blocks[0]; ulong num2 = 0uL; for (int num3 = num - 1; num3 >= 0; num3--) { ulong left = (num2 << 32) | lhs._blocks[num3]; ulong num4; (num4, num2) = Math.DivRem(left, right); if (num4 == 0L && num3 == num - 1) { num--; } else { quo._blocks[num3] = (uint)num4; } } quo._length = num; SetUInt32(out rem, (uint)num2); return; } if (length2 > length) { SetZero(out quo); SetValue(out rem, ref lhs); return; } int num5 = length - length2 + 1; SetValue(out rem, ref lhs); int num6 = length; uint num7 = rhs._blocks[length2 - 1]; uint num8 = rhs._blocks[length2 - 2]; int num9 = BitOperations.LeadingZeroCount(num7); int num10 = 32 - num9; if (num9 > 0) { num7 = (num7 << num9) | (num8 >> num10); num8 <<= num9; if (length2 > 2) { num8 |= rhs._blocks[length2 - 3] >> num10; } } for (int num11 = length; num11 >= length2; num11--) { int num12 = num11 - length2; uint num13 = ((num11 < length) ? rem._blocks[num11] : 0u); ulong num14 = ((ulong)num13 << 32) | rem._blocks[num11 - 1]; uint num15 = ((num11 > 1) ? rem._blocks[num11 - 2] : 0u); if (num9 > 0) { num14 = (num14 << num9) | (num15 >> num10); num15 <<= num9; if (num11 > 2) { num15 |= rem._blocks[num11 - 3] >> num10; } } ulong num16 = num14 / num7; if (num16 > uint.MaxValue) { num16 = 4294967295uL; } while (DivideGuessTooBig(num16, num14, num15, num7, num8)) { num16--; } if (num16 != 0) { uint num17 = SubtractDivisor(ref rem, num12, ref rhs, num16); if (num17 != num13) { num17 = AddDivisor(ref rem, num12, ref rhs); num16--; } } if (num5 != 0) { if (num16 == 0L && num12 == num5 - 1) { num5--; } else { quo._blocks[num12] = (uint)num16; } } if (num11 < num6) { num6--; } } quo._length = num5; for (int num18 = num6 - 1; num18 >= 0; num18--) { if (rem._blocks[num18] == 0) { num6--; } } rem._length = num6; } public unsafe static uint HeuristicDivide(ref BigInteger dividend, ref BigInteger divisor) { int num = divisor._length; if (dividend._length < num) { return 0u; } int num2 = num - 1; uint num3 = dividend._blocks[num2] / (divisor._blocks[num2] + 1); if (num3 != 0) { int num4 = 0; ulong num5 = 0uL; ulong num6 = 0uL; do { ulong num7 = (ulong)((long)divisor._blocks[num4] * (long)num3) + num6; num6 = num7 >> 32; ulong num8 = (ulong)((long)dividend._blocks[num4] - (long)(uint)num7) - num5; num5 = (num8 >> 32) & 1; dividend._blocks[num4] = (uint)num8; num4++; } while (num4 < num); while (num > 0 && dividend._blocks[num - 1] == 0) { num--; } dividend._length = num; } if (Compare(ref dividend, ref divisor) >= 0) { num3++; int num9 = 0; ulong num10 = 0uL; do { ulong num11 = (ulong)((long)dividend._blocks[num9] - (long)divisor._blocks[num9]) - num10; num10 = (num11 >> 32) & 1; dividend._blocks[num9] = (uint)num11; num9++; } while (num9 < num); while (num > 0 && dividend._blocks[num - 1] == 0) { num--; } dividend._length = num; } return num3; } public unsafe static void Multiply(ref BigInteger lhs, uint value, out BigInteger result) { if (lhs._length <= 1) { SetUInt64(out result, (ulong)lhs.ToUInt32() * (ulong)value); return; } switch (value) { case 0u: SetZero(out result); return; case 1u: SetValue(out result, ref lhs); return; } int length = lhs._length; int i = 0; uint num = 0u; for (; i < length; i++) { ulong num2 = (ulong)((long)lhs._blocks[i] * (long)value + num); result._blocks[i] = (uint)num2; num = (uint)(num2 >> 32); } int num3 = length; if (num != 0) { if ((uint)num3 >= 116u) { SetZero(out result); return; } result._blocks[i] = num; num3++; } result._length = num3; } public unsafe static void Multiply(ref BigInteger lhs, ref BigInteger rhs, out BigInteger result) { if (lhs._length <= 1) { Multiply(ref rhs, lhs.ToUInt32(), out result); return; } if (rhs._length <= 1) { Multiply(ref lhs, rhs.ToUInt32(), out result); return; } ref BigInteger reference = ref lhs; int length = lhs._length; ref BigInteger reference2 = ref rhs; int length2 = rhs._length; if (length < length2) { reference = ref rhs; length = rhs._length; reference2 = ref lhs; length2 = lhs._length; } int num = length2 + length; if ((uint)num > 116u) { SetZero(out result); return; } result._length = num; result.Clear((uint)num); int num2 = 0; int num3 = 0; while (num2 < length2) { if (reference2._blocks[num2] != 0) { int num4 = 0; int num5 = num3; ulong num6 = 0uL; do { ulong num7 = (ulong)(result._blocks[num5] + (long)reference2._blocks[num2] * (long)reference._blocks[num4]) + num6; num6 = num7 >> 32; result._blocks[num5] = (uint)num7; num5++; num4++; } while (num4 < length); result._blocks[num5] = (uint)num6; } num2++; num3++; } if (num > 0 && result._blocks[num - 1] == 0) { result._length--; } } public unsafe static void Pow2(uint exponent, out BigInteger result) { uint remainder; uint num = DivRem32(exponent, out remainder); result._length = (int)(num + 1); if ((uint)result._length > 116u) { SetZero(out result); return; } if (num != 0) { result.Clear(num); } result._blocks[num] = (uint)(1 << (int)remainder); } public unsafe static void Pow10(uint exponent, out BigInteger result) { SetUInt32(out var result2, s_Pow10UInt32Table[exponent & 7]); ref BigInteger reference = ref result2; SetZero(out var result3); ref BigInteger reference2 = ref result3; exponent >>= 3; uint num = 0u; while (exponent != 0) { if ((exponent & (true ? 1u : 0u)) != 0) { fixed (uint* ptr = &s_Pow10BigNumTable[s_Pow10BigNumTableIndices[num]]) { Multiply(ref reference, ref *(BigInteger*)ptr, out reference2); } ref BigInteger reference3 = ref reference2; reference2 = ref reference; reference = ref reference3; } num++; exponent >>= 1; } SetValue(out result, ref reference); } private unsafe static uint AddDivisor(ref BigInteger lhs, int lhsStartIndex, ref BigInteger rhs) { int length = lhs._length; int length2 = rhs._length; ulong num = 0uL; for (int i = 0; i < length2; i++) { ref uint reference = ref lhs._blocks[lhsStartIndex + i]; ulong num2 = reference + num + rhs._blocks[i]; reference = (uint)num2; num = num2 >> 32; } return (uint)num; } private static bool DivideGuessTooBig(ulong q, ulong valHi, uint valLo, uint divHi, uint divLo) { ulong num = divHi * q; ulong num2 = divLo * q; num += num2 >> 32; num2 &= 0xFFFFFFFFu; if (num < valHi) { return false; } if (num > valHi) { return true; } if (num2 < valLo) { return false; } if (num2 > valLo) { return true; } return false; } private unsafe static uint SubtractDivisor(ref BigInteger lhs, int lhsStartIndex, ref BigInteger rhs, ulong q) { int num = lhs._length - lhsStartIndex; int length = rhs._length; ulong num2 = 0uL; for (int i = 0; i < length; i++) { num2 += rhs._blocks[i] * q; uint num3 = (uint)num2; num2 >>= 32; ref uint reference = ref lhs._blocks[lhsStartIndex + i]; if (reference < num3) { num2++; } reference -= num3; } return (uint)num2; } public unsafe void Add(uint value) { int length = _length; if (length == 0) { SetUInt32(out this, value); return; } _blocks[0] += value; if (_blocks[0] >= value) { return; } for (int i = 1; i < length; i++) { ref uint reference = ref _blocks[i]; reference++; if (_blocks[i] != 0) { return; } } if ((uint)length >= 116u) { SetZero(out this); return; } _blocks[length] = 1u; _length = length + 1; } public unsafe uint GetBlock(uint index) { return _blocks[index]; } public int GetLength() { return _length; } public bool IsZero() { return _length == 0; } public void Multiply(uint value) { Multiply(ref this, value, out this); } public void Multiply(ref BigInteger value) { if (value._length <= 1) { Multiply(ref this, value.ToUInt32(), out this); return; } SetValue(out var result, ref this); Multiply(ref result, ref value, out this); } public unsafe void Multiply10() { if (IsZero()) { return; } int num = 0; int length = _length; ulong num2 = 0uL; do { ulong num3 = _blocks[num]; ulong num4 = (num3 << 3) + (num3 << 1) + num2; num2 = num4 >> 32; _blocks[num] = (uint)num4; num++; } while (num < length); if (num2 != 0L) { if ((uint)length >= 116u) { SetZero(out this); return; } _blocks[num] = (uint)num2; _length = length + 1; } } public void MultiplyPow10(uint exponent) { if (exponent <= 9) { Multiply(s_Pow10UInt32Table[exponent]); } else if (!IsZero()) { Pow10(exponent, out var result); Multiply(ref result); } } public unsafe static void SetUInt32(out BigInteger result, uint value) { if (value == 0) { SetZero(out result); return; } result._blocks[0] = value; result._length = 1; } public unsafe static void SetUInt64(out BigInteger result, ulong value) { if (value <= uint.MaxValue) { SetUInt32(out result, (uint)value); return; } result._blocks[0] = (uint)value; result._blocks[1] = (uint)(value >> 32); result._length = 2; } public unsafe static void SetValue(out BigInteger result, ref BigInteger value) { Buffer.Memmove(elementCount: (nuint)(result._length = value._length), destination: ref result._blocks[0], source: ref value._blocks[0]); } public static void SetZero(out BigInteger result) { result._length = 0; } public unsafe void ShiftLeft(uint shift) { int length = _length; if (length == 0 || shift == 0) { return; } uint remainder; uint num = DivRem32(shift, out remainder); int num2 = length - 1; int num3 = num2 + (int)num; if (remainder == 0) { if ((uint)length >= 116u) { SetZero(out this); return; } while (num2 >= 0) { _blocks[num3] = _blocks[num2]; num2--; num3--; } _length += (int)num; Clear(num); return; } num3++; if ((uint)length >= 116u) { SetZero(out this); return; } _length = num3 + 1; uint num4 = 32 - remainder; uint num5 = 0u; uint num6 = _blocks[num2]; uint num7 = num6 >> (int)num4; while (num2 > 0) { _blocks[num3] = num5 | num7; num5 = num6 << (int)remainder; num2--; num3--; num6 = _blocks[num2]; num7 = num6 >> (int)num4; } _blocks[num3] = num5 | num7; _blocks[num3 - 1] = num6 << (int)remainder; Clear(num); if (_blocks[_length - 1] == 0) { _length--; } } public unsafe uint ToUInt32() { if (_length > 0) { return _blocks[0]; } return 0u; } public unsafe ulong ToUInt64() { if (_length > 1) { return ((ulong)_blocks[1] << 32) + _blocks[0]; } if (_length > 0) { return _blocks[0]; } return 0uL; } private unsafe void Clear(uint length) { Buffer.ZeroMemory((byte*)Unsafe.AsPointer(ref _blocks[0]), length * 4); } private static uint DivRem32(uint value, out uint remainder) { remainder = value & 0x1Fu; return value >> 5; } } internal readonly ref struct DiyFp { public readonly ulong f; public readonly int e; public static DiyFp CreateAndGetBoundaries(double value, out DiyFp mMinus, out DiyFp mPlus) { DiyFp result = new DiyFp(value); result.GetBoundaries(52, out mMinus, out mPlus); return result; } public static DiyFp CreateAndGetBoundaries(float value, out DiyFp mMinus, out DiyFp mPlus) { DiyFp result = new DiyFp(value); result.GetBoundaries(23, out mMinus, out mPlus); return result; } public static DiyFp CreateAndGetBoundaries(Half value, out DiyFp mMinus, out DiyFp mPlus) { DiyFp result = new DiyFp(value); result.GetBoundaries(10, out mMinus, out mPlus); return result; } public DiyFp(double value) { f = ExtractFractionAndBiasedExponent(value, out e); } public DiyFp(float value) { f = ExtractFractionAndBiasedExponent(value, out e); } public DiyFp(Half value) { f = ExtractFractionAndBiasedExponent(value, out e); } public DiyFp(ulong f, int e) { this.f = f; this.e = e; } public DiyFp Multiply(in DiyFp other) { uint num = (uint)(f >> 32); uint num2 = (uint)f; uint num3 = (uint)(other.f >> 32); uint num4 = (uint)other.f; ulong num5 = (ulong)num * (ulong)num3; ulong num6 = (ulong)num2 * (ulong)num3; ulong num7 = (ulong)num * (ulong)num4; ulong num8 = (ulong)num2 * (ulong)num4; ulong num9 = (num8 >> 32) + (uint)num7 + (uint)num6; num9 += 2147483648u; return new DiyFp(num5 + (num7 >> 32) + (num6 >> 32) + (num9 >> 32), e + other.e + 64); } public DiyFp Normalize() { int num = BitOperations.LeadingZeroCount(f); return new DiyFp(f << num, e - num); } public DiyFp Subtract(in DiyFp other) { return new DiyFp(f - other.f, e); } private void GetBoundaries(int implicitBitIndex, out DiyFp mMinus, out DiyFp mPlus) { mPlus = new DiyFp((f << 1) + 1, e - 1).Normalize(); if (f == (ulong)(1L << implicitBitIndex)) { mMinus = new DiyFp((f << 2) - 1, e - 2); } else { mMinus = new DiyFp((f << 1) - 1, e - 1); } mMinus = new DiyFp(mMinus.f << mMinus.e - mPlus.e, mPlus.e); } } internal static class Grisu3 { private static readonly short[] s_CachedPowersBinaryExponent = new short[87] { -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954, -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661, -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369, -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77, -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216, 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508, 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800, 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066 }; private static readonly short[] s_CachedPowersDecimalExponent = new short[87] { -348, -340, -332, -324, -316, -308, -300, -292, -284, -276, -268, -260, -252, -244, -236, -228, -220, -212, -204, -196, -188, -180, -172, -164, -156, -148, -140, -132, -124, -116, -108, -100, -92, -84, -76, -68, -60, -52, -44, -36, -28, -20, -12, -4, 4, 12, 20, 28, 36, 44, 52, 60, 68, 76, 84, 92, 100, 108, 116, 124, 132, 140, 148, 156, 164, 172, 180, 188, 196, 204, 212, 220, 228, 236, 244, 252, 260, 268, 276, 284, 292, 300, 308, 316, 324, 332, 340 }; private static readonly ulong[] s_CachedPowersSignificand = new ulong[87] { 18054884314459144840uL, 13451937075301367670uL, 10022474136428063862uL, 14934650266808366570uL, 11127181549972568877uL, 16580792590934885855uL, 12353653155963782858uL, 18408377700990114895uL, 13715310171984221708uL, 10218702384817765436uL, 15227053142812498563uL, 11345038669416679861uL, 16905424996341287883uL, 12595523146049147757uL, 9384396036005875287uL, 13983839803942852151uL, 10418772551374772303uL, 15525180923007089351uL, 11567161174868858868uL, 17236413322193710309uL, 12842128665889583758uL, 9568131466127621947uL, 14257626930069360058uL, 10622759856335341974uL, 15829145694278690180uL, 11793632577567316726uL, 17573882009934360870uL, 13093562431584567480uL, 9755464219737475723uL, 14536774485912137811uL, 10830740992659433045uL, 16139061738043178685uL, 12024538023802026127uL, 17917957937422433684uL, 13349918974505688015uL, 9946464728195732843uL, 14821387422376473014uL, 11042794154864902060uL, 16455045573212060422uL, 12259964326927110867uL, 18268770466636286478uL, 13611294676837538539uL, 10141204801825835212uL, 15111572745182864684uL, 11258999068426240000uL, 16777216000000000000uL, 12500000000000000000uL, 9313225746154785156uL, 13877787807814456755uL, 10339757656912845936uL, 15407439555097886824uL, 11479437019748901445uL, 17105694144590052135uL, 12744735289059618216uL, 9495567745759798747uL, 14149498560666738074uL, 10542197943230523224uL, 15709099088952724970uL, 11704190886730495818uL, 17440603504673385349uL, 12994262207056124023uL, 9681479787123295682uL, 14426529090290212157uL, 10748601772107342003uL, 16016664761464807395uL, 11933345169920330789uL, 17782069995880619868uL, 13248674568444952270uL, 9871031767461413346uL, 14708983551653345445uL, 10959046745042015199uL, 16330252207878254650uL, 12166986024289022870uL, 18130221999122236476uL, 13508068024458167312uL, 10064294952495520794uL, 14996968138956309548uL, 11173611982879273257uL, 16649979327439178909uL, 12405201291620119593uL, 9242595204427927429uL, 13772540099066387757uL, 10261342003245940623uL, 15290591125556738113uL, 11392378155556871081uL, 16975966327722178521uL, 12648080533535911531uL }; private static readonly uint[] s_SmallPowersOfTen = new uint[10] { 1u, 10u, 100u, 1000u, 10000u, 100000u, 1000000u, 10000000u, 100000000u, 1000000000u }; public static bool TryRunDouble(double value, int requestedDigits, ref NumberBuffer number) { double value2 = (double.IsNegative(value) ? (0.0 - value) : value); DiyFp diyFp; bool flag; int length; int decimalExponent; if (requestedDigits == -1) { diyFp = DiyFp.CreateAndGetBoundaries(value2, out var mMinus, out var mPlus); DiyFp w = diyFp.Normalize(); flag = TryRunShortest(in mMinus, in w, in mPlus, number.Digits, out length, out decimalExponent); } else { diyFp = new DiyFp(value2); DiyFp w2 = diyFp.Normalize(); flag = TryRunCounted(in w2, requestedDigits, number.Digits, out length, out decimalExponent); } if (flag) { number.Scale = length + decimalExponent; number.Digits[length] = 0; number.DigitsCount = length; } return flag; } public static bool TryRunHalf(Half value, int requestedDigits, ref NumberBuffer number) { Half value2 = (Half.IsNegative(value) ? Half.Negate(value) : value); DiyFp diyFp; bool flag; int length; int decimalExponent; if (requestedDigits == -1) { diyFp = DiyFp.CreateAndGetBoundaries(value2, out var mMinus, out var mPlus); DiyFp w = diyFp.Normalize(); flag = TryRunShortest(in mMinus, in w, in mPlus, number.Digits, out length, out decimalExponent); } else { diyFp = new DiyFp(value2); DiyFp w2 = diyFp.Normalize(); flag = TryRunCounted(in w2, requestedDigits, number.Digits, out length, out decimalExponent); } if (flag) { number.Scale = length + decimalExponent; number.Digits[length] = 0; number.DigitsCount = length; } return flag; } public static bool TryRunSingle(float value, int requestedDigits, ref NumberBuffer number) { float value2 = (float.IsNegative(value) ? (0f - value) : value); DiyFp diyFp; bool flag; int length; int decimalExponent; if (requestedDigits == -1) { diyFp = DiyFp.CreateAndGetBoundaries(value2, out var mMinus, out var mPlus); DiyFp w = diyFp.Normalize(); flag = TryRunShortest(in mMinus, in w, in mPlus, number.Digits, out length, out decimalExponent); } else { diyFp = new DiyFp(value2); DiyFp w2 = diyFp.Normalize(); flag = TryRunCounted(in w2, requestedDigits, number.Digits, out length, out decimalExponent); } if (flag) { number.Scale = length + decimalExponent; number.Digits[length] = 0; number.DigitsCount = length; } return flag; } private static bool TryRunCounted(in DiyFp w, int requestedDigits, Span buffer, out int length, out int decimalExponent) { int minExponent = -60 - (w.e + 64); int maxExponent = -32 - (w.e + 64); int decimalExponent2; DiyFp other = GetCachedPowerForBinaryExponentRange(minExponent, maxExponent, out decimalExponent2); DiyFp w2 = w.Multiply(in other); int kappa; bool result = TryDigitGenCounted(in w2, requestedDigits, buffer, out length, out kappa); decimalExponent = -decimalExponent2 + kappa; return result; } private static bool TryRunShortest(in DiyFp boundaryMinus, in DiyFp w, in DiyFp boundaryPlus, Span buffer, out int length, out int decimalExponent) { int minExponent = -60 - (w.e + 64); int maxExponent = -32 - (w.e + 64); int decimalExponent2; DiyFp other = GetCachedPowerForBinaryExponentRange(minExponent, maxExponent, out decimalExponent2); DiyFp w2 = w.Multiply(in other); DiyFp low = boundaryMinus.Multiply(in other); DiyFp high = boundaryPlus.Multiply(in other); int kappa; bool result = TryDigitGenShortest(in low, in w2, in high, buffer, out length, out kappa); decimalExponent = -decimalExponent2 + kappa; return result; } private static uint BiggestPowerTen(uint number, int numberBits, out int exponentPlusOne) { int num = (numberBits + 1) * 1233 >> 12; uint num2 = s_SmallPowersOfTen[num]; if (number < num2) { num--; num2 = s_SmallPowersOfTen[num]; } exponentPlusOne = num + 1; return num2; } private static bool TryDigitGenCounted(in DiyFp w, int requestedDigits, Span buffer, out int length, out int kappa) { ulong num = 1uL; DiyFp diyFp = new DiyFp((ulong)(1L << -w.e), w.e); uint num2 = (uint)(w.f >> -diyFp.e); ulong num3 = w.f & (diyFp.f - 1); if (num3 == 0L && (requestedDigits >= 11 || num2 < s_SmallPowersOfTen[requestedDigits - 1])) { length = 0; kappa = 0; return false; } uint num4 = BiggestPowerTen(num2, 64 - -diyFp.e, out kappa); length = 0; while (kappa > 0) { uint num5; (num5, num2) = Math.DivRem(num2, num4); buffer[length] = (byte)(48 + num5); length++; requestedDigits--; kappa--; if (requestedDigits == 0) { break; } num4 /= 10; } if (requestedDigits == 0) { ulong rest = ((ulong)num2 << -diyFp.e) + num3; return TryRoundWeedCounted(buffer, length, rest, (ulong)num4 << -diyFp.e, num, ref kappa); } while (requestedDigits > 0 && num3 > num) { num3 *= 10; num *= 10; uint num6 = (uint)(num3 >> -diyFp.e); buffer[length] = (byte)(48 + num6); length++; requestedDigits--; kappa--; num3 &= diyFp.f - 1; } if (requestedDigits != 0) { buffer[0] = 0; length = 0; kappa = 0; return false; } return TryRoundWeedCounted(buffer, length, num3, diyFp.f, num, ref kappa); } private static bool TryDigitGenShortest(in DiyFp low, in DiyFp w, in DiyFp high, Span buffer, out int length, out int kappa) { ulong num = 1uL; DiyFp other = new DiyFp(low.f - num, low.e); DiyFp diyFp = new DiyFp(high.f + num, high.e); DiyFp diyFp2 = diyFp.Subtract(in other); DiyFp diyFp3 = new DiyFp((ulong)(1L << -w.e), w.e); uint num2 = (uint)(diyFp.f >> -diyFp3.e); ulong num3 = diyFp.f & (diyFp3.f - 1); uint num4 = BiggestPowerTen(num2, 64 - -diyFp3.e, out kappa); length = 0; while (kappa > 0) { uint num5; (num5, num2) = Math.DivRem(num2, num4); buffer[length] = (byte)(48 + num5); length++; kappa--; ulong num6 = ((ulong)num2 << -diyFp3.e) + num3; if (num6 < diyFp2.f) { return TryRoundWeedShortest(buffer, length, diyFp.Subtract(in w).f, diyFp2.f, num6, (ulong)num4 << -diyFp3.e, num); } num4 /= 10; } do { num3 *= 10; num *= 10; diyFp2 = new DiyFp(diyFp2.f * 10, diyFp2.e); uint num7 = (uint)(num3 >> -diyFp3.e); buffer[length] = (byte)(48 + num7); length++; kappa--; num3 &= diyFp3.f - 1; } while (num3 >= diyFp2.f); return TryRoundWeedShortest(buffer, length, diyFp.Subtract(in w).f * num, diyFp2.f, num3, diyFp3.f, num); } private static DiyFp GetCachedPowerForBinaryExponentRange(int minExponent, int maxExponent, out int decimalExponent) { double num = Math.Ceiling((double)(minExponent + 64 - 1) * 0.3010299956639812); int num2 = (348 + (int)num - 1) / 8 + 1; decimalExponent = s_CachedPowersDecimalExponent[num2]; return new DiyFp(s_CachedPowersSignificand[num2], s_CachedPowersBinaryExponent[num2]); } private static bool TryRoundWeedCounted(Span buffer, int length, ulong rest, ulong tenKappa, ulong unit, ref int kappa) { if (unit >= tenKappa || tenKappa - unit <= unit) { return false; } if (tenKappa - rest > rest && tenKappa - 2 * rest >= 2 * unit) { return true; } if (rest > unit && (tenKappa <= rest - unit || tenKappa - (rest - unit) <= rest - unit)) { buffer[length - 1]++; int num = length - 1; while (num > 0 && buffer[num] == 58) { buffer[num] = 48; buffer[num - 1]++; num--; } if (buffer[0] == 58) { buffer[0] = 49; kappa++; } return true; } return false; } private static bool TryRoundWeedShortest(Span buffer, int length, ulong distanceTooHighW, ulong unsafeInterval, ulong rest, ulong tenKappa, ulong unit) { ulong num = distanceTooHighW - unit; ulong num2 = distanceTooHighW + unit; while (rest < num && unsafeInterval - rest >= tenKappa && (rest + tenKappa < num || num - rest >= rest + tenKappa - num)) { buffer[length - 1]--; rest += tenKappa; } if (rest < num2 && unsafeInterval - rest >= tenKappa && (rest + tenKappa < num2 || num2 - rest > rest + tenKappa - num2)) { return false; } if (2 * unit <= rest) { return rest <= unsafeInterval - 4 * unit; } return false; } } internal ref struct NumberBuffer { public int DigitsCount; public int Scale; public bool IsNegative; public bool HasNonZeroTail; public NumberBufferKind Kind; public Span Digits; public unsafe NumberBuffer(NumberBufferKind kind, byte* digits, int digitsLength) { DigitsCount = 0; Scale = 0; IsNegative = false; HasNonZeroTail = false; Kind = kind; Digits = new Span(digits, digitsLength); Digits[0] = 0; } public unsafe byte* GetDigitsPointer() { return (byte*)Unsafe.AsPointer(ref Digits[0]); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('['); stringBuilder.Append('"'); for (int i = 0; i < Digits.Length; i++) { byte b = Digits[i]; if (b == 0) { break; } stringBuilder.Append((char)b); } stringBuilder.Append('"'); stringBuilder.Append(", Length = ").Append(DigitsCount); stringBuilder.Append(", Scale = ").Append(Scale); stringBuilder.Append(", IsNegative = ").Append(IsNegative); stringBuilder.Append(", HasNonZeroTail = ").Append(HasNonZeroTail); stringBuilder.Append(", Kind = ").Append(Kind); stringBuilder.Append(']'); return stringBuilder.ToString(); } } internal enum NumberBufferKind : byte { Unknown, Integer, Decimal, FloatingPoint } public readonly struct FloatingPointInfo { public static readonly FloatingPointInfo Double = new FloatingPointInfo(52, 11, 1023, 1023, 9218868437227405312uL); public static readonly FloatingPointInfo Single = new FloatingPointInfo(23, 8, 127, 127, 2139095040uL); public static readonly FloatingPointInfo Half = new FloatingPointInfo(10, 5, 15, 15, 31744uL); [CompilerGenerated] private readonly ushort k__BackingField; public ulong ZeroBits { get; } public ulong InfinityBits { get; } public ulong NormalMantissaMask { get; } public ulong DenormalMantissaMask { get; } public int MinBinaryExponent { get; } public int MaxBinaryExponent { get; } public int ExponentBias { get; } public int OverflowDecimalExponent { get; } public ushort NormalMantissaBits { get; } public ushort DenormalMantissaBits { get; } public FloatingPointInfo(ushort denormalMantissaBits, ushort exponentBits, int maxBinaryExponent, int exponentBias, ulong infinityBits) { k__BackingField = exponentBits; DenormalMantissaBits = denormalMantissaBits; NormalMantissaBits = (ushort)(denormalMantissaBits + 1); OverflowDecimalExponent = (maxBinaryExponent + 2 * NormalMantissaBits) / 3; ExponentBias = exponentBias; MaxBinaryExponent = maxBinaryExponent; MinBinaryExponent = 1 - maxBinaryExponent; DenormalMantissaMask = (ulong)((1L << (int)denormalMantissaBits) - 1); NormalMantissaMask = (ulong)((1L << (int)NormalMantissaBits) - 1); InfinityBits = infinityBits; ZeroBits = 0uL; } } internal enum ParsingStatus { OK, Failed, Overflow } private static readonly string[] s_singleDigitStringCache = new string[10] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; private static readonly string[] s_posCurrencyFormats = new string[4] { "$#", "#$", "$ #", "# $" }; private static readonly string[] s_negCurrencyFormats = new string[17] { "($#)", "-$#", "$-#", "$#-", "(#$)", "-#$", "#-$", "#$-", "-# $", "-$ #", "# $-", "$ #-", "$ -#", "#- $", "($ #)", "(# $)", "$- #" }; private static readonly string[] s_posPercentFormats = new string[4] { "# %", "#%", "%#", "% #" }; private static readonly string[] s_negPercentFormats = new string[12] { "-# %", "-#%", "-%#", "%-#", "%#-", "#-%", "#%-", "-% #", "# %-", "% #-", "% -#", "#- %" }; private static readonly string[] s_negNumberFormats = new string[5] { "(#)", "-#", "- #", "#-", "# -" }; private static readonly float[] s_Pow10SingleTable = new float[11] { 1f, 10f, 100f, 1000f, 10000f, 100000f, 1000000f, 10000000f, 100000000f, 1E+09f, 1E+10f }; private static readonly double[] s_Pow10DoubleTable = new double[23] { 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, 10000000.0, 100000000.0, 1000000000.0, 10000000000.0, 100000000000.0, 1000000000000.0, 10000000000000.0, 100000000000000.0, 1000000000000000.0, 10000000000000000.0, 1E+17, 1E+18, 1E+19, 1E+20, 1E+21, 1E+22 }; public static void Dragon4Double(double value, int cutoffNumber, bool isSignificantDigits, ref NumberBuffer number) { double num = (double.IsNegative(value) ? (0.0 - value) : value); int exponent; ulong num2 = ExtractFractionAndBiasedExponent(value, out exponent); bool hasUnequalMargins = false; uint mantissaHighBitIdx; if (num2 >> 52 != 0L) { mantissaHighBitIdx = 52u; hasUnequalMargins = num2 == 4503599627370496L; } else { mantissaHighBitIdx = (uint)BitOperations.Log2(num2); } int decimalExponent; int num3 = (int)Dragon4(num2, exponent, mantissaHighBitIdx, hasUnequalMargins, cutoffNumber, isSignificantDigits, number.Digits, out decimalExponent); number.Scale = decimalExponent + 1; number.Digits[num3] = 0; number.DigitsCount = num3; } public static void Dragon4Half(Half value, int cutoffNumber, bool isSignificantDigits, ref NumberBuffer number) { Half half = (Half.IsNegative(value) ? Half.Negate(value) : value); int exponent; ushort num = ExtractFractionAndBiasedExponent(value, out exponent); bool hasUnequalMargins = false; uint mantissaHighBitIdx; if (num >> 10 != 0) { mantissaHighBitIdx = 10u; hasUnequalMargins = num == 1024; } else { mantissaHighBitIdx = (uint)BitOperations.Log2(num); } int decimalExponent; int num2 = (int)Dragon4(num, exponent, mantissaHighBitIdx, hasUnequalMargins, cutoffNumber, isSignificantDigits, number.Digits, out decimalExponent); number.Scale = decimalExponent + 1; number.Digits[num2] = 0; number.DigitsCount = num2; } public static void Dragon4Single(float value, int cutoffNumber, bool isSignificantDigits, ref NumberBuffer number) { float num = (float.IsNegative(value) ? (0f - value) : value); int exponent; uint num2 = ExtractFractionAndBiasedExponent(value, out exponent); bool hasUnequalMargins = false; uint mantissaHighBitIdx; if (num2 >> 23 != 0) { mantissaHighBitIdx = 23u; hasUnequalMargins = num2 == 8388608; } else { mantissaHighBitIdx = (uint)BitOperations.Log2(num2); } int decimalExponent; int num3 = (int)Dragon4(num2, exponent, mantissaHighBitIdx, hasUnequalMargins, cutoffNumber, isSignificantDigits, number.Digits, out decimalExponent); number.Scale = decimalExponent + 1; number.Digits[num3] = 0; number.DigitsCount = num3; } private unsafe static uint Dragon4(ulong mantissa, int exponent, uint mantissaHighBitIdx, bool hasUnequalMargins, int cutoffNumber, bool isSignificantDigits, Span buffer, out int decimalExponent) { int num = 0; BigInteger result; BigInteger result2; BigInteger result3; BigInteger* ptr; if (hasUnequalMargins) { BigInteger result4; if (exponent > 0) { BigInteger.SetUInt64(out result, 4 * mantissa); result.ShiftLeft((uint)exponent); BigInteger.SetUInt32(out result2, 4u); BigInteger.Pow2((uint)exponent, out result3); BigInteger.Pow2((uint)(exponent + 1), out result4); } else { BigInteger.SetUInt64(out result, 4 * mantissa); BigInteger.Pow2((uint)(-exponent + 2), out result2); BigInteger.SetUInt32(out result3, 1u); BigInteger.SetUInt32(out result4, 2u); } ptr = &result4; } else { if (exponent > 0) { BigInteger.SetUInt64(out result, 2 * mantissa); result.ShiftLeft((uint)exponent); BigInteger.SetUInt32(out result2, 2u); BigInteger.Pow2((uint)exponent, out result3); } else { BigInteger.SetUInt64(out result, 2 * mantissa); BigInteger.Pow2((uint)(-exponent + 1), out result2); BigInteger.SetUInt32(out result3, 1u); } ptr = &result3; } int num2 = (int)Math.Ceiling((double)((int)mantissaHighBitIdx + exponent) * 0.3010299956639812 - 0.69); if (num2 > 0) { result2.MultiplyPow10((uint)num2); } else if (num2 < 0) { BigInteger.Pow10((uint)(-num2), out var result5); result.Multiply(ref result5); result3.Multiply(ref result5); if (ptr != &result3) { BigInteger.Multiply(ref result3, 2u, out *ptr); } } bool flag = mantissa % 2 == 0; bool flag2 = false; if (cutoffNumber == -1) { BigInteger.Add(ref result, ref *ptr, out var result6); int num3 = BigInteger.Compare(ref result6, ref result2); flag2 = (flag ? (num3 >= 0) : (num3 > 0)); } else { flag2 = BigInteger.Compare(ref result, ref result2) >= 0; } if (flag2) { num2++; } else { result.Multiply10(); result3.Multiply10(); if (ptr != &result3) { BigInteger.Multiply(ref result3, 2u, out *ptr); } } int num4 = num2 - buffer.Length; if (cutoffNumber != -1) { int num5 = 0; num5 = ((!isSignificantDigits) ? (-cutoffNumber) : (num2 - cutoffNumber)); if (num5 > num4) { num4 = num5; } } num2 = (decimalExponent = num2 - 1); uint block = result2.GetBlock((uint)(result2.GetLength() - 1)); if (block < 8 || block > 429496729) { uint num6 = (uint)BitOperations.Log2(block); uint shift = (59 - num6) % 32; result2.ShiftLeft(shift); result.ShiftLeft(shift); result3.ShiftLeft(shift); if (ptr != &result3) { BigInteger.Multiply(ref result3, 2u, out *ptr); } } bool flag3; bool flag4; uint num7; if (cutoffNumber == -1) { while (true) { num7 = BigInteger.HeuristicDivide(ref result, ref result2); BigInteger.Add(ref result, ref *ptr, out var result7); int num8 = BigInteger.Compare(ref result, ref result3); int num9 = BigInteger.Compare(ref result7, ref result2); if (flag) { flag3 = num8 <= 0; flag4 = num9 >= 0; } else { flag3 = num8 < 0; flag4 = num9 > 0; } if (flag3 || flag4 || num2 == num4) { break; } buffer[num] = (byte)(48 + num7); num++; result.Multiply10(); result3.Multiply10(); if (ptr != &result3) { BigInteger.Multiply(ref result3, 2u, out *ptr); } num2--; } } else { if (num2 < num4) { num7 = BigInteger.HeuristicDivide(ref result, ref result2); if (num7 > 5 || (num7 == 5 && !result.IsZero())) { decimalExponent++; num7 = 1u; } buffer[num] = (byte)(48 + num7); return (uint)(num + 1); } flag3 = false; flag4 = false; while (true) { num7 = BigInteger.HeuristicDivide(ref result, ref result2); if (result.IsZero() || num2 <= num4) { break; } buffer[num] = (byte)(48 + num7); num++; result.Multiply10(); num2--; } } bool flag5 = flag3; if (flag3 == flag4) { result.ShiftLeft(1u); int num10 = BigInteger.Compare(ref result, ref result2); flag5 = num10 < 0; if (num10 == 0) { flag5 = (num7 & 1) == 0; } } if (flag5) { buffer[num] = (byte)(48 + num7); num++; } else if (num7 == 9) { while (true) { if (num == 0) { buffer[num] = 49; num++; decimalExponent++; break; } num--; if (buffer[num] != 57) { buffer[num]++; num++; break; } } } else { buffer[num] = (byte)(48 + num7 + 1); num++; } return (uint)num; } public unsafe static string FormatDecimal(decimal value, ReadOnlySpan format, NumberFormatInfo info) { int digits; char c = ParseFormatSpecifier(format, out digits); byte* digits2 = stackalloc byte[31]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Decimal, digits2, 31); DecimalToNumber(ref value, ref number); char* pointer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(new Span(pointer, 32)); if (c != 0) { NumberToString(ref sb, ref number, c, digits, info); } else { NumberToStringFormat(ref sb, ref number, format, info); } return sb.ToString(); } public unsafe static bool TryFormatDecimal(decimal value, ReadOnlySpan format, NumberFormatInfo info, Span destination, out int charsWritten) { int digits; char c = ParseFormatSpecifier(format, out digits); byte* digits2 = stackalloc byte[31]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Decimal, digits2, 31); DecimalToNumber(ref value, ref number); char* pointer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(new Span(pointer, 32)); if (c != 0) { NumberToString(ref sb, ref number, c, digits, info); } else { NumberToStringFormat(ref sb, ref number, format, info); } return sb.TryCopyTo(destination, out charsWritten); } internal unsafe static void DecimalToNumber(ref decimal d, ref NumberBuffer number) { byte* digitsPointer = number.GetDigitsPointer(); number.DigitsCount = 29; number.IsNegative = d.IsNegative; byte* bufferEnd = digitsPointer + 29; while ((d.Mid | d.High) != 0) { bufferEnd = UInt32ToDecChars(bufferEnd, decimal.DecDivMod1E9(ref d), 9); } bufferEnd = UInt32ToDecChars(bufferEnd, d.Low, 0); int num = (number.DigitsCount = (int)(digitsPointer + 29 - bufferEnd)); number.Scale = num - d.Scale; byte* digitsPointer2 = number.GetDigitsPointer(); while (--num >= 0) { *(digitsPointer2++) = *(bufferEnd++); } *digitsPointer2 = 0; } public static string FormatDouble(double value, string format, NumberFormatInfo info) { Span initialBuffer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(initialBuffer); return FormatDouble(ref sb, value, format, info) ?? sb.ToString(); } public static bool TryFormatDouble(double value, ReadOnlySpan format, NumberFormatInfo info, Span destination, out int charsWritten) { Span initialBuffer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(initialBuffer); string text = FormatDouble(ref sb, value, format, info); if (text == null) { return sb.TryCopyTo(destination, out charsWritten); } return TryCopyTo(text, destination, out charsWritten); } private static int GetFloatingPointMaxDigitsAndPrecision(char fmt, ref int precision, NumberFormatInfo info, out bool isSignificantDigits) { if (fmt == '\0') { isSignificantDigits = true; return precision; } int result = precision; switch (fmt) { case 'C': case 'c': if (precision == -1) { precision = info.CurrencyDecimalDigits; } isSignificantDigits = false; break; case 'E': case 'e': if (precision == -1) { precision = 6; } precision++; isSignificantDigits = true; break; case 'F': case 'N': case 'f': case 'n': if (precision == -1) { precision = info.NumberDecimalDigits; } isSignificantDigits = false; break; case 'G': case 'g': if (precision == 0) { precision = -1; } isSignificantDigits = true; break; case 'P': case 'p': if (precision == -1) { precision = info.PercentDecimalDigits; } precision += 2; isSignificantDigits = false; break; case 'R': case 'r': precision = -1; isSignificantDigits = true; break; default: throw new FormatException(SR.Argument_BadFormatSpecifier); } return result; } private unsafe static string FormatDouble(ref ValueStringBuilder sb, double value, ReadOnlySpan format, NumberFormatInfo info) { if (!double.IsFinite(value)) { if (double.IsNaN(value)) { return info.NaNSymbol; } if (!double.IsNegative(value)) { return info.PositiveInfinitySymbol; } return info.NegativeInfinitySymbol; } int digits; char c = ParseFormatSpecifier(format, out digits); byte* digits2 = stackalloc byte[769]; if (c == '\0') { digits = 15; } NumberBuffer number = new NumberBuffer(NumberBufferKind.FloatingPoint, digits2, 769); number.IsNegative = double.IsNegative(value); bool isSignificantDigits; int nMaxDigits = GetFloatingPointMaxDigitsAndPrecision(c, ref digits, info, out isSignificantDigits); if (value != 0.0 && (!isSignificantDigits || !Grisu3.TryRunDouble(value, digits, ref number))) { Dragon4Double(value, digits, isSignificantDigits, ref number); } if (c != 0) { if (digits == -1) { nMaxDigits = Math.Max(number.DigitsCount, 17); } NumberToString(ref sb, ref number, c, nMaxDigits, info); } else { NumberToStringFormat(ref sb, ref number, format, info); } return null; } public static string FormatSingle(float value, string format, NumberFormatInfo info) { Span initialBuffer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(initialBuffer); return FormatSingle(ref sb, value, format, info) ?? sb.ToString(); } public static bool TryFormatSingle(float value, ReadOnlySpan format, NumberFormatInfo info, Span destination, out int charsWritten) { Span initialBuffer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(initialBuffer); string text = FormatSingle(ref sb, value, format, info); if (text == null) { return sb.TryCopyTo(destination, out charsWritten); } return TryCopyTo(text, destination, out charsWritten); } private unsafe static string FormatSingle(ref ValueStringBuilder sb, float value, ReadOnlySpan format, NumberFormatInfo info) { if (!float.IsFinite(value)) { if (float.IsNaN(value)) { return info.NaNSymbol; } if (!float.IsNegative(value)) { return info.PositiveInfinitySymbol; } return info.NegativeInfinitySymbol; } int digits; char c = ParseFormatSpecifier(format, out digits); byte* digits2 = stackalloc byte[114]; if (c == '\0') { digits = 7; } NumberBuffer number = new NumberBuffer(NumberBufferKind.FloatingPoint, digits2, 114); number.IsNegative = float.IsNegative(value); bool isSignificantDigits; int nMaxDigits = GetFloatingPointMaxDigitsAndPrecision(c, ref digits, info, out isSignificantDigits); if (value != 0f && (!isSignificantDigits || !Grisu3.TryRunSingle(value, digits, ref number))) { Dragon4Single(value, digits, isSignificantDigits, ref number); } if (c != 0) { if (digits == -1) { nMaxDigits = Math.Max(number.DigitsCount, 9); } NumberToString(ref sb, ref number, c, nMaxDigits, info); } else { NumberToStringFormat(ref sb, ref number, format, info); } return null; } public static string FormatHalf(Half value, string format, NumberFormatInfo info) { Span initialBuffer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(initialBuffer); return FormatHalf(ref sb, value, format, info) ?? sb.ToString(); } private unsafe static string FormatHalf(ref ValueStringBuilder sb, Half value, ReadOnlySpan format, NumberFormatInfo info) { if (!Half.IsFinite(value)) { if (Half.IsNaN(value)) { return info.NaNSymbol; } if (!Half.IsNegative(value)) { return info.PositiveInfinitySymbol; } return info.NegativeInfinitySymbol; } int digits; char c = ParseFormatSpecifier(format, out digits); byte* digits2 = stackalloc byte[21]; if (c == '\0') { digits = 5; } NumberBuffer number = new NumberBuffer(NumberBufferKind.FloatingPoint, digits2, 21); number.IsNegative = Half.IsNegative(value); bool isSignificantDigits; int nMaxDigits = GetFloatingPointMaxDigitsAndPrecision(c, ref digits, info, out isSignificantDigits); if (value != default(Half) && (!isSignificantDigits || !Grisu3.TryRunHalf(value, digits, ref number))) { Dragon4Half(value, digits, isSignificantDigits, ref number); } if (c != 0) { if (digits == -1) { nMaxDigits = Math.Max(number.DigitsCount, 5); } NumberToString(ref sb, ref number, c, nMaxDigits, info); } else { NumberToStringFormat(ref sb, ref number, format, info); } return null; } public static bool TryFormatHalf(Half value, ReadOnlySpan format, NumberFormatInfo info, Span destination, out int charsWritten) { Span initialBuffer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(initialBuffer); string text = FormatHalf(ref sb, value, format, info); if (text == null) { return sb.TryCopyTo(destination, out charsWritten); } return TryCopyTo(text, destination, out charsWritten); } private static bool TryCopyTo(string source, Span destination, out int charsWritten) { if (source.TryCopyTo(destination)) { charsWritten = source.Length; return true; } charsWritten = 0; return false; } private static char GetHexBase(char fmt) { return (char)(fmt - 33); } public static string FormatInt32(int value, int hexMask, string format, IFormatProvider provider) { if (string.IsNullOrEmpty(format)) { if (value < 0) { return NegativeInt32ToDecStr(value, -1, NumberFormatInfo.GetInstance(provider).NegativeSign); } return UInt32ToDecStr((uint)value); } return FormatInt32Slow(value, hexMask, format, provider); unsafe static string FormatInt32Slow(int value, int hexMask, string format, IFormatProvider provider) { ReadOnlySpan format2 = format; int digits; char c = ParseFormatSpecifier(format2, out digits); char c2 = (char)(c & 0xFFDFu); if ((c2 == 'G') ? (digits < 1) : (c2 == 'D')) { if (value < 0) { return NegativeInt32ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign); } return UInt32ToDecStr((uint)value, digits); } if (c2 == 'X') { return Int32ToHexStr(value & hexMask, GetHexBase(c), digits); } NumberFormatInfo instance = NumberFormatInfo.GetInstance(provider); byte* digits2 = stackalloc byte[11]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, digits2, 11); Int32ToNumber(value, ref number); char* pointer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(new Span(pointer, 32)); if (c != 0) { NumberToString(ref sb, ref number, c, digits, instance); } else { NumberToStringFormat(ref sb, ref number, format2, instance); } return sb.ToString(); } } public static bool TryFormatInt32(int value, int hexMask, ReadOnlySpan format, IFormatProvider provider, Span destination, out int charsWritten) { if (format.Length == 0) { if (value < 0) { return TryNegativeInt32ToDecStr(value, -1, NumberFormatInfo.GetInstance(provider).NegativeSign, destination, out charsWritten); } return TryUInt32ToDecStr((uint)value, -1, destination, out charsWritten); } return TryFormatInt32Slow(value, hexMask, format, provider, destination, out charsWritten); unsafe static bool TryFormatInt32Slow(int value, int hexMask, ReadOnlySpan format, IFormatProvider provider, Span destination, out int charsWritten) { int digits; char c = ParseFormatSpecifier(format, out digits); char c2 = (char)(c & 0xFFDFu); if ((c2 == 'G') ? (digits < 1) : (c2 == 'D')) { if (value < 0) { return TryNegativeInt32ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign, destination, out charsWritten); } return TryUInt32ToDecStr((uint)value, digits, destination, out charsWritten); } if (c2 == 'X') { return TryInt32ToHexStr(value & hexMask, GetHexBase(c), digits, destination, out charsWritten); } NumberFormatInfo instance = NumberFormatInfo.GetInstance(provider); byte* digits2 = stackalloc byte[11]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, digits2, 11); Int32ToNumber(value, ref number); char* pointer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(new Span(pointer, 32)); if (c != 0) { NumberToString(ref sb, ref number, c, digits, instance); } else { NumberToStringFormat(ref sb, ref number, format, instance); } return sb.TryCopyTo(destination, out charsWritten); } } public static string FormatUInt32(uint value, string format, IFormatProvider provider) { if (string.IsNullOrEmpty(format)) { return UInt32ToDecStr(value); } return FormatUInt32Slow(value, format, provider); unsafe static string FormatUInt32Slow(uint value, string format, IFormatProvider provider) { ReadOnlySpan format2 = format; int digits; char c = ParseFormatSpecifier(format2, out digits); char c2 = (char)(c & 0xFFDFu); if ((c2 == 'G') ? (digits < 1) : (c2 == 'D')) { return UInt32ToDecStr(value, digits); } if (c2 == 'X') { return Int32ToHexStr((int)value, GetHexBase(c), digits); } NumberFormatInfo instance = NumberFormatInfo.GetInstance(provider); byte* digits2 = stackalloc byte[11]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, digits2, 11); UInt32ToNumber(value, ref number); char* pointer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(new Span(pointer, 32)); if (c != 0) { NumberToString(ref sb, ref number, c, digits, instance); } else { NumberToStringFormat(ref sb, ref number, format2, instance); } return sb.ToString(); } } public static bool TryFormatUInt32(uint value, ReadOnlySpan format, IFormatProvider provider, Span destination, out int charsWritten) { if (format.Length == 0) { return TryUInt32ToDecStr(value, -1, destination, out charsWritten); } return TryFormatUInt32Slow(value, format, provider, destination, out charsWritten); unsafe static bool TryFormatUInt32Slow(uint value, ReadOnlySpan format, IFormatProvider provider, Span destination, out int charsWritten) { int digits; char c = ParseFormatSpecifier(format, out digits); char c2 = (char)(c & 0xFFDFu); if ((c2 == 'G') ? (digits < 1) : (c2 == 'D')) { return TryUInt32ToDecStr(value, digits, destination, out charsWritten); } if (c2 == 'X') { return TryInt32ToHexStr((int)value, GetHexBase(c), digits, destination, out charsWritten); } NumberFormatInfo instance = NumberFormatInfo.GetInstance(provider); byte* digits2 = stackalloc byte[11]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, digits2, 11); UInt32ToNumber(value, ref number); char* pointer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(new Span(pointer, 32)); if (c != 0) { NumberToString(ref sb, ref number, c, digits, instance); } else { NumberToStringFormat(ref sb, ref number, format, instance); } return sb.TryCopyTo(destination, out charsWritten); } } public static string FormatInt64(long value, string format, IFormatProvider provider) { if (string.IsNullOrEmpty(format)) { if (value < 0) { return NegativeInt64ToDecStr(value, -1, NumberFormatInfo.GetInstance(provider).NegativeSign); } return UInt64ToDecStr((ulong)value, -1); } return FormatInt64Slow(value, format, provider); unsafe static string FormatInt64Slow(long value, string format, IFormatProvider provider) { ReadOnlySpan format2 = format; int digits; char c = ParseFormatSpecifier(format2, out digits); char c2 = (char)(c & 0xFFDFu); if ((c2 == 'G') ? (digits < 1) : (c2 == 'D')) { if (value < 0) { return NegativeInt64ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign); } return UInt64ToDecStr((ulong)value, digits); } if (c2 == 'X') { return Int64ToHexStr(value, GetHexBase(c), digits); } NumberFormatInfo instance = NumberFormatInfo.GetInstance(provider); byte* digits2 = stackalloc byte[20]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, digits2, 20); Int64ToNumber(value, ref number); char* pointer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(new Span(pointer, 32)); if (c != 0) { NumberToString(ref sb, ref number, c, digits, instance); } else { NumberToStringFormat(ref sb, ref number, format2, instance); } return sb.ToString(); } } public static bool TryFormatInt64(long value, ReadOnlySpan format, IFormatProvider provider, Span destination, out int charsWritten) { if (format.Length == 0) { if (value < 0) { return TryNegativeInt64ToDecStr(value, -1, NumberFormatInfo.GetInstance(provider).NegativeSign, destination, out charsWritten); } return TryUInt64ToDecStr((ulong)value, -1, destination, out charsWritten); } return TryFormatInt64Slow(value, format, provider, destination, out charsWritten); unsafe static bool TryFormatInt64Slow(long value, ReadOnlySpan format, IFormatProvider provider, Span destination, out int charsWritten) { int digits; char c = ParseFormatSpecifier(format, out digits); char c2 = (char)(c & 0xFFDFu); if ((c2 == 'G') ? (digits < 1) : (c2 == 'D')) { if (value < 0) { return TryNegativeInt64ToDecStr(value, digits, NumberFormatInfo.GetInstance(provider).NegativeSign, destination, out charsWritten); } return TryUInt64ToDecStr((ulong)value, digits, destination, out charsWritten); } if (c2 == 'X') { return TryInt64ToHexStr(value, GetHexBase(c), digits, destination, out charsWritten); } NumberFormatInfo instance = NumberFormatInfo.GetInstance(provider); byte* digits2 = stackalloc byte[20]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, digits2, 20); Int64ToNumber(value, ref number); char* pointer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(new Span(pointer, 32)); if (c != 0) { NumberToString(ref sb, ref number, c, digits, instance); } else { NumberToStringFormat(ref sb, ref number, format, instance); } return sb.TryCopyTo(destination, out charsWritten); } } public static string FormatUInt64(ulong value, string format, IFormatProvider provider) { if (string.IsNullOrEmpty(format)) { return UInt64ToDecStr(value, -1); } return FormatUInt64Slow(value, format, provider); unsafe static string FormatUInt64Slow(ulong value, string format, IFormatProvider provider) { ReadOnlySpan format2 = format; int digits; char c = ParseFormatSpecifier(format2, out digits); char c2 = (char)(c & 0xFFDFu); if ((c2 == 'G') ? (digits < 1) : (c2 == 'D')) { return UInt64ToDecStr(value, digits); } if (c2 == 'X') { return Int64ToHexStr((long)value, GetHexBase(c), digits); } NumberFormatInfo instance = NumberFormatInfo.GetInstance(provider); byte* digits2 = stackalloc byte[21]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, digits2, 21); UInt64ToNumber(value, ref number); char* pointer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(new Span(pointer, 32)); if (c != 0) { NumberToString(ref sb, ref number, c, digits, instance); } else { NumberToStringFormat(ref sb, ref number, format2, instance); } return sb.ToString(); } } public static bool TryFormatUInt64(ulong value, ReadOnlySpan format, IFormatProvider provider, Span destination, out int charsWritten) { if (format.Length == 0) { return TryUInt64ToDecStr(value, -1, destination, out charsWritten); } return TryFormatUInt64Slow(value, format, provider, destination, out charsWritten); unsafe static bool TryFormatUInt64Slow(ulong value, ReadOnlySpan format, IFormatProvider provider, Span destination, out int charsWritten) { int digits; char c = ParseFormatSpecifier(format, out digits); char c2 = (char)(c & 0xFFDFu); if ((c2 == 'G') ? (digits < 1) : (c2 == 'D')) { return TryUInt64ToDecStr(value, digits, destination, out charsWritten); } if (c2 == 'X') { return TryInt64ToHexStr((long)value, GetHexBase(c), digits, destination, out charsWritten); } NumberFormatInfo instance = NumberFormatInfo.GetInstance(provider); byte* digits2 = stackalloc byte[21]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, digits2, 21); UInt64ToNumber(value, ref number); char* pointer = stackalloc char[32]; ValueStringBuilder sb = new ValueStringBuilder(new Span(pointer, 32)); if (c != 0) { NumberToString(ref sb, ref number, c, digits, instance); } else { NumberToStringFormat(ref sb, ref number, format, instance); } return sb.TryCopyTo(destination, out charsWritten); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static void Int32ToNumber(int value, ref NumberBuffer number) { number.DigitsCount = 10; if (value >= 0) { number.IsNegative = false; } else { number.IsNegative = true; value = -value; } byte* digitsPointer = number.GetDigitsPointer(); byte* ptr = UInt32ToDecChars(digitsPointer + 10, (uint)value, 0); int num = (number.Scale = (number.DigitsCount = (int)(digitsPointer + 10 - ptr))); byte* digitsPointer2 = number.GetDigitsPointer(); while (--num >= 0) { *(digitsPointer2++) = *(ptr++); } *digitsPointer2 = 0; } public static string Int32ToDecStr(int value) { if (value < 0) { return NegativeInt32ToDecStr(value, -1, NumberFormatInfo.CurrentInfo.NegativeSign); } return UInt32ToDecStr((uint)value); } private unsafe static string NegativeInt32ToDecStr(int value, int digits, string sNegative) { if (digits < 1) { digits = 1; } int num = Math.Max(digits, FormattingHelpers.CountDigits((uint)(-value))) + sNegative.Length; string text = string.FastAllocateString(num); fixed (char* ptr = text) { char* ptr2 = UInt32ToDecChars(ptr + num, (uint)(-value), digits); for (int num2 = sNegative.Length - 1; num2 >= 0; num2--) { *(--ptr2) = sNegative[num2]; } } return text; } private unsafe static bool TryNegativeInt32ToDecStr(int value, int digits, string sNegative, Span destination, out int charsWritten) { if (digits < 1) { digits = 1; } int num = Math.Max(digits, FormattingHelpers.CountDigits((uint)(-value))) + sNegative.Length; if (num > destination.Length) { charsWritten = 0; return false; } charsWritten = num; fixed (char* ptr = &MemoryMarshal.GetReference(destination)) { char* ptr2 = UInt32ToDecChars(ptr + num, (uint)(-value), digits); for (int num2 = sNegative.Length - 1; num2 >= 0; num2--) { *(--ptr2) = sNegative[num2]; } } return true; } private unsafe static string Int32ToHexStr(int value, char hexBase, int digits) { if (digits < 1) { digits = 1; } int num = Math.Max(digits, FormattingHelpers.CountHexDigits((uint)value)); string text = string.FastAllocateString(num); fixed (char* ptr = text) { char* ptr2 = Int32ToHexChars(ptr + num, (uint)value, hexBase, digits); } return text; } private unsafe static bool TryInt32ToHexStr(int value, char hexBase, int digits, Span destination, out int charsWritten) { if (digits < 1) { digits = 1; } int num = Math.Max(digits, FormattingHelpers.CountHexDigits((uint)value)); if (num > destination.Length) { charsWritten = 0; return false; } charsWritten = num; fixed (char* ptr = &MemoryMarshal.GetReference(destination)) { char* ptr2 = Int32ToHexChars(ptr + num, (uint)value, hexBase, digits); } return true; } private unsafe static char* Int32ToHexChars(char* buffer, uint value, int hexBase, int digits) { while (--digits >= 0 || value != 0) { byte b = (byte)(value & 0xFu); *(--buffer) = (char)(b + ((b < 10) ? 48 : hexBase)); value >>= 4; } return buffer; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static void UInt32ToNumber(uint value, ref NumberBuffer number) { number.DigitsCount = 10; number.IsNegative = false; byte* digitsPointer = number.GetDigitsPointer(); byte* ptr = UInt32ToDecChars(digitsPointer + 10, value, 0); int num = (number.Scale = (number.DigitsCount = (int)(digitsPointer + 10 - ptr))); byte* digitsPointer2 = number.GetDigitsPointer(); while (--num >= 0) { *(digitsPointer2++) = *(ptr++); } *digitsPointer2 = 0; } internal unsafe static byte* UInt32ToDecChars(byte* bufferEnd, uint value, int digits) { while (--digits >= 0 || value != 0) { uint num; (value, num) = Math.DivRem(value, 10u); *(--bufferEnd) = (byte)(num + 48); } return bufferEnd; } internal unsafe static char* UInt32ToDecChars(char* bufferEnd, uint value, int digits) { while (--digits >= 0 || value != 0) { uint num; (value, num) = Math.DivRem(value, 10u); *(--bufferEnd) = (char)(num + 48); } return bufferEnd; } internal unsafe static string UInt32ToDecStr(uint value) { int num = FormattingHelpers.CountDigits(value); if (num == 1) { return s_singleDigitStringCache[value]; } string text = string.FastAllocateString(num); fixed (char* ptr = text) { char* ptr2 = ptr + num; do { uint num2; (value, num2) = Math.DivRem(value, 10u); *(--ptr2) = (char)(num2 + 48); } while (value != 0); } return text; } private unsafe static string UInt32ToDecStr(uint value, int digits) { if (digits <= 1) { return UInt32ToDecStr(value); } int num = Math.Max(digits, FormattingHelpers.CountDigits(value)); string text = string.FastAllocateString(num); fixed (char* ptr = text) { char* bufferEnd = ptr + num; bufferEnd = UInt32ToDecChars(bufferEnd, value, digits); } return text; } private unsafe static bool TryUInt32ToDecStr(uint value, int digits, Span destination, out int charsWritten) { int num = Math.Max(digits, FormattingHelpers.CountDigits(value)); if (num > destination.Length) { charsWritten = 0; return false; } charsWritten = num; fixed (char* ptr = &MemoryMarshal.GetReference(destination)) { char* ptr2 = ptr + num; if (digits <= 1) { do { uint num2; (value, num2) = Math.DivRem(value, 10u); *(--ptr2) = (char)(num2 + 48); } while (value != 0); } else { ptr2 = UInt32ToDecChars(ptr2, value, digits); } } return true; } private unsafe static void Int64ToNumber(long input, ref NumberBuffer number) { ulong value = (ulong)input; number.IsNegative = input < 0; number.DigitsCount = 19; if (number.IsNegative) { value = (ulong)(-input); } byte* digitsPointer = number.GetDigitsPointer(); byte* bufferEnd = digitsPointer + 19; while (High32(value) != 0) { bufferEnd = UInt32ToDecChars(bufferEnd, Int64DivMod1E9(ref value), 9); } bufferEnd = UInt32ToDecChars(bufferEnd, Low32(value), 0); int num = (number.Scale = (number.DigitsCount = (int)(digitsPointer + 19 - bufferEnd))); byte* digitsPointer2 = number.GetDigitsPointer(); while (--num >= 0) { *(digitsPointer2++) = *(bufferEnd++); } *digitsPointer2 = 0; } public static string Int64ToDecStr(long value) { if (value < 0) { return NegativeInt64ToDecStr(value, -1, NumberFormatInfo.CurrentInfo.NegativeSign); } return UInt64ToDecStr((ulong)value, -1); } private unsafe static string NegativeInt64ToDecStr(long input, int digits, string sNegative) { if (digits < 1) { digits = 1; } ulong value = (ulong)(-input); int num = Math.Max(digits, FormattingHelpers.CountDigits(value)) + sNegative.Length; string text = string.FastAllocateString(num); fixed (char* ptr = text) { char* bufferEnd = ptr + num; while (High32(value) != 0) { bufferEnd = UInt32ToDecChars(bufferEnd, Int64DivMod1E9(ref value), 9); digits -= 9; } bufferEnd = UInt32ToDecChars(bufferEnd, Low32(value), digits); for (int num2 = sNegative.Length - 1; num2 >= 0; num2--) { *(--bufferEnd) = sNegative[num2]; } } return text; } private unsafe static bool TryNegativeInt64ToDecStr(long input, int digits, string sNegative, Span destination, out int charsWritten) { if (digits < 1) { digits = 1; } ulong value = (ulong)(-input); int num = Math.Max(digits, FormattingHelpers.CountDigits((ulong)(-input))) + sNegative.Length; if (num > destination.Length) { charsWritten = 0; return false; } charsWritten = num; fixed (char* ptr = &MemoryMarshal.GetReference(destination)) { char* bufferEnd = ptr + num; while (High32(value) != 0) { bufferEnd = UInt32ToDecChars(bufferEnd, Int64DivMod1E9(ref value), 9); digits -= 9; } bufferEnd = UInt32ToDecChars(bufferEnd, Low32(value), digits); for (int num2 = sNegative.Length - 1; num2 >= 0; num2--) { *(--bufferEnd) = sNegative[num2]; } } return true; } private unsafe static string Int64ToHexStr(long value, char hexBase, int digits) { int num = Math.Max(digits, FormattingHelpers.CountHexDigits((ulong)value)); string text = string.FastAllocateString(num); fixed (char* ptr = text) { char* buffer = ptr + num; if (High32((ulong)value) != 0) { buffer = Int32ToHexChars(buffer, Low32((ulong)value), hexBase, 8); buffer = Int32ToHexChars(buffer, High32((ulong)value), hexBase, digits - 8); } else { buffer = Int32ToHexChars(buffer, Low32((ulong)value), hexBase, Math.Max(digits, 1)); } } return text; } private unsafe static bool TryInt64ToHexStr(long value, char hexBase, int digits, Span destination, out int charsWritten) { int num = Math.Max(digits, FormattingHelpers.CountHexDigits((ulong)value)); if (num > destination.Length) { charsWritten = 0; return false; } charsWritten = num; fixed (char* ptr = &MemoryMarshal.GetReference(destination)) { char* buffer = ptr + num; if (High32((ulong)value) != 0) { buffer = Int32ToHexChars(buffer, Low32((ulong)value), hexBase, 8); buffer = Int32ToHexChars(buffer, High32((ulong)value), hexBase, digits - 8); } else { buffer = Int32ToHexChars(buffer, Low32((ulong)value), hexBase, Math.Max(digits, 1)); } } return true; } private unsafe static void UInt64ToNumber(ulong value, ref NumberBuffer number) { number.DigitsCount = 20; number.IsNegative = false; byte* digitsPointer = number.GetDigitsPointer(); byte* bufferEnd = digitsPointer + 20; while (High32(value) != 0) { bufferEnd = UInt32ToDecChars(bufferEnd, Int64DivMod1E9(ref value), 9); } bufferEnd = UInt32ToDecChars(bufferEnd, Low32(value), 0); int num = (number.Scale = (number.DigitsCount = (int)(digitsPointer + 20 - bufferEnd))); byte* digitsPointer2 = number.GetDigitsPointer(); while (--num >= 0) { *(digitsPointer2++) = *(bufferEnd++); } *digitsPointer2 = 0; } internal unsafe static string UInt64ToDecStr(ulong value, int digits) { if (digits < 1) { digits = 1; } int num = Math.Max(digits, FormattingHelpers.CountDigits(value)); if (num == 1) { return s_singleDigitStringCache[value]; } string text = string.FastAllocateString(num); fixed (char* ptr = text) { char* bufferEnd = ptr + num; while (High32(value) != 0) { bufferEnd = UInt32ToDecChars(bufferEnd, Int64DivMod1E9(ref value), 9); digits -= 9; } bufferEnd = UInt32ToDecChars(bufferEnd, Low32(value), digits); } return text; } private unsafe static bool TryUInt64ToDecStr(ulong value, int digits, Span destination, out int charsWritten) { if (digits < 1) { digits = 1; } int num = Math.Max(digits, FormattingHelpers.CountDigits(value)); if (num > destination.Length) { charsWritten = 0; return false; } charsWritten = num; fixed (char* ptr = &MemoryMarshal.GetReference(destination)) { char* bufferEnd = ptr + num; while (High32(value) != 0) { bufferEnd = UInt32ToDecChars(bufferEnd, Int64DivMod1E9(ref value), 9); digits -= 9; } bufferEnd = UInt32ToDecChars(bufferEnd, Low32(value), digits); } return true; } internal static char ParseFormatSpecifier(ReadOnlySpan format, out int digits) { char c = '\0'; if (format.Length > 0) { c = format[0]; if ((uint)(c - 65) <= 25u || (uint)(c - 97) <= 25u) { if (format.Length == 1) { digits = -1; return c; } if (format.Length == 2) { int num = format[1] - 48; if ((uint)num < 10u) { digits = num; return c; } } else if (format.Length == 3) { int num2 = format[1] - 48; int num3 = format[2] - 48; if ((uint)num2 < 10u && (uint)num3 < 10u) { digits = num2 * 10 + num3; return c; } } int num4 = 0; int num5 = 1; while (num5 < format.Length && (uint)(format[num5] - 48) < 10u) { int num6 = num4 * 10 + format[num5++] - 48; if (num6 < num4) { throw new FormatException(SR.Argument_BadFormatSpecifier); } num4 = num6; } if (num5 == format.Length || format[num5] == '\0') { digits = num4; return c; } } } digits = -1; if (format.Length != 0 && c != 0) { return '\0'; } return 'G'; } internal static void NumberToString(ref ValueStringBuilder sb, ref NumberBuffer number, char format, int nMaxDigits, NumberFormatInfo info) { bool isCorrectlyRounded = number.Kind == NumberBufferKind.FloatingPoint; bool bSuppressScientific; switch (format) { case 'C': case 'c': if (nMaxDigits < 0) { nMaxDigits = info.CurrencyDecimalDigits; } RoundNumber(ref number, number.Scale + nMaxDigits, isCorrectlyRounded); FormatCurrency(ref sb, ref number, nMaxDigits, info); return; case 'F': case 'f': if (nMaxDigits < 0) { nMaxDigits = info.NumberDecimalDigits; } RoundNumber(ref number, number.Scale + nMaxDigits, isCorrectlyRounded); if (number.IsNegative) { sb.Append(info.NegativeSign); } FormatFixed(ref sb, ref number, nMaxDigits, null, info.NumberDecimalSeparator, null); return; case 'N': case 'n': if (nMaxDigits < 0) { nMaxDigits = info.NumberDecimalDigits; } RoundNumber(ref number, number.Scale + nMaxDigits, isCorrectlyRounded); FormatNumber(ref sb, ref number, nMaxDigits, info); return; case 'E': case 'e': if (nMaxDigits < 0) { nMaxDigits = 6; } nMaxDigits++; RoundNumber(ref number, nMaxDigits, isCorrectlyRounded); if (number.IsNegative) { sb.Append(info.NegativeSign); } FormatScientific(ref sb, ref number, nMaxDigits, info, format); return; case 'G': case 'g': bSuppressScientific = false; if (nMaxDigits < 1) { if (number.Kind == NumberBufferKind.Decimal && nMaxDigits == -1) { bSuppressScientific = true; if (number.Digits[0] != 0) { goto IL_0189; } goto IL_019e; } nMaxDigits = number.DigitsCount; } RoundNumber(ref number, nMaxDigits, isCorrectlyRounded); goto IL_0189; case 'P': case 'p': if (nMaxDigits < 0) { nMaxDigits = info.PercentDecimalDigits; } number.Scale += 2; RoundNumber(ref number, number.Scale + nMaxDigits, isCorrectlyRounded); FormatPercent(ref sb, ref number, nMaxDigits, info); return; case 'R': case 'r': { if (number.Kind != NumberBufferKind.FloatingPoint) { break; } format = (char)(format - 11); goto case 'G'; } IL_0189: if (number.IsNegative) { sb.Append(info.NegativeSign); } goto IL_019e; IL_019e: FormatGeneral(ref sb, ref number, nMaxDigits, info, (char)(format - 2), bSuppressScientific); return; } throw new FormatException(SR.Argument_BadFormatSpecifier); } internal unsafe static void NumberToStringFormat(ref ValueStringBuilder sb, ref NumberBuffer number, ReadOnlySpan format, NumberFormatInfo info) { int num = 0; byte* digitsPointer = number.GetDigitsPointer(); int num2 = FindSection(format, (*digitsPointer == 0) ? 2 : (number.IsNegative ? 1 : 0)); int num3; int num4; bool flag; bool flag2; int num5; int num6; int num9; while (true) { num3 = 0; num4 = -1; num5 = int.MaxValue; num6 = 0; flag = false; int num7 = -1; flag2 = false; int num8 = 0; num9 = num2; fixed (char* ptr = &MemoryMarshal.GetReference(format)) { char c; while (num9 < format.Length && (c = ptr[num9++]) != 0) { switch (c) { case ';': break; case '#': num3++; continue; case '0': if (num5 == int.MaxValue) { num5 = num3; } num3++; num6 = num3; continue; case '.': if (num4 < 0) { num4 = num3; } continue; case ',': if (num3 <= 0 || num4 >= 0) { continue; } if (num7 >= 0) { if (num7 == num3) { num++; continue; } flag2 = true; } num7 = num3; num = 1; continue; case '%': num8 += 2; continue; case '‰': num8 += 3; continue; case '"': case '\'': while (num9 < format.Length && ptr[num9] != 0 && ptr[num9++] != c) { } continue; case '\\': if (num9 < format.Length && ptr[num9] != 0) { num9++; } continue; case 'E': case 'e': if ((num9 < format.Length && ptr[num9] == '0') || (num9 + 1 < format.Length && (ptr[num9] == '+' || ptr[num9] == '-') && ptr[num9 + 1] == '0')) { while (++num9 < format.Length && ptr[num9] == '0') { } flag = true; } continue; default: continue; } break; } } if (num4 < 0) { num4 = num3; } if (num7 >= 0) { if (num7 == num4) { num8 -= num * 3; } else { flag2 = true; } } if (*digitsPointer != 0) { number.Scale += num8; int pos = (flag ? num3 : (number.Scale + num3 - num4)); RoundNumber(ref number, pos, isCorrectlyRounded: false); if (*digitsPointer != 0) { break; } num9 = FindSection(format, 2); if (num9 == num2) { break; } num2 = num9; continue; } if (number.Kind != NumberBufferKind.FloatingPoint) { number.IsNegative = false; } number.Scale = 0; break; } num5 = ((num5 < num4) ? (num4 - num5) : 0); num6 = ((num6 > num4) ? (num4 - num6) : 0); int num10; int num11; if (flag) { num10 = num4; num11 = 0; } else { num10 = ((number.Scale > num4) ? number.Scale : num4); num11 = number.Scale - num4; } num9 = num2; Span span = stackalloc int[4]; int num12 = -1; if (flag2 && info.NumberGroupSeparator.Length > 0) { int[] numberGroupSizes = info._numberGroupSizes; int num13 = 0; int i = 0; int num14 = numberGroupSizes.Length; if (num14 != 0) { i = numberGroupSizes[num13]; } int num15 = i; int num16 = num10 + ((num11 < 0) ? num11 : 0); for (int num17 = ((num5 > num16) ? num5 : num16); num17 > i; i += num15) { if (num15 == 0) { break; } num12++; if (num12 >= span.Length) { int[] array = new int[span.Length * 2]; span.CopyTo(array); span = array; } span[num12] = i; if (num13 < num14 - 1) { num13++; num15 = numberGroupSizes[num13]; } } } if (number.IsNegative && num2 == 0 && number.Scale != 0) { sb.Append(info.NegativeSign); } bool flag3 = false; fixed (char* ptr3 = &MemoryMarshal.GetReference(format)) { byte* ptr2 = digitsPointer; char c; while (num9 < format.Length && (c = ptr3[num9++]) != 0 && c != ';') { if (num11 > 0 && (c == '#' || c == '.' || c == '0')) { while (num11 > 0) { sb.Append((char)((*ptr2 != 0) ? (*(ptr2++)) : 48)); if (flag2 && num10 > 1 && num12 >= 0 && num10 == span[num12] + 1) { sb.Append(info.NumberGroupSeparator); num12--; } num10--; num11--; } } switch (c) { case '#': case '0': if (num11 < 0) { num11++; c = ((num10 <= num5) ? '0' : '\0'); } else { c = ((*ptr2 != 0) ? ((char)(*(ptr2++))) : ((num10 > num6) ? '0' : '\0')); } if (c != 0) { sb.Append(c); if (flag2 && num10 > 1 && num12 >= 0 && num10 == span[num12] + 1) { sb.Append(info.NumberGroupSeparator); num12--; } } num10--; break; case '.': if (!(num10 != 0 || flag3) && (num6 < 0 || (num4 < num3 && *ptr2 != 0))) { sb.Append(info.NumberDecimalSeparator); flag3 = true; } break; case '‰': sb.Append(info.PerMilleSymbol); break; case '%': sb.Append(info.PercentSymbol); break; case '"': case '\'': while (num9 < format.Length && ptr3[num9] != 0 && ptr3[num9] != c) { sb.Append(ptr3[num9++]); } if (num9 < format.Length && ptr3[num9] != 0) { num9++; } break; case '\\': if (num9 < format.Length && ptr3[num9] != 0) { sb.Append(ptr3[num9++]); } break; case 'E': case 'e': { bool positiveSign = false; int num18 = 0; if (flag) { if (num9 < format.Length && ptr3[num9] == '0') { num18++; } else if (num9 + 1 < format.Length && ptr3[num9] == '+' && ptr3[num9 + 1] == '0') { positiveSign = true; } else if (num9 + 1 >= format.Length || ptr3[num9] != '-' || ptr3[num9 + 1] != '0') { sb.Append(c); break; } while (++num9 < format.Length && ptr3[num9] == '0') { num18++; } if (num18 > 10) { num18 = 10; } int value = ((*digitsPointer != 0) ? (number.Scale - num4) : 0); FormatExponent(ref sb, info, value, c, num18, positiveSign); flag = false; break; } sb.Append(c); if (num9 < format.Length) { if (ptr3[num9] == '+' || ptr3[num9] == '-') { sb.Append(ptr3[num9++]); } while (num9 < format.Length && ptr3[num9] == '0') { sb.Append(ptr3[num9++]); } } break; } default: sb.Append(c); break; case ',': break; } } } if (number.IsNegative && num2 == 0 && number.Scale == 0 && sb.Length > 0) { sb.Insert(0, info.NegativeSign); } } private static void FormatCurrency(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info) { string text = (number.IsNegative ? s_negCurrencyFormats[info.CurrencyNegativePattern] : s_posCurrencyFormats[info.CurrencyPositivePattern]); string text2 = text; foreach (char c in text2) { switch (c) { case '#': FormatFixed(ref sb, ref number, nMaxDigits, info._currencyGroupSizes, info.CurrencyDecimalSeparator, info.CurrencyGroupSeparator); break; case '-': sb.Append(info.NegativeSign); break; case '$': sb.Append(info.CurrencySymbol); break; default: sb.Append(c); break; } } } private unsafe static void FormatFixed(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, int[] groupDigits, string sDecimal, string sGroup) { int num = number.Scale; byte* ptr = number.GetDigitsPointer(); if (num > 0) { if (groupDigits != null) { int num2 = 0; int num3 = num; int num4 = 0; if (groupDigits.Length != 0) { int num5 = groupDigits[num2]; while (num > num5 && groupDigits[num2] != 0) { num3 += sGroup.Length; if (num2 < groupDigits.Length - 1) { num2++; } num5 += groupDigits[num2]; if (num5 < 0 || num3 < 0) { throw new ArgumentOutOfRangeException(); } } num4 = ((num5 != 0) ? groupDigits[0] : 0); } num2 = 0; int num6 = 0; int digitsCount = number.DigitsCount; int num7 = ((num < digitsCount) ? num : digitsCount); fixed (char* ptr2 = &MemoryMarshal.GetReference(sb.AppendSpan(num3))) { char* ptr3 = ptr2 + num3 - 1; for (int num8 = num - 1; num8 >= 0; num8--) { *(ptr3--) = (char)((num8 < num7) ? ptr[num8] : 48); if (num4 > 0) { num6++; if (num6 == num4 && num8 != 0) { for (int num9 = sGroup.Length - 1; num9 >= 0; num9--) { *(ptr3--) = sGroup[num9]; } if (num2 < groupDigits.Length - 1) { num2++; num4 = groupDigits[num2]; } num6 = 0; } } } ptr += num7; } } else { do { sb.Append((char)((*ptr != 0) ? (*(ptr++)) : 48)); } while (--num > 0); } } else { sb.Append('0'); } if (nMaxDigits > 0) { sb.Append(sDecimal); if (num < 0 && nMaxDigits > 0) { int num10 = Math.Min(-num, nMaxDigits); sb.Append('0', num10); num += num10; nMaxDigits -= num10; } while (nMaxDigits > 0) { sb.Append((char)((*ptr != 0) ? (*(ptr++)) : 48)); nMaxDigits--; } } } private static void FormatNumber(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info) { string text = (number.IsNegative ? s_negNumberFormats[info.NumberNegativePattern] : "#"); string text2 = text; foreach (char c in text2) { switch (c) { case '#': FormatFixed(ref sb, ref number, nMaxDigits, info._numberGroupSizes, info.NumberDecimalSeparator, info.NumberGroupSeparator); break; case '-': sb.Append(info.NegativeSign); break; default: sb.Append(c); break; } } } private unsafe static void FormatScientific(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info, char expChar) { byte* digitsPointer = number.GetDigitsPointer(); sb.Append((char)((*digitsPointer != 0) ? (*(digitsPointer++)) : 48)); if (nMaxDigits != 1) { sb.Append(info.NumberDecimalSeparator); } while (--nMaxDigits > 0) { sb.Append((char)((*digitsPointer != 0) ? (*(digitsPointer++)) : 48)); } int value = ((number.Digits[0] != 0) ? (number.Scale - 1) : 0); FormatExponent(ref sb, info, value, expChar, 3, positiveSign: true); } private unsafe static void FormatExponent(ref ValueStringBuilder sb, NumberFormatInfo info, int value, char expChar, int minDigits, bool positiveSign) { sb.Append(expChar); if (value < 0) { sb.Append(info.NegativeSign); value = -value; } else if (positiveSign) { sb.Append(info.PositiveSign); } char* ptr = stackalloc char[10]; char* ptr2 = UInt32ToDecChars(ptr + 10, (uint)value, minDigits); sb.Append(ptr2, (int)(ptr + 10 - ptr2)); } private unsafe static void FormatGeneral(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info, char expChar, bool bSuppressScientific) { int i = number.Scale; bool flag = false; if (!bSuppressScientific && (i > nMaxDigits || i < -3)) { i = 1; flag = true; } byte* digitsPointer = number.GetDigitsPointer(); if (i > 0) { do { sb.Append((char)((*digitsPointer != 0) ? (*(digitsPointer++)) : 48)); } while (--i > 0); } else { sb.Append('0'); } if (*digitsPointer != 0 || i < 0) { sb.Append(info.NumberDecimalSeparator); for (; i < 0; i++) { sb.Append('0'); } while (*digitsPointer != 0) { sb.Append((char)(*(digitsPointer++))); } } if (flag) { FormatExponent(ref sb, info, number.Scale - 1, expChar, 2, positiveSign: true); } } private static void FormatPercent(ref ValueStringBuilder sb, ref NumberBuffer number, int nMaxDigits, NumberFormatInfo info) { string text = (number.IsNegative ? s_negPercentFormats[info.PercentNegativePattern] : s_posPercentFormats[info.PercentPositivePattern]); string text2 = text; foreach (char c in text2) { switch (c) { case '#': FormatFixed(ref sb, ref number, nMaxDigits, info._percentGroupSizes, info.PercentDecimalSeparator, info.PercentGroupSeparator); break; case '-': sb.Append(info.NegativeSign); break; case '%': sb.Append(info.PercentSymbol); break; default: sb.Append(c); break; } } } internal unsafe static void RoundNumber(ref NumberBuffer number, int pos, bool isCorrectlyRounded) { byte* digitsPointer = number.GetDigitsPointer(); int j; for (j = 0; j < pos && digitsPointer[j] != 0; j++) { } if (j == pos && ShouldRoundUp(digitsPointer, j, number.Kind, isCorrectlyRounded)) { while (j > 0 && digitsPointer[j - 1] == 57) { j--; } if (j > 0) { byte* num = digitsPointer + (j - 1); (*num)++; } else { number.Scale++; *digitsPointer = 49; j = 1; } } else { while (j > 0 && digitsPointer[j - 1] == 48) { j--; } } if (j == 0) { if (number.Kind != NumberBufferKind.FloatingPoint) { number.IsNegative = false; } number.Scale = 0; } digitsPointer[j] = 0; number.DigitsCount = j; unsafe static bool ShouldRoundUp(byte* dig, int i, NumberBufferKind numberKind, bool isCorrectlyRounded) { byte b = dig[i]; if (b == 0 || isCorrectlyRounded) { return false; } return b >= 53; } } private unsafe static int FindSection(ReadOnlySpan format, int section) { if (section == 0) { return 0; } fixed (char* ptr = &MemoryMarshal.GetReference(format)) { int num = 0; while (true) { if (num >= format.Length) { return 0; } char c; char c2 = (c = ptr[num++]); if ((uint)c2 <= 34u) { if (c2 == '\0') { break; } if (c2 != '"') { continue; } } else if (c2 != '\'') { switch (c2) { default: continue; case '\\': if (num < format.Length && ptr[num] != 0) { num++; } continue; case ';': break; } if (--section == 0) { if (num >= format.Length || ptr[num] == '\0' || ptr[num] == ';') { break; } return num; } continue; } while (num < format.Length && ptr[num] != 0 && ptr[num++] != c) { } } return 0; } } private static uint Low32(ulong value) { return (uint)value; } private static uint High32(ulong value) { return (uint)((value & 0xFFFFFFFF00000000uL) >> 32); } private static uint Int64DivMod1E9(ref ulong value) { uint result = (uint)(value % 1000000000); value /= 1000000000uL; return result; } private static ulong ExtractFractionAndBiasedExponent(double value, out int exponent) { ulong num = BitConverter.DoubleToUInt64Bits(value); ulong num2 = num & 0xFFFFFFFFFFFFFuL; exponent = (int)(num >> 52) & 0x7FF; if (exponent != 0) { num2 |= 0x10000000000000uL; exponent -= 1075; } else { exponent = -1074; } return num2; } private static ushort ExtractFractionAndBiasedExponent(Half value, out int exponent) { ushort num = BitConverter.HalfToUInt16Bits(value); ushort num2 = (ushort)(num & 0x3FFu); exponent = (num >> 10) & 0x1F; if (exponent != 0) { num2 = (ushort)(num2 | 0x400u); exponent -= 25; } else { exponent = -24; } return num2; } private static uint ExtractFractionAndBiasedExponent(float value, out int exponent) { uint num = BitConverter.SingleToUInt32Bits(value); uint num2 = num & 0x7FFFFFu; exponent = (int)((num >> 23) & 0xFF); if (exponent != 0) { num2 |= 0x800000u; exponent -= 150; } else { exponent = -149; } return num2; } private unsafe static void AccumulateDecimalDigitsIntoBigInteger(ref NumberBuffer number, uint firstIndex, uint lastIndex, out BigInteger result) { BigInteger.SetZero(out result); byte* ptr = number.GetDigitsPointer() + firstIndex; uint num = lastIndex - firstIndex; while (num != 0) { uint num2 = Math.Min(num, 9u); uint value = DigitsToUInt32(ptr, (int)num2); result.MultiplyPow10(num2); result.Add(value); ptr += num2; num -= num2; } } private static ulong AssembleFloatingPointBits(in FloatingPointInfo info, ulong initialMantissa, int initialExponent, bool hasZeroTail) { uint num = BigInteger.CountSignificantBits(initialMantissa); int num2 = (int)(info.NormalMantissaBits - num); int num3 = initialExponent - num2; ulong num4 = initialMantissa; int num5 = num3; if (num3 > info.MaxBinaryExponent) { return info.InfinityBits; } if (num3 < info.MinBinaryExponent) { int num6 = num2 + num3 + info.ExponentBias - 1; num5 = -info.ExponentBias; if (num6 < 0) { num4 = RightShiftWithRounding(num4, -num6, hasZeroTail); if (num4 == 0L) { return info.ZeroBits; } if (num4 > info.DenormalMantissaMask) { num5 = initialExponent - (num6 + 1) - num2; } } else { num4 <<= num6; } } else if (num2 < 0) { num4 = RightShiftWithRounding(num4, -num2, hasZeroTail); if (num4 > info.NormalMantissaMask) { num4 >>= 1; num5++; if (num5 > info.MaxBinaryExponent) { return info.InfinityBits; } } } else if (num2 > 0) { num4 <<= num2; } num4 &= info.DenormalMantissaMask; ulong num7 = (ulong)((long)(num5 + info.ExponentBias) << (int)info.DenormalMantissaBits); return num7 | num4; } private static ulong ConvertBigIntegerToFloatingPointBits(ref BigInteger value, in FloatingPointInfo info, uint integerBitsOfPrecision, bool hasNonZeroFractionalPart) { int denormalMantissaBits = info.DenormalMantissaBits; if (integerBitsOfPrecision <= 64) { return AssembleFloatingPointBits(in info, value.ToUInt64(), denormalMantissaBits, !hasNonZeroFractionalPart); } (uint Quotient, uint Remainder) tuple = Math.DivRem(integerBitsOfPrecision, 32u); uint item = tuple.Quotient; uint item2 = tuple.Remainder; uint num = item - 1; uint num2 = num - 1; int num3 = denormalMantissaBits + (int)(num2 * 32); bool flag = !hasNonZeroFractionalPart; ulong initialMantissa; if (item2 == 0) { initialMantissa = ((ulong)value.GetBlock(num) << 32) + value.GetBlock(num2); } else { int num4 = (int)item2; int num5 = 64 - num4; int num6 = num5 - 32; num3 += (int)item2; uint block = value.GetBlock(num2); uint num7 = block >> num4; ulong num8 = (ulong)value.GetBlock(num) << num6; ulong num9 = (ulong)value.GetBlock(item) << num5; initialMantissa = num9 + num8 + num7; uint num10 = (uint)((1 << (int)item2) - 1); flag = flag && (block & num10) == 0; } for (uint num11 = 0u; num11 != num2; num11++) { flag &= value.GetBlock(num11) == 0; } return AssembleFloatingPointBits(in info, initialMantissa, num3, flag); } private unsafe static uint DigitsToUInt32(byte* p, int count) { byte* ptr = p + count; uint num = (uint)(*p - 48); for (p++; p < ptr; p++) { num = 10 * num + *p - 48; } return num; } private unsafe static ulong DigitsToUInt64(byte* p, int count) { byte* ptr = p + count; ulong num = (ulong)(*p - 48); for (p++; p < ptr; p++) { num = 10 * num + *p - 48; } return num; } private unsafe static ulong NumberToDoubleFloatingPointBits(ref NumberBuffer number, in FloatingPointInfo info) { uint digitsCount = (uint)number.DigitsCount; uint num = (uint)Math.Max(0, number.Scale); uint num2 = Math.Min(num, digitsCount); uint num3 = digitsCount - num2; uint num4 = (uint)Math.Abs(number.Scale - num2 - num3); byte* digitsPointer = number.GetDigitsPointer(); if (digitsCount <= 15 && num4 <= 22) { double num5 = DigitsToUInt64(digitsPointer, (int)digitsCount); double num6 = s_Pow10DoubleTable[num4]; num5 = ((num3 == 0) ? (num5 * num6) : (num5 / num6)); return BitConverter.DoubleToUInt64Bits(num5); } return NumberToFloatingPointBitsSlow(ref number, in info, num, num2, num3); } private unsafe static ushort NumberToHalfFloatingPointBits(ref NumberBuffer number, in FloatingPointInfo info) { uint digitsCount = (uint)number.DigitsCount; uint num = (uint)Math.Max(0, number.Scale); uint num2 = Math.Min(num, digitsCount); uint num3 = digitsCount - num2; uint num4 = (uint)Math.Abs(number.Scale - num2 - num3); byte* digitsPointer = number.GetDigitsPointer(); if (digitsCount <= 7 && num4 <= 10) { float num5 = DigitsToUInt32(digitsPointer, (int)digitsCount); float num6 = s_Pow10SingleTable[num4]; num5 = ((num3 == 0) ? (num5 * num6) : (num5 / num6)); return BitConverter.HalfToUInt16Bits((Half)num5); } if (digitsCount <= 15 && num4 <= 22) { double num7 = DigitsToUInt64(digitsPointer, (int)digitsCount); double num8 = s_Pow10DoubleTable[num4]; num7 = ((num3 == 0) ? (num7 * num8) : (num7 / num8)); return BitConverter.HalfToUInt16Bits((Half)num7); } return (ushort)NumberToFloatingPointBitsSlow(ref number, in info, num, num2, num3); } private unsafe static uint NumberToSingleFloatingPointBits(ref NumberBuffer number, in FloatingPointInfo info) { uint digitsCount = (uint)number.DigitsCount; uint num = (uint)Math.Max(0, number.Scale); uint num2 = Math.Min(num, digitsCount); uint num3 = digitsCount - num2; uint num4 = (uint)Math.Abs(number.Scale - num2 - num3); byte* digitsPointer = number.GetDigitsPointer(); if (digitsCount <= 7 && num4 <= 10) { float num5 = DigitsToUInt32(digitsPointer, (int)digitsCount); float num6 = s_Pow10SingleTable[num4]; num5 = ((num3 == 0) ? (num5 * num6) : (num5 / num6)); return BitConverter.SingleToUInt32Bits(num5); } if (digitsCount <= 15 && num4 <= 22) { double num7 = DigitsToUInt64(digitsPointer, (int)digitsCount); double num8 = s_Pow10DoubleTable[num4]; num7 = ((num3 == 0) ? (num7 * num8) : (num7 / num8)); return BitConverter.SingleToUInt32Bits((float)num7); } return (uint)NumberToFloatingPointBitsSlow(ref number, in info, num, num2, num3); } private static ulong NumberToFloatingPointBitsSlow(ref NumberBuffer number, in FloatingPointInfo info, uint positiveExponent, uint integerDigitsPresent, uint fractionalDigitsPresent) { uint num = (uint)(info.NormalMantissaBits + 1); uint digitsCount = (uint)number.DigitsCount; uint num2 = positiveExponent - integerDigitsPresent; uint lastIndex = digitsCount; AccumulateDecimalDigitsIntoBigInteger(ref number, 0u, integerDigitsPresent, out var result); if (num2 != 0) { if (num2 > info.OverflowDecimalExponent) { return info.InfinityBits; } result.MultiplyPow10(num2); } uint num3 = BigInteger.CountSignificantBits(ref result); if (num3 >= num || fractionalDigitsPresent == 0) { return ConvertBigIntegerToFloatingPointBits(ref result, in info, num3, fractionalDigitsPresent != 0); } uint num4 = fractionalDigitsPresent; if (number.Scale < 0) { num4 += (uint)(-number.Scale); } if (num3 == 0 && num4 - (int)digitsCount > info.OverflowDecimalExponent) { return info.ZeroBits; } AccumulateDecimalDigitsIntoBigInteger(ref number, integerDigitsPresent, lastIndex, out var result2); if (result2.IsZero()) { return ConvertBigIntegerToFloatingPointBits(ref result, in info, num3, fractionalDigitsPresent != 0); } BigInteger.Pow10(num4, out var result3); uint num5 = BigInteger.CountSignificantBits(ref result2); uint num6 = BigInteger.CountSignificantBits(ref result3); uint num7 = 0u; if (num6 > num5) { num7 = num6 - num5; } if (num7 != 0) { result2.ShiftLeft(num7); } uint num8 = num - num3; uint num9 = num8; if (num3 != 0) { if (num7 > num9) { return ConvertBigIntegerToFloatingPointBits(ref result, in info, num3, fractionalDigitsPresent != 0); } num9 -= num7; } uint num10 = num7; if (BigInteger.Compare(ref result2, ref result3) < 0) { num10++; } result2.ShiftLeft(num9); BigInteger.DivRem(ref result2, ref result3, out var quo, out var rem); ulong num11 = quo.ToUInt64(); bool flag = !number.HasNonZeroTail && rem.IsZero(); uint num12 = BigInteger.CountSignificantBits(num11); if (num12 > num8) { int num13 = (int)(num12 - num8); flag = flag && (num11 & (ulong)((1L << num13) - 1)) == 0; num11 >>= num13; } ulong num14 = result.ToUInt64(); ulong initialMantissa = (num14 << (int)num8) + num11; int initialExponent = (int)((num3 != 0) ? (num3 - 2) : (0 - num10 - 1)); return AssembleFloatingPointBits(in info, initialMantissa, initialExponent, flag); } private static ulong RightShiftWithRounding(ulong value, int shift, bool hasZeroTail) { if (shift >= 64) { return 0uL; } ulong num = (ulong)((1L << shift - 1) - 1); ulong num2 = (ulong)(1L << shift - 1); ulong num3 = (ulong)(1L << shift); bool lsbBit = (value & num3) != 0; bool roundBit = (value & num2) != 0; bool hasTailBits = !hasZeroTail || (value & num) != 0; return (value >> shift) + (ulong)(ShouldRoundUp(lsbBit, roundBit, hasTailBits) ? 1 : 0); } private static bool ShouldRoundUp(bool lsbBit, bool roundBit, bool hasTailBits) { if (roundBit) { return hasTailBits || lsbBit; } return false; } private unsafe static bool TryNumberToInt32(ref NumberBuffer number, ref int value) { int num = number.Scale; if (num > 10 || num < number.DigitsCount) { return false; } byte* digitsPointer = number.GetDigitsPointer(); int num2 = 0; while (--num >= 0) { if ((uint)num2 > 214748364u) { return false; } num2 *= 10; if (*digitsPointer != 0) { num2 += *(digitsPointer++) - 48; } } if (number.IsNegative) { num2 = -num2; if (num2 > 0) { return false; } } else if (num2 < 0) { return false; } value = num2; return true; } private unsafe static bool TryNumberToInt64(ref NumberBuffer number, ref long value) { int num = number.Scale; if (num > 19 || num < number.DigitsCount) { return false; } byte* digitsPointer = number.GetDigitsPointer(); long num2 = 0L; while (--num >= 0) { if ((ulong)num2 > 922337203685477580uL) { return false; } num2 *= 10; if (*digitsPointer != 0) { num2 += *(digitsPointer++) - 48; } } if (number.IsNegative) { num2 = -num2; if (num2 > 0) { return false; } } else if (num2 < 0) { return false; } value = num2; return true; } private unsafe static bool TryNumberToUInt32(ref NumberBuffer number, ref uint value) { int num = number.Scale; if (num > 10 || num < number.DigitsCount || number.IsNegative) { return false; } byte* digitsPointer = number.GetDigitsPointer(); uint num2 = 0u; while (--num >= 0) { if (num2 > 429496729) { return false; } num2 *= 10; if (*digitsPointer != 0) { uint num3 = num2 + (uint)(*(digitsPointer++) - 48); if (num3 < num2) { return false; } num2 = num3; } } value = num2; return true; } private unsafe static bool TryNumberToUInt64(ref NumberBuffer number, ref ulong value) { int num = number.Scale; if (num > 20 || num < number.DigitsCount || number.IsNegative) { return false; } byte* digitsPointer = number.GetDigitsPointer(); ulong num2 = 0uL; while (--num >= 0) { if (num2 > 1844674407370955161L) { return false; } num2 *= 10; if (*digitsPointer != 0) { ulong num3 = num2 + (ulong)(*(digitsPointer++) - 48); if (num3 < num2) { return false; } num2 = num3; } } value = num2; return true; } internal static int ParseInt32(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { int result; ParsingStatus parsingStatus = TryParseInt32(value, styles, info, out result); if (parsingStatus != 0) { ThrowOverflowOrFormatException(parsingStatus, TypeCode.Int32); } return result; } internal static long ParseInt64(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { long result; ParsingStatus parsingStatus = TryParseInt64(value, styles, info, out result); if (parsingStatus != 0) { ThrowOverflowOrFormatException(parsingStatus, TypeCode.Int64); } return result; } internal static uint ParseUInt32(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { uint result; ParsingStatus parsingStatus = TryParseUInt32(value, styles, info, out result); if (parsingStatus != 0) { ThrowOverflowOrFormatException(parsingStatus, TypeCode.UInt32); } return result; } internal static ulong ParseUInt64(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { ulong result; ParsingStatus parsingStatus = TryParseUInt64(value, styles, info, out result); if (parsingStatus != 0) { ThrowOverflowOrFormatException(parsingStatus, TypeCode.UInt64); } return result; } private unsafe static bool TryParseNumber(ref char* str, char* strEnd, NumberStyles styles, ref NumberBuffer number, NumberFormatInfo info) { string text = null; bool flag = false; string value; string value2; if ((styles & NumberStyles.AllowCurrencySymbol) != 0) { text = info.CurrencySymbol; value = info.CurrencyDecimalSeparator; value2 = info.CurrencyGroupSeparator; flag = true; } else { value = info.NumberDecimalSeparator; value2 = info.NumberGroupSeparator; } int num = 0; char* ptr = str; char c = ((ptr < strEnd) ? (*ptr) : '\0'); while (true) { if (!IsWhite(c) || (styles & NumberStyles.AllowLeadingWhite) == 0 || (((uint)num & (true ? 1u : 0u)) != 0 && (num & 0x20) == 0 && info.NumberNegativePattern != 2)) { char* ptr2; if ((styles & NumberStyles.AllowLeadingSign) != 0 && (num & 1) == 0 && ((ptr2 = MatchChars(ptr, strEnd, info.PositiveSign)) != null || ((ptr2 = MatchNegativeSignChars(ptr, strEnd, info)) != null && (number.IsNegative = true)))) { num |= 1; ptr = ptr2 - 1; } else if (c == '(' && (styles & NumberStyles.AllowParentheses) != 0 && (num & 1) == 0) { num |= 3; number.IsNegative = true; } else { if (text == null || (ptr2 = MatchChars(ptr, strEnd, text)) == null) { break; } num |= 0x20; text = null; ptr = ptr2 - 1; } } c = ((++ptr < strEnd) ? (*ptr) : '\0'); } int num2 = 0; int num3 = 0; int num4 = number.Digits.Length - 1; int num5 = 0; while (true) { char* ptr2; if (IsDigit(c)) { num |= 4; if (c != '0' || ((uint)num & 8u) != 0) { if (num2 < num4) { number.Digits[num2] = (byte)c; if (c != '0' || number.Kind != NumberBufferKind.Integer) { num3 = num2 + 1; } } else if (c != '0') { number.HasNonZeroTail = true; } if ((num & 0x10) == 0) { number.Scale++; } if (num2 < num4) { num5 = ((c == '0') ? (num5 + 1) : 0); } num2++; num |= 8; } else if (((uint)num & 0x10u) != 0) { number.Scale--; } } else if ((styles & NumberStyles.AllowDecimalPoint) != 0 && (num & 0x10) == 0 && ((ptr2 = MatchChars(ptr, strEnd, value)) != null || (flag && (num & 0x20) == 0 && (ptr2 = MatchChars(ptr, strEnd, info.NumberDecimalSeparator)) != null))) { num |= 0x10; ptr = ptr2 - 1; } else { if ((styles & NumberStyles.AllowThousands) == 0 || (num & 4) == 0 || ((uint)num & 0x10u) != 0 || ((ptr2 = MatchChars(ptr, strEnd, value2)) == null && (!flag || ((uint)num & 0x20u) != 0 || (ptr2 = MatchChars(ptr, strEnd, info.NumberGroupSeparator)) == null))) { break; } ptr = ptr2 - 1; } c = ((++ptr < strEnd) ? (*ptr) : '\0'); } bool flag2 = false; number.DigitsCount = num3; number.Digits[num3] = 0; if (((uint)num & 4u) != 0) { if ((c == 'E' || c == 'e') && (styles & NumberStyles.AllowExponent) != 0) { char* ptr3 = ptr; c = ((++ptr < strEnd) ? (*ptr) : '\0'); char* ptr2; if ((ptr2 = MatchChars(ptr, strEnd, info._positiveSign)) != null) { c = (((ptr = ptr2) < strEnd) ? (*ptr) : '\0'); } else if ((ptr2 = MatchNegativeSignChars(ptr, strEnd, info)) != null) { c = (((ptr = ptr2) < strEnd) ? (*ptr) : '\0'); flag2 = true; } if (IsDigit(c)) { int num6 = 0; do { num6 = num6 * 10 + (c - 48); c = ((++ptr < strEnd) ? (*ptr) : '\0'); if (num6 > 1000) { num6 = 9999; while (IsDigit(c)) { c = ((++ptr < strEnd) ? (*ptr) : '\0'); } } } while (IsDigit(c)); if (flag2) { num6 = -num6; } number.Scale += num6; } else { ptr = ptr3; c = ((ptr < strEnd) ? (*ptr) : '\0'); } } if (number.Kind == NumberBufferKind.FloatingPoint && !number.HasNonZeroTail) { int num7 = num3 - number.Scale; if (num7 > 0) { num5 = Math.Min(num5, num7); number.DigitsCount = num3 - num5; number.Digits[number.DigitsCount] = 0; } } while (true) { if (!IsWhite(c) || (styles & NumberStyles.AllowTrailingWhite) == 0) { char* ptr2; if ((styles & NumberStyles.AllowTrailingSign) != 0 && (num & 1) == 0 && ((ptr2 = MatchChars(ptr, strEnd, info.PositiveSign)) != null || ((ptr2 = MatchNegativeSignChars(ptr, strEnd, info)) != null && (number.IsNegative = true)))) { num |= 1; ptr = ptr2 - 1; } else if (c == ')' && ((uint)num & 2u) != 0) { num &= -3; } else { if (text == null || (ptr2 = MatchChars(ptr, strEnd, text)) == null) { break; } text = null; ptr = ptr2 - 1; } } c = ((++ptr < strEnd) ? (*ptr) : '\0'); } if ((num & 2) == 0) { if ((num & 8) == 0) { if (number.Kind != NumberBufferKind.Decimal) { number.Scale = 0; } if (number.Kind == NumberBufferKind.Integer && (num & 0x10) == 0) { number.IsNegative = false; } } str = ptr; return true; } } str = ptr; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static ParsingStatus TryParseInt32(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out int result) { if ((styles & ~NumberStyles.Integer) == 0) { return TryParseInt32IntegerStyle(value, styles, info, out result); } if ((styles & NumberStyles.AllowHexSpecifier) != 0) { result = 0; return TryParseUInt32HexNumberStyle(value, styles, out Unsafe.As(ref result)); } return TryParseInt32Number(value, styles, info, out result); } private unsafe static ParsingStatus TryParseInt32Number(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out int result) { result = 0; byte* digits = stackalloc byte[11]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, digits, 11); if (!TryStringToNumber(value, styles, ref number, info)) { return ParsingStatus.Failed; } if (!TryNumberToInt32(ref number, ref result)) { return ParsingStatus.Overflow; } return ParsingStatus.OK; } internal static ParsingStatus TryParseInt32IntegerStyle(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out int result) { int i; int num; if (!value.IsEmpty) { i = 0; num = value[0]; if ((styles & NumberStyles.AllowLeadingWhite) == 0 || !IsWhite(num)) { goto IL_0048; } while (true) { i++; if ((uint)i >= (uint)value.Length) { break; } num = value[i]; if (IsWhite(num)) { continue; } goto IL_0048; } } goto IL_0289; IL_027a: bool flag; if (!flag) { goto IL_027d; } goto IL_0291; IL_0289: result = 0; return ParsingStatus.Failed; IL_0299: if (IsWhite(num)) { if ((styles & NumberStyles.AllowTrailingWhite) == 0) { goto IL_0289; } for (i++; i < value.Length && IsWhite(value[i]); i++) { } if ((uint)i >= (uint)value.Length) { goto IL_027a; } } if (TrailingZeros(value, i)) { goto IL_027a; } goto IL_0289; IL_027d: int num2; int num3; result = num2 * num3; return ParsingStatus.OK; IL_0048: num3 = 1; if ((styles & NumberStyles.AllowLeadingSign) != 0) { if (info.HasInvariantNumberSigns) { if (num == 45) { num3 = -1; i++; if ((uint)i >= (uint)value.Length) { goto IL_0289; } num = value[i]; } else if (num == 43) { i++; if ((uint)i >= (uint)value.Length) { goto IL_0289; } num = value[i]; } } else if (info.AllowHyphenDuringParsing && num == 45) { num3 = -1; i++; if ((uint)i >= (uint)value.Length) { goto IL_0289; } num = value[i]; } else { value = value.Slice(i); i = 0; string positiveSign = info.PositiveSign; string negativeSign = info.NegativeSign; if (!string.IsNullOrEmpty(positiveSign) && value.StartsWith(positiveSign)) { i += positiveSign.Length; if ((uint)i >= (uint)value.Length) { goto IL_0289; } num = value[i]; } else if (!string.IsNullOrEmpty(negativeSign) && value.StartsWith(negativeSign)) { num3 = -1; i += negativeSign.Length; if ((uint)i >= (uint)value.Length) { goto IL_0289; } num = value[i]; } } } flag = false; num2 = 0; if (IsDigit(num)) { if (num != 48) { goto IL_01aa; } while (true) { i++; if ((uint)i >= (uint)value.Length) { break; } num = value[i]; if (num == 48) { continue; } goto IL_019f; } goto IL_027d; } goto IL_0289; IL_01aa: num2 = num - 48; i++; int num4 = 0; while (num4 < 8) { if ((uint)i >= (uint)value.Length) { goto IL_027d; } num = value[i]; if (IsDigit(num)) { i++; num2 = 10 * num2 + num - 48; num4++; continue; } goto IL_0299; } if ((uint)i >= (uint)value.Length) { goto IL_027d; } num = value[i]; if (IsDigit(num)) { i++; flag = num2 > 214748364; num2 = num2 * 10 + num - 48; flag = flag || (uint)num2 > (uint)(int.MaxValue + (num3 >>> 31)); if ((uint)i >= (uint)value.Length) { goto IL_027a; } num = value[i]; while (IsDigit(num)) { flag = true; i++; if ((uint)i < (uint)value.Length) { num = value[i]; continue; } goto IL_0291; } } goto IL_0299; IL_019f: if (IsDigit(num)) { goto IL_01aa; } goto IL_0299; IL_0291: result = 0; return ParsingStatus.Overflow; } internal static ParsingStatus TryParseInt64IntegerStyle(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out long result) { int i; int num; if (!value.IsEmpty) { i = 0; num = value[0]; if ((styles & NumberStyles.AllowLeadingWhite) == 0 || !IsWhite(num)) { goto IL_0048; } while (true) { i++; if ((uint)i >= (uint)value.Length) { break; } num = value[i]; if (IsWhite(num)) { continue; } goto IL_0048; } } goto IL_029f; IL_028f: bool flag; if (!flag) { goto IL_0292; } goto IL_02a8; IL_029f: result = 0L; return ParsingStatus.Failed; IL_02b1: if (IsWhite(num)) { if ((styles & NumberStyles.AllowTrailingWhite) == 0) { goto IL_029f; } for (i++; i < value.Length && IsWhite(value[i]); i++) { } if ((uint)i >= (uint)value.Length) { goto IL_028f; } } if (TrailingZeros(value, i)) { goto IL_028f; } goto IL_029f; IL_0292: long num2; int num3; result = num2 * num3; return ParsingStatus.OK; IL_0048: num3 = 1; if ((styles & NumberStyles.AllowLeadingSign) != 0) { if (info.HasInvariantNumberSigns) { if (num == 45) { num3 = -1; i++; if ((uint)i >= (uint)value.Length) { goto IL_029f; } num = value[i]; } else if (num == 43) { i++; if ((uint)i >= (uint)value.Length) { goto IL_029f; } num = value[i]; } } else if (info.AllowHyphenDuringParsing && num == 45) { num3 = -1; i++; if ((uint)i >= (uint)value.Length) { goto IL_029f; } num = value[i]; } else { value = value.Slice(i); i = 0; string positiveSign = info.PositiveSign; string negativeSign = info.NegativeSign; if (!string.IsNullOrEmpty(positiveSign) && value.StartsWith(positiveSign)) { i += positiveSign.Length; if ((uint)i >= (uint)value.Length) { goto IL_029f; } num = value[i]; } else if (!string.IsNullOrEmpty(negativeSign) && value.StartsWith(negativeSign)) { num3 = -1; i += negativeSign.Length; if ((uint)i >= (uint)value.Length) { goto IL_029f; } num = value[i]; } } } flag = false; num2 = 0L; if (IsDigit(num)) { if (num != 48) { goto IL_01ab; } while (true) { i++; if ((uint)i >= (uint)value.Length) { break; } num = value[i]; if (num == 48) { continue; } goto IL_01a0; } goto IL_0292; } goto IL_029f; IL_01ab: num2 = num - 48; i++; int num4 = 0; while (num4 < 17) { if ((uint)i >= (uint)value.Length) { goto IL_0292; } num = value[i]; if (IsDigit(num)) { i++; num2 = 10 * num2 + num - 48; num4++; continue; } goto IL_02b1; } if ((uint)i >= (uint)value.Length) { goto IL_0292; } num = value[i]; if (IsDigit(num)) { i++; flag = num2 > 922337203685477580L; num2 = num2 * 10 + num - 48; flag = flag || (ulong)num2 > (ulong)(long.MaxValue + (long)(uint)(num3 >>> 31)); if ((uint)i >= (uint)value.Length) { goto IL_028f; } num = value[i]; while (IsDigit(num)) { flag = true; i++; if ((uint)i < (uint)value.Length) { num = value[i]; continue; } goto IL_02a8; } } goto IL_02b1; IL_01a0: if (IsDigit(num)) { goto IL_01ab; } goto IL_02b1; IL_02a8: result = 0L; return ParsingStatus.Overflow; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static ParsingStatus TryParseInt64(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out long result) { if ((styles & ~NumberStyles.Integer) == 0) { return TryParseInt64IntegerStyle(value, styles, info, out result); } if ((styles & NumberStyles.AllowHexSpecifier) != 0) { result = 0L; return TryParseUInt64HexNumberStyle(value, styles, out Unsafe.As(ref result)); } return TryParseInt64Number(value, styles, info, out result); } private unsafe static ParsingStatus TryParseInt64Number(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out long result) { result = 0L; byte* digits = stackalloc byte[20]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, digits, 20); if (!TryStringToNumber(value, styles, ref number, info)) { return ParsingStatus.Failed; } if (!TryNumberToInt64(ref number, ref result)) { return ParsingStatus.Overflow; } return ParsingStatus.OK; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static ParsingStatus TryParseUInt32(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out uint result) { if ((styles & ~NumberStyles.Integer) == 0) { return TryParseUInt32IntegerStyle(value, styles, info, out result); } if ((styles & NumberStyles.AllowHexSpecifier) != 0) { return TryParseUInt32HexNumberStyle(value, styles, out result); } return TryParseUInt32Number(value, styles, info, out result); } private unsafe static ParsingStatus TryParseUInt32Number(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out uint result) { result = 0u; byte* digits = stackalloc byte[11]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, digits, 11); if (!TryStringToNumber(value, styles, ref number, info)) { return ParsingStatus.Failed; } if (!TryNumberToUInt32(ref number, ref result)) { return ParsingStatus.Overflow; } return ParsingStatus.OK; } internal static ParsingStatus TryParseUInt32IntegerStyle(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out uint result) { int i; int num; if (!value.IsEmpty) { i = 0; num = value[0]; if ((styles & NumberStyles.AllowLeadingWhite) == 0 || !IsWhite(num)) { goto IL_0048; } while (true) { i++; if ((uint)i >= (uint)value.Length) { break; } num = value[i]; if (IsWhite(num)) { continue; } goto IL_0048; } } goto IL_0281; IL_0278: int num2; result = (uint)num2; return ParsingStatus.OK; IL_0281: result = 0u; return ParsingStatus.Failed; IL_0275: bool flag; if (!flag) { goto IL_0278; } goto IL_0289; IL_0289: result = 0u; return ParsingStatus.Overflow; IL_0048: flag = false; if ((styles & NumberStyles.AllowLeadingSign) != 0) { if (info.HasInvariantNumberSigns) { if (num == 43) { i++; if ((uint)i >= (uint)value.Length) { goto IL_0281; } num = value[i]; } else if (num == 45) { flag = true; i++; if ((uint)i >= (uint)value.Length) { goto IL_0281; } num = value[i]; } } else if (info.AllowHyphenDuringParsing && num == 45) { flag = true; i++; if ((uint)i >= (uint)value.Length) { goto IL_0281; } num = value[i]; } else { value = value.Slice(i); i = 0; string positiveSign = info.PositiveSign; string negativeSign = info.NegativeSign; if (!string.IsNullOrEmpty(positiveSign) && value.StartsWith(positiveSign)) { i += positiveSign.Length; if ((uint)i >= (uint)value.Length) { goto IL_0281; } num = value[i]; } else if (!string.IsNullOrEmpty(negativeSign) && value.StartsWith(negativeSign)) { flag = true; i += negativeSign.Length; if ((uint)i >= (uint)value.Length) { goto IL_0281; } num = value[i]; } } } num2 = 0; if (IsDigit(num)) { if (num != 48) { goto IL_01a7; } while (true) { i++; if ((uint)i >= (uint)value.Length) { break; } num = value[i]; if (num == 48) { continue; } goto IL_019c; } goto IL_0278; } goto IL_0281; IL_0293: if (IsWhite(num)) { if ((styles & NumberStyles.AllowTrailingWhite) == 0) { goto IL_0281; } for (i++; i < value.Length && IsWhite(value[i]); i++) { } if ((uint)i >= (uint)value.Length) { goto IL_0275; } } if (TrailingZeros(value, i)) { goto IL_0275; } goto IL_0281; IL_019c: if (IsDigit(num)) { goto IL_01a7; } flag = false; goto IL_0293; IL_01a7: num2 = num - 48; i++; int num3 = 0; while (num3 < 8) { if ((uint)i >= (uint)value.Length) { goto IL_0275; } num = value[i]; if (IsDigit(num)) { i++; num2 = 10 * num2 + num - 48; num3++; continue; } goto IL_0293; } if ((uint)i >= (uint)value.Length) { goto IL_0275; } num = value[i]; if (IsDigit(num)) { i++; flag = flag || (uint)num2 > 429496729u || (num2 == 429496729 && num > 53); num2 = num2 * 10 + num - 48; if ((uint)i >= (uint)value.Length) { goto IL_0275; } num = value[i]; while (IsDigit(num)) { flag = true; i++; if ((uint)i < (uint)value.Length) { num = value[i]; continue; } goto IL_0289; } } goto IL_0293; } internal static ParsingStatus TryParseUInt32HexNumberStyle(ReadOnlySpan value, NumberStyles styles, out uint result) { int i; int num; if (!value.IsEmpty) { i = 0; num = value[0]; if ((styles & NumberStyles.AllowLeadingWhite) == 0 || !IsWhite(num)) { goto IL_0048; } while (true) { i++; if ((uint)i >= (uint)value.Length) { break; } num = value[i]; if (IsWhite(num)) { continue; } goto IL_0048; } } goto IL_011f; IL_0087: uint num2 = (uint)HexConverter.FromChar(num); i++; int num3 = 0; while (num3 < 7) { if ((uint)i >= (uint)value.Length) { goto IL_0116; } num = value[i]; uint num4 = (uint)HexConverter.FromChar(num); if (num4 != 255) { i++; num2 = 16 * num2 + num4; num3++; continue; } goto IL_012f; } if ((uint)i >= (uint)value.Length) { goto IL_0116; } num = value[i]; if (HexConverter.IsHexChar(num)) { while (true) { i++; if ((uint)i >= (uint)value.Length) { break; } num = value[i]; if (HexConverter.IsHexChar(num)) { continue; } goto IL_010f; } goto IL_0127; } goto IL_012f; IL_0127: result = 0u; return ParsingStatus.Overflow; IL_010f: bool flag = true; goto IL_012f; IL_011f: result = 0u; return ParsingStatus.Failed; IL_0048: flag = false; num2 = 0u; if (HexConverter.IsHexChar(num)) { if (num != 48) { goto IL_0087; } while (true) { i++; if ((uint)i >= (uint)value.Length) { break; } num = value[i]; if (num == 48) { continue; } goto IL_007c; } goto IL_0116; } goto IL_011f; IL_0113: if (!flag) { goto IL_0116; } goto IL_0127; IL_012f: if (IsWhite(num)) { if ((styles & NumberStyles.AllowTrailingWhite) == 0) { goto IL_011f; } for (i++; i < value.Length && IsWhite(value[i]); i++) { } if ((uint)i >= (uint)value.Length) { goto IL_0113; } } if (TrailingZeros(value, i)) { goto IL_0113; } goto IL_011f; IL_0116: result = num2; return ParsingStatus.OK; IL_007c: if (HexConverter.IsHexChar(num)) { goto IL_0087; } goto IL_012f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static ParsingStatus TryParseUInt64(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out ulong result) { if ((styles & ~NumberStyles.Integer) == 0) { return TryParseUInt64IntegerStyle(value, styles, info, out result); } if ((styles & NumberStyles.AllowHexSpecifier) != 0) { return TryParseUInt64HexNumberStyle(value, styles, out result); } return TryParseUInt64Number(value, styles, info, out result); } private unsafe static ParsingStatus TryParseUInt64Number(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out ulong result) { result = 0uL; byte* digits = stackalloc byte[21]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Integer, digits, 21); if (!TryStringToNumber(value, styles, ref number, info)) { return ParsingStatus.Failed; } if (!TryNumberToUInt64(ref number, ref result)) { return ParsingStatus.Overflow; } return ParsingStatus.OK; } internal static ParsingStatus TryParseUInt64IntegerStyle(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out ulong result) { int i; int num; if (!value.IsEmpty) { i = 0; num = value[0]; if ((styles & NumberStyles.AllowLeadingWhite) == 0 || !IsWhite(num)) { goto IL_0048; } while (true) { i++; if ((uint)i >= (uint)value.Length) { break; } num = value[i]; if (IsWhite(num)) { continue; } goto IL_0048; } } goto IL_0295; IL_028c: long num2; result = (ulong)num2; return ParsingStatus.OK; IL_0295: result = 0uL; return ParsingStatus.Failed; IL_0289: bool flag; if (!flag) { goto IL_028c; } goto IL_029e; IL_029e: result = 0uL; return ParsingStatus.Overflow; IL_0048: flag = false; if ((styles & NumberStyles.AllowLeadingSign) != 0) { if (info.HasInvariantNumberSigns) { if (num == 43) { i++; if ((uint)i >= (uint)value.Length) { goto IL_0295; } num = value[i]; } else if (num == 45) { flag = true; i++; if ((uint)i >= (uint)value.Length) { goto IL_0295; } num = value[i]; } } else if (info.AllowHyphenDuringParsing && num == 45) { flag = true; i++; if ((uint)i >= (uint)value.Length) { goto IL_0295; } num = value[i]; } else { value = value.Slice(i); i = 0; string positiveSign = info.PositiveSign; string negativeSign = info.NegativeSign; if (!string.IsNullOrEmpty(positiveSign) && value.StartsWith(positiveSign)) { i += positiveSign.Length; if ((uint)i >= (uint)value.Length) { goto IL_0295; } num = value[i]; } else if (!string.IsNullOrEmpty(negativeSign) && value.StartsWith(negativeSign)) { flag = true; i += negativeSign.Length; if ((uint)i >= (uint)value.Length) { goto IL_0295; } num = value[i]; } } } num2 = 0L; if (IsDigit(num)) { if (num != 48) { goto IL_01a8; } while (true) { i++; if ((uint)i >= (uint)value.Length) { break; } num = value[i]; if (num == 48) { continue; } goto IL_019d; } goto IL_028c; } goto IL_0295; IL_02a9: if (IsWhite(num)) { if ((styles & NumberStyles.AllowTrailingWhite) == 0) { goto IL_0295; } for (i++; i < value.Length && IsWhite(value[i]); i++) { } if ((uint)i >= (uint)value.Length) { goto IL_0289; } } if (TrailingZeros(value, i)) { goto IL_0289; } goto IL_0295; IL_019d: if (IsDigit(num)) { goto IL_01a8; } flag = false; goto IL_02a9; IL_01a8: num2 = num - 48; i++; int num3 = 0; while (num3 < 18) { if ((uint)i >= (uint)value.Length) { goto IL_0289; } num = value[i]; if (IsDigit(num)) { i++; num2 = 10 * num2 + num - 48; num3++; continue; } goto IL_02a9; } if ((uint)i >= (uint)value.Length) { goto IL_0289; } num = value[i]; if (IsDigit(num)) { i++; flag = flag || (ulong)num2 > 1844674407370955161uL || (num2 == 1844674407370955161L && num > 53); num2 = num2 * 10 + num - 48; if ((uint)i >= (uint)value.Length) { goto IL_0289; } num = value[i]; while (IsDigit(num)) { flag = true; i++; if ((uint)i < (uint)value.Length) { num = value[i]; continue; } goto IL_029e; } } goto IL_02a9; } private static ParsingStatus TryParseUInt64HexNumberStyle(ReadOnlySpan value, NumberStyles styles, out ulong result) { int i; int num; if (!value.IsEmpty) { i = 0; num = value[0]; if ((styles & NumberStyles.AllowLeadingWhite) == 0 || !IsWhite(num)) { goto IL_0048; } while (true) { i++; if ((uint)i >= (uint)value.Length) { break; } num = value[i]; if (IsWhite(num)) { continue; } goto IL_0048; } } goto IL_0124; IL_0088: ulong num2 = (uint)HexConverter.FromChar(num); i++; int num3 = 0; while (num3 < 15) { if ((uint)i >= (uint)value.Length) { goto IL_011b; } num = value[i]; uint num4 = (uint)HexConverter.FromChar(num); if (num4 != 255) { i++; num2 = 16 * num2 + num4; num3++; continue; } goto IL_0136; } if ((uint)i >= (uint)value.Length) { goto IL_011b; } num = value[i]; if (HexConverter.IsHexChar(num)) { while (true) { i++; if ((uint)i >= (uint)value.Length) { break; } num = value[i]; if (HexConverter.IsHexChar(num)) { continue; } goto IL_0114; } goto IL_012d; } goto IL_0136; IL_012d: result = 0uL; return ParsingStatus.Overflow; IL_0114: bool flag = true; goto IL_0136; IL_0124: result = 0uL; return ParsingStatus.Failed; IL_0048: flag = false; num2 = 0uL; if (HexConverter.IsHexChar(num)) { if (num != 48) { goto IL_0088; } while (true) { i++; if ((uint)i >= (uint)value.Length) { break; } num = value[i]; if (num == 48) { continue; } goto IL_007d; } goto IL_011b; } goto IL_0124; IL_0118: if (!flag) { goto IL_011b; } goto IL_012d; IL_0136: if (IsWhite(num)) { if ((styles & NumberStyles.AllowTrailingWhite) == 0) { goto IL_0124; } for (i++; i < value.Length && IsWhite(value[i]); i++) { } if ((uint)i >= (uint)value.Length) { goto IL_0118; } } if (TrailingZeros(value, i)) { goto IL_0118; } goto IL_0124; IL_011b: result = num2; return ParsingStatus.OK; IL_007d: if (HexConverter.IsHexChar(num)) { goto IL_0088; } goto IL_0136; } internal static decimal ParseDecimal(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { decimal result; ParsingStatus parsingStatus = TryParseDecimal(value, styles, info, out result); if (parsingStatus != 0) { ThrowOverflowOrFormatException(parsingStatus, TypeCode.Decimal); } return result; } internal unsafe static bool TryNumberToDecimal(ref NumberBuffer number, ref decimal value) { byte* ptr = number.GetDigitsPointer(); int num = number.Scale; bool isNegative = number.IsNegative; uint num2 = *ptr; if (num2 == 0) { value = new decimal(0, 0, 0, isNegative, (byte)Math.Clamp(-num, 0, 28)); return true; } if (num > 29) { return false; } ulong num3 = 0uL; while (num > -28) { num--; num3 *= 10; num3 += num2 - 48; num2 = *(++ptr); if (num3 >= 1844674407370955161L) { break; } if (num2 != 0) { continue; } while (num > 0) { num--; num3 *= 10; if (num3 >= 1844674407370955161L) { break; } } break; } uint num4 = 0u; while ((num > 0 || (num2 != 0 && num > -28)) && (num4 < 429496729 || (num4 == 429496729 && (num3 < 11068046444225730969uL || (num3 == 11068046444225730969uL && num2 <= 53))))) { ulong num5 = (ulong)(uint)num3 * 10uL; ulong num6 = (ulong)((long)(uint)(num3 >> 32) * 10L) + (num5 >> 32); num3 = (uint)num5 + (num6 << 32); num4 = (uint)(int)(num6 >> 32) + num4 * 10; if (num2 != 0) { num2 -= 48; num3 += num2; if (num3 < num2) { num4++; } num2 = *(++ptr); } num--; } if (num2 >= 53) { if (num2 == 53 && (num3 & 1) == 0L) { num2 = *(++ptr); bool flag = !number.HasNonZeroTail; while (num2 != 0 && flag) { flag = flag && num2 == 48; num2 = *(++ptr); } if (flag) { goto IL_01a8; } } if (++num3 == 0L && ++num4 == 0) { num3 = 11068046444225730970uL; num4 = 429496729u; num++; } } goto IL_01a8; IL_01a8: if (num > 0) { return false; } if (num <= -29) { value = new decimal(0, 0, 0, isNegative, 28); } else { value = new decimal((int)num3, (int)(num3 >> 32), (int)num4, isNegative, (byte)(-num)); } return true; } internal static double ParseDouble(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { if (!TryParseDouble(value, styles, info, out var result)) { ThrowOverflowOrFormatException(ParsingStatus.Failed); } return result; } internal static float ParseSingle(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { if (!TryParseSingle(value, styles, info, out var result)) { ThrowOverflowOrFormatException(ParsingStatus.Failed); } return result; } internal static Half ParseHalf(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info) { if (!TryParseHalf(value, styles, info, out var result)) { ThrowOverflowOrFormatException(ParsingStatus.Failed); } return result; } internal unsafe static ParsingStatus TryParseDecimal(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out decimal result) { byte* digits = stackalloc byte[31]; NumberBuffer number = new NumberBuffer(NumberBufferKind.Decimal, digits, 31); result = default(decimal); if (!TryStringToNumber(value, styles, ref number, info)) { return ParsingStatus.Failed; } if (!TryNumberToDecimal(ref number, ref result)) { return ParsingStatus.Overflow; } return ParsingStatus.OK; } internal static bool SpanStartsWith(ReadOnlySpan span, char c) { if (!span.IsEmpty) { return span[0] == c; } return false; } internal unsafe static bool TryParseDouble(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out double result) { byte* digits = stackalloc byte[769]; NumberBuffer number = new NumberBuffer(NumberBufferKind.FloatingPoint, digits, 769); if (!TryStringToNumber(value, styles, ref number, info)) { ReadOnlySpan span = value.Trim(); if (span.EqualsOrdinalIgnoreCase(info.PositiveInfinitySymbol)) { result = double.PositiveInfinity; } else if (span.EqualsOrdinalIgnoreCase(info.NegativeInfinitySymbol)) { result = double.NegativeInfinity; } else if (span.EqualsOrdinalIgnoreCase(info.NaNSymbol)) { result = double.NaN; } else if (span.StartsWith(info.PositiveSign, StringComparison.OrdinalIgnoreCase)) { span = span.Slice(info.PositiveSign.Length); if (span.EqualsOrdinalIgnoreCase(info.PositiveInfinitySymbol)) { result = double.PositiveInfinity; } else { if (!span.EqualsOrdinalIgnoreCase(info.NaNSymbol)) { result = 0.0; return false; } result = double.NaN; } } else { if ((!span.StartsWith(info.NegativeSign, StringComparison.OrdinalIgnoreCase) || !span.Slice(info.NegativeSign.Length).EqualsOrdinalIgnoreCase(info.NaNSymbol)) && (!info.AllowHyphenDuringParsing || !SpanStartsWith(span, '-') || !span.Slice(1).EqualsOrdinalIgnoreCase(info.NaNSymbol))) { result = 0.0; return false; } result = double.NaN; } } else { result = NumberToDouble(ref number); } return true; } internal unsafe static bool TryParseHalf(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out Half result) { byte* digits = stackalloc byte[21]; NumberBuffer number = new NumberBuffer(NumberBufferKind.FloatingPoint, digits, 21); if (!TryStringToNumber(value, styles, ref number, info)) { ReadOnlySpan span = value.Trim(); if (span.EqualsOrdinalIgnoreCase(info.PositiveInfinitySymbol)) { result = Half.PositiveInfinity; } else if (span.EqualsOrdinalIgnoreCase(info.NegativeInfinitySymbol)) { result = Half.NegativeInfinity; } else if (span.EqualsOrdinalIgnoreCase(info.NaNSymbol)) { result = Half.NaN; } else if (span.StartsWith(info.PositiveSign, StringComparison.OrdinalIgnoreCase)) { span = span.Slice(info.PositiveSign.Length); if (!info.PositiveInfinitySymbol.StartsWith(info.PositiveSign, StringComparison.OrdinalIgnoreCase) && span.EqualsOrdinalIgnoreCase(info.PositiveInfinitySymbol)) { result = Half.PositiveInfinity; } else { if (info.NaNSymbol.StartsWith(info.PositiveSign, StringComparison.OrdinalIgnoreCase) || !span.EqualsOrdinalIgnoreCase(info.NaNSymbol)) { result = (Half)0f; return false; } result = Half.NaN; } } else if (span.StartsWith(info.NegativeSign, StringComparison.OrdinalIgnoreCase) && !info.NaNSymbol.StartsWith(info.NegativeSign, StringComparison.OrdinalIgnoreCase) && span.Slice(info.NegativeSign.Length).EqualsOrdinalIgnoreCase(info.NaNSymbol)) { result = Half.NaN; } else { if (!info.AllowHyphenDuringParsing || !SpanStartsWith(span, '-') || info.NaNSymbol.StartsWith(info.NegativeSign, StringComparison.OrdinalIgnoreCase) || info.NaNSymbol.StartsWith('-') || !span.Slice(1).EqualsOrdinalIgnoreCase(info.NaNSymbol)) { result = (Half)0f; return false; } result = Half.NaN; } } else { result = NumberToHalf(ref number); } return true; } internal unsafe static bool TryParseSingle(ReadOnlySpan value, NumberStyles styles, NumberFormatInfo info, out float result) { byte* digits = stackalloc byte[114]; NumberBuffer number = new NumberBuffer(NumberBufferKind.FloatingPoint, digits, 114); if (!TryStringToNumber(value, styles, ref number, info)) { ReadOnlySpan span = value.Trim(); if (span.EqualsOrdinalIgnoreCase(info.PositiveInfinitySymbol)) { result = float.PositiveInfinity; } else if (span.EqualsOrdinalIgnoreCase(info.NegativeInfinitySymbol)) { result = float.NegativeInfinity; } else if (span.EqualsOrdinalIgnoreCase(info.NaNSymbol)) { result = float.NaN; } else if (span.StartsWith(info.PositiveSign, StringComparison.OrdinalIgnoreCase)) { span = span.Slice(info.PositiveSign.Length); if (!info.PositiveInfinitySymbol.StartsWith(info.PositiveSign, StringComparison.OrdinalIgnoreCase) && span.EqualsOrdinalIgnoreCase(info.PositiveInfinitySymbol)) { result = float.PositiveInfinity; } else { if (info.NaNSymbol.StartsWith(info.PositiveSign, StringComparison.OrdinalIgnoreCase) || !span.EqualsOrdinalIgnoreCase(info.NaNSymbol)) { result = 0f; return false; } result = float.NaN; } } else if (span.StartsWith(info.NegativeSign, StringComparison.OrdinalIgnoreCase) && !info.NaNSymbol.StartsWith(info.NegativeSign, StringComparison.OrdinalIgnoreCase) && span.Slice(info.NegativeSign.Length).EqualsOrdinalIgnoreCase(info.NaNSymbol)) { result = float.NaN; } else { if (!info.AllowHyphenDuringParsing || !SpanStartsWith(span, '-') || info.NaNSymbol.StartsWith(info.NegativeSign, StringComparison.OrdinalIgnoreCase) || info.NaNSymbol.StartsWith('-') || !span.Slice(1).EqualsOrdinalIgnoreCase(info.NaNSymbol)) { result = 0f; return false; } result = float.NaN; } } else { result = NumberToSingle(ref number); } return true; } internal unsafe static bool TryStringToNumber(ReadOnlySpan value, NumberStyles styles, ref NumberBuffer number, NumberFormatInfo info) { fixed (char* ptr = &MemoryMarshal.GetReference(value)) { char* str = ptr; if (!TryParseNumber(ref str, str + value.Length, styles, ref number, info) || ((int)(str - ptr) < value.Length && !TrailingZeros(value, (int)(str - ptr)))) { return false; } } return true; } private static bool TrailingZeros(ReadOnlySpan value, int index) { for (int i = index; (uint)i < (uint)value.Length; i++) { if (value[i] != 0) { return false; } } return true; } private static bool IsSpaceReplacingChar(char c) { if (c != '\u00a0') { return c == '\u202f'; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static char* MatchNegativeSignChars(char* p, char* pEnd, NumberFormatInfo info) { char* ptr = MatchChars(p, pEnd, info.NegativeSign); if (ptr == null && info.AllowHyphenDuringParsing && p < pEnd && *p == '-') { ptr = p + 1; } return ptr; } private unsafe static char* MatchChars(char* p, char* pEnd, string value) { fixed (char* ptr = value) { char* ptr2 = ptr; if (*ptr2 != 0) { while (true) { char c = ((p < pEnd) ? (*p) : '\0'); if (c != *ptr2 && (!IsSpaceReplacingChar(*ptr2) || c != ' ')) { break; } p++; ptr2++; if (*ptr2 == '\0') { return p; } } } } return null; } private static bool IsWhite(int ch) { if (ch != 32 && (uint)(ch - 9) > 4u) { return false; } return true; } private static bool IsDigit(int ch) { return (uint)(ch - 48) <= 9u; } [DoesNotReturn] internal static void ThrowOverflowOrFormatException(ParsingStatus status, TypeCode type = TypeCode.Empty) { throw GetException(status, type); } [DoesNotReturn] internal static void ThrowOverflowException(TypeCode type) { throw GetException(ParsingStatus.Overflow, type); } private static Exception GetException(ParsingStatus status, TypeCode type) { if (status == ParsingStatus.Failed) { return new FormatException(SR.Format_InvalidString); } return new OverflowException(type switch { TypeCode.SByte => SR.Overflow_SByte, TypeCode.Byte => SR.Overflow_Byte, TypeCode.Int16 => SR.Overflow_Int16, TypeCode.UInt16 => SR.Overflow_UInt16, TypeCode.Int32 => SR.Overflow_Int32, TypeCode.UInt32 => SR.Overflow_UInt32, TypeCode.Int64 => SR.Overflow_Int64, TypeCode.UInt64 => SR.Overflow_UInt64, _ => SR.Overflow_Decimal, }); } internal static double NumberToDouble(ref NumberBuffer number) { double num; if (number.DigitsCount == 0 || number.Scale < -324) { num = 0.0; } else if (number.Scale > 309) { num = double.PositiveInfinity; } else { ulong value = NumberToDoubleFloatingPointBits(ref number, in FloatingPointInfo.Double); num = BitConverter.UInt64BitsToDouble(value); } if (!number.IsNegative) { return num; } return 0.0 - num; } internal static Half NumberToHalf(ref NumberBuffer number) { Half half; if (number.DigitsCount == 0 || number.Scale < -8) { half = default(Half); } else if (number.Scale > 5) { half = Half.PositiveInfinity; } else { ushort value = NumberToHalfFloatingPointBits(ref number, in FloatingPointInfo.Half); half = new Half(value); } if (!number.IsNegative) { return half; } return Half.Negate(half); } internal static float NumberToSingle(ref NumberBuffer number) { float num; if (number.DigitsCount == 0 || number.Scale < -45) { num = 0f; } else if (number.Scale > 39) { num = float.PositiveInfinity; } else { uint value = NumberToSingleFloatingPointBits(ref number, in FloatingPointInfo.Single); num = BitConverter.UInt32BitsToSingle(value); } if (!number.IsNegative) { return num; } return 0f - num; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ObjectDisposedException : InvalidOperationException { private readonly string _objectName; public override string Message { get { string objectName = ObjectName; if (string.IsNullOrEmpty(objectName)) { return base.Message; } string text = SR.Format(SR.ObjectDisposed_ObjectName_Name, objectName); return base.Message + "\r\n" + text; } } public string ObjectName => _objectName ?? string.Empty; private ObjectDisposedException() : this(null, SR.ObjectDisposed_Generic) { } public ObjectDisposedException(string? objectName) : this(objectName, SR.ObjectDisposed_Generic) { } public ObjectDisposedException(string? objectName, string? message) : base(message) { base.HResult = -2146232798; _objectName = objectName; } public ObjectDisposedException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146232798; } protected ObjectDisposedException(SerializationInfo info, StreamingContext context) : base(info, context) { _objectName = info.GetString("ObjectName"); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("ObjectName", ObjectName, typeof(string)); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] public 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; } } public sealed class OperatingSystem : ISerializable, ICloneable { private readonly Version _version; private readonly PlatformID _platform; private readonly string _servicePack; private string _versionString; public PlatformID Platform => _platform; public string ServicePack => _servicePack ?? string.Empty; public Version Version => _version; public string VersionString { get { if (_versionString == null) { string value = _platform switch { PlatformID.Win32S => "Microsoft Win32S ", PlatformID.Win32Windows => (_version.Major > 4 || (_version.Major == 4 && _version.Minor > 0)) ? "Microsoft Windows 98 " : "Microsoft Windows 95 ", PlatformID.Win32NT => "Microsoft Windows NT ", PlatformID.WinCE => "Microsoft Windows CE ", PlatformID.Unix => "Unix ", PlatformID.Xbox => "Xbox ", PlatformID.MacOSX => "Mac OS X ", PlatformID.Other => "Other ", _ => " ", }; Span span = stackalloc char[128]; string versionString; if (!string.IsNullOrEmpty(_servicePack)) { IFormatProvider formatProvider = null; IFormatProvider provider = formatProvider; Span span2 = span; Span initialBuffer = span2; DefaultInterpolatedStringHandler handler = new DefaultInterpolatedStringHandler(1, 3, formatProvider, span2); handler.AppendFormatted(value); handler.AppendFormatted(_version.ToString(3)); handler.AppendLiteral(" "); handler.AppendFormatted(_servicePack); versionString = string.Create(provider, initialBuffer, ref handler); } else { IFormatProvider formatProvider = null; IFormatProvider provider2 = formatProvider; Span span2 = span; Span initialBuffer2 = span2; DefaultInterpolatedStringHandler handler2 = new DefaultInterpolatedStringHandler(0, 2, formatProvider, span2); handler2.AppendFormatted(value); handler2.AppendFormatted(_version); versionString = string.Create(provider2, initialBuffer2, ref handler2); } _versionString = versionString; } return _versionString; } } public OperatingSystem(PlatformID platform, Version version) : this(platform, version, null) { } internal OperatingSystem(PlatformID platform, Version version, string servicePack) { if (platform < PlatformID.Win32S || platform > PlatformID.Other) { throw new ArgumentOutOfRangeException("platform", platform, SR.Format(SR.Arg_EnumIllegalVal, platform)); } if (version == null) { throw new ArgumentNullException("version"); } _platform = platform; _version = version; _servicePack = servicePack; } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public object Clone() { return new OperatingSystem(_platform, _version, _servicePack); } public override string ToString() { return VersionString; } public static bool IsOSPlatform(string platform) { if (platform == null) { throw new ArgumentNullException("platform"); } return platform.Equals("WINDOWS", StringComparison.OrdinalIgnoreCase); } public static bool IsOSPlatformVersionAtLeast(string platform, int major, int minor = 0, int build = 0, int revision = 0) { if (IsOSPlatform(platform)) { return IsOSVersionAtLeast(major, minor, build, revision); } return false; } public static bool IsBrowser() { return false; } public static bool IsLinux() { return false; } public static bool IsFreeBSD() { return false; } public static bool IsFreeBSDVersionAtLeast(int major, int minor = 0, int build = 0, int revision = 0) { if (IsFreeBSD()) { } return false; } public static bool IsAndroid() { return false; } public static bool IsAndroidVersionAtLeast(int major, int minor = 0, int build = 0, int revision = 0) { if (IsAndroid()) { } return false; } [SupportedOSPlatformGuard("maccatalyst")] public static bool IsIOS() { return false; } [SupportedOSPlatformGuard("maccatalyst")] public static bool IsIOSVersionAtLeast(int major, int minor = 0, int build = 0) { if (IsIOS()) { } return false; } public static bool IsMacOS() { return false; } public static bool IsMacOSVersionAtLeast(int major, int minor = 0, int build = 0) { if (IsMacOS()) { } return false; } public static bool IsMacCatalyst() { return false; } public static bool IsMacCatalystVersionAtLeast(int major, int minor = 0, int build = 0) { if (IsMacCatalyst()) { } return false; } public static bool IsTvOS() { return false; } public static bool IsTvOSVersionAtLeast(int major, int minor = 0, int build = 0) { if (IsTvOS()) { } return false; } public static bool IsWatchOS() { return false; } public static bool IsWatchOSVersionAtLeast(int major, int minor = 0, int build = 0) { if (IsWatchOS()) { } return false; } public static bool IsWindows() { return true; } public static bool IsWindowsVersionAtLeast(int major, int minor = 0, int build = 0, int revision = 0) { IsWindows(); return IsOSVersionAtLeast(major, minor, build, revision); } private static bool IsOSVersionAtLeast(int major, int minor, int build, int revision) { Version version = Environment.OSVersion.Version; if (version.Major != major) { return version.Major > major; } if (version.Minor != minor) { return version.Minor > minor; } if (version.Build != build) { return version.Build > build; } if (version.Revision < revision) { if (version.Revision == -1) { return revision == 0; } return false; } return true; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class OperationCanceledException : SystemException { [NonSerialized] private CancellationToken _cancellationToken; public CancellationToken CancellationToken { get { return _cancellationToken; } private set { _cancellationToken = value; } } public OperationCanceledException() : base(SR.OperationCanceled) { base.HResult = -2146233029; } public OperationCanceledException(string? message) : base(message) { base.HResult = -2146233029; } public OperationCanceledException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233029; } public OperationCanceledException(CancellationToken token) : this() { CancellationToken = token; } public OperationCanceledException(string? message, CancellationToken token) : this(message) { CancellationToken = token; } public OperationCanceledException(string? message, Exception? innerException, CancellationToken token) : this(message, innerException) { CancellationToken = token; } protected OperationCanceledException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class OutOfMemoryException : SystemException { public OutOfMemoryException() : base(Exception.GetMessageFromNativeResources(ExceptionMessageKind.OutOfMemory)) { base.HResult = -2147024882; } public OutOfMemoryException(string? message) : base(message) { base.HResult = -2147024882; } public OutOfMemoryException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2147024882; } protected OutOfMemoryException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class OverflowException : ArithmeticException { public OverflowException() : base(SR.Arg_OverflowException) { base.HResult = -2146233066; } public OverflowException(string? message) : base(message) { base.HResult = -2146233066; } public OverflowException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233066; } protected OverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [AttributeUsage(AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)] public sealed class ParamArrayAttribute : Attribute { } internal readonly struct ParamsArray { private static readonly object[] s_oneArgArray = new object[1]; private static readonly object[] s_twoArgArray = new object[2]; private static readonly object[] s_threeArgArray = new object[3]; private readonly object _arg0; private readonly object _arg1; private readonly object _arg2; private readonly object[] _args; public int Length => _args.Length; public object this[int index] { get { if (index != 0) { return GetAtSlow(index); } return _arg0; } } public ParamsArray(object arg0) { _arg0 = arg0; _arg1 = null; _arg2 = null; _args = s_oneArgArray; } public ParamsArray(object arg0, object arg1) { _arg0 = arg0; _arg1 = arg1; _arg2 = null; _args = s_twoArgArray; } public ParamsArray(object arg0, object arg1, object arg2) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; _args = s_threeArgArray; } public ParamsArray(object[] args) { int num = args.Length; _arg0 = ((num > 0) ? args[0] : null); _arg1 = ((num > 1) ? args[1] : null); _arg2 = ((num > 2) ? args[2] : null); _args = args; } private object GetAtSlow(int index) { return index switch { 1 => _arg1, 2 => _arg2, _ => _args[index], }; } } internal static class ParseNumbers { public static long StringToLong(ReadOnlySpan s, int radix, int flags) { int currPos = 0; return StringToLong(s, radix, flags, ref currPos); } public static long StringToLong(ReadOnlySpan s, int radix, int flags, ref int currPos) { int i = currPos; int num = ((-1 == radix) ? 10 : radix); if (num != 2 && num != 10 && num != 8 && num != 16) { throw new ArgumentException(SR.Arg_InvalidBase, "radix"); } int length = s.Length; if (i < 0 || i >= length) { throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Index); } if ((flags & 0x1000) == 0 && (flags & 0x2000) == 0) { EatWhiteSpace(s, ref i); if (i == length) { throw new FormatException(SR.Format_EmptyInputString); } } int num2 = 1; if (s[i] == '-') { if (num != 10) { throw new ArgumentException(SR.Arg_CannotHaveNegativeValue); } if (((uint)flags & 0x200u) != 0) { throw new OverflowException(SR.Overflow_NegativeUnsigned); } num2 = -1; i++; } else if (s[i] == '+') { i++; } if ((radix == -1 || radix == 16) && i + 1 < length && s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X')) { num = 16; i += 2; } int num3 = i; long num4 = GrabLongs(num, s, ref i, (flags & 0x200) != 0); if (i == num3) { throw new FormatException(SR.Format_NoParsibleDigits); } if (((uint)flags & 0x1000u) != 0 && i < length) { throw new FormatException(SR.Format_ExtraJunkAtEnd); } currPos = i; if (num4 == long.MinValue && num2 == 1 && num == 10 && (flags & 0x200) == 0) { Number.ThrowOverflowException(TypeCode.Int64); } if (num == 10) { num4 *= num2; } return num4; } public static int StringToInt(ReadOnlySpan s, int radix, int flags) { int currPos = 0; return StringToInt(s, radix, flags, ref currPos); } public static int StringToInt(ReadOnlySpan s, int radix, int flags, ref int currPos) { int i = currPos; int num = ((-1 == radix) ? 10 : radix); if (num != 2 && num != 10 && num != 8 && num != 16) { throw new ArgumentException(SR.Arg_InvalidBase, "radix"); } int length = s.Length; if (i < 0 || i >= length) { throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_Index); } if ((flags & 0x1000) == 0 && (flags & 0x2000) == 0) { EatWhiteSpace(s, ref i); if (i == length) { throw new FormatException(SR.Format_EmptyInputString); } } int num2 = 1; if (s[i] == '-') { if (num != 10) { throw new ArgumentException(SR.Arg_CannotHaveNegativeValue); } if (((uint)flags & 0x200u) != 0) { throw new OverflowException(SR.Overflow_NegativeUnsigned); } num2 = -1; i++; } else if (s[i] == '+') { i++; } if ((radix == -1 || radix == 16) && i + 1 < length && s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X')) { num = 16; i += 2; } int num3 = i; int num4 = GrabInts(num, s, ref i, (flags & 0x200) != 0); if (i == num3) { throw new FormatException(SR.Format_NoParsibleDigits); } if (((uint)flags & 0x1000u) != 0 && i < length) { throw new FormatException(SR.Format_ExtraJunkAtEnd); } currPos = i; if (((uint)flags & 0x400u) != 0) { if ((uint)num4 > 255u) { Number.ThrowOverflowException(TypeCode.SByte); } } else if (((uint)flags & 0x800u) != 0) { if ((uint)num4 > 65535u) { Number.ThrowOverflowException(TypeCode.Int16); } } else if (num4 == int.MinValue && num2 == 1 && num == 10 && (flags & 0x200) == 0) { Number.ThrowOverflowException(TypeCode.Int32); } if (num == 10) { num4 *= num2; } return num4; } public unsafe static string IntToString(int n, int radix, int width, char paddingChar, int flags) { Span span = stackalloc char[66]; if (radix < 2 || radix > 36) { throw new ArgumentException(SR.Arg_InvalidBase, "radix"); } bool flag = false; uint num; if (n < 0) { flag = true; num = (uint)((10 == radix) ? (-n) : n); } else { num = (uint)n; } if (((uint)flags & 0x40u) != 0) { num &= 0xFFu; } else if (((uint)flags & 0x80u) != 0) { num &= 0xFFFFu; } int num2; if (num == 0) { span[0] = '0'; num2 = 1; } else { num2 = 0; for (int i = 0; i < span.Length; i++) { uint num3 = num / (uint)radix; uint num4 = num - (uint)((int)num3 * radix); num = num3; span[i] = ((num4 < 10) ? ((char)(num4 + 48)) : ((char)(num4 + 97 - 10))); if (num == 0) { num2 = i + 1; break; } } } if (radix != 10 && ((uint)flags & 0x20u) != 0) { if (16 == radix) { span[num2++] = 'x'; span[num2++] = '0'; } else if (8 == radix) { span[num2++] = '0'; } } if (10 == radix) { if (flag) { span[num2++] = '-'; } else if (((uint)flags & 0x10u) != 0) { span[num2++] = '+'; } else if (((uint)flags & 8u) != 0) { span[num2++] = ' '; } } string text = string.FastAllocateString(Math.Max(width, num2)); fixed (char* ptr = text) { char* ptr2 = ptr; int num5 = text.Length - num2; if (((uint)flags & (true ? 1u : 0u)) != 0) { for (int j = 0; j < num5; j++) { *(ptr2++) = paddingChar; } for (int k = 0; k < num2; k++) { *(ptr2++) = span[num2 - k - 1]; } } else { for (int l = 0; l < num2; l++) { *(ptr2++) = span[num2 - l - 1]; } for (int m = 0; m < num5; m++) { *(ptr2++) = paddingChar; } } } return text; } public unsafe static string LongToString(long n, int radix, int width, char paddingChar, int flags) { Span span = stackalloc char[67]; if (radix < 2 || radix > 36) { throw new ArgumentException(SR.Arg_InvalidBase, "radix"); } bool flag = false; ulong num; if (n < 0) { flag = true; num = (ulong)((10 == radix) ? (-n) : n); } else { num = (ulong)n; } if (((uint)flags & 0x40u) != 0) { num &= 0xFF; } else if (((uint)flags & 0x80u) != 0) { num &= 0xFFFF; } else if (((uint)flags & 0x100u) != 0) { num &= 0xFFFFFFFFu; } int num2; if (num == 0L) { span[0] = '0'; num2 = 1; } else { num2 = 0; for (int i = 0; i < span.Length; i++) { ulong num3 = num / (ulong)radix; int num4 = (int)((long)num - (long)num3 * (long)radix); num = num3; span[i] = ((num4 < 10) ? ((char)(num4 + 48)) : ((char)(num4 + 97 - 10))); if (num == 0L) { num2 = i + 1; break; } } } if (radix != 10 && ((uint)flags & 0x20u) != 0) { if (16 == radix) { span[num2++] = 'x'; span[num2++] = '0'; } else if (8 == radix) { span[num2++] = '0'; } else if (((uint)flags & 0x4000u) != 0) { span[num2++] = '#'; span[num2++] = (char)(radix % 10 + 48); span[num2++] = (char)(radix / 10 + 48); } } if (10 == radix) { if (flag) { span[num2++] = '-'; } else if (((uint)flags & 0x10u) != 0) { span[num2++] = '+'; } else if (((uint)flags & 8u) != 0) { span[num2++] = ' '; } } string text = string.FastAllocateString(Math.Max(width, num2)); fixed (char* ptr = text) { char* ptr2 = ptr; int num5 = text.Length - num2; if (((uint)flags & (true ? 1u : 0u)) != 0) { for (int j = 0; j < num5; j++) { *(ptr2++) = paddingChar; } for (int k = 0; k < num2; k++) { *(ptr2++) = span[num2 - k - 1]; } } else { for (int l = 0; l < num2; l++) { *(ptr2++) = span[num2 - l - 1]; } for (int m = 0; m < num5; m++) { *(ptr2++) = paddingChar; } } } return text; } private static void EatWhiteSpace(ReadOnlySpan s, ref int i) { int j; for (j = i; j < s.Length && char.IsWhiteSpace(s[j]); j++) { } i = j; } private static long GrabLongs(int radix, ReadOnlySpan s, ref int i, bool isUnsigned) { ulong num = 0uL; if (radix == 10 && !isUnsigned) { ulong num2 = 922337203685477580uL; int result; while (i < s.Length && IsDigit(s[i], radix, out result)) { if (num > num2 || (long)num < 0L) { Number.ThrowOverflowException(TypeCode.Int64); } num = (ulong)((long)num * (long)radix + result); i++; } if ((long)num < 0L && num != 9223372036854775808uL) { Number.ThrowOverflowException(TypeCode.Int64); } } else { ulong num2 = radix switch { 8 => 2305843009213693951uL, 16 => 1152921504606846975uL, 10 => 1844674407370955161uL, _ => 9223372036854775807uL, }; int result2; while (i < s.Length && IsDigit(s[i], radix, out result2)) { if (num > num2) { Number.ThrowOverflowException(TypeCode.UInt64); } ulong num3 = (ulong)((long)num * (long)radix + result2); if (num3 < num) { Number.ThrowOverflowException(TypeCode.UInt64); } num = num3; i++; } } return (long)num; } private static int GrabInts(int radix, ReadOnlySpan s, ref int i, bool isUnsigned) { uint num = 0u; if (radix == 10 && !isUnsigned) { uint num2 = 214748364u; int result; while (i < s.Length && IsDigit(s[i], radix, out result)) { if (num > num2 || (int)num < 0) { Number.ThrowOverflowException(TypeCode.Int32); } num = (uint)((int)num * radix + result); i++; } if ((int)num < 0 && num != 2147483648u) { Number.ThrowOverflowException(TypeCode.Int32); } } else { uint num2 = radix switch { 8 => 536870911u, 16 => 268435455u, 10 => 429496729u, _ => 2147483647u, }; int result2; while (i < s.Length && IsDigit(s[i], radix, out result2)) { if (num > num2) { Number.ThrowOverflowException(TypeCode.UInt32); } uint num3 = (uint)((int)num * radix + result2); if (num3 < num) { Number.ThrowOverflowException(TypeCode.UInt32); } num = num3; i++; } } return (int)num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsDigit(char c, int radix, out int result) { int num; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': num = (result = c - 48); break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': num = (result = c - 65 + 10); break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': num = (result = c - 97 + 10); break; default: result = -1; return false; } return num < radix; } } internal static class PasteArguments { internal static void AppendArgument(ref ValueStringBuilder stringBuilder, string argument) { if (stringBuilder.Length != 0) { stringBuilder.Append(' '); } if (argument.Length != 0 && ContainsNoWhitespaceOrQuotes(argument)) { stringBuilder.Append(argument); return; } stringBuilder.Append('"'); int num = 0; while (num < argument.Length) { char c = argument[num++]; switch (c) { case '\\': { int num2 = 1; while (num < argument.Length && argument[num] == '\\') { num++; num2++; } if (num == argument.Length) { stringBuilder.Append('\\', num2 * 2); } else if (argument[num] == '"') { stringBuilder.Append('\\', num2 * 2 + 1); stringBuilder.Append('"'); num++; } else { stringBuilder.Append('\\', num2); } break; } case '"': stringBuilder.Append('\\'); stringBuilder.Append('"'); break; default: stringBuilder.Append(c); break; } } stringBuilder.Append('"'); } private static bool ContainsNoWhitespaceOrQuotes(string s) { foreach (char c in s) { if (char.IsWhiteSpace(c) || c == '"') { return false; } } return true; } internal static string Paste(IEnumerable arguments, bool pasteFirstArgumentUsingArgV0Rules) { Span initialBuffer = stackalloc char[256]; ValueStringBuilder stringBuilder = new ValueStringBuilder(initialBuffer); foreach (string argument in arguments) { if (pasteFirstArgumentUsingArgV0Rules) { pasteFirstArgumentUsingArgV0Rules = false; bool flag = false; string text = argument; foreach (char c in text) { if (c == '"') { throw new ApplicationException(SR.Argv_IncludeDoubleQuote); } if (char.IsWhiteSpace(c)) { flag = true; } } if (argument.Length == 0 || flag) { stringBuilder.Append('"'); stringBuilder.Append(argument); stringBuilder.Append('"'); } else { stringBuilder.Append(argument); } } else { AppendArgument(ref stringBuilder, argument); } } return stringBuilder.ToString(); } } public enum PlatformID { [EditorBrowsable(EditorBrowsableState.Never)] Win32S, [EditorBrowsable(EditorBrowsableState.Never)] Win32Windows, Win32NT, [EditorBrowsable(EditorBrowsableState.Never)] WinCE, Unix, [EditorBrowsable(EditorBrowsableState.Never)] Xbox, [EditorBrowsable(EditorBrowsableState.Never)] MacOSX, Other } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class PlatformNotSupportedException : NotSupportedException { public PlatformNotSupportedException() : base(SR.Arg_PlatformNotSupported) { base.HResult = -2146233031; } public PlatformNotSupportedException(string? message) : base(message) { base.HResult = -2146233031; } public PlatformNotSupportedException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233031; } protected PlatformNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class Progress : IProgress { private readonly SynchronizationContext _synchronizationContext; private readonly Action _handler; private readonly SendOrPostCallback _invokeHandlers; public event EventHandler? ProgressChanged; public Progress() { _synchronizationContext = SynchronizationContext.Current ?? ProgressStatics.DefaultContext; _invokeHandlers = InvokeHandlers; } public Progress(Action handler) : this() { _handler = handler ?? throw new ArgumentNullException("handler"); } protected virtual void OnReport(T value) { Action handler = _handler; EventHandler progressChanged = this.ProgressChanged; if (handler != null || progressChanged != null) { _synchronizationContext.Post(_invokeHandlers, value); } } void IProgress.Report(T value) { OnReport(value); } private void InvokeHandlers(object state) { T val = (T)state; Action handler = _handler; EventHandler progressChanged = this.ProgressChanged; handler?.Invoke(val); progressChanged?.Invoke(this, val); } } internal static class ProgressStatics { internal static readonly SynchronizationContext DefaultContext = new SynchronizationContext(); } public class Random { private sealed class ThreadSafeRandom : Random { [ThreadStatic] private static XoshiroImpl t_random; private static XoshiroImpl LocalRandom => t_random ?? Create(); public ThreadSafeRandom() : base(isThreadSafeRandom: true) { } [MethodImpl(MethodImplOptions.NoInlining)] private static XoshiroImpl Create() { return t_random = new XoshiroImpl(); } public override int Next() { return LocalRandom.Next(); } public override int Next(int maxValue) { if (maxValue < 0) { ThrowMaxValueMustBeNonNegative(); } return LocalRandom.Next(maxValue); } public override int Next(int minValue, int maxValue) { if (minValue > maxValue) { ThrowMinMaxValueSwapped(); } return LocalRandom.Next(minValue, maxValue); } public override long NextInt64() { return LocalRandom.NextInt64(); } public override long NextInt64(long maxValue) { if (maxValue < 0) { ThrowMaxValueMustBeNonNegative(); } return LocalRandom.NextInt64(maxValue); } public override long NextInt64(long minValue, long maxValue) { if (minValue > maxValue) { ThrowMinMaxValueSwapped(); } return LocalRandom.NextInt64(minValue, maxValue); } public override float NextSingle() { return LocalRandom.NextSingle(); } public override double NextDouble() { return LocalRandom.NextDouble(); } public override void NextBytes(byte[] buffer) { if (buffer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer); } LocalRandom.NextBytes(buffer); } public override void NextBytes(Span buffer) { LocalRandom.NextBytes(buffer); } protected override double Sample() { throw new NotSupportedException(); } } internal abstract class ImplBase { public abstract double Sample(); public abstract int Next(); public abstract int Next(int maxValue); public abstract int Next(int minValue, int maxValue); public abstract long NextInt64(); public abstract long NextInt64(long maxValue); public abstract long NextInt64(long minValue, long maxValue); public abstract float NextSingle(); public abstract double NextDouble(); public abstract void NextBytes(byte[] buffer); public abstract void NextBytes(Span buffer); } private sealed class Net5CompatSeedImpl : ImplBase { private CompatPrng _prng; public Net5CompatSeedImpl(int seed) { _prng = new CompatPrng(seed); } public override double Sample() { return _prng.Sample(); } public override int Next() { return _prng.InternalSample(); } public override int Next(int maxValue) { return (int)(_prng.Sample() * (double)maxValue); } public override int Next(int minValue, int maxValue) { long num = (long)maxValue - (long)minValue; if (num > int.MaxValue) { return (int)((long)(_prng.GetSampleForLargeRange() * (double)num) + minValue); } return (int)(_prng.Sample() * (double)num) + minValue; } public override long NextInt64() { ulong num; do { num = NextUInt64() >> 1; } while (num == long.MaxValue); return (long)num; } public override long NextInt64(long maxValue) { return NextInt64(0L, maxValue); } public override long NextInt64(long minValue, long maxValue) { ulong num = (ulong)(maxValue - minValue); if (num > 1) { int num2 = BitOperations.Log2Ceiling(num); ulong num3; do { num3 = NextUInt64() >> 64 - num2; } while (num3 >= num); return (long)num3 + minValue; } return minValue; } private ulong NextUInt64() { return (uint)Next(4194304) | ((ulong)(uint)Next(4194304) << 22) | ((ulong)(uint)Next(1048576) << 44); } public override double NextDouble() { return _prng.Sample(); } public override float NextSingle() { return (float)_prng.Sample(); } public override void NextBytes(byte[] buffer) { _prng.NextBytes(buffer); } public override void NextBytes(Span buffer) { _prng.NextBytes(buffer); } } private sealed class Net5CompatDerivedImpl : ImplBase { private readonly Random _parent; private CompatPrng _prng; public Net5CompatDerivedImpl(Random parent) : this(parent, Shared.Next()) { } public Net5CompatDerivedImpl(Random parent, int seed) { _parent = parent; _prng = new CompatPrng(seed); } public override double Sample() { return _prng.Sample(); } public override int Next() { return _prng.InternalSample(); } public override int Next(int maxValue) { return (int)(_parent.Sample() * (double)maxValue); } public override int Next(int minValue, int maxValue) { long num = (long)maxValue - (long)minValue; if (num > int.MaxValue) { return (int)((long)(_prng.GetSampleForLargeRange() * (double)num) + minValue); } return (int)(_parent.Sample() * (double)num) + minValue; } public override long NextInt64() { ulong num; do { num = NextUInt64() >> 1; } while (num == long.MaxValue); return (long)num; } public override long NextInt64(long maxValue) { return NextInt64(0L, maxValue); } public override long NextInt64(long minValue, long maxValue) { ulong num = (ulong)(maxValue - minValue); if (num > 1) { int num2 = BitOperations.Log2Ceiling(num); ulong num3; do { num3 = NextUInt64() >> 64 - num2; } while (num3 >= num); return (long)num3 + minValue; } return minValue; } private ulong NextUInt64() { return (uint)_parent.Next(4194304) | ((ulong)(uint)_parent.Next(4194304) << 22) | ((ulong)(uint)_parent.Next(1048576) << 44); } public override double NextDouble() { return _parent.Sample(); } public override float NextSingle() { return (float)_parent.Sample(); } public override void NextBytes(byte[] buffer) { _prng.NextBytes(buffer); } public override void NextBytes(Span buffer) { for (int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)_parent.Next(); } } } private struct CompatPrng { private int[] _seedArray; private int _inext; private int _inextp; public CompatPrng(int seed) { int[] array = new int[56]; int num = ((seed == int.MinValue) ? int.MaxValue : Math.Abs(seed)); int num2 = (array[55] = 161803398 - num); int num3 = 1; int num4 = 0; for (int i = 1; i < 55; i++) { if ((num4 += 21) >= 55) { num4 -= 55; } array[num4] = num3; num3 = num2 - num3; if (num3 < 0) { num3 += int.MaxValue; } num2 = array[num4]; } for (int j = 1; j < 5; j++) { for (int k = 1; k < 56; k++) { int num5 = k + 30; if (num5 >= 55) { num5 -= 55; } array[k] -= array[1 + num5]; if (array[k] < 0) { array[k] += int.MaxValue; } } } _seedArray = array; _inext = 0; _inextp = 21; } internal double Sample() { return (double)InternalSample() * 4.656612875245797E-10; } internal void NextBytes(Span buffer) { for (int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)InternalSample(); } } internal int InternalSample() { int inext = _inext; if (++inext >= 56) { inext = 1; } int inextp = _inextp; if (++inextp >= 56) { inextp = 1; } int[] seedArray = _seedArray; int num = seedArray[inext] - seedArray[inextp]; if (num == int.MaxValue) { num--; } if (num < 0) { num += int.MaxValue; } seedArray[inext] = num; _inext = inext; _inextp = inextp; return num; } internal double GetSampleForLargeRange() { int num = InternalSample(); if (InternalSample() % 2 == 0) { num = -num; } double num2 = num; num2 += 2147483646.0; return num2 / 4294967293.0; } } internal sealed class XoshiroImpl : ImplBase { private uint _s0; private uint _s1; private uint _s2; private uint _s3; public unsafe XoshiroImpl() { uint* ptr = stackalloc uint[4]; do { Interop.GetRandomBytes((byte*)ptr, 16); _s0 = *ptr; _s1 = ptr[1]; _s2 = ptr[2]; _s3 = ptr[3]; } while ((_s0 | _s1 | _s2 | _s3) == 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal uint NextUInt32() { uint s = _s0; uint s2 = _s1; uint s3 = _s2; uint s4 = _s3; uint result = BitOperations.RotateLeft(s2 * 5, 7) * 9; uint num = s2 << 9; s3 ^= s; s4 ^= s2; s2 ^= s3; s ^= s4; s3 ^= num; s4 = BitOperations.RotateLeft(s4, 11); _s0 = s; _s1 = s2; _s2 = s3; _s3 = s4; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ulong NextUInt64() { return ((ulong)NextUInt32() << 32) | NextUInt32(); } public override int Next() { uint num; do { num = NextUInt32() >> 1; } while (num == int.MaxValue); return (int)num; } public override int Next(int maxValue) { if (maxValue > 1) { int num = BitOperations.Log2Ceiling((uint)maxValue); uint num2; do { num2 = NextUInt32() >> 32 - num; } while (num2 >= (uint)maxValue); return (int)num2; } return 0; } public override int Next(int minValue, int maxValue) { uint num = (uint)(maxValue - minValue); if (num > 1) { int num2 = BitOperations.Log2Ceiling(num); uint num3; do { num3 = NextUInt32() >> 32 - num2; } while (num3 >= num); return (int)num3 + minValue; } return minValue; } public override long NextInt64() { ulong num; do { num = NextUInt64() >> 1; } while (num == long.MaxValue); return (long)num; } public override long NextInt64(long maxValue) { if (maxValue <= int.MaxValue) { return Next((int)maxValue); } if (maxValue > 1) { int num = BitOperations.Log2Ceiling((ulong)maxValue); ulong num2; do { num2 = NextUInt64() >> 64 - num; } while (num2 >= (ulong)maxValue); return (long)num2; } return 0L; } public override long NextInt64(long minValue, long maxValue) { ulong num = (ulong)(maxValue - minValue); if (num <= int.MaxValue) { return Next((int)num) + minValue; } if (num > 1) { int num2 = BitOperations.Log2Ceiling(num); ulong num3; do { num3 = NextUInt64() >> 64 - num2; } while (num3 >= num); return (long)num3 + minValue; } return minValue; } public override void NextBytes(byte[] buffer) { NextBytes((Span)buffer); } public unsafe override void NextBytes(Span buffer) { uint num = _s0; uint num2 = _s1; uint num3 = _s2; uint num4 = _s3; while (buffer.Length >= 4) { Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(buffer), BitOperations.RotateLeft(num2 * 5, 7) * 9); uint num5 = num2 << 9; num3 ^= num; num4 ^= num2; num2 ^= num3; num ^= num4; num3 ^= num5; num4 = BitOperations.RotateLeft(num4, 11); buffer = buffer.Slice(4); } if (!buffer.IsEmpty) { uint num6 = BitOperations.RotateLeft(num2 * 5, 7) * 9; byte* ptr = (byte*)(&num6); for (int i = 0; i < buffer.Length; i++) { buffer[i] = ptr[i]; } uint num7 = num2 << 9; num3 ^= num; num4 ^= num2; num2 ^= num3; num ^= num4; num3 ^= num7; num4 = BitOperations.RotateLeft(num4, 11); } _s0 = num; _s1 = num2; _s2 = num3; _s3 = num4; } public override double NextDouble() { return (double)(NextUInt64() >> 11) * 1.1102230246251565E-16; } public override float NextSingle() { return (float)(NextUInt32() >> 8) * 5.9604645E-08f; } public override double Sample() { throw new NotSupportedException(); } } private readonly ImplBase _impl; public static Random Shared { get; } = new ThreadSafeRandom(); public Random() { _impl = ((GetType() == typeof(Random)) ? ((ImplBase)new XoshiroImpl()) : ((ImplBase)new Net5CompatDerivedImpl(this))); } public Random(int Seed) { _impl = ((GetType() == typeof(Random)) ? ((ImplBase)new Net5CompatSeedImpl(Seed)) : ((ImplBase)new Net5CompatDerivedImpl(this, Seed))); } private protected Random(bool isThreadSafeRandom) { _impl = null; } public virtual int Next() { return _impl.Next(); } public virtual int Next(int maxValue) { if (maxValue < 0) { ThrowMaxValueMustBeNonNegative(); } return _impl.Next(maxValue); } public virtual int Next(int minValue, int maxValue) { if (minValue > maxValue) { ThrowMinMaxValueSwapped(); } return _impl.Next(minValue, maxValue); } public virtual long NextInt64() { return _impl.NextInt64(); } public virtual long NextInt64(long maxValue) { if (maxValue < 0) { ThrowMaxValueMustBeNonNegative(); } return _impl.NextInt64(maxValue); } public virtual long NextInt64(long minValue, long maxValue) { if (minValue > maxValue) { ThrowMinMaxValueSwapped(); } return _impl.NextInt64(minValue, maxValue); } public virtual float NextSingle() { return _impl.NextSingle(); } public virtual double NextDouble() { return _impl.NextDouble(); } public virtual void NextBytes(byte[] buffer) { if (buffer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer); } _impl.NextBytes(buffer); } public virtual void NextBytes(Span buffer) { _impl.NextBytes(buffer); } protected virtual double Sample() { return _impl.Sample(); } private static void ThrowMaxValueMustBeNonNegative() { throw new ArgumentOutOfRangeException("maxValue", SR.Format(SR.ArgumentOutOfRange_NeedNonNegNum, "maxValue")); } private static void ThrowMinMaxValueSwapped() { throw new ArgumentOutOfRangeException("minValue", SR.Format(SR.Argument_MinMaxValue, "minValue", "maxValue")); } } public readonly struct Range : IEquatable { public Index Start { get; } public Index End { get; } public static Range All => Index.Start..Index.End; public Range(Index start, Index end) { Start = start; End = end; } public override bool Equals([NotNullWhen(true)] object? value) { if (value is Range range && range.Start.Equals(Start)) { return range.End.Equals(End); } return false; } public bool Equals(Range other) { if (other.Start.Equals(Start)) { return other.End.Equals(End); } return false; } public override int GetHashCode() { return HashCode.Combine(Start.GetHashCode(), End.GetHashCode()); } public override string ToString() { Span span = stackalloc char[24]; int num = 0; if (Start.IsFromEnd) { span[0] = '^'; num = 1; } bool flag = ((uint)Start.Value).TryFormat(span.Slice(num), out var charsWritten); num += charsWritten; span[num++] = '.'; span[num++] = '.'; if (End.IsFromEnd) { span[num++] = '^'; } flag = ((uint)End.Value).TryFormat(span.Slice(num), out charsWritten); return new string(span[..(num + charsWritten)]); } public static Range StartAt(Index start) { return start..Index.End; } public static Range EndAt(Index end) { return Index.Start..end; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public (int Offset, int Length) GetOffsetAndLength(int length) { Index start = Start; int num = ((!start.IsFromEnd) ? start.Value : (length - start.Value)); Index end = End; int num2 = ((!end.IsFromEnd) ? end.Value : (length - end.Value)); if ((uint)num2 > (uint)length || (uint)num > (uint)num2) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); } return (num, num2 - num); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class RankException : SystemException { public RankException() : base(SR.Arg_RankException) { base.HResult = -2146233065; } public RankException(string? message) : base(message) { base.HResult = -2146233065; } public RankException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233065; } protected RankException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [DebuggerTypeProxy(typeof(MemoryDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] public readonly struct ReadOnlyMemory : IEquatable> { private readonly object _object; private readonly int _index; private readonly int _length; internal const int RemoveFlagsBitMask = int.MaxValue; public static ReadOnlyMemory Empty => default(ReadOnlyMemory); public int Length => _length; public bool IsEmpty => _length == 0; public unsafe ReadOnlySpan Span { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { ref T ptr = ref Unsafe.NullRef(); int length = 0; object @object = _object; if (@object != null) { if (typeof(T) == typeof(char) && @object.GetType() == typeof(string)) { ptr = ref Unsafe.As(ref Unsafe.As(@object).GetRawStringData()); length = Unsafe.As(@object).Length; } else if (RuntimeHelpers.ObjectHasComponentSize(@object)) { ptr = ref MemoryMarshal.GetArrayDataReference(Unsafe.As(@object)); length = Unsafe.As(@object).Length; } else { Span span = Unsafe.As>(@object).GetSpan(); ptr = ref MemoryMarshal.GetReference(span); length = span.Length; } nuint num = (uint)_index & 0x7FFFFFFFu; int length2 = _length; if ((uint)num > (uint)length || (uint)length2 > (uint)(length - (int)num)) { ThrowHelper.ThrowArgumentOutOfRangeException(); } ptr = ref Unsafe.Add(ref ptr, (IntPtr)(void*)num); length = length2; } return new ReadOnlySpan(ref ptr, length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory(T[]? array) { if (array == null) { this = default(ReadOnlyMemory); 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) { ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(ReadOnlyMemory); return; } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { 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[]? array) { return new ReadOnlyMemory(array); } public static implicit operator ReadOnlyMemory(ArraySegment segment) { return new ReadOnlyMemory(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); } return $"System.ReadOnlyMemory<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory Slice(int start) { if ((uint)start > (uint)_length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return new ReadOnlyMemory(_object, _index + start, _length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlyMemory Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); } return new ReadOnlyMemory(_object, _index + start, length); } public void CopyTo(Memory destination) { Span.CopyTo(destination.Span); } public bool TryCopyTo(Memory destination) { return Span.TryCopyTo(destination.Span); } public unsafe MemoryHandle Pin() { object @object = _object; if (@object != null) { if (typeof(T) == typeof(char) && @object is string text) { GCHandle handle = GCHandle.Alloc(@object, GCHandleType.Pinned); return new MemoryHandle(Unsafe.AsPointer(ref Unsafe.Add(ref text.GetRawStringData(), _index)), handle); } if (RuntimeHelpers.ObjectHasComponentSize(@object)) { if (_index < 0) { void* pointer = Unsafe.Add(Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(@object))), _index & 0x7FFFFFFF); return new MemoryHandle(pointer); } GCHandle handle2 = GCHandle.Alloc(@object, GCHandleType.Pinned); void* pointer2 = Unsafe.Add(Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(@object))), _index); return new MemoryHandle(pointer2, handle2); } return Unsafe.As>(@object).Pin(_index); } return default(MemoryHandle); } public T[] ToArray() { return Span.ToArray(); } [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ReadOnlyMemory other) { return Equals(other); } if (obj is Memory memory) { return Equals(memory); } return false; } public bool Equals(ReadOnlyMemory 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; } return HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal object GetObjectStartLength(out int start, out int length) { start = _index; length = _length; return _object; } } [DebuggerTypeProxy(typeof(SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] [NonVersionable] public readonly ref struct ReadOnlySpan { public ref struct Enumerator { private readonly ReadOnlySpan _span; private int _index; public ref readonly T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _span[_index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(ReadOnlySpan 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; } } internal readonly ByReference _pointer; private readonly int _length; public ref readonly T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] [NonVersionable] get { if ((uint)index >= (uint)_length) { ThrowHelper.ThrowIndexOutOfRangeException(); } return ref Unsafe.Add(ref _pointer.Value, (nint)(uint)index); } } public int Length { [NonVersionable] get { return _length; } } public bool IsEmpty { [NonVersionable] get { return 0u >= (uint)_length; } } public static ReadOnlySpan Empty => default(ReadOnlySpan); [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[]? array) { if (array == null) { this = default(ReadOnlySpan); return; } _pointer = new ByReference(ref MemoryMarshal.GetArrayDataReference(array)); _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan(T[]? array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(ReadOnlySpan); return; } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(); } _pointer = new ByReference(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), (nint)(uint)start)); _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe ReadOnlySpan(void* pointer, int length) { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); } if (length < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(); } _pointer = new ByReference(ref Unsafe.As(ref *(byte*)pointer)); _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ReadOnlySpan(ref T ptr, int length) { _pointer = new ByReference(ref ptr); _length = length; } public static bool operator !=(ReadOnlySpan left, ReadOnlySpan right) { return !(left == right); } [Obsolete("Equals() on ReadOnlySpan has will always throw an exception. Use the equality operator instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan); } [Obsolete("GetHashCode() on ReadOnlySpan will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(SR.NotSupported_CannotCallGetHashCodeOnSpan); } public static implicit operator ReadOnlySpan(T[]? array) { return new ReadOnlySpan(array); } public static implicit operator ReadOnlySpan(ArraySegment segment) { return new ReadOnlySpan(segment.Array, segment.Offset, segment.Count); } public Enumerator GetEnumerator() { return new Enumerator(this); } [EditorBrowsable(EditorBrowsableState.Never)] public ref readonly T GetPinnableReference() { ref T result = ref Unsafe.NullRef(); if (_length != 0) { result = ref _pointer.Value; } return ref result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(Span destination) { if ((uint)_length <= (uint)destination.Length) { Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (uint)_length); } else { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } public bool TryCopyTo(Span destination) { bool result = false; if ((uint)_length <= (uint)destination.Length) { Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (uint)_length); result = true; } return result; } public static bool operator ==(ReadOnlySpan left, ReadOnlySpan right) { if (left._length == right._length) { return Unsafe.AreSame(ref left._pointer.Value, ref right._pointer.Value); } return false; } public override string ToString() { if (typeof(T) == typeof(char)) { return new string(new ReadOnlySpan(ref Unsafe.As(ref _pointer.Value), _length)); } return $"System.ReadOnlySpan<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan Slice(int start) { if ((uint)start > (uint)_length) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return new ReadOnlySpan(ref Unsafe.Add(ref _pointer.Value, (nint)(uint)start), _length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ReadOnlySpan Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return new ReadOnlySpan(ref Unsafe.Add(ref _pointer.Value, (nint)(uint)start), length); } public T[] ToArray() { if (_length == 0) { return Array.Empty(); } T[] array = new T[_length]; Buffer.Memmove(ref MemoryMarshal.GetArrayDataReference(array), ref _pointer.Value, (uint)_length); return array; } } public class ResolveEventArgs : EventArgs { public string Name { get; } public Assembly? RequestingAssembly { get; } public ResolveEventArgs(string name) { Name = name; } public ResolveEventArgs(string name, Assembly? requestingAssembly) { Name = name; RequestingAssembly = requestingAssembly; } } public delegate Assembly? ResolveEventHandler(object? sender, ResolveEventArgs args); [Serializable] [CLSCompliant(false)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct SByte : IComparable, IConvertible, ISpanFormattable, IFormattable, IComparable, IEquatable, IBinaryInteger, IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IShiftOperators, IMinMaxValue, ISignedNumber { private readonly sbyte m_value; public const sbyte MaxValue = 127; public const sbyte MinValue = -128; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IAdditiveIdentity.AdditiveIdentity => 0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IMinMaxValue.MinValue => sbyte.MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IMinMaxValue.MaxValue => sbyte.MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IMultiplicativeIdentity.MultiplicativeIdentity => 1; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte INumber.One => 1; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte INumber.Zero => 0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte ISignedNumber.NegativeOne => -1; public int CompareTo(object? obj) { if (obj == null) { return 1; } if (!(obj is sbyte)) { throw new ArgumentException(SR.Arg_MustBeSByte); } return this - (sbyte)obj; } public int CompareTo(sbyte value) { return this - value; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is sbyte)) { return false; } return this == (sbyte)obj; } [NonVersionable] public bool Equals(sbyte obj) { return this == obj; } public override int GetHashCode() { return this; } public override string ToString() { return Number.Int32ToDecStr(this); } public string ToString(string? format) { return ToString(format, null); } public string ToString(IFormatProvider? provider) { return Number.FormatInt32(this, 0, null, provider); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatInt32(this, 255, format, provider); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return Number.TryFormatInt32(this, 255, format, provider, destination, out charsWritten); } public static sbyte Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static sbyte Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, style, NumberFormatInfo.CurrentInfo); } public static sbyte Parse(string s, IFormatProvider? provider) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static sbyte Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, style, NumberFormatInfo.GetInstance(provider)); } public static sbyte Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static sbyte Parse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info) { int result; Number.ParsingStatus parsingStatus = Number.TryParseInt32(s, style, info, out result); if (parsingStatus != 0) { Number.ThrowOverflowOrFormatException(parsingStatus, TypeCode.SByte); } if ((uint)(result - -128 - ((int)(style & NumberStyles.AllowHexSpecifier) >> 2)) > 255u) { Number.ThrowOverflowException(TypeCode.SByte); } return (sbyte)result; } public static bool TryParse([NotNullWhen(true)] string? s, out sbyte result) { if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan s, out sbyte result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out sbyte result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan)s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out sbyte result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out sbyte result) { if (Number.TryParseInt32(s, style, info, out var result2) != 0 || (uint)(result2 - -128 - ((int)(style & NumberStyles.AllowHexSpecifier) >> 2)) > 255u) { result = 0; return false; } result = (sbyte)result2; return true; } public TypeCode GetTypeCode() { return TypeCode.SByte; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(this); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(this); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return this; } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return this; } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "SByte", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IAdditionOperators.op_Addition(sbyte left, sbyte right) { return (sbyte)(left + right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IBinaryInteger.LeadingZeroCount(sbyte value) { return (sbyte)(BitOperations.LeadingZeroCount((byte)value) - 24); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IBinaryInteger.PopCount(sbyte value) { return (sbyte)BitOperations.PopCount((byte)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IBinaryInteger.RotateLeft(sbyte value, int rotateAmount) { return (sbyte)((value << (rotateAmount & 7)) | ((byte)value >> ((8 - rotateAmount) & 7))); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IBinaryInteger.RotateRight(sbyte value, int rotateAmount) { return (sbyte)(((byte)value >> (rotateAmount & 7)) | (value << ((8 - rotateAmount) & 7))); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IBinaryInteger.TrailingZeroCount(sbyte value) { return (sbyte)(BitOperations.TrailingZeroCount(value << 24) - 24); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IBinaryNumber.IsPow2(sbyte value) { return BitOperations.IsPow2(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IBinaryNumber.Log2(sbyte value) { if (value < 0) { ThrowHelper.ThrowValueArgumentOutOfRange_NeedNonNegNumException(); } return (sbyte)BitOperations.Log2((byte)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IBitwiseOperators.op_BitwiseAnd(sbyte left, sbyte right) { return (sbyte)(left & right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IBitwiseOperators.op_BitwiseOr(sbyte left, sbyte right) { return (sbyte)(left | right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IBitwiseOperators.op_ExclusiveOr(sbyte left, sbyte right) { return (sbyte)(left ^ right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IBitwiseOperators.op_OnesComplement(sbyte value) { return (sbyte)(~value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(sbyte left, sbyte right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(sbyte left, sbyte right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(sbyte left, sbyte right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(sbyte left, sbyte right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IDecrementOperators.op_Decrement(sbyte value) { return --value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IDivisionOperators.op_Division(sbyte left, sbyte right) { return (sbyte)(left / right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(sbyte left, sbyte right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(sbyte left, sbyte right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IIncrementOperators.op_Increment(sbyte value) { return ++value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IModulusOperators.op_Modulus(sbyte left, sbyte right) { return (sbyte)(left % right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IMultiplyOperators.op_Multiply(sbyte left, sbyte right) { return (sbyte)(left * right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte INumber.Abs(sbyte value) { return Math.Abs(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte INumber.Clamp(sbyte value, sbyte min, sbyte max) { return Math.Clamp(value, min, max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte INumber.Create(TOther value) { checked { if (typeof(TOther) == typeof(byte)) { return (sbyte)(byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (sbyte)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (sbyte)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (sbyte)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (sbyte)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (sbyte)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (sbyte)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (sbyte)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (sbyte)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (sbyte)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (sbyte)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (sbyte)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (sbyte)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { byte b = (byte)(object)value; if (b <= 127) { return (sbyte)b; } return sbyte.MaxValue; } if (typeof(TOther) == typeof(char)) { char c = (char)(object)value; if (c <= '\u007f') { return (sbyte)c; } return sbyte.MaxValue; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (!(num > 127m)) { if (!(num < -128m)) { return (sbyte)num; } return sbyte.MinValue; } return sbyte.MaxValue; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (!(num2 > 127.0)) { if (!(num2 < -128.0)) { return (sbyte)num2; } return sbyte.MinValue; } return sbyte.MaxValue; } if (typeof(TOther) == typeof(short)) { short num3 = (short)(object)value; if (num3 <= 127) { if (num3 >= -128) { return (sbyte)num3; } return sbyte.MinValue; } return sbyte.MaxValue; } if (typeof(TOther) == typeof(int)) { int num4 = (int)(object)value; if (num4 <= 127) { if (num4 >= -128) { return (sbyte)num4; } return sbyte.MinValue; } return sbyte.MaxValue; } if (typeof(TOther) == typeof(long)) { long num5 = (long)(object)value; if (num5 <= 127) { if (num5 >= -128) { return (sbyte)num5; } return sbyte.MinValue; } return sbyte.MaxValue; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr <= 127) { if ((nint)intPtr >= -128) { return (sbyte)(nint)intPtr; } return sbyte.MinValue; } return sbyte.MaxValue; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { float num6 = (float)(object)value; if (!(num6 > 127f)) { if (!(num6 < -128f)) { return (sbyte)num6; } return sbyte.MinValue; } return sbyte.MaxValue; } if (typeof(TOther) == typeof(ushort)) { ushort num7 = (ushort)(object)value; if (num7 <= 127) { return (sbyte)num7; } return sbyte.MaxValue; } if (typeof(TOther) == typeof(uint)) { uint num8 = (uint)(object)value; if ((long)num8 <= 127L) { return (sbyte)num8; } return sbyte.MaxValue; } if (typeof(TOther) == typeof(ulong)) { ulong num9 = (ulong)(object)value; if (num9 <= 127) { return (sbyte)num9; } return sbyte.MaxValue; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr <= 127) { return (sbyte)(nuint)uIntPtr; } return sbyte.MaxValue; } ThrowHelper.ThrowNotSupportedException(); return 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (sbyte)(byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (sbyte)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (sbyte)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (sbyte)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (sbyte)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (sbyte)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (sbyte)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (sbyte)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (sbyte)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (sbyte)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (sbyte)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (sbyte)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (sbyte)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (sbyte Quotient, sbyte Remainder) INumber.DivRem(sbyte left, sbyte right) { return Math.DivRem(left, right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte INumber.Max(sbyte x, sbyte y) { return Math.Max(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte INumber.Min(sbyte x, sbyte y) { return Math.Min(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte INumber.Sign(sbyte value) { return (sbyte)Math.Sign(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out sbyte result) { if (typeof(TOther) == typeof(byte)) { byte b = (byte)(object)value; if (b > 127) { result = 0; return false; } result = (sbyte)b; return true; } if (typeof(TOther) == typeof(char)) { char c = (char)(object)value; if (c > '\u007f') { result = 0; return false; } result = (sbyte)c; return true; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (num < -128m || num > 127m) { result = 0; return false; } result = (sbyte)num; return true; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (num2 < -128.0 || num2 > 127.0) { result = 0; return false; } result = (sbyte)num2; return true; } if (typeof(TOther) == typeof(short)) { short num3 = (short)(object)value; if (num3 < -128 || num3 > 127) { result = 0; return false; } result = (sbyte)num3; return true; } if (typeof(TOther) == typeof(int)) { int num4 = (int)(object)value; if (num4 < -128 || num4 > 127) { result = 0; return false; } result = (sbyte)num4; return true; } if (typeof(TOther) == typeof(long)) { long num5 = (long)(object)value; if (num5 < -128 || num5 > 127) { result = 0; return false; } result = (sbyte)num5; return true; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr < -128 || (nint)intPtr > 127) { result = 0; return false; } result = (sbyte)(nint)intPtr; return true; } if (typeof(TOther) == typeof(sbyte)) { result = (sbyte)(object)value; return true; } if (typeof(TOther) == typeof(float)) { float num6 = (float)(object)value; if (num6 < -128f || num6 > 127f) { result = 0; return false; } result = (sbyte)num6; return true; } if (typeof(TOther) == typeof(ushort)) { ushort num7 = (ushort)(object)value; if (num7 > 127) { result = 0; return false; } result = (sbyte)num7; return true; } if (typeof(TOther) == typeof(uint)) { uint num8 = (uint)(object)value; if ((long)num8 > 127L) { result = 0; return false; } result = (sbyte)num8; return true; } if (typeof(TOther) == typeof(ulong)) { ulong num9 = (ulong)(object)value; if (num9 > 127) { result = 0; return false; } result = (sbyte)num9; return true; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr > 127) { result = 0; return false; } result = (sbyte)(nuint)uIntPtr; return true; } ThrowHelper.ThrowNotSupportedException(); result = 0; return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out sbyte result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out sbyte result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out sbyte result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IShiftOperators.op_LeftShift(sbyte value, int shiftAmount) { return (sbyte)(value << shiftAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IShiftOperators.op_RightShift(sbyte value, int shiftAmount) { return (sbyte)(value >> shiftAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out sbyte result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte ISubtractionOperators.op_Subtraction(sbyte left, sbyte right) { return (sbyte)(left - right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IUnaryNegationOperators.op_UnaryNegation(sbyte value) { return (sbyte)(-value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static sbyte IUnaryPlusOperators.op_UnaryPlus(sbyte value) { return value; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)] public sealed class SerializableAttribute : Attribute { } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Single : IComparable, IConvertible, ISpanFormattable, IFormattable, IComparable, IEquatable, IBinaryFloatingPoint, IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IFloatingPoint, ISignedNumber, IMinMaxValue { private readonly float m_value; public const float MinValue = -3.4028235E+38f; public const float Epsilon = 1E-45f; public const float MaxValue = 3.4028235E+38f; public const float PositiveInfinity = 1f / 0f; public const float NegativeInfinity = -1f / 0f; public const float NaN = 0f / 0f; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IAdditiveIdentity.AdditiveIdentity => 0f; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.E => (float)Math.E; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Epsilon => float.Epsilon; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.NaN => float.NaN; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.NegativeInfinity => float.NegativeInfinity; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.NegativeZero => -0f; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Pi => (float)Math.PI; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.PositiveInfinity => float.PositiveInfinity; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Tau => (float)Math.PI * 2f; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IMinMaxValue.MinValue => float.MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IMinMaxValue.MaxValue => float.MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IMultiplicativeIdentity.MultiplicativeIdentity => 1f; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float INumber.One => 1f; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float INumber.Zero => 0f; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float ISignedNumber.NegativeOne => -1f; [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsFinite(float f) { int num = BitConverter.SingleToInt32Bits(f); return (num & 0x7FFFFFFF) < 2139095040; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsInfinity(float f) { int num = BitConverter.SingleToInt32Bits(f); return (num & 0x7FFFFFFF) == 2139095040; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsNaN(float f) { return f != f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsNegative(float f) { return BitConverter.SingleToInt32Bits(f) < 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsNegativeInfinity(float f) { return f == float.NegativeInfinity; } [NonVersionable] public static bool IsNormal(float f) { int num = BitConverter.SingleToInt32Bits(f); num &= 0x7FFFFFFF; if (num < 2139095040 && num != 0) { return (num & 0x7F800000) != 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [NonVersionable] public static bool IsPositiveInfinity(float f) { return f == float.PositiveInfinity; } [NonVersionable] public static bool IsSubnormal(float f) { int num = BitConverter.SingleToInt32Bits(f); num &= 0x7FFFFFFF; if (num < 2139095040 && num != 0) { return (num & 0x7F800000) == 0; } return false; } internal static int ExtractExponentFromBits(uint bits) { return (int)((bits >> 23) & 0xFF); } internal static uint ExtractSignificandFromBits(uint bits) { return bits & 0x7FFFFFu; } public int CompareTo(object? value) { if (value == null) { return 1; } if (value is float num) { if (this < num) { return -1; } if (this > num) { return 1; } if (this == num) { return 0; } if (IsNaN(this)) { if (!IsNaN(num)) { return -1; } return 0; } return 1; } throw new ArgumentException(SR.Arg_MustBeSingle); } public int CompareTo(float value) { if (this < value) { return -1; } if (this > value) { return 1; } if (this == value) { return 0; } if (IsNaN(this)) { if (!IsNaN(value)) { return -1; } return 0; } return 1; } [NonVersionable] public static bool operator ==(float left, float right) { return left == right; } [NonVersionable] public static bool operator !=(float left, float right) { return left != right; } [NonVersionable] public static bool operator <(float left, float right) { return left < right; } [NonVersionable] public static bool operator >(float left, float right) { return left > right; } [NonVersionable] public static bool operator <=(float left, float right) { return left <= right; } [NonVersionable] public static bool operator >=(float left, float right) { return left >= right; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is float num)) { return false; } if (num == this) { return true; } if (IsNaN(num)) { return IsNaN(this); } return false; } public bool Equals(float obj) { if (obj == this) { return true; } if (IsNaN(obj)) { return IsNaN(this); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override int GetHashCode() { int num = Unsafe.As(ref Unsafe.AsRef(in m_value)); if (((num - 1) & 0x7FFFFFFF) >= 2139095040) { num &= 0x7F800000; } return num; } public override string ToString() { return Number.FormatSingle(this, null, NumberFormatInfo.CurrentInfo); } public string ToString(IFormatProvider? provider) { return Number.FormatSingle(this, null, NumberFormatInfo.GetInstance(provider)); } public string ToString(string? format) { return Number.FormatSingle(this, format, NumberFormatInfo.CurrentInfo); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatSingle(this, format, NumberFormatInfo.GetInstance(provider)); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return Number.TryFormatSingle(this, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten); } public static float Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo); } public static float Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseSingle(s, style, NumberFormatInfo.CurrentInfo); } public static float Parse(string s, IFormatProvider? provider) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider)); } public static float Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider)); } public static float Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Float | NumberStyles.AllowThousands, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider)); } public static bool TryParse([NotNullWhen(true)] string? s, out float result) { if (s == null) { result = 0f; return false; } return TryParse((ReadOnlySpan)s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan s, out float result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out float result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); if (s == null) { result = 0f; return false; } return TryParse((ReadOnlySpan)s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out float result) { NumberFormatInfo.ValidateParseStyleFloatingPoint(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out float result) { return Number.TryParseSingle(s, style, info, out result); } public TypeCode GetTypeCode() { return TypeCode.Single; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(this); } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "Char")); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { return this; } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IAdditionOperators.op_Addition(float left, float right) { return left + right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IBinaryNumber.IsPow2(float value) { uint num = BitConverter.SingleToUInt32Bits(value); uint num2 = (num >> 23) & 0xFFu; uint num3 = num & 0x7FFFFFu; if (value > 0f && num2 != 0 && num2 != 255) { return num3 == 0; } return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IBinaryNumber.Log2(float value) { return MathF.Log2(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IBitwiseOperators.op_BitwiseAnd(float left, float right) { uint value = BitConverter.SingleToUInt32Bits(left) & BitConverter.SingleToUInt32Bits(right); return BitConverter.UInt32BitsToSingle(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IBitwiseOperators.op_BitwiseOr(float left, float right) { uint value = BitConverter.SingleToUInt32Bits(left) | BitConverter.SingleToUInt32Bits(right); return BitConverter.UInt32BitsToSingle(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IBitwiseOperators.op_ExclusiveOr(float left, float right) { uint value = BitConverter.SingleToUInt32Bits(left) ^ BitConverter.SingleToUInt32Bits(right); return BitConverter.UInt32BitsToSingle(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IBitwiseOperators.op_OnesComplement(float value) { uint value2 = ~BitConverter.SingleToUInt32Bits(value); return BitConverter.UInt32BitsToSingle(value2); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(float left, float right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(float left, float right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(float left, float right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(float left, float right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IDecrementOperators.op_Decrement(float value) { return value -= 1f; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IDivisionOperators.op_Division(float left, float right) { return left / right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(float left, float right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(float left, float right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Acos(float x) { return MathF.Acos(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Acosh(float x) { return MathF.Acosh(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Asin(float x) { return MathF.Asin(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Asinh(float x) { return MathF.Asinh(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Atan(float x) { return MathF.Atan(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Atan2(float y, float x) { return MathF.Atan2(y, x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Atanh(float x) { return MathF.Atanh(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.BitIncrement(float x) { return MathF.BitIncrement(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.BitDecrement(float x) { return MathF.BitDecrement(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Cbrt(float x) { return MathF.Cbrt(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Ceiling(float x) { return MathF.Ceiling(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.CopySign(float x, float y) { return MathF.CopySign(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Cos(float x) { return MathF.Cos(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Cosh(float x) { return MathF.Cosh(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Exp(float x) { return MathF.Exp(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Floor(float x) { return MathF.Floor(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.FusedMultiplyAdd(float left, float right, float addend) { return MathF.FusedMultiplyAdd(left, right, addend); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.IEEERemainder(float left, float right) { return MathF.IEEERemainder(left, right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TInteger IFloatingPoint.ILogB(float x) { return TInteger.Create(MathF.ILogB(x)); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Log(float x) { return MathF.Log(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Log(float x, float newBase) { return MathF.Log(x, newBase); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Log2(float x) { return MathF.Log2(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Log10(float x) { return MathF.Log10(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.MaxMagnitude(float x, float y) { return MathF.MaxMagnitude(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.MinMagnitude(float x, float y) { return MathF.MinMagnitude(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Pow(float x, float y) { return MathF.Pow(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Round(float x) { return MathF.Round(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Round(float x, TInteger digits) { return MathF.Round(x, int.Create(digits)); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Round(float x, MidpointRounding mode) { return MathF.Round(x, mode); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Round(float x, TInteger digits, MidpointRounding mode) { return MathF.Round(x, int.Create(digits), mode); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.ScaleB(float x, TInteger n) { return MathF.ScaleB(x, int.Create(n)); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Sin(float x) { return MathF.Sin(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Sinh(float x) { return MathF.Sinh(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Sqrt(float x) { return MathF.Sqrt(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Tan(float x) { return MathF.Tan(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Tanh(float x) { return MathF.Tanh(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IFloatingPoint.Truncate(float x) { return MathF.Truncate(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsFinite(float x) { return IsFinite(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsInfinity(float x) { return IsInfinity(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsNaN(float x) { return IsNaN(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsNegative(float x) { return IsNegative(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsNegativeInfinity(float x) { return IsNegativeInfinity(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsNormal(float x) { return IsNormal(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsPositiveInfinity(float x) { return IsPositiveInfinity(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IFloatingPoint.IsSubnormal(float x) { return IsSubnormal(x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IIncrementOperators.op_Increment(float value) { return value += 1f; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IModulusOperators.op_Modulus(float left, float right) { return left % right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IMultiplyOperators.op_Multiply(float left, float right) { return left * right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float INumber.Abs(float value) { return MathF.Abs(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float INumber.Clamp(float value, float min, float max) { return Math.Clamp(value, min, max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float INumber.Create(TOther value) { if (typeof(TOther) == typeof(byte)) { return (int)(byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (int)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (float)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (float)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (int)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (nint)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (int)(byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (int)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (float)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (float)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (int)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (nint)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0f; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (int)(byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (int)(char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (float)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (float)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (short)(object)value; } if (typeof(TOther) == typeof(int)) { return (int)(object)value; } if (typeof(TOther) == typeof(long)) { return (long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (int)(ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (nint)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0f; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (float Quotient, float Remainder) INumber.DivRem(float left, float right) { return (left / right, left % right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float INumber.Max(float x, float y) { return MathF.Max(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float INumber.Min(float x, float y) { return MathF.Min(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float INumber.Sign(float value) { return MathF.Sign(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out float result) { if (typeof(TOther) == typeof(byte)) { result = (int)(byte)(object)value; return true; } if (typeof(TOther) == typeof(char)) { result = (int)(char)(object)value; return true; } if (typeof(TOther) == typeof(decimal)) { result = (float)(decimal)(object)value; return true; } if (typeof(TOther) == typeof(double)) { result = (float)(double)(object)value; return true; } if (typeof(TOther) == typeof(short)) { result = (short)(object)value; return true; } if (typeof(TOther) == typeof(int)) { result = (int)(object)value; return true; } if (typeof(TOther) == typeof(long)) { result = (long)(object)value; return true; } if (typeof(TOther) == typeof(IntPtr)) { result = (nint)(IntPtr)(object)value; return true; } if (typeof(TOther) == typeof(sbyte)) { result = (sbyte)(object)value; return true; } if (typeof(TOther) == typeof(float)) { result = (float)(object)value; return true; } if (typeof(TOther) == typeof(ushort)) { result = (int)(ushort)(object)value; return true; } if (typeof(TOther) == typeof(uint)) { result = (uint)(object)value; return true; } if (typeof(TOther) == typeof(ulong)) { result = (ulong)(object)value; return true; } if (typeof(TOther) == typeof(UIntPtr)) { result = (nint)(nuint)(UIntPtr)(object)value; return true; } ThrowHelper.ThrowNotSupportedException(); result = 0f; return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out float result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out float result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out float result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out float result) { return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float ISubtractionOperators.op_Subtraction(float left, float right) { return left - right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IUnaryNegationOperators.op_UnaryNegation(float value) { return 0f - value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static float IUnaryPlusOperators.op_UnaryPlus(float value) { return value; } } [DebuggerTypeProxy(typeof(SpanDebugView<>))] [DebuggerDisplay("{ToString(),raw}")] [NonVersionable] public readonly ref struct Span { public ref struct Enumerator { private readonly Span _span; private int _index; public ref T Current { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref _span[_index]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Enumerator(Span 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; } } internal readonly ByReference _pointer; private readonly int _length; public ref T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] [NonVersionable] get { if ((uint)index >= (uint)_length) { ThrowHelper.ThrowIndexOutOfRangeException(); } return ref Unsafe.Add(ref _pointer.Value, (nint)(uint)index); } } public int Length { [NonVersionable] get { return _length; } } public bool IsEmpty { [NonVersionable] get { return 0u >= (uint)_length; } } public static Span Empty => default(Span); [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[]? array) { if (array == null) { this = default(Span); return; } if (!typeof(T).IsValueType && array.GetType() != typeof(T[])) { ThrowHelper.ThrowArrayTypeMismatchException(); } _pointer = new ByReference(ref MemoryMarshal.GetArrayDataReference(array)); _length = array.Length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span(T[]? array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(); } this = default(Span); return; } if (!typeof(T).IsValueType && array.GetType() != typeof(T[])) { ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(); } _pointer = new ByReference(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), (nint)(uint)start)); _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public unsafe Span(void* pointer, int length) { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); } if (length < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(); } _pointer = new ByReference(ref Unsafe.As(ref *(byte*)pointer)); _length = length; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal Span(ref T ptr, int length) { _pointer = new ByReference(ref ptr); _length = length; } public static bool operator !=(Span left, Span right) { return !(left == right); } [Obsolete("Equals() on Span will always throw an exception. Use the equality operator instead.")] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object? obj) { throw new NotSupportedException(SR.NotSupported_CannotCallEqualsOnSpan); } [Obsolete("GetHashCode() on Span will always throw an exception.")] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() { throw new NotSupportedException(SR.NotSupported_CannotCallGetHashCodeOnSpan); } public static implicit operator Span(T[]? array) { return new Span(array); } public static implicit operator Span(ArraySegment segment) { return new Span(segment.Array, segment.Offset, segment.Count); } public Enumerator GetEnumerator() { return new Enumerator(this); } [EditorBrowsable(EditorBrowsableState.Never)] public ref T GetPinnableReference() { ref T result = ref Unsafe.NullRef(); if (_length != 0) { result = ref _pointer.Value; } return ref result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe void Clear() { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { SpanHelpers.ClearWithReferences(ref Unsafe.As(ref _pointer.Value), (nuint)(uint)_length * (nuint)(Unsafe.SizeOf() / sizeof(UIntPtr))); } else { SpanHelpers.ClearWithoutReferences(ref Unsafe.As(ref _pointer.Value), (nuint)(uint)_length * (nuint)Unsafe.SizeOf()); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Fill(T value) { if (Unsafe.SizeOf() == 1) { Unsafe.InitBlockUnaligned(ref Unsafe.As(ref _pointer.Value), Unsafe.As(ref value), (uint)_length); } else { SpanHelpers.Fill(ref _pointer.Value, (uint)_length, value); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void CopyTo(Span destination) { if ((uint)_length <= (uint)destination.Length) { Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (uint)_length); } else { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } } public bool TryCopyTo(Span destination) { bool result = false; if ((uint)_length <= (uint)destination.Length) { Buffer.Memmove(ref destination._pointer.Value, ref _pointer.Value, (uint)_length); result = true; } return result; } public static bool operator ==(Span left, Span right) { if (left._length == right._length) { return Unsafe.AreSame(ref left._pointer.Value, ref right._pointer.Value); } return false; } public static implicit operator ReadOnlySpan(Span span) { return new ReadOnlySpan(ref span._pointer.Value, span._length); } public override string ToString() { if (typeof(T) == typeof(char)) { return new string(new ReadOnlySpan(ref Unsafe.As(ref _pointer.Value), _length)); } return $"System.Span<{typeof(T).Name}>[{_length}]"; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span Slice(int start) { if ((uint)start > (uint)_length) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return new Span(ref Unsafe.Add(ref _pointer.Value, (nint)(uint)start), _length - start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span Slice(int start, int length) { if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return new Span(ref Unsafe.Add(ref _pointer.Value, (nint)(uint)start), length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[] ToArray() { if (_length == 0) { return Array.Empty(); } T[] array = new T[_length]; Buffer.Memmove(ref MemoryMarshal.GetArrayDataReference(array), ref _pointer.Value, (uint)_length); return array; } } internal sealed class SpanDebugView { private readonly T[] _array; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public T[] Items => _array; public SpanDebugView(Span span) { _array = span.ToArray(); } public SpanDebugView(ReadOnlySpan span) { _array = span.ToArray(); } } internal static class SpanHelpers { internal readonly struct ComparerComparable : IComparable where TComparer : IComparer { 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); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int BinarySearch(this ReadOnlySpan span, TComparable comparable) where TComparable : IComparable { if (comparable == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparable); } return BinarySearch(ref MemoryMarshal.GetReference(span), span.Length, comparable); } public static int BinarySearch(ref T spanStart, int length, TComparable comparable) where TComparable : IComparable { int num = 0; int num2 = length - 1; while (num <= num2) { int num3 = num2 + num >>> 1; int num4 = comparable.CompareTo(Unsafe.Add(ref spanStart, num3)); if (num4 == 0) { return num3; } if (num4 > 0) { num = num3 + 1; } else { num2 = num3 - 1; } } return ~num; } public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return 0; } byte value2 = value; ref byte second = ref Unsafe.Add(ref value, 1); int num = valueLength - 1; int num2 = searchSpaceLength - num; int num3 = 0; while (num2 > 0) { int num4 = IndexOf(ref Unsafe.Add(ref searchSpace, num3), value2, num2); if (num4 == -1) { break; } num2 -= num4; num3 += num4; if (num2 <= 0) { break; } if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num3 + 1), ref second, (nuint)num)) { return num3; } num2--; num3++; } return -1; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public static bool Contains(ref byte searchSpace, byte value, int length) { nuint num = 0u; nuint num2 = (uint)length; if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { num2 = UnalignedCountVector(ref searchSpace); } while (true) { if (num2 >= 8) { num2 -= 8; if (value == Unsafe.AddByteOffset(ref searchSpace, num + 0) || value == Unsafe.AddByteOffset(ref searchSpace, num + 1) || value == Unsafe.AddByteOffset(ref searchSpace, num + 2) || value == Unsafe.AddByteOffset(ref searchSpace, num + 3) || value == Unsafe.AddByteOffset(ref searchSpace, num + 4) || value == Unsafe.AddByteOffset(ref searchSpace, num + 5) || value == Unsafe.AddByteOffset(ref searchSpace, num + 6) || value == Unsafe.AddByteOffset(ref searchSpace, num + 7)) { break; } num += 8; continue; } if (num2 >= 4) { num2 -= 4; if (value == Unsafe.AddByteOffset(ref searchSpace, num + 0) || value == Unsafe.AddByteOffset(ref searchSpace, num + 1) || value == Unsafe.AddByteOffset(ref searchSpace, num + 2) || value == Unsafe.AddByteOffset(ref searchSpace, num + 3)) { break; } num += 4; } while (num2 != 0) { num2--; if (value == Unsafe.AddByteOffset(ref searchSpace, num)) { goto end_IL_00bd; } num++; } if (Vector.IsHardwareAccelerated && num < (uint)length) { num2 = ((uint)length - num) & (nuint)(~(Vector.Count - 1)); Vector left = new Vector(value); for (; num2 > num; num += (nuint)Vector.Count) { Vector other = Vector.Equals(left, LoadVector(ref searchSpace, num)); if (!Vector.Zero.Equals(other)) { goto end_IL_00bd; } } if (num < (uint)length) { num2 = (uint)length - num; continue; } } return false; continue; end_IL_00bd: break; } return true; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public unsafe static int IndexOf(ref byte searchSpace, byte value, int length) { nuint num = 0u; nuint num2 = (uint)length; if (Sse2.IsSupported || AdvSimd.Arm64.IsSupported) { if (length >= Vector128.Count * 2) { num2 = UnalignedCountVector128(ref searchSpace); } } else if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { num2 = UnalignedCountVector(ref searchSpace); } while (true) { if (num2 >= 8) { num2 -= 8; if (value == Unsafe.AddByteOffset(ref searchSpace, num)) { goto IL_033c; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 1)) { goto IL_033f; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 2)) { goto IL_0345; } if (value != Unsafe.AddByteOffset(ref searchSpace, num + 3)) { if (value != Unsafe.AddByteOffset(ref searchSpace, num + 4)) { if (value != Unsafe.AddByteOffset(ref searchSpace, num + 5)) { if (value != Unsafe.AddByteOffset(ref searchSpace, num + 6)) { if (value == Unsafe.AddByteOffset(ref searchSpace, num + 7)) { break; } num += 8; continue; } return (int)(num + 6); } return (int)(num + 5); } return (int)(num + 4); } goto IL_034b; } if (num2 >= 4) { num2 -= 4; if (value == Unsafe.AddByteOffset(ref searchSpace, num)) { goto IL_033c; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 1)) { goto IL_033f; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 2)) { goto IL_0345; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 3)) { goto IL_034b; } num += 4; } while (num2 != 0) { num2--; if (value != Unsafe.AddByteOffset(ref searchSpace, num)) { num++; continue; } goto IL_033c; } if (Avx2.IsSupported) { if (num < (uint)length) { if ((((uint)Unsafe.AsPointer(ref searchSpace) + num) & (nuint)(Vector256.Count - 1)) != 0) { Vector128 left = Vector128.Create(value); Vector128 right = LoadVector128(ref searchSpace, num); int num3 = Sse2.MoveMask(Sse2.CompareEqual(left, right)); if (num3 != 0) { return (int)(num + (uint)BitOperations.TrailingZeroCount(num3)); } num += (nuint)Vector128.Count; } num2 = GetByteVector256SpanLength(num, length); if (num2 > num) { Vector256 left2 = Vector256.Create(value); do { Vector256 right2 = LoadVector256(ref searchSpace, num); int num4 = Avx2.MoveMask(Avx2.CompareEqual(left2, right2)); if (num4 == 0) { num += (nuint)Vector256.Count; continue; } return (int)(num + (uint)BitOperations.TrailingZeroCount(num4)); } while (num2 > num); } num2 = GetByteVector128SpanLength(num, length); if (num2 > num) { Vector128 left3 = Vector128.Create(value); Vector128 right3 = LoadVector128(ref searchSpace, num); int num5 = Sse2.MoveMask(Sse2.CompareEqual(left3, right3)); if (num5 != 0) { return (int)(num + (uint)BitOperations.TrailingZeroCount(num5)); } num += (nuint)Vector128.Count; } if (num < (uint)length) { num2 = (uint)length - num; continue; } } } else if (Sse2.IsSupported) { if (num < (uint)length) { num2 = GetByteVector128SpanLength(num, length); Vector128 left4 = Vector128.Create(value); for (; num2 > num; num += (nuint)Vector128.Count) { Vector128 right4 = LoadVector128(ref searchSpace, num); int num6 = Sse2.MoveMask(Sse2.CompareEqual(left4, right4)); if (num6 != 0) { return (int)(num + (uint)BitOperations.TrailingZeroCount(num6)); } } if (num < (uint)length) { num2 = (uint)length - num; continue; } } } else { if (AdvSimd.Arm64.IsSupported) { } if (Vector.IsHardwareAccelerated && num < (uint)length) { num2 = GetByteVectorSpanLength(num, length); Vector left5 = new Vector(value); for (; num2 > num; num += (nuint)Vector.Count) { Vector vector = Vector.Equals(left5, LoadVector(ref searchSpace, num)); if (!Vector.Zero.Equals(vector)) { return (int)num + LocateFirstFoundByte(vector); } } if (num < (uint)length) { num2 = (uint)length - num; continue; } } } return -1; IL_0345: return (int)(num + 2); IL_033f: return (int)(num + 1); IL_034b: return (int)(num + 3); IL_033c: return (int)num; } return (int)(num + 7); } public static int LastIndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength) { if (valueLength == 0) { return searchSpaceLength; } byte value2 = value; ref byte second = ref Unsafe.Add(ref value, 1); int num = valueLength - 1; int num2 = 0; while (true) { int num3 = searchSpaceLength - num2 - num; if (num3 <= 0) { break; } int num4 = LastIndexOf(ref searchSpace, value2, num3); if (num4 == -1) { break; } if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num4 + 1), ref second, (uint)num)) { return num4; } num2 += num3 - num4; } return -1; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public static int LastIndexOf(ref byte searchSpace, byte value, int length) { nuint num = (uint)length; nuint num2 = (uint)length; if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { num2 = UnalignedCountVectorFromEnd(ref searchSpace, length); } while (true) { if (num2 >= 8) { num2 -= 8; num -= 8; if (value == Unsafe.AddByteOffset(ref searchSpace, num + 7)) { break; } if (value != Unsafe.AddByteOffset(ref searchSpace, num + 6)) { if (value != Unsafe.AddByteOffset(ref searchSpace, num + 5)) { if (value != Unsafe.AddByteOffset(ref searchSpace, num + 4)) { if (value != Unsafe.AddByteOffset(ref searchSpace, num + 3)) { if (value != Unsafe.AddByteOffset(ref searchSpace, num + 2)) { if (value != Unsafe.AddByteOffset(ref searchSpace, num + 1)) { if (value != Unsafe.AddByteOffset(ref searchSpace, num)) { continue; } goto IL_01ba; } goto IL_01bd; } goto IL_01c3; } goto IL_01c9; } return (int)(num + 4); } return (int)(num + 5); } return (int)(num + 6); } if (num2 >= 4) { num2 -= 4; num -= 4; if (value == Unsafe.AddByteOffset(ref searchSpace, num + 3)) { goto IL_01c9; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 2)) { goto IL_01c3; } if (value == Unsafe.AddByteOffset(ref searchSpace, num + 1)) { goto IL_01bd; } if (value == Unsafe.AddByteOffset(ref searchSpace, num)) { goto IL_01ba; } } while (num2 != 0) { num2--; num--; if (value != Unsafe.AddByteOffset(ref searchSpace, num)) { continue; } goto IL_01ba; } if (Vector.IsHardwareAccelerated && num != 0) { num2 = num & (nuint)(~(Vector.Count - 1)); Vector left = new Vector(value); while (num2 > (nuint)(Vector.Count - 1)) { Vector vector = Vector.Equals(left, LoadVector(ref searchSpace, num - (nuint)Vector.Count)); if (Vector.Zero.Equals(vector)) { num -= (nuint)Vector.Count; num2 -= (nuint)Vector.Count; continue; } return (int)num - Vector.Count + LocateLastFoundByte(vector); } if (num != 0) { num2 = num; continue; } } return -1; IL_01ba: return (int)num; IL_01c3: return (int)(num + 2); IL_01c9: return (int)(num + 3); IL_01bd: return (int)(num + 1); } return (int)(num + 7); } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public static int IndexOfAny(ref byte searchSpace, byte value0, byte value1, int length) { nuint num = 0u; nuint num2 = (uint)length; if (Sse2.IsSupported || AdvSimd.Arm64.IsSupported) { nint num3 = (nint)length - (nint)Vector128.Count; if (num3 >= 0) { num2 = (nuint)num3; goto IL_0212; } } else if (Vector.IsHardwareAccelerated) { nint num4 = (nint)length - (nint)Vector.Count; if (num4 >= 0) { num2 = (nuint)num4; goto IL_0212; } } while (num2 >= 8) { num2 -= 8; uint num5 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 == num5 || value1 == num5) { goto IL_01e5; } num5 = Unsafe.AddByteOffset(ref searchSpace, num + 1); if (value0 == num5 || value1 == num5) { goto IL_01e8; } num5 = Unsafe.AddByteOffset(ref searchSpace, num + 2); if (value0 == num5 || value1 == num5) { goto IL_01ee; } num5 = Unsafe.AddByteOffset(ref searchSpace, num + 3); if (value0 != num5 && value1 != num5) { num5 = Unsafe.AddByteOffset(ref searchSpace, num + 4); if (value0 != num5 && value1 != num5) { num5 = Unsafe.AddByteOffset(ref searchSpace, num + 5); if (value0 != num5 && value1 != num5) { num5 = Unsafe.AddByteOffset(ref searchSpace, num + 6); if (value0 != num5 && value1 != num5) { num5 = Unsafe.AddByteOffset(ref searchSpace, num + 7); if (value0 != num5 && value1 != num5) { num += 8; continue; } return (int)(num + 7); } return (int)(num + 6); } return (int)(num + 5); } return (int)(num + 4); } goto IL_01f4; } if (num2 >= 4) { num2 -= 4; uint num5 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 == num5 || value1 == num5) { goto IL_01e5; } num5 = Unsafe.AddByteOffset(ref searchSpace, num + 1); if (value0 == num5 || value1 == num5) { goto IL_01e8; } num5 = Unsafe.AddByteOffset(ref searchSpace, num + 2); if (value0 == num5 || value1 == num5) { goto IL_01ee; } num5 = Unsafe.AddByteOffset(ref searchSpace, num + 3); if (value0 == num5 || value1 == num5) { goto IL_01f4; } num += 4; } while (num2 != 0) { uint num5 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 != num5 && value1 != num5) { num++; num2--; continue; } goto IL_01e5; } goto IL_01e3; IL_01ee: return (int)(num + 2); IL_03ec: Vector vector; num += (nuint)LocateFirstFoundByte(vector); goto IL_01e5; IL_01e3: return -1; IL_01e5: return (int)num; IL_033c: int num6; num += (nuint)BitOperations.TrailingZeroCount(num6); goto IL_01e5; IL_01e8: return (int)(num + 1); IL_0212: if (Sse2.IsSupported) { if (Avx2.IsSupported && num2 >= (nuint)Vector128.Count) { Vector256 left = Vector256.Create(value0); Vector256 left2 = Vector256.Create(value1); num2 -= (nuint)Vector128.Count; Vector256 right; while (num2 > num) { right = LoadVector256(ref searchSpace, num); num6 = Avx2.MoveMask(Avx2.Or(Avx2.CompareEqual(left, right), Avx2.CompareEqual(left2, right))); if (num6 == 0) { num += (nuint)Vector256.Count; continue; } goto IL_033c; } right = LoadVector256(ref searchSpace, num2); num = num2; num6 = Avx2.MoveMask(Avx2.Or(Avx2.CompareEqual(left, right), Avx2.CompareEqual(left2, right))); if (num6 == 0) { goto IL_01e3; } } else { Vector128 left3 = Vector128.Create(value0); Vector128 left4 = Vector128.Create(value1); Vector128 right2; while (num2 > num) { right2 = LoadVector128(ref searchSpace, num); num6 = Sse2.MoveMask(Sse2.Or(Sse2.CompareEqual(left3, right2), Sse2.CompareEqual(left4, right2)).AsByte()); if (num6 == 0) { num += (nuint)Vector128.Count; continue; } goto IL_033c; } right2 = LoadVector128(ref searchSpace, num2); num = num2; num6 = Sse2.MoveMask(Sse2.Or(Sse2.CompareEqual(left3, right2), Sse2.CompareEqual(left4, right2))); if (num6 == 0) { goto IL_01e3; } } goto IL_033c; } if (AdvSimd.Arm64.IsSupported) { } if (!Vector.IsHardwareAccelerated) { goto IL_01e5; } Vector right3 = new Vector(value0); Vector right4 = new Vector(value1); while (num2 > num) { vector = LoadVector(ref searchSpace, num); vector = Vector.BitwiseOr(Vector.Equals(vector, right3), Vector.Equals(vector, right4)); if (Vector.Zero.Equals(vector)) { num += (nuint)Vector.Count; continue; } goto IL_03ec; } vector = LoadVector(ref searchSpace, num2); num = num2; vector = Vector.BitwiseOr(Vector.Equals(vector, right3), Vector.Equals(vector, right4)); if (Vector.Zero.Equals(vector)) { goto IL_01e3; } goto IL_03ec; IL_01f4: return (int)(num + 3); } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public static int IndexOfAny(ref byte searchSpace, byte value0, byte value1, byte value2, int length) { nuint num = 0u; nuint num2 = (uint)length; if (Sse2.IsSupported || AdvSimd.Arm64.IsSupported) { if (length >= Vector128.Count * 2) { num2 = UnalignedCountVector128(ref searchSpace); } } else if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { num2 = UnalignedCountVector(ref searchSpace); } while (true) { if (num2 >= 8) { num2 -= 8; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_0504; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 1); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_0507; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 2); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_050d; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 3); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 4); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 5); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 6); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 7); if (value0 == num3 || value1 == num3 || value2 == num3) { break; } num += 8; continue; } return (int)(num + 6); } return (int)(num + 5); } return (int)(num + 4); } goto IL_0513; } if (num2 >= 4) { num2 -= 4; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_0504; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 1); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_0507; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 2); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_050d; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 3); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_0513; } num += 4; } while (num2 != 0) { num2--; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 != num3 && value1 != num3 && value2 != num3) { num++; continue; } goto IL_0504; } if (Avx2.IsSupported) { if (num < (uint)length) { num2 = GetByteVector256SpanLength(num, length); if (num2 > num) { Vector256 left = Vector256.Create(value0); Vector256 left2 = Vector256.Create(value1); Vector256 left3 = Vector256.Create(value2); do { Vector256 right = LoadVector256(ref searchSpace, num); Vector256 left4 = Avx2.CompareEqual(left, right); Vector256 right2 = Avx2.CompareEqual(left2, right); Vector256 right3 = Avx2.CompareEqual(left3, right); int num4 = Avx2.MoveMask(Avx2.Or(Avx2.Or(left4, right2), right3)); if (num4 == 0) { num += (nuint)Vector256.Count; continue; } return (int)(num + (uint)BitOperations.TrailingZeroCount(num4)); } while (num2 > num); } num2 = GetByteVector128SpanLength(num, length); if (num2 > num) { Vector128 left5 = Vector128.Create(value0); Vector128 left6 = Vector128.Create(value1); Vector128 left7 = Vector128.Create(value2); Vector128 right4 = LoadVector128(ref searchSpace, num); Vector128 left8 = Sse2.CompareEqual(left5, right4); Vector128 right5 = Sse2.CompareEqual(left6, right4); Vector128 right6 = Sse2.CompareEqual(left7, right4); int num5 = Sse2.MoveMask(Sse2.Or(Sse2.Or(left8, right5), right6)); if (num5 != 0) { return (int)(num + (uint)BitOperations.TrailingZeroCount(num5)); } num += (nuint)Vector128.Count; } if (num < (uint)length) { num2 = (uint)length - num; continue; } } } else if (Sse2.IsSupported) { if (num < (uint)length) { num2 = GetByteVector128SpanLength(num, length); Vector128 left9 = Vector128.Create(value0); Vector128 left10 = Vector128.Create(value1); Vector128 left11 = Vector128.Create(value2); for (; num2 > num; num += (nuint)Vector128.Count) { Vector128 right7 = LoadVector128(ref searchSpace, num); Vector128 left12 = Sse2.CompareEqual(left9, right7); Vector128 right8 = Sse2.CompareEqual(left10, right7); Vector128 right9 = Sse2.CompareEqual(left11, right7); int num6 = Sse2.MoveMask(Sse2.Or(Sse2.Or(left12, right8), right9)); if (num6 != 0) { return (int)(num + (uint)BitOperations.TrailingZeroCount(num6)); } } if (num < (uint)length) { num2 = (uint)length - num; continue; } } } else { if (AdvSimd.Arm64.IsSupported) { } if (Vector.IsHardwareAccelerated && num < (uint)length) { num2 = GetByteVectorSpanLength(num, length); Vector right10 = new Vector(value0); Vector right11 = new Vector(value1); Vector right12 = new Vector(value2); for (; num2 > num; num += (nuint)Vector.Count) { Vector left13 = LoadVector(ref searchSpace, num); Vector vector = Vector.BitwiseOr(Vector.BitwiseOr(Vector.Equals(left13, right10), Vector.Equals(left13, right11)), Vector.Equals(left13, right12)); if (!Vector.Zero.Equals(vector)) { return (int)num + LocateFirstFoundByte(vector); } } if (num < (uint)length) { num2 = (uint)length - num; continue; } } } return -1; IL_0507: return (int)(num + 1); IL_0513: return (int)(num + 3); IL_050d: return (int)(num + 2); IL_0504: return (int)num; } return (int)(num + 7); } public static int LastIndexOfAny(ref byte searchSpace, byte value0, byte value1, int length) { nuint num = (uint)length; nuint num2 = (uint)length; if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { num2 = UnalignedCountVectorFromEnd(ref searchSpace, length); } while (true) { if (num2 >= 8) { num2 -= 8; num -= 8; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num + 7); if (value0 == num3 || value1 == num3) { break; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 6); if (value0 != num3 && value1 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 5); if (value0 != num3 && value1 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 4); if (value0 != num3 && value1 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 3); if (value0 != num3 && value1 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 2); if (value0 != num3 && value1 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 1); if (value0 != num3 && value1 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 != num3 && value1 != num3) { continue; } goto IL_027c; } goto IL_027f; } goto IL_0285; } goto IL_028b; } return (int)(num + 4); } return (int)(num + 5); } return (int)(num + 6); } if (num2 >= 4) { num2 -= 4; num -= 4; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num + 3); if (value0 == num3 || value1 == num3) { goto IL_028b; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 2); if (value0 == num3 || value1 == num3) { goto IL_0285; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 1); if (value0 == num3 || value1 == num3) { goto IL_027f; } num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 == num3 || value1 == num3) { goto IL_027c; } } while (num2 != 0) { num2--; num--; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 != num3 && value1 != num3) { continue; } goto IL_027c; } if (Vector.IsHardwareAccelerated && num != 0) { num2 = num & (nuint)(~(Vector.Count - 1)); Vector right = new Vector(value0); Vector right2 = new Vector(value1); while (num2 > (nuint)(Vector.Count - 1)) { Vector left = LoadVector(ref searchSpace, num - (nuint)Vector.Count); Vector vector = Vector.BitwiseOr(Vector.Equals(left, right), Vector.Equals(left, right2)); if (Vector.Zero.Equals(vector)) { num -= (nuint)Vector.Count; num2 -= (nuint)Vector.Count; continue; } return (int)num - Vector.Count + LocateLastFoundByte(vector); } if (num != 0) { num2 = num; continue; } } return -1; IL_027c: return (int)num; IL_028b: return (int)(num + 3); IL_027f: return (int)(num + 1); IL_0285: return (int)(num + 2); } return (int)(num + 7); } public static int LastIndexOfAny(ref byte searchSpace, byte value0, byte value1, byte value2, int length) { nuint num = (uint)length; nuint num2 = (uint)length; if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { num2 = UnalignedCountVectorFromEnd(ref searchSpace, length); } while (true) { if (num2 >= 8) { num2 -= 8; num -= 8; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num + 7); if (value0 == num3 || value1 == num3 || value2 == num3) { break; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 6); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 5); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 4); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 3); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 2); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num + 1); if (value0 != num3 && value1 != num3 && value2 != num3) { num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 != num3 && value1 != num3 && value2 != num3) { continue; } goto IL_0310; } goto IL_0313; } goto IL_0319; } goto IL_031f; } return (int)(num + 4); } return (int)(num + 5); } return (int)(num + 6); } if (num2 >= 4) { num2 -= 4; num -= 4; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num + 3); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_031f; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 2); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_0319; } num3 = Unsafe.AddByteOffset(ref searchSpace, num + 1); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_0313; } num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 == num3 || value1 == num3 || value2 == num3) { goto IL_0310; } } while (num2 != 0) { num2--; num--; uint num3 = Unsafe.AddByteOffset(ref searchSpace, num); if (value0 != num3 && value1 != num3 && value2 != num3) { continue; } goto IL_0310; } if (Vector.IsHardwareAccelerated && num != 0) { num2 = num & (nuint)(~(Vector.Count - 1)); Vector right = new Vector(value0); Vector right2 = new Vector(value1); Vector right3 = new Vector(value2); while (num2 > (nuint)(Vector.Count - 1)) { Vector left = LoadVector(ref searchSpace, num - (nuint)Vector.Count); Vector vector = Vector.BitwiseOr(Vector.BitwiseOr(Vector.Equals(left, right), Vector.Equals(left, right2)), Vector.Equals(left, right3)); if (Vector.Zero.Equals(vector)) { num -= (nuint)Vector.Count; num2 -= (nuint)Vector.Count; continue; } return (int)num - Vector.Count + LocateLastFoundByte(vector); } if (num != 0) { num2 = num; continue; } } return -1; IL_0310: return (int)num; IL_031f: return (int)(num + 3); IL_0319: return (int)(num + 2); IL_0313: return (int)(num + 1); } return (int)(num + 7); } public unsafe static bool SequenceEqual(ref byte first, ref byte second, nuint length) { if (length < (nuint)sizeof(UIntPtr)) { uint num = 0u; nuint num2 = length & 2; if (num2 != 0) { num = LoadUShort(ref first); num -= LoadUShort(ref second); } if ((length & 1) != 0) { num |= (uint)(Unsafe.AddByteOffset(ref first, num2) - Unsafe.AddByteOffset(ref second, num2)); } return num == 0; } if (Unsafe.AreSame(ref first, ref second)) { goto IL_0052; } nuint num4; nuint num6; nuint num8; Vector256 value; Vector128 value2; if (Sse2.IsSupported) { if (Avx2.IsSupported && length >= (nuint)Vector256.Count) { nuint num3 = 0u; num4 = length - (nuint)Vector256.Count; if (num4 == 0) { goto IL_00b3; } while (true) { value = Avx2.CompareEqual(LoadVector256(ref first, num3), LoadVector256(ref second, num3)); if (Avx2.MoveMask(value) != -1) { break; } num3 += (nuint)Vector256.Count; if (num4 > num3) { continue; } goto IL_00b3; } } else { if (length < 16) { goto IL_01bd; } nuint num5 = 0u; num6 = length - 16; if (num6 == 0) { goto IL_0128; } while (true) { value2 = Sse2.CompareEqual(LoadVector128(ref first, num5), LoadVector128(ref second, num5)); if (Sse2.MoveMask(value2) != 65535) { break; } num5 += 16; if (num6 > num5) { continue; } goto IL_0128; } } } else { if (!Vector.IsHardwareAccelerated || length < (nuint)Vector.Count) { goto IL_01bd; } nuint num7 = 0u; num8 = length - (nuint)Vector.Count; if (num8 == 0) { goto IL_01a1; } while (!(LoadVector(ref first, num7) != LoadVector(ref second, num7))) { num7 += (nuint)Vector.Count; if (num8 > num7) { continue; } goto IL_01a1; } } goto IL_020e; IL_01a1: if (LoadVector(ref first, num8) == LoadVector(ref second, num8)) { goto IL_0052; } goto IL_020e; IL_01f6: nuint num9; return LoadNUInt(ref first, num9) == LoadNUInt(ref second, num9); IL_01bd: nuint num10 = 0u; num9 = length - (nuint)sizeof(UIntPtr); if (num9 == 0) { goto IL_01f6; } while (LoadNUInt(ref first, num10) == LoadNUInt(ref second, num10)) { num10 += (nuint)sizeof(UIntPtr); if (num9 > num10) { continue; } goto IL_01f6; } goto IL_020e; IL_00b3: value = Avx2.CompareEqual(LoadVector256(ref first, num4), LoadVector256(ref second, num4)); if (Avx2.MoveMask(value) == -1) { goto IL_0052; } goto IL_020e; IL_0052: return true; IL_0128: value2 = Sse2.CompareEqual(LoadVector128(ref first, num6), LoadVector128(ref second, num6)); if (Sse2.MoveMask(value2) == 65535) { goto IL_0052; } goto IL_020e; IL_020e: return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateFirstFoundByte(Vector match) { Vector vector = Vector.AsVectorUInt64(match); ulong num = 0uL; int i; for (i = 0; i < Vector.Count; i++) { num = vector[i]; if (num != 0L) { break; } } return i * 8 + LocateFirstFoundByte(num); } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public unsafe static int SequenceCompareTo(ref byte first, int firstLength, ref byte second, int secondLength) { nuint num; uint num6; nuint num3; nuint num2; if (!Unsafe.AreSame(ref first, ref second)) { num = (uint)(((uint)firstLength < (uint)secondLength) ? firstLength : secondLength); num2 = 0u; num3 = num; if (!Avx2.IsSupported) { if (Sse2.IsSupported) { if (num3 >= (nuint)Vector128.Count) { num3 -= (nuint)Vector128.Count; while (true) { uint num4; if (num3 > num2) { num4 = (uint)Sse2.MoveMask(Sse2.CompareEqual(LoadVector128(ref first, num2), LoadVector128(ref second, num2))); if (num4 == 65535) { num2 += (nuint)Vector128.Count; continue; } } else { num2 = num3; num4 = (uint)Sse2.MoveMask(Sse2.CompareEqual(LoadVector128(ref first, num2), LoadVector128(ref second, num2))); if (num4 == 65535) { break; } } uint value = ~num4; num2 += (uint)BitOperations.TrailingZeroCount(value); return Unsafe.AddByteOffset(ref first, num2).CompareTo(Unsafe.AddByteOffset(ref second, num2)); } goto IL_0277; } } else if (Vector.IsHardwareAccelerated && num3 > (nuint)Vector.Count) { for (num3 -= (nuint)Vector.Count; num3 > num2 && !(LoadVector(ref first, num2) != LoadVector(ref second, num2)); num2 += (nuint)Vector.Count) { } goto IL_0273; } goto IL_021b; } if (num3 >= (nuint)Vector256.Count) { num3 -= (nuint)Vector256.Count; while (true) { uint num5; if (num3 > num2) { num5 = (uint)Avx2.MoveMask(Avx2.CompareEqual(LoadVector256(ref first, num2), LoadVector256(ref second, num2))); if (num5 == uint.MaxValue) { num2 += (nuint)Vector256.Count; continue; } } else { num2 = num3; num5 = (uint)Avx2.MoveMask(Avx2.CompareEqual(LoadVector256(ref first, num2), LoadVector256(ref second, num2))); if (num5 == uint.MaxValue) { break; } } uint value2 = ~num5; num2 += (uint)BitOperations.TrailingZeroCount(value2); return Unsafe.AddByteOffset(ref first, num2).CompareTo(Unsafe.AddByteOffset(ref second, num2)); } } else { if (num3 < (nuint)Vector128.Count) { goto IL_021b; } num3 -= (nuint)Vector128.Count; if (num3 > num2) { num6 = (uint)Sse2.MoveMask(Sse2.CompareEqual(LoadVector128(ref first, num2), LoadVector128(ref second, num2))); if (num6 != 65535) { goto IL_0111; } } num2 = num3; num6 = (uint)Sse2.MoveMask(Sse2.CompareEqual(LoadVector128(ref first, num2), LoadVector128(ref second, num2))); if (num6 != 65535) { goto IL_0111; } } } goto IL_0277; IL_021b: if (num3 > (nuint)sizeof(UIntPtr)) { for (num3 -= (nuint)sizeof(UIntPtr); num3 > num2 && LoadNUInt(ref first, num2) == LoadNUInt(ref second, num2); num2 += (nuint)sizeof(UIntPtr)) { } } goto IL_0273; IL_0111: uint value3 = ~num6; num2 += (uint)BitOperations.TrailingZeroCount(value3); return Unsafe.AddByteOffset(ref first, num2).CompareTo(Unsafe.AddByteOffset(ref second, num2)); IL_0273: for (; num > num2; num2++) { int num7 = Unsafe.AddByteOffset(ref first, num2).CompareTo(Unsafe.AddByteOffset(ref second, num2)); if (num7 != 0) { return num7; } } goto IL_0277; IL_0277: return firstLength - secondLength; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateLastFoundByte(Vector match) { Vector vector = Vector.AsVectorUInt64(match); ulong num = 0uL; int num2 = Vector.Count - 1; for (int i = 0; i < Vector.Count; i++) { num = vector[num2]; if (num != 0L) { break; } num2--; } return num2 * 8 + LocateLastFoundByte(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateFirstFoundByte(ulong match) { return BitOperations.TrailingZeroCount(match) >> 3; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateLastFoundByte(ulong match) { return BitOperations.Log2(match) >> 3; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ushort LoadUShort(ref byte start) { return Unsafe.ReadUnaligned(ref start); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static nuint LoadNUInt(ref byte start, nuint offset) { return Unsafe.ReadUnaligned(ref Unsafe.AddByteOffset(ref start, offset)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector LoadVector(ref byte start, nuint offset) { return Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref start, offset)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector128 LoadVector128(ref byte start, nuint offset) { return Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref start, offset)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector256 LoadVector256(ref byte start, nuint offset) { return Unsafe.ReadUnaligned>(ref Unsafe.AddByteOffset(ref start, offset)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static nuint GetByteVectorSpanLength(nuint offset, int length) { return (uint)((length - (int)offset) & ~(Vector.Count - 1)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static nuint GetByteVector128SpanLength(nuint offset, int length) { return (uint)((length - (int)offset) & ~(Vector128.Count - 1)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static nuint GetByteVector256SpanLength(nuint offset, int length) { return (uint)((length - (int)offset) & ~(Vector256.Count - 1)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static nuint UnalignedCountVector(ref byte searchSpace) { nint num = (nint)Unsafe.AsPointer(ref searchSpace) & (nint)(Vector.Count - 1); return (nuint)((Vector.Count - num) & (Vector.Count - 1)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static nuint UnalignedCountVector128(ref byte searchSpace) { nint num = (nint)Unsafe.AsPointer(ref searchSpace) & (nint)(Vector128.Count - 1); return (uint)((Vector128.Count - num) & (Vector128.Count - 1)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static nuint UnalignedCountVectorFromEnd(ref byte searchSpace, int length) { nint num = (nint)Unsafe.AsPointer(ref searchSpace) & (nint)(Vector.Count - 1); return (uint)(((length & (Vector.Count - 1)) + num) & (Vector.Count - 1)); } public static int IndexOf(ref char searchSpace, int searchSpaceLength, ref char value, int valueLength) { if (valueLength == 0) { return 0; } char value2 = value; ref char source = ref Unsafe.Add(ref value, 1); int num = valueLength - 1; int num2 = searchSpaceLength - num; int num3 = 0; while (num2 > 0) { int num4 = IndexOf(ref Unsafe.Add(ref searchSpace, num3), value2, num2); if (num4 == -1) { break; } num2 -= num4; num3 += num4; if (num2 <= 0) { break; } if (SequenceEqual(ref Unsafe.As(ref Unsafe.Add(ref searchSpace, num3 + 1)), ref Unsafe.As(ref source), (nuint)(uint)num * (nuint)2u)) { return num3; } num2--; num3++; } return -1; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public unsafe static int SequenceCompareTo(ref char first, int firstLength, ref char second, int secondLength) { int result = firstLength - secondLength; if (!Unsafe.AreSame(ref first, ref second)) { nuint num = (uint)(((uint)firstLength < (uint)secondLength) ? firstLength : secondLength); nuint num2 = 0u; if (num >= (nuint)(sizeof(UIntPtr) / 2)) { if (Vector.IsHardwareAccelerated && num >= (nuint)Vector.Count) { nuint num3 = num - (nuint)Vector.Count; while (!(Unsafe.ReadUnaligned>(ref Unsafe.As(ref Unsafe.Add(ref first, (nint)num2))) != Unsafe.ReadUnaligned>(ref Unsafe.As(ref Unsafe.Add(ref second, (nint)num2))))) { num2 += (nuint)Vector.Count; if (num3 < num2) { break; } } } for (; num >= (nuint)((nint)num2 + (nint)(sizeof(UIntPtr) / 2)) && Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.Add(ref first, (nint)num2))) == Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.Add(ref second, (nint)num2))); num2 += (nuint)(sizeof(UIntPtr) / 2)) { } } for (; num2 < num; num2++) { int num4 = Unsafe.Add(ref first, (nint)num2).CompareTo(Unsafe.Add(ref second, (nint)num2)); if (num4 != 0) { return num4; } } } return result; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public unsafe static bool Contains(ref char searchSpace, char value, int length) { fixed (char* ptr = &searchSpace) { char* ptr2 = ptr; char* ptr3 = ptr2 + length; if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { int num = ((int)ptr2 & (Unsafe.SizeOf>() - 1)) / 2; length = (Vector.Count - num) & (Vector.Count - 1); } while (true) { if (length >= 4) { length -= 4; if (value == *ptr2 || value == ptr2[1] || value == ptr2[2] || value == ptr2[3]) { break; } ptr2 += 4; continue; } while (length > 0) { length--; if (value == *ptr2) { goto end_IL_0079; } ptr2++; } if (Vector.IsHardwareAccelerated && ptr2 < ptr3) { length = (int)((ptr3 - ptr2) & ~(Vector.Count - 1)); Vector left = new Vector(value); while (length > 0) { Vector other = Vector.Equals(left, Unsafe.Read>(ptr2)); if (!Vector.Zero.Equals(other)) { goto end_IL_0079; } ptr2 += Vector.Count; length -= Vector.Count; } if (ptr2 < ptr3) { length = (int)(ptr3 - ptr2); continue; } } return false; continue; end_IL_0079: break; } return true; } } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public unsafe static int IndexOf(ref char searchSpace, char value, int length) { nint num = 0; nint num2 = length; if (((int)Unsafe.AsPointer(ref searchSpace) & 1) == 0) { if (Sse2.IsSupported || AdvSimd.Arm64.IsSupported) { if (length >= Vector128.Count * 2) { num2 = UnalignedCountVector128(ref searchSpace); } } else if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { num2 = UnalignedCountVector(ref searchSpace); } } while (true) { if (num2 >= 4) { ref char reference = ref Unsafe.Add(ref searchSpace, num); if (value == reference) { break; } if (value != Unsafe.Add(ref reference, 1)) { if (value != Unsafe.Add(ref reference, 2)) { if (value != Unsafe.Add(ref reference, 3)) { num += 4; num2 -= 4; continue; } return (int)(num + 3); } return (int)(num + 2); } return (int)(num + 1); } while (num2 > 0) { if (value == Unsafe.Add(ref searchSpace, num)) { goto end_IL_0090; } num++; num2--; } if (Avx2.IsSupported) { if (num < length) { if (((nuint)Unsafe.AsPointer(ref Unsafe.Add(ref searchSpace, num)) & (nuint)(Vector256.Count - 1)) != 0) { Vector128 left = Vector128.Create(value); Vector128 right = LoadVector128(ref searchSpace, num); int num3 = Sse2.MoveMask(Sse2.CompareEqual(left, right).AsByte()); if (num3 != 0) { return (int)(num + (uint)BitOperations.TrailingZeroCount(num3) / 2u); } num += Vector128.Count; } num2 = GetCharVector256SpanLength(num, length); if (num2 > 0) { Vector256 left2 = Vector256.Create(value); do { Vector256 right2 = LoadVector256(ref searchSpace, num); int num4 = Avx2.MoveMask(Avx2.CompareEqual(left2, right2).AsByte()); if (num4 == 0) { num += Vector256.Count; num2 -= Vector256.Count; continue; } return (int)(num + (uint)BitOperations.TrailingZeroCount(num4) / 2u); } while (num2 > 0); } num2 = GetCharVector128SpanLength(num, length); if (num2 > 0) { Vector128 left3 = Vector128.Create(value); Vector128 right3 = LoadVector128(ref searchSpace, num); int num5 = Sse2.MoveMask(Sse2.CompareEqual(left3, right3).AsByte()); if (num5 != 0) { return (int)(num + (uint)BitOperations.TrailingZeroCount(num5) / 2u); } num += Vector128.Count; } if (num < length) { num2 = length - num; continue; } } } else if (Sse2.IsSupported) { if (num < length) { num2 = GetCharVector128SpanLength(num, length); if (num2 > 0) { Vector128 left4 = Vector128.Create(value); do { Vector128 right4 = LoadVector128(ref searchSpace, num); int num6 = Sse2.MoveMask(Sse2.CompareEqual(left4, right4).AsByte()); if (num6 == 0) { num += Vector128.Count; num2 -= Vector128.Count; continue; } return (int)(num + (uint)BitOperations.TrailingZeroCount(num6) / 2u); } while (num2 > 0); } if (num < length) { num2 = length - num; continue; } } } else { if (AdvSimd.Arm64.IsSupported) { } if (Vector.IsHardwareAccelerated && num < length) { num2 = GetCharVectorSpanLength(num, length); if (num2 > 0) { Vector left5 = new Vector(value); do { Vector vector = Vector.Equals(left5, LoadVector(ref searchSpace, num)); if (Vector.Zero.Equals(vector)) { num += Vector.Count; num2 -= Vector.Count; continue; } return (int)(num + LocateFirstFoundChar(vector)); } while (num2 > 0); } if (num < length) { num2 = length - num; continue; } } } return -1; continue; end_IL_0090: break; } return (int)num; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public static int IndexOfAny(ref char searchStart, char value0, char value1, int length) { nuint num = 0u; nuint num2 = (uint)length; int num4; if (Sse2.IsSupported) { nint num3 = (nint)length - (nint)Vector128.Count; if (num3 >= 0) { num2 = (nuint)num3; if (Sse2.IsSupported) { if (Avx2.IsSupported && num2 >= (nuint)Vector128.Count) { Vector256 left = Vector256.Create(value0); Vector256 left2 = Vector256.Create(value1); num2 -= (nuint)Vector128.Count; Vector256 right; while (num2 > num) { right = LoadVector256(ref searchStart, num); num4 = Avx2.MoveMask(Avx2.Or(Avx2.CompareEqual(left, right), Avx2.CompareEqual(left2, right)).AsByte()); if (num4 == 0) { num += (nuint)Vector256.Count; continue; } goto IL_0211; } right = LoadVector256(ref searchStart, num2); num = num2; num4 = Avx2.MoveMask(Avx2.Or(Avx2.CompareEqual(left, right), Avx2.CompareEqual(left2, right)).AsByte()); if (num4 == 0) { goto IL_00c1; } } else { Vector128 left3 = Vector128.Create(value0); Vector128 left4 = Vector128.Create(value1); Vector128 right2; while (num2 > num) { right2 = LoadVector128(ref searchStart, num); num4 = Sse2.MoveMask(Sse2.Or(Sse2.CompareEqual(left3, right2), Sse2.CompareEqual(left4, right2)).AsByte()); if (num4 == 0) { num += (nuint)Vector128.Count; continue; } goto IL_0211; } right2 = LoadVector128(ref searchStart, num2); num = num2; num4 = Sse2.MoveMask(Sse2.Or(Sse2.CompareEqual(left3, right2), Sse2.CompareEqual(left4, right2)).AsByte()); if (num4 == 0) { goto IL_00c1; } } goto IL_0211; } goto IL_0223; } } else if (Vector.IsHardwareAccelerated) { nint num5 = (nint)length - (nint)Vector.Count; if (num5 >= 0) { num2 = (nuint)num5; goto IL_0223; } } while (num2 >= 4) { ref char reference = ref Add(ref searchStart, num); int num6 = reference; if (value0 != num6 && value1 != num6) { num6 = Unsafe.Add(ref reference, 1); if (value0 != num6 && value1 != num6) { num6 = Unsafe.Add(ref reference, 2); if (value0 != num6 && value1 != num6) { num6 = Unsafe.Add(ref reference, 3); if (value0 != num6 && value1 != num6) { num += 4; num2 -= 4; continue; } return (int)(num + 3); } return (int)(num + 2); } return (int)(num + 1); } goto IL_00d5; } while (num2 != 0) { int num6 = Add(ref searchStart, num); if (value0 != num6 && value1 != num6) { num++; num2--; continue; } goto IL_00d5; } goto IL_00c1; IL_0211: num += (nuint)(uint)BitOperations.TrailingZeroCount(num4) >> 1; goto IL_00d5; IL_00c1: return -1; IL_02c3: Vector vector; num += (uint)LocateFirstFoundChar(vector); goto IL_00d5; IL_0223: if (!Sse2.IsSupported && Vector.IsHardwareAccelerated) { Vector right3 = new Vector(value0); Vector right4 = new Vector(value1); while (num2 > num) { vector = LoadVector(ref searchStart, num); vector = Vector.BitwiseOr(Vector.Equals(vector, right3), Vector.Equals(vector, right4)); if (Vector.Zero.Equals(vector)) { num += (nuint)Vector.Count; continue; } goto IL_02c3; } vector = LoadVector(ref searchStart, num2); num = num2; vector = Vector.BitwiseOr(Vector.Equals(vector, right3), Vector.Equals(vector, right4)); if (!Vector.Zero.Equals(vector)) { goto IL_02c3; } } goto IL_00c1; IL_00d5: return (int)num; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public static int IndexOfAny(ref char searchStart, char value0, char value1, char value2, int length) { nuint num = 0u; nuint num2 = (uint)length; int num4; if (Sse2.IsSupported) { nint num3 = (nint)length - (nint)Vector128.Count; if (num3 >= 0) { num2 = (nuint)num3; if (Sse2.IsSupported) { if (Avx2.IsSupported && num2 >= (nuint)Vector128.Count) { Vector256 left = Vector256.Create(value0); Vector256 left2 = Vector256.Create(value1); Vector256 left3 = Vector256.Create(value2); num2 -= (nuint)Vector128.Count; Vector256 right; while (num2 > num) { right = LoadVector256(ref searchStart, num); num4 = Avx2.MoveMask(Avx2.Or(Avx2.Or(Avx2.CompareEqual(left, right), Avx2.CompareEqual(left2, right)), Avx2.CompareEqual(left3, right)).AsByte()); if (num4 == 0) { num += (nuint)Vector256.Count; continue; } goto IL_027f; } right = LoadVector256(ref searchStart, num2); num = num2; num4 = Avx2.MoveMask(Avx2.Or(Avx2.Or(Avx2.CompareEqual(left, right), Avx2.CompareEqual(left2, right)), Avx2.CompareEqual(left3, right)).AsByte()); if (num4 == 0) { goto IL_00e7; } } else { Vector128 left4 = Vector128.Create(value0); Vector128 left5 = Vector128.Create(value1); Vector128 left6 = Vector128.Create(value2); Vector128 right2; while (num2 > num) { right2 = LoadVector128(ref searchStart, num); num4 = Sse2.MoveMask(Sse2.Or(Sse2.Or(Sse2.CompareEqual(left4, right2), Sse2.CompareEqual(left5, right2)), Sse2.CompareEqual(left6, right2)).AsByte()); if (num4 == 0) { num += (nuint)Vector128.Count; continue; } goto IL_027f; } right2 = LoadVector128(ref searchStart, num2); num = num2; num4 = Sse2.MoveMask(Sse2.Or(Sse2.Or(Sse2.CompareEqual(left4, right2), Sse2.CompareEqual(left5, right2)), Sse2.CompareEqual(left6, right2)).AsByte()); if (num4 == 0) { goto IL_00e7; } } goto IL_027f; } goto IL_0291; } } else if (Vector.IsHardwareAccelerated) { nint num5 = (nint)length - (nint)Vector.Count; if (num5 >= 0) { num2 = (nuint)num5; goto IL_0291; } } while (num2 >= 4) { ref char reference = ref Add(ref searchStart, num); int num6 = reference; if (value0 != num6 && value1 != num6 && value2 != num6) { num6 = Unsafe.Add(ref reference, 1); if (value0 != num6 && value1 != num6 && value2 != num6) { num6 = Unsafe.Add(ref reference, 2); if (value0 != num6 && value1 != num6 && value2 != num6) { num6 = Unsafe.Add(ref reference, 3); if (value0 != num6 && value1 != num6 && value2 != num6) { num += 4; num2 -= 4; continue; } return (int)(num + 3); } return (int)(num + 2); } return (int)(num + 1); } goto IL_00fb; } while (num2 != 0) { int num6 = Add(ref searchStart, num); if (value0 != num6 && value1 != num6 && value2 != num6) { num++; num2--; continue; } goto IL_00fb; } goto IL_00e7; IL_027f: num += (nuint)(uint)BitOperations.TrailingZeroCount(num4) >> 1; goto IL_00fb; IL_00e7: return -1; IL_0355: Vector vector; num += (uint)LocateFirstFoundChar(vector); goto IL_00fb; IL_0291: if (!Sse2.IsSupported && Vector.IsHardwareAccelerated) { Vector right3 = new Vector(value0); Vector right4 = new Vector(value1); Vector right5 = new Vector(value2); while (num2 > num) { vector = LoadVector(ref searchStart, num); vector = Vector.BitwiseOr(Vector.BitwiseOr(Vector.Equals(vector, right3), Vector.Equals(vector, right4)), Vector.Equals(vector, right5)); if (Vector.Zero.Equals(vector)) { num += (nuint)Vector.Count; continue; } goto IL_0355; } vector = LoadVector(ref searchStart, num2); num = num2; vector = Vector.BitwiseOr(Vector.BitwiseOr(Vector.Equals(vector, right3), Vector.Equals(vector, right4)), Vector.Equals(vector, right5)); if (!Vector.Zero.Equals(vector)) { goto IL_0355; } } goto IL_00e7; IL_00fb: return (int)num; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public static int IndexOfAny(ref char searchStart, char value0, char value1, char value2, char value3, int length) { nuint num = 0u; nuint num2 = (uint)length; int num4; if (Sse2.IsSupported) { nint num3 = (nint)length - (nint)Vector128.Count; if (num3 >= 0) { num2 = (nuint)num3; if (Sse2.IsSupported) { if (Avx2.IsSupported && num2 >= (nuint)Vector128.Count) { Vector256 left = Vector256.Create(value0); Vector256 left2 = Vector256.Create(value1); Vector256 left3 = Vector256.Create(value2); Vector256 left4 = Vector256.Create(value3); num2 -= (nuint)Vector128.Count; Vector256 right; while (num2 > num) { right = LoadVector256(ref searchStart, num); num4 = Avx2.MoveMask(Avx2.CompareEqual(left, right).AsByte()); num4 |= Avx2.MoveMask(Avx2.CompareEqual(left2, right).AsByte()); num4 |= Avx2.MoveMask(Avx2.CompareEqual(left3, right).AsByte()); num4 |= Avx2.MoveMask(Avx2.CompareEqual(left4, right).AsByte()); if (num4 == 0) { num += (nuint)Vector256.Count; continue; } goto IL_036f; } right = LoadVector256(ref searchStart, num2); num = num2; num4 = Avx2.MoveMask(Avx2.CompareEqual(left, right).AsByte()); num4 |= Avx2.MoveMask(Avx2.CompareEqual(left2, right).AsByte()); num4 |= Avx2.MoveMask(Avx2.CompareEqual(left3, right).AsByte()); num4 |= Avx2.MoveMask(Avx2.CompareEqual(left4, right).AsByte()); if (num4 == 0) { goto IL_0115; } } else { Vector128 left5 = Vector128.Create(value0); Vector128 left6 = Vector128.Create(value1); Vector128 left7 = Vector128.Create(value2); Vector128 left8 = Vector128.Create(value3); Vector128 right2; while (num2 > num) { right2 = LoadVector128(ref searchStart, num); num4 = Sse2.MoveMask(Sse2.CompareEqual(left5, right2).AsByte()); num4 |= Sse2.MoveMask(Sse2.CompareEqual(left6, right2).AsByte()); num4 |= Sse2.MoveMask(Sse2.CompareEqual(left7, right2).AsByte()); num4 |= Sse2.MoveMask(Sse2.CompareEqual(left8, right2).AsByte()); if (num4 == 0) { num += (nuint)Vector128.Count; continue; } goto IL_036f; } right2 = LoadVector128(ref searchStart, num2); num = num2; num4 = Sse2.MoveMask(Sse2.CompareEqual(left5, right2).AsByte()); num4 |= Sse2.MoveMask(Sse2.CompareEqual(left6, right2).AsByte()); num4 |= Sse2.MoveMask(Sse2.CompareEqual(left7, right2).AsByte()); num4 |= Sse2.MoveMask(Sse2.CompareEqual(left8, right2).AsByte()); if (num4 == 0) { goto IL_0115; } } goto IL_036f; } goto IL_0381; } } else if (Vector.IsHardwareAccelerated) { nint num5 = (nint)length - (nint)Vector.Count; if (num5 >= 0) { num2 = (nuint)num5; goto IL_0381; } } while (num2 >= 4) { ref char reference = ref Add(ref searchStart, num); int num6 = reference; if (value0 != num6 && value1 != num6 && value2 != num6 && value3 != num6) { num6 = Unsafe.Add(ref reference, 1); if (value0 != num6 && value1 != num6 && value2 != num6 && value3 != num6) { num6 = Unsafe.Add(ref reference, 2); if (value0 != num6 && value1 != num6 && value2 != num6 && value3 != num6) { num6 = Unsafe.Add(ref reference, 3); if (value0 != num6 && value1 != num6 && value2 != num6 && value3 != num6) { num += 4; num2 -= 4; continue; } return (int)(num + 3); } return (int)(num + 2); } return (int)(num + 1); } goto IL_0129; } while (num2 != 0) { int num6 = Add(ref searchStart, num); if (value0 != num6 && value1 != num6 && value2 != num6 && value3 != num6) { num++; num2--; continue; } goto IL_0129; } goto IL_0115; IL_036f: num += (nuint)(uint)BitOperations.TrailingZeroCount(num4) >> 1; goto IL_0129; IL_0115: return -1; IL_046a: Vector vector; num += (uint)LocateFirstFoundChar(vector); goto IL_0129; IL_0381: if (!Sse2.IsSupported && Vector.IsHardwareAccelerated) { Vector right3 = new Vector(value0); Vector right4 = new Vector(value1); Vector right5 = new Vector(value2); Vector right6 = new Vector(value3); while (num2 > num) { vector = LoadVector(ref searchStart, num); vector = Vector.BitwiseOr(Vector.BitwiseOr(Vector.BitwiseOr(Vector.Equals(vector, right3), Vector.Equals(vector, right4)), Vector.Equals(vector, right5)), Vector.Equals(vector, right6)); if (Vector.Zero.Equals(vector)) { num += (nuint)Vector.Count; continue; } goto IL_046a; } vector = LoadVector(ref searchStart, num2); num = num2; vector = Vector.BitwiseOr(Vector.BitwiseOr(Vector.BitwiseOr(Vector.Equals(vector, right3), Vector.Equals(vector, right4)), Vector.Equals(vector, right5)), Vector.Equals(vector, right6)); if (!Vector.Zero.Equals(vector)) { goto IL_046a; } } goto IL_0115; IL_0129: return (int)num; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public static int IndexOfAny(ref char searchStart, char value0, char value1, char value2, char value3, char value4, int length) { nuint num = 0u; nuint num2 = (uint)length; int num4; if (Sse2.IsSupported) { nint num3 = (nint)length - (nint)Vector128.Count; if (num3 >= 0) { num2 = (nuint)num3; if (Sse2.IsSupported) { if (Avx2.IsSupported && num2 >= (nuint)Vector128.Count) { Vector256 left = Vector256.Create(value0); Vector256 left2 = Vector256.Create(value1); Vector256 left3 = Vector256.Create(value2); Vector256 left4 = Vector256.Create(value3); Vector256 left5 = Vector256.Create(value4); num2 -= (nuint)Vector128.Count; Vector256 right; while (num2 > num) { right = LoadVector256(ref searchStart, num); num4 = Avx2.MoveMask(Avx2.CompareEqual(left, right).AsByte()); num4 |= Avx2.MoveMask(Avx2.CompareEqual(left2, right).AsByte()); num4 |= Avx2.MoveMask(Avx2.CompareEqual(left3, right).AsByte()); num4 |= Avx2.MoveMask(Avx2.CompareEqual(left4, right).AsByte()); num4 |= Avx2.MoveMask(Avx2.CompareEqual(left5, right).AsByte()); if (num4 == 0) { num += (nuint)Vector256.Count; continue; } goto IL_040f; } right = LoadVector256(ref searchStart, num2); num = num2; num4 = Avx2.MoveMask(Avx2.CompareEqual(left, right).AsByte()); num4 |= Avx2.MoveMask(Avx2.CompareEqual(left2, right).AsByte()); num4 |= Avx2.MoveMask(Avx2.CompareEqual(left3, right).AsByte()); num4 |= Avx2.MoveMask(Avx2.CompareEqual(left4, right).AsByte()); num4 |= Avx2.MoveMask(Avx2.CompareEqual(left5, right).AsByte()); if (num4 == 0) { goto IL_0134; } } else { Vector128 left6 = Vector128.Create(value0); Vector128 left7 = Vector128.Create(value1); Vector128 left8 = Vector128.Create(value2); Vector128 left9 = Vector128.Create(value3); Vector128 left10 = Vector128.Create(value4); Vector128 right2; while (num2 > num) { right2 = LoadVector128(ref searchStart, num); num4 = Sse2.MoveMask(Sse2.CompareEqual(left6, right2).AsByte()); num4 |= Sse2.MoveMask(Sse2.CompareEqual(left7, right2).AsByte()); num4 |= Sse2.MoveMask(Sse2.CompareEqual(left8, right2).AsByte()); num4 |= Sse2.MoveMask(Sse2.CompareEqual(left9, right2).AsByte()); num4 |= Sse2.MoveMask(Sse2.CompareEqual(left10, right2).AsByte()); if (num4 == 0) { num += (nuint)Vector128.Count; continue; } goto IL_040f; } right2 = LoadVector128(ref searchStart, num2); num = num2; num4 = Sse2.MoveMask(Sse2.CompareEqual(left6, right2).AsByte()); num4 |= Sse2.MoveMask(Sse2.CompareEqual(left7, right2).AsByte()); num4 |= Sse2.MoveMask(Sse2.CompareEqual(left8, right2).AsByte()); num4 |= Sse2.MoveMask(Sse2.CompareEqual(left9, right2).AsByte()); num4 |= Sse2.MoveMask(Sse2.CompareEqual(left10, right2).AsByte()); if (num4 == 0) { goto IL_0134; } } goto IL_040f; } goto IL_0421; } } else if (Vector.IsHardwareAccelerated) { nint num5 = (nint)length - (nint)Vector.Count; if (num5 >= 0) { num2 = (nuint)num5; goto IL_0421; } } while (num2 >= 4) { ref char reference = ref Add(ref searchStart, num); int num6 = reference; if (value0 != num6 && value1 != num6 && value2 != num6 && value3 != num6 && value4 != num6) { num6 = Unsafe.Add(ref reference, 1); if (value0 != num6 && value1 != num6 && value2 != num6 && value3 != num6 && value4 != num6) { num6 = Unsafe.Add(ref reference, 2); if (value0 != num6 && value1 != num6 && value2 != num6 && value3 != num6 && value4 != num6) { num6 = Unsafe.Add(ref reference, 3); if (value0 != num6 && value1 != num6 && value2 != num6 && value3 != num6 && value4 != num6) { num += 4; num2 -= 4; continue; } return (int)(num + 3); } return (int)(num + 2); } return (int)(num + 1); } goto IL_0148; } while (num2 != 0) { int num6 = Add(ref searchStart, num); if (value0 != num6 && value1 != num6 && value2 != num6 && value3 != num6 && value4 != num6) { num++; num2--; continue; } goto IL_0148; } goto IL_0134; IL_040f: num += (nuint)(uint)BitOperations.TrailingZeroCount(num4) >> 1; goto IL_0148; IL_0134: return -1; IL_052f: Vector vector; num += (uint)LocateFirstFoundChar(vector); goto IL_0148; IL_0421: if (!Sse2.IsSupported && Vector.IsHardwareAccelerated) { Vector right3 = new Vector(value0); Vector right4 = new Vector(value1); Vector right5 = new Vector(value2); Vector right6 = new Vector(value3); Vector right7 = new Vector(value4); while (num2 > num) { vector = LoadVector(ref searchStart, num); vector = Vector.BitwiseOr(Vector.BitwiseOr(Vector.BitwiseOr(Vector.BitwiseOr(Vector.Equals(vector, right3), Vector.Equals(vector, right4)), Vector.Equals(vector, right5)), Vector.Equals(vector, right6)), Vector.Equals(vector, right7)); if (Vector.Zero.Equals(vector)) { num += (nuint)Vector.Count; continue; } goto IL_052f; } vector = LoadVector(ref searchStart, num2); num = num2; vector = Vector.BitwiseOr(Vector.BitwiseOr(Vector.BitwiseOr(Vector.BitwiseOr(Vector.Equals(vector, right3), Vector.Equals(vector, right4)), Vector.Equals(vector, right5)), Vector.Equals(vector, right6)), Vector.Equals(vector, right7)); if (!Vector.Zero.Equals(vector)) { goto IL_052f; } } goto IL_0134; IL_0148: return (int)num; } [MethodImpl(MethodImplOptions.AggressiveOptimization)] public unsafe static int LastIndexOf(ref char searchSpace, char value, int length) { fixed (char* ptr = &searchSpace) { char* ptr2 = ptr + length; char* ptr3 = ptr; if (Vector.IsHardwareAccelerated && length >= Vector.Count * 2) { length = ((int)ptr2 & (Unsafe.SizeOf>() - 1)) / 2; } while (true) { if (length >= 4) { length -= 4; ptr2 -= 4; if (ptr2[3] == value) { break; } if (ptr2[2] != value) { if (ptr2[1] != value) { if (*ptr2 != value) { continue; } goto IL_011d; } return (int)(ptr2 - ptr3) + 1; } return (int)(ptr2 - ptr3) + 2; } while (length > 0) { length--; ptr2--; if (*ptr2 != value) { continue; } goto IL_011d; } if (Vector.IsHardwareAccelerated && ptr2 > ptr3) { length = (int)((ptr2 - ptr3) & ~(Vector.Count - 1)); Vector left = new Vector(value); while (length > 0) { char* ptr4 = ptr2 - Vector.Count; Vector vector = Vector.Equals(left, Unsafe.Read>(ptr4)); if (Vector.Zero.Equals(vector)) { ptr2 -= Vector.Count; length -= Vector.Count; continue; } return (int)(ptr4 - ptr3) + LocateLastFoundChar(vector); } if (ptr2 > ptr3) { length = (int)(ptr2 - ptr3); continue; } } return -1; IL_011d: return (int)(ptr2 - ptr3); } return (int)(ptr2 - ptr3) + 3; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateFirstFoundChar(Vector match) { Vector vector = Vector.AsVectorUInt64(match); ulong num = 0uL; int i; for (i = 0; i < Vector.Count; i++) { num = vector[i]; if (num != 0L) { break; } } return i * 4 + LocateFirstFoundChar(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateFirstFoundChar(ulong match) { return BitOperations.TrailingZeroCount(match) >> 4; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateLastFoundChar(Vector match) { Vector vector = Vector.AsVectorUInt64(match); ulong num = 0uL; int num2 = Vector.Count - 1; for (int i = 0; i < Vector.Count; i++) { num = vector[num2]; if (num != 0L) { break; } num2--; } return num2 * 4 + LocateLastFoundChar(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int LocateLastFoundChar(ulong match) { return BitOperations.Log2(match) >> 4; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector LoadVector(ref char start, nint offset) { return Unsafe.ReadUnaligned>(ref Unsafe.As(ref Unsafe.Add(ref start, offset))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector LoadVector(ref char start, nuint offset) { return Unsafe.ReadUnaligned>(ref Unsafe.As(ref Unsafe.Add(ref start, (nint)offset))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector128 LoadVector128(ref char start, nint offset) { return Unsafe.ReadUnaligned>(ref Unsafe.As(ref Unsafe.Add(ref start, offset))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector128 LoadVector128(ref char start, nuint offset) { return Unsafe.ReadUnaligned>(ref Unsafe.As(ref Unsafe.Add(ref start, (nint)offset))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector256 LoadVector256(ref char start, nint offset) { return Unsafe.ReadUnaligned>(ref Unsafe.As(ref Unsafe.Add(ref start, offset))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector256 LoadVector256(ref char start, nuint offset) { return Unsafe.ReadUnaligned>(ref Unsafe.As(ref Unsafe.Add(ref start, (nint)offset))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ref char Add(ref char start, nuint offset) { return ref Unsafe.Add(ref start, (nint)offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static nint GetCharVectorSpanLength(nint offset, nint length) { return (length - offset) & ~(Vector.Count - 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static nint GetCharVector128SpanLength(nint offset, nint length) { return (length - offset) & ~(Vector128.Count - 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static nint GetCharVector256SpanLength(nint offset, nint length) { return (length - offset) & ~(Vector256.Count - 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static nint UnalignedCountVector(ref char searchSpace) { return (nint)(uint)(-(int)Unsafe.AsPointer(ref searchSpace) / 2) & (nint)(Vector.Count - 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static nint UnalignedCountVector128(ref char searchSpace) { return (nint)(uint)(-(int)Unsafe.AsPointer(ref searchSpace) / 2) & (nint)(Vector128.Count - 1); } public unsafe static void ClearWithoutReferences(ref byte b, nuint byteLength) { if (byteLength == 0) { return; } ulong num = byteLength; ulong num2 = num - 1; if (num2 <= 21) { switch (num2) { case 0uL: b = 0; return; case 1uL: Unsafe.As(ref b) = 0; return; case 2uL: Unsafe.As(ref b) = 0; Unsafe.Add(ref b, 2) = 0; return; case 3uL: Unsafe.As(ref b) = 0; return; case 4uL: Unsafe.As(ref b) = 0; Unsafe.Add(ref b, 4) = 0; return; case 5uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; return; case 6uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.Add(ref b, 6) = 0; return; case 7uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; return; case 8uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.Add(ref b, 8) = 0; return; case 9uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 8)) = 0; return; case 10uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 8)) = 0; Unsafe.Add(ref b, 10) = 0; return; case 11uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 8)) = 0; return; case 12uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 8)) = 0; Unsafe.Add(ref b, 12) = 0; return; case 13uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 8)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 12)) = 0; return; case 14uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 8)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 12)) = 0; Unsafe.Add(ref b, 14) = 0; return; case 15uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 8)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 12)) = 0; return; case 16uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 8)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 12)) = 0; Unsafe.Add(ref b, 16) = 0; return; case 17uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 8)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 12)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 16)) = 0; return; case 18uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 8)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 12)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 16)) = 0; Unsafe.Add(ref b, 18) = 0; return; case 19uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 8)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 12)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 16)) = 0; return; case 20uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 8)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 12)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 16)) = 0; Unsafe.Add(ref b, 20) = 0; return; case 21uL: Unsafe.As(ref b) = 0; Unsafe.As(ref Unsafe.Add(ref b, 4)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 8)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 12)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 16)) = 0; Unsafe.As(ref Unsafe.Add(ref b, 20)) = 0; return; } } nuint num3; if (byteLength < 512) { num3 = 0u; if (((nuint)Unsafe.AsPointer(ref b) & (nuint)3u) != 0) { if (((nuint)Unsafe.AsPointer(ref b) & (nuint)1u) != 0) { b = 0; num3++; if (((nuint)Unsafe.AsPointer(ref b) & (nuint)2u) != 0) { goto IL_046b; } } Unsafe.As(ref Unsafe.AddByteOffset(ref b, num3)) = 0; num3 += 2; } goto IL_046b; } Buffer._ZeroMemory(ref b, byteLength); return; IL_046b: if (((nuint)((byte*)Unsafe.AsPointer(ref b) - 1) & (nuint)4u) == 0) { Unsafe.As(ref Unsafe.AddByteOffset(ref b, num3)) = 0; num3 += 4; } nuint num4 = byteLength - 16; byteLength -= num3; nuint num5; do { num5 = num3 + 16; Unsafe.As(ref Unsafe.AddByteOffset(ref b, num3)) = 0; Unsafe.As(ref Unsafe.AddByteOffset(ref b, num3 + 4)) = 0; Unsafe.As(ref Unsafe.AddByteOffset(ref b, num3 + 8)) = 0; Unsafe.As(ref Unsafe.AddByteOffset(ref b, num3 + 12)) = 0; num3 = num5; } while (num5 <= num4); if ((byteLength & 8) != 0) { Unsafe.As(ref Unsafe.AddByteOffset(ref b, num3)) = 0; Unsafe.As(ref Unsafe.AddByteOffset(ref b, num3 + 4)) = 0; num3 += 8; } if ((byteLength & 4) != 0) { Unsafe.As(ref Unsafe.AddByteOffset(ref b, num3)) = 0; num3 += 4; } if ((byteLength & 2) != 0) { Unsafe.As(ref Unsafe.AddByteOffset(ref b, num3)) = 0; num3 += 2; } if ((byteLength & 1) != 0) { Unsafe.AddByteOffset(ref b, num3) = 0; } } public static void ClearWithReferences(ref IntPtr ip, nuint pointerSizeLength) { while (pointerSizeLength >= 8) { Unsafe.Add(ref Unsafe.Add(ref ip, (nint)pointerSizeLength), -1) = default(IntPtr); Unsafe.Add(ref Unsafe.Add(ref ip, (nint)pointerSizeLength), -2) = default(IntPtr); Unsafe.Add(ref Unsafe.Add(ref ip, (nint)pointerSizeLength), -3) = default(IntPtr); Unsafe.Add(ref Unsafe.Add(ref ip, (nint)pointerSizeLength), -4) = default(IntPtr); Unsafe.Add(ref Unsafe.Add(ref ip, (nint)pointerSizeLength), -5) = default(IntPtr); Unsafe.Add(ref Unsafe.Add(ref ip, (nint)pointerSizeLength), -6) = default(IntPtr); Unsafe.Add(ref Unsafe.Add(ref ip, (nint)pointerSizeLength), -7) = default(IntPtr); Unsafe.Add(ref Unsafe.Add(ref ip, (nint)pointerSizeLength), -8) = default(IntPtr); pointerSizeLength -= 8; } if (pointerSizeLength < 4) { if (pointerSizeLength < 2) { if (pointerSizeLength == 0) { return; } goto IL_012f; } } else { Unsafe.Add(ref ip, 2) = default(IntPtr); Unsafe.Add(ref ip, 3) = default(IntPtr); Unsafe.Add(ref Unsafe.Add(ref ip, (nint)pointerSizeLength), -3) = default(IntPtr); Unsafe.Add(ref Unsafe.Add(ref ip, (nint)pointerSizeLength), -2) = default(IntPtr); } Unsafe.Add(ref ip, 1) = default(IntPtr); Unsafe.Add(ref Unsafe.Add(ref ip, (nint)pointerSizeLength), -1) = default(IntPtr); goto IL_012f; IL_012f: ip = default(IntPtr); } public static void Fill(ref T refData, nuint numElements, T value) { if (!RuntimeHelpers.IsReferenceOrContainsReferences() && Vector.IsHardwareAccelerated && Unsafe.SizeOf() <= Vector.Count && BitOperations.IsPow2(Unsafe.SizeOf()) && numElements >= (uint)(Vector.Count / Unsafe.SizeOf())) { T source = value; Vector value2; if (Unsafe.SizeOf() == 1) { value2 = new Vector(Unsafe.As(ref source)); } else if (Unsafe.SizeOf() == 2) { value2 = (Vector)new Vector(Unsafe.As(ref source)); } else if (Unsafe.SizeOf() == 4) { value2 = ((typeof(T) == typeof(float)) ? ((Vector)new Vector((float)(object)source)) : ((Vector)new Vector(Unsafe.As(ref source)))); } else if (Unsafe.SizeOf() == 8) { value2 = ((typeof(T) == typeof(double)) ? ((Vector)new Vector((double)(object)source)) : ((Vector)new Vector(Unsafe.As(ref source)))); } else if (Unsafe.SizeOf() == 16) { Vector128 vector = Unsafe.As>(ref source); if (Vector.Count == 16) { value2 = vector.AsVector(); } else { if (Vector.Count != 32) { goto IL_022e; } value2 = Vector256.Create(vector, vector).AsVector(); } } else { if (Unsafe.SizeOf() != 32 || Vector.Count != 32) { goto IL_022e; } value2 = Unsafe.As>(ref source).AsVector(); } ref byte source2 = ref Unsafe.As(ref refData); nuint num = numElements * (nuint)Unsafe.SizeOf(); nuint num2 = num & (nuint)(2 * -Vector.Count); nuint num3 = 0u; if (numElements >= (uint)(2 * Vector.Count / Unsafe.SizeOf())) { do { Unsafe.WriteUnaligned(ref Unsafe.AddByteOffset(ref source2, num3), value2); Unsafe.WriteUnaligned(ref Unsafe.AddByteOffset(ref source2, num3 + (nuint)Vector.Count), value2); num3 += (uint)(2 * Vector.Count); } while (num3 < num2); } if ((num & (nuint)Vector.Count) != 0) { Unsafe.WriteUnaligned(ref Unsafe.AddByteOffset(ref source2, num3), value2); } Unsafe.WriteUnaligned(ref Unsafe.AddByteOffset(ref source2, num - (nuint)Vector.Count), value2); return; } goto IL_022e; IL_022e: nuint num4 = 0u; if (numElements >= 8) { nuint num5 = numElements & ~(nuint)7u; do { Unsafe.Add(ref refData, (nint)(num4 + 0)) = value; Unsafe.Add(ref refData, (nint)(num4 + 1)) = value; Unsafe.Add(ref refData, (nint)(num4 + 2)) = value; Unsafe.Add(ref refData, (nint)(num4 + 3)) = value; Unsafe.Add(ref refData, (nint)(num4 + 4)) = value; Unsafe.Add(ref refData, (nint)(num4 + 5)) = value; Unsafe.Add(ref refData, (nint)(num4 + 6)) = value; Unsafe.Add(ref refData, (nint)(num4 + 7)) = value; } while ((num4 += 8) < num5); } if ((numElements & 4) != 0) { Unsafe.Add(ref refData, (nint)(num4 + 0)) = value; Unsafe.Add(ref refData, (nint)(num4 + 1)) = value; Unsafe.Add(ref refData, (nint)(num4 + 2)) = value; Unsafe.Add(ref refData, (nint)(num4 + 3)) = value; num4 += 4; } if ((numElements & 2) != 0) { Unsafe.Add(ref refData, (nint)(num4 + 0)) = value; Unsafe.Add(ref refData, (nint)(num4 + 1)) = value; num4 += 2; } if ((numElements & 1) != 0) { Unsafe.Add(ref refData, (nint)num4) = value; } } public static int IndexOf(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) where T : IEquatable { if (valueLength == 0) { return 0; } T value2 = value; ref T second = ref Unsafe.Add(ref value, 1); int num = valueLength - 1; int num2 = 0; while (true) { int num3 = searchSpaceLength - num2 - num; if (num3 <= 0) { break; } int num4 = IndexOf(ref Unsafe.Add(ref searchSpace, num2), value2, num3); if (num4 == -1) { break; } num2 += num4; if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num2 + 1), ref second, num)) { return num2; } num2++; } return -1; } public static bool Contains(ref T searchSpace, T value, int length) where T : IEquatable { nint num = 0; if (default(T) != null || value != null) { while (length >= 8) { length -= 8; if (!value.Equals(Unsafe.Add(ref searchSpace, num + 0)) && !value.Equals(Unsafe.Add(ref searchSpace, num + 1)) && !value.Equals(Unsafe.Add(ref searchSpace, num + 2)) && !value.Equals(Unsafe.Add(ref searchSpace, num + 3)) && !value.Equals(Unsafe.Add(ref searchSpace, num + 4)) && !value.Equals(Unsafe.Add(ref searchSpace, num + 5)) && !value.Equals(Unsafe.Add(ref searchSpace, num + 6)) && !value.Equals(Unsafe.Add(ref searchSpace, num + 7))) { num += 8; continue; } goto IL_0220; } if (length >= 4) { length -= 4; if (value.Equals(Unsafe.Add(ref searchSpace, num + 0)) || value.Equals(Unsafe.Add(ref searchSpace, num + 1)) || value.Equals(Unsafe.Add(ref searchSpace, num + 2)) || value.Equals(Unsafe.Add(ref searchSpace, num + 3))) { goto IL_0220; } num += 4; } while (length > 0) { length--; if (!value.Equals(Unsafe.Add(ref searchSpace, num))) { num++; continue; } goto IL_0220; } } else { nint num2 = length; num = 0; while (num < num2) { if (Unsafe.Add(ref searchSpace, num) != null) { num++; continue; } goto IL_0220; } } return false; IL_0220: return true; } public static int IndexOf(ref T searchSpace, T value, int length) where T : IEquatable { nint num = 0; if (default(T) != null || value != null) { while (length >= 8) { length -= 8; if (value.Equals(Unsafe.Add(ref searchSpace, num))) { goto IL_021a; } if (value.Equals(Unsafe.Add(ref searchSpace, num + 1))) { goto IL_021d; } if (value.Equals(Unsafe.Add(ref searchSpace, num + 2))) { goto IL_0223; } if (!value.Equals(Unsafe.Add(ref searchSpace, num + 3))) { if (!value.Equals(Unsafe.Add(ref searchSpace, num + 4))) { if (!value.Equals(Unsafe.Add(ref searchSpace, num + 5))) { if (!value.Equals(Unsafe.Add(ref searchSpace, num + 6))) { if (!value.Equals(Unsafe.Add(ref searchSpace, num + 7))) { num += 8; continue; } return (int)(num + 7); } return (int)(num + 6); } return (int)(num + 5); } return (int)(num + 4); } goto IL_0229; } if (length >= 4) { length -= 4; if (value.Equals(Unsafe.Add(ref searchSpace, num))) { goto IL_021a; } if (value.Equals(Unsafe.Add(ref searchSpace, num + 1))) { goto IL_021d; } if (value.Equals(Unsafe.Add(ref searchSpace, num + 2))) { goto IL_0223; } if (value.Equals(Unsafe.Add(ref searchSpace, num + 3))) { goto IL_0229; } num += 4; } while (length > 0) { if (!value.Equals(Unsafe.Add(ref searchSpace, num))) { num++; length--; continue; } goto IL_021a; } } else { nint num2 = length; num = 0; while (num < num2) { if (Unsafe.Add(ref searchSpace, num) != null) { num++; continue; } goto IL_021a; } } return -1; IL_0223: return (int)(num + 2); IL_021d: return (int)(num + 1); IL_021a: return (int)num; IL_0229: return (int)(num + 3); } public static int IndexOfAny(ref T searchSpace, T value0, T value1, int length) where T : IEquatable { int i = 0; if (default(T) != null || (value0 != null && value1 != null)) { while (length - i >= 8) { T other = Unsafe.Add(ref searchSpace, i); if (value0.Equals(other) || value1.Equals(other)) { goto IL_0350; } other = Unsafe.Add(ref searchSpace, i + 1); if (value0.Equals(other) || value1.Equals(other)) { goto IL_0352; } other = Unsafe.Add(ref searchSpace, i + 2); if (value0.Equals(other) || value1.Equals(other)) { goto IL_0356; } other = Unsafe.Add(ref searchSpace, i + 3); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, i + 4); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, i + 5); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, i + 6); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, i + 7); if (!value0.Equals(other) && !value1.Equals(other)) { i += 8; continue; } return i + 7; } return i + 6; } return i + 5; } return i + 4; } goto IL_035a; } if (length - i >= 4) { T other = Unsafe.Add(ref searchSpace, i); if (value0.Equals(other) || value1.Equals(other)) { goto IL_0350; } other = Unsafe.Add(ref searchSpace, i + 1); if (value0.Equals(other) || value1.Equals(other)) { goto IL_0352; } other = Unsafe.Add(ref searchSpace, i + 2); if (value0.Equals(other) || value1.Equals(other)) { goto IL_0356; } other = Unsafe.Add(ref searchSpace, i + 3); if (value0.Equals(other) || value1.Equals(other)) { goto IL_035a; } i += 4; } while (i < length) { T other = Unsafe.Add(ref searchSpace, i); if (!value0.Equals(other) && !value1.Equals(other)) { i++; continue; } goto IL_0350; } } else { for (i = 0; i < length; i++) { T other = Unsafe.Add(ref searchSpace, i); if (other == null) { if (value0 != null && value1 != null) { continue; } } else if (!other.Equals(value0) && !other.Equals(value1)) { continue; } goto IL_0350; } } return -1; IL_0352: return i + 1; IL_035a: return i + 3; IL_0350: return i; IL_0356: return i + 2; } public static int IndexOfAny(ref T searchSpace, T value0, T value1, T value2, int length) where T : IEquatable { int i = 0; if (default(T) != null || (value0 != null && value1 != null && value2 != null)) { while (length - i >= 8) { T other = Unsafe.Add(ref searchSpace, i); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_0471; } other = Unsafe.Add(ref searchSpace, i + 1); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_0473; } other = Unsafe.Add(ref searchSpace, i + 2); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_0477; } other = Unsafe.Add(ref searchSpace, i + 3); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, i + 4); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, i + 5); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, i + 6); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, i + 7); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { i += 8; continue; } return i + 7; } return i + 6; } return i + 5; } return i + 4; } goto IL_047b; } if (length - i >= 4) { T other = Unsafe.Add(ref searchSpace, i); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_0471; } other = Unsafe.Add(ref searchSpace, i + 1); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_0473; } other = Unsafe.Add(ref searchSpace, i + 2); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_0477; } other = Unsafe.Add(ref searchSpace, i + 3); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_047b; } i += 4; } while (i < length) { T other = Unsafe.Add(ref searchSpace, i); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { i++; continue; } goto IL_0471; } } else { for (i = 0; i < length; i++) { T other = Unsafe.Add(ref searchSpace, i); if (other == null) { if (value0 != null && value1 != null && value2 != null) { continue; } } else if (!other.Equals(value0) && !other.Equals(value1) && !other.Equals(value2)) { continue; } goto IL_0471; } } return -1; IL_0477: return i + 2; IL_0471: return i; IL_047b: return i + 3; IL_0473: return i + 1; } public static int IndexOfAny(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) where T : IEquatable { if (valueLength == 0) { return -1; } if (typeof(T).IsValueType) { for (int i = 0; i < searchSpaceLength; i++) { T other = Unsafe.Add(ref searchSpace, i); for (int j = 0; j < valueLength; j++) { if (Unsafe.Add(ref value, j).Equals(other)) { return i; } } } } else { for (int k = 0; k < searchSpaceLength; k++) { T val = Unsafe.Add(ref searchSpace, k); if (val != null) { for (int l = 0; l < valueLength; l++) { if (val.Equals(Unsafe.Add(ref value, l))) { return k; } } continue; } for (int m = 0; m < valueLength; m++) { if (Unsafe.Add(ref value, m) == null) { return k; } } } } return -1; } public static int LastIndexOf(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) where T : IEquatable { if (valueLength == 0) { return searchSpaceLength; } T value2 = value; ref T second = ref Unsafe.Add(ref value, 1); int num = valueLength - 1; int num2 = 0; while (true) { int num3 = searchSpaceLength - num2 - num; if (num3 <= 0) { break; } int num4 = LastIndexOf(ref searchSpace, value2, num3); if (num4 == -1) { break; } if (SequenceEqual(ref Unsafe.Add(ref searchSpace, num4 + 1), ref second, num)) { return num4; } num2 += num3 - num4; } return -1; } public static int LastIndexOf(ref T searchSpace, T value, int length) where T : IEquatable { if (default(T) != null || value != null) { while (length >= 8) { length -= 8; if (!value.Equals(Unsafe.Add(ref searchSpace, length + 7))) { if (!value.Equals(Unsafe.Add(ref searchSpace, length + 6))) { if (!value.Equals(Unsafe.Add(ref searchSpace, length + 5))) { if (!value.Equals(Unsafe.Add(ref searchSpace, length + 4))) { if (!value.Equals(Unsafe.Add(ref searchSpace, length + 3))) { if (!value.Equals(Unsafe.Add(ref searchSpace, length + 2))) { if (!value.Equals(Unsafe.Add(ref searchSpace, length + 1))) { if (!value.Equals(Unsafe.Add(ref searchSpace, length))) { continue; } goto IL_01fe; } goto IL_0200; } goto IL_0204; } goto IL_0208; } return length + 4; } return length + 5; } return length + 6; } return length + 7; } if (length >= 4) { length -= 4; if (value.Equals(Unsafe.Add(ref searchSpace, length + 3))) { goto IL_0208; } if (value.Equals(Unsafe.Add(ref searchSpace, length + 2))) { goto IL_0204; } if (value.Equals(Unsafe.Add(ref searchSpace, length + 1))) { goto IL_0200; } if (value.Equals(Unsafe.Add(ref searchSpace, length))) { goto IL_01fe; } } while (length > 0) { length--; if (!value.Equals(Unsafe.Add(ref searchSpace, length))) { continue; } goto IL_01fe; } } else { length--; while (length >= 0) { if (Unsafe.Add(ref searchSpace, length) != null) { length--; continue; } goto IL_01fe; } } return -1; IL_0208: return length + 3; IL_0204: return length + 2; IL_0200: return length + 1; IL_01fe: return length; } public static int LastIndexOfAny(ref T searchSpace, T value0, T value1, int length) where T : IEquatable { if (default(T) != null || (value0 != null && value1 != null)) { while (length >= 8) { length -= 8; T other = Unsafe.Add(ref searchSpace, length + 7); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, length + 6); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, length + 5); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, length + 4); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, length + 3); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, length + 2); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, length + 1); if (!value0.Equals(other) && !value1.Equals(other)) { other = Unsafe.Add(ref searchSpace, length); if (!value0.Equals(other) && !value1.Equals(other)) { continue; } goto IL_0351; } goto IL_0353; } goto IL_0357; } goto IL_035b; } return length + 4; } return length + 5; } return length + 6; } return length + 7; } if (length >= 4) { length -= 4; T other = Unsafe.Add(ref searchSpace, length + 3); if (value0.Equals(other) || value1.Equals(other)) { goto IL_035b; } other = Unsafe.Add(ref searchSpace, length + 2); if (value0.Equals(other) || value1.Equals(other)) { goto IL_0357; } other = Unsafe.Add(ref searchSpace, length + 1); if (value0.Equals(other) || value1.Equals(other)) { goto IL_0353; } other = Unsafe.Add(ref searchSpace, length); if (value0.Equals(other) || value1.Equals(other)) { goto IL_0351; } } while (length > 0) { length--; T other = Unsafe.Add(ref searchSpace, length); if (!value0.Equals(other) && !value1.Equals(other)) { continue; } goto IL_0351; } } else { for (length--; length >= 0; length--) { T other = Unsafe.Add(ref searchSpace, length); if (other == null) { if (value0 != null && value1 != null) { continue; } } else if (!other.Equals(value0) && !other.Equals(value1)) { continue; } goto IL_0351; } } return -1; IL_0357: return length + 2; IL_0351: return length; IL_035b: return length + 3; IL_0353: return length + 1; } public static int LastIndexOfAny(ref T searchSpace, T value0, T value1, T value2, int length) where T : IEquatable { if (default(T) != null || (value0 != null && value1 != null)) { while (length >= 8) { length -= 8; T other = Unsafe.Add(ref searchSpace, length + 7); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, length + 6); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, length + 5); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, length + 4); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, length + 3); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, length + 2); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, length + 1); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { other = Unsafe.Add(ref searchSpace, length); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { continue; } goto IL_047a; } goto IL_047d; } goto IL_0482; } goto IL_0487; } return length + 4; } return length + 5; } return length + 6; } return length + 7; } if (length >= 4) { length -= 4; T other = Unsafe.Add(ref searchSpace, length + 3); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_0487; } other = Unsafe.Add(ref searchSpace, length + 2); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_0482; } other = Unsafe.Add(ref searchSpace, length + 1); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_047d; } other = Unsafe.Add(ref searchSpace, length); if (value0.Equals(other) || value1.Equals(other) || value2.Equals(other)) { goto IL_047a; } } while (length > 0) { length--; T other = Unsafe.Add(ref searchSpace, length); if (!value0.Equals(other) && !value1.Equals(other) && !value2.Equals(other)) { continue; } goto IL_047a; } } else { for (length--; length >= 0; length--) { T other = Unsafe.Add(ref searchSpace, length); if (other == null) { if (value0 != null && value1 != null && value2 != null) { continue; } } else if (!other.Equals(value0) && !other.Equals(value1) && !other.Equals(value2)) { continue; } goto IL_047a; } } return -1; IL_0482: return length + 2; IL_047a: return length; IL_0487: return length + 3; IL_047d: return length + 1; } public static int LastIndexOfAny(ref T searchSpace, int searchSpaceLength, ref T value, int valueLength) where T : IEquatable { if (valueLength == 0) { return -1; } if (typeof(T).IsValueType) { for (int num = searchSpaceLength - 1; num >= 0; num--) { T other = Unsafe.Add(ref searchSpace, num); for (int i = 0; i < valueLength; i++) { if (Unsafe.Add(ref value, i).Equals(other)) { return num; } } } } else { for (int num2 = searchSpaceLength - 1; num2 >= 0; num2--) { T val = Unsafe.Add(ref searchSpace, num2); if (val != null) { for (int j = 0; j < valueLength; j++) { if (val.Equals(Unsafe.Add(ref value, j))) { return num2; } } } else { for (int k = 0; k < valueLength; k++) { if (Unsafe.Add(ref value, k) == null) { return num2; } } } } } return -1; } public static bool SequenceEqual(ref T first, ref T second, int length) where T : IEquatable { if (!Unsafe.AreSame(ref first, ref second)) { nint num = 0; while (true) { if (length >= 8) { length -= 8; T val = Unsafe.Add(ref first, num); T val2 = Unsafe.Add(ref second, num); if (val?.Equals(val2) ?? (val2 == null)) { val = Unsafe.Add(ref first, num + 1); val2 = Unsafe.Add(ref second, num + 1); if (val?.Equals(val2) ?? (val2 == null)) { val = Unsafe.Add(ref first, num + 2); val2 = Unsafe.Add(ref second, num + 2); if (val?.Equals(val2) ?? (val2 == null)) { val = Unsafe.Add(ref first, num + 3); val2 = Unsafe.Add(ref second, num + 3); if (val?.Equals(val2) ?? (val2 == null)) { val = Unsafe.Add(ref first, num + 4); val2 = Unsafe.Add(ref second, num + 4); if (val?.Equals(val2) ?? (val2 == null)) { val = Unsafe.Add(ref first, num + 5); val2 = Unsafe.Add(ref second, num + 5); if (val?.Equals(val2) ?? (val2 == null)) { val = Unsafe.Add(ref first, num + 6); val2 = Unsafe.Add(ref second, num + 6); if (val?.Equals(val2) ?? (val2 == null)) { val = Unsafe.Add(ref first, num + 7); val2 = Unsafe.Add(ref second, num + 7); if (val?.Equals(val2) ?? (val2 == null)) { num += 8; continue; } } } } } } } } } else { if (length < 4) { goto IL_03b8; } length -= 4; T val = Unsafe.Add(ref first, num); T val2 = Unsafe.Add(ref second, num); if (val?.Equals(val2) ?? (val2 == null)) { val = Unsafe.Add(ref first, num + 1); val2 = Unsafe.Add(ref second, num + 1); if (val?.Equals(val2) ?? (val2 == null)) { val = Unsafe.Add(ref first, num + 2); val2 = Unsafe.Add(ref second, num + 2); if (val?.Equals(val2) ?? (val2 == null)) { val = Unsafe.Add(ref first, num + 3); val2 = Unsafe.Add(ref second, num + 3); if (val?.Equals(val2) ?? (val2 == null)) { num += 4; goto IL_03b8; } } } } } goto IL_03be; IL_03b8: while (length > 0) { T val = Unsafe.Add(ref first, num); T val2 = Unsafe.Add(ref second, num); if (val?.Equals(val2) ?? (val2 == null)) { num++; length--; continue; } goto IL_03be; } break; IL_03be: return false; } } return true; } public static int SequenceCompareTo(ref T first, int firstLength, ref T second, int secondLength) where T : IComparable { int num = firstLength; if (num > secondLength) { num = secondLength; } for (int i = 0; i < num; i++) { T val = Unsafe.Add(ref second, i); int num2 = Unsafe.Add(ref first, i)?.CompareTo(val) ?? ((val != null) ? (-1) : 0); if (num2 != 0) { return num2; } } return firstLength.CompareTo(secondLength); } } internal static class SR { private static readonly object _lock = new object(); private static List _currentlyLoading; private static int _infinitelyRecursingCount; private static bool _resourceManagerInited; 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(Strings))); internal static string Acc_CreateAbstEx => GetResourceString("Acc_CreateAbstEx"); internal static string Acc_CreateArgIterator => GetResourceString("Acc_CreateArgIterator"); internal static string Acc_CreateGenericEx => GetResourceString("Acc_CreateGenericEx"); internal static string Acc_CreateInterfaceEx => GetResourceString("Acc_CreateInterfaceEx"); internal static string Acc_CreateVoid => GetResourceString("Acc_CreateVoid"); internal static string Acc_NotClassInit => GetResourceString("Acc_NotClassInit"); internal static string Acc_ReadOnly => GetResourceString("Acc_ReadOnly"); internal static string Access_Void => GetResourceString("Access_Void"); internal static string AggregateException_ctor_DefaultMessage => GetResourceString("AggregateException_ctor_DefaultMessage"); internal static string AggregateException_ctor_InnerExceptionNull => GetResourceString("AggregateException_ctor_InnerExceptionNull"); internal static string AggregateException_DeserializationFailure => GetResourceString("AggregateException_DeserializationFailure"); internal static string AggregateException_InnerException => GetResourceString("AggregateException_InnerException"); internal static string AppDomain_Name => GetResourceString("AppDomain_Name"); internal static string AppDomain_NoContextPolicies => GetResourceString("AppDomain_NoContextPolicies"); internal static string AppDomain_Policy_PrincipalTwice => GetResourceString("AppDomain_Policy_PrincipalTwice"); internal static string AmbiguousImplementationException_NullMessage => GetResourceString("AmbiguousImplementationException_NullMessage"); internal static string Arg_AccessException => GetResourceString("Arg_AccessException"); internal static string Arg_AccessViolationException => GetResourceString("Arg_AccessViolationException"); internal static string Arg_AmbiguousMatchException => GetResourceString("Arg_AmbiguousMatchException"); internal static string Arg_ApplicationException => GetResourceString("Arg_ApplicationException"); internal static string Arg_ArgumentException => GetResourceString("Arg_ArgumentException"); internal static string Arg_ArgumentOutOfRangeException => GetResourceString("Arg_ArgumentOutOfRangeException"); internal static string Arg_ArithmeticException => GetResourceString("Arg_ArithmeticException"); internal static string Arg_ArrayLengthsDiffer => GetResourceString("Arg_ArrayLengthsDiffer"); internal static string Arg_ArrayPlusOffTooSmall => GetResourceString("Arg_ArrayPlusOffTooSmall"); internal static string Arg_ArrayTypeMismatchException => GetResourceString("Arg_ArrayTypeMismatchException"); internal static string Arg_ArrayZeroError => GetResourceString("Arg_ArrayZeroError"); internal static string Arg_BadDecimal => GetResourceString("Arg_BadDecimal"); internal static string Arg_BadImageFormatException => GetResourceString("Arg_BadImageFormatException"); internal static string Arg_BadLiteralFormat => GetResourceString("Arg_BadLiteralFormat"); internal static string Arg_BogusIComparer => GetResourceString("Arg_BogusIComparer"); internal static string Arg_BufferTooSmall => GetResourceString("Arg_BufferTooSmall"); internal static string Arg_CannotBeNaN => GetResourceString("Arg_CannotBeNaN"); internal static string Arg_CannotHaveNegativeValue => GetResourceString("Arg_CannotHaveNegativeValue"); internal static string Arg_CannotMixComparisonInfrastructure => GetResourceString("Arg_CannotMixComparisonInfrastructure"); internal static string Arg_CannotUnloadAppDomainException => GetResourceString("Arg_CannotUnloadAppDomainException"); internal static string Arg_CATypeResolutionFailed => GetResourceString("Arg_CATypeResolutionFailed"); internal static string Arg_COMAccess => GetResourceString("Arg_COMAccess"); internal static string Arg_COMException => GetResourceString("Arg_COMException"); internal static string Arg_COMPropSetPut => GetResourceString("Arg_COMPropSetPut"); internal static string Arg_CreatInstAccess => GetResourceString("Arg_CreatInstAccess"); internal static string Arg_CryptographyException => GetResourceString("Arg_CryptographyException"); internal static string Arg_CustomAttributeFormatException => GetResourceString("Arg_CustomAttributeFormatException"); internal static string Arg_DataMisalignedException => GetResourceString("Arg_DataMisalignedException"); internal static string Arg_DecBitCtor => GetResourceString("Arg_DecBitCtor"); internal static string Arg_DirectoryNotFoundException => GetResourceString("Arg_DirectoryNotFoundException"); internal static string Arg_DivideByZero => GetResourceString("Arg_DivideByZero"); internal static string Arg_DlgtNullInst => GetResourceString("Arg_DlgtNullInst"); internal static string Arg_DlgtTargMeth => GetResourceString("Arg_DlgtTargMeth"); internal static string Arg_DlgtTypeMis => GetResourceString("Arg_DlgtTypeMis"); internal static string Arg_DllNotFoundException => GetResourceString("Arg_DllNotFoundException"); internal static string Arg_DuplicateWaitObjectException => GetResourceString("Arg_DuplicateWaitObjectException"); internal static string Arg_EHClauseNotClause => GetResourceString("Arg_EHClauseNotClause"); internal static string Arg_EHClauseNotFilter => GetResourceString("Arg_EHClauseNotFilter"); internal static string Arg_EmptyArray => GetResourceString("Arg_EmptyArray"); internal static string Arg_EndOfStreamException => GetResourceString("Arg_EndOfStreamException"); internal static string Arg_EntryPointNotFoundException => GetResourceString("Arg_EntryPointNotFoundException"); internal static string Arg_EnumAndObjectMustBeSameType => GetResourceString("Arg_EnumAndObjectMustBeSameType"); internal static string Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType => GetResourceString("Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType"); internal static string Arg_EnumIllegalVal => GetResourceString("Arg_EnumIllegalVal"); internal static string Arg_EnumLitValueNotFound => GetResourceString("Arg_EnumLitValueNotFound"); internal static string Arg_EnumUnderlyingTypeAndObjectMustBeSameType => GetResourceString("Arg_EnumUnderlyingTypeAndObjectMustBeSameType"); internal static string Arg_EnumValueNotFound => GetResourceString("Arg_EnumValueNotFound"); internal static string Arg_ExecutionEngineException => GetResourceString("Arg_ExecutionEngineException"); internal static string Arg_ExternalException => GetResourceString("Arg_ExternalException"); internal static string Arg_FieldAccessException => GetResourceString("Arg_FieldAccessException"); internal static string Arg_FieldDeclTarget => GetResourceString("Arg_FieldDeclTarget"); internal static string Arg_FldGetArgErr => GetResourceString("Arg_FldGetArgErr"); internal static string Arg_FldGetPropSet => GetResourceString("Arg_FldGetPropSet"); internal static string Arg_FldSetArgErr => GetResourceString("Arg_FldSetArgErr"); internal static string Arg_FldSetGet => GetResourceString("Arg_FldSetGet"); internal static string Arg_FldSetInvoke => GetResourceString("Arg_FldSetInvoke"); internal static string Arg_FldSetPropGet => GetResourceString("Arg_FldSetPropGet"); internal static string Arg_FormatException => GetResourceString("Arg_FormatException"); internal static string Arg_GenericParameter => GetResourceString("Arg_GenericParameter"); internal static string Arg_GetMethNotFnd => GetResourceString("Arg_GetMethNotFnd"); internal static string Arg_GuidArrayCtor => GetResourceString("Arg_GuidArrayCtor"); internal static string Arg_HandleNotAsync => GetResourceString("Arg_HandleNotAsync"); internal static string Arg_HandleNotSync => GetResourceString("Arg_HandleNotSync"); internal static string Arg_HexStyleNotSupported => GetResourceString("Arg_HexStyleNotSupported"); internal static string Arg_HTCapacityOverflow => GetResourceString("Arg_HTCapacityOverflow"); internal static string Arg_IndexMustBeInt => GetResourceString("Arg_IndexMustBeInt"); internal static string Arg_IndexOutOfRangeException => GetResourceString("Arg_IndexOutOfRangeException"); internal static string Arg_InsufficientExecutionStackException => GetResourceString("Arg_InsufficientExecutionStackException"); internal static string Arg_InvalidANSIString => GetResourceString("Arg_InvalidANSIString"); internal static string Arg_InvalidBase => GetResourceString("Arg_InvalidBase"); internal static string Arg_InvalidCastException => GetResourceString("Arg_InvalidCastException"); internal static string Arg_InvalidComObjectException => GetResourceString("Arg_InvalidComObjectException"); internal static string Arg_InvalidFilterCriteriaException => GetResourceString("Arg_InvalidFilterCriteriaException"); internal static string Arg_InvalidHandle => GetResourceString("Arg_InvalidHandle"); internal static string Arg_InvalidHexStyle => GetResourceString("Arg_InvalidHexStyle"); internal static string Arg_InvalidNeutralResourcesLanguage_Asm_Culture => GetResourceString("Arg_InvalidNeutralResourcesLanguage_Asm_Culture"); internal static string Arg_InvalidNeutralResourcesLanguage_FallbackLoc => GetResourceString("Arg_InvalidNeutralResourcesLanguage_FallbackLoc"); internal static string Arg_InvalidSatelliteContract_Asm_Ver => GetResourceString("Arg_InvalidSatelliteContract_Asm_Ver"); internal static string Arg_InvalidOleVariantTypeException => GetResourceString("Arg_InvalidOleVariantTypeException"); internal static string Arg_InvalidOperationException => GetResourceString("Arg_InvalidOperationException"); internal static string Arg_InvalidTypeInRetType => GetResourceString("Arg_InvalidTypeInRetType"); internal static string Arg_InvalidTypeInSignature => GetResourceString("Arg_InvalidTypeInSignature"); internal static string Arg_IOException => GetResourceString("Arg_IOException"); internal static string Arg_KeyNotFound => GetResourceString("Arg_KeyNotFound"); internal static string Arg_KeyNotFoundWithKey => GetResourceString("Arg_KeyNotFoundWithKey"); internal static string Arg_LongerThanDestArray => GetResourceString("Arg_LongerThanDestArray"); internal static string Arg_LongerThanSrcArray => GetResourceString("Arg_LongerThanSrcArray"); internal static string Arg_LongerThanSrcString => GetResourceString("Arg_LongerThanSrcString"); internal static string Arg_LowerBoundsMustMatch => GetResourceString("Arg_LowerBoundsMustMatch"); internal static string Arg_MarshalAsAnyRestriction => GetResourceString("Arg_MarshalAsAnyRestriction"); internal static string Arg_MarshalDirectiveException => GetResourceString("Arg_MarshalDirectiveException"); internal static string Arg_MethodAccessException => GetResourceString("Arg_MethodAccessException"); internal static string Arg_MissingFieldException => GetResourceString("Arg_MissingFieldException"); internal static string Arg_MissingManifestResourceException => GetResourceString("Arg_MissingManifestResourceException"); internal static string Arg_MissingMemberException => GetResourceString("Arg_MissingMemberException"); internal static string Arg_MissingMethodException => GetResourceString("Arg_MissingMethodException"); internal static string Arg_MulticastNotSupportedException => GetResourceString("Arg_MulticastNotSupportedException"); internal static string Arg_MustBeBoolean => GetResourceString("Arg_MustBeBoolean"); internal static string Arg_MustBeByte => GetResourceString("Arg_MustBeByte"); internal static string Arg_MustBeChar => GetResourceString("Arg_MustBeChar"); internal static string Arg_MustBeDateOnly => GetResourceString("Arg_MustBeDateOnly"); internal static string Arg_MustBeTimeOnly => GetResourceString("Arg_MustBeTimeOnly"); internal static string Arg_MustBeDateTime => GetResourceString("Arg_MustBeDateTime"); internal static string Arg_MustBeDateTimeOffset => GetResourceString("Arg_MustBeDateTimeOffset"); internal static string Arg_MustBeDecimal => GetResourceString("Arg_MustBeDecimal"); internal static string Arg_MustBeDelegate => GetResourceString("Arg_MustBeDelegate"); internal static string Arg_MustBeDouble => GetResourceString("Arg_MustBeDouble"); internal static string Arg_MustBeDriveLetterOrRootDir => GetResourceString("Arg_MustBeDriveLetterOrRootDir"); internal static string Arg_MustBeEnum => GetResourceString("Arg_MustBeEnum"); internal static string Arg_MustBeEnumBaseTypeOrEnum => GetResourceString("Arg_MustBeEnumBaseTypeOrEnum"); internal static string Arg_MustBeGuid => GetResourceString("Arg_MustBeGuid"); internal static string Arg_MustBeInt16 => GetResourceString("Arg_MustBeInt16"); internal static string Arg_MustBeInt32 => GetResourceString("Arg_MustBeInt32"); internal static string Arg_MustBeInt64 => GetResourceString("Arg_MustBeInt64"); internal static string Arg_MustBeIntPtr => GetResourceString("Arg_MustBeIntPtr"); internal static string Arg_MustBeNFloat => GetResourceString("Arg_MustBeNFloat"); internal static string Arg_MustBePointer => GetResourceString("Arg_MustBePointer"); internal static string Arg_MustBePrimArray => GetResourceString("Arg_MustBePrimArray"); internal static string Arg_MustBeRuntimeAssembly => GetResourceString("Arg_MustBeRuntimeAssembly"); internal static string Arg_MustBeSByte => GetResourceString("Arg_MustBeSByte"); internal static string Arg_MustBeSingle => GetResourceString("Arg_MustBeSingle"); internal static string Arg_MustBeString => GetResourceString("Arg_MustBeString"); internal static string Arg_MustBeTimeSpan => GetResourceString("Arg_MustBeTimeSpan"); internal static string Arg_MustBeType => GetResourceString("Arg_MustBeType"); internal static string Arg_MustBeTrue => GetResourceString("Arg_MustBeTrue"); internal static string Arg_MustBeUInt16 => GetResourceString("Arg_MustBeUInt16"); internal static string Arg_MustBeUInt32 => GetResourceString("Arg_MustBeUInt32"); internal static string Arg_MustBeUInt64 => GetResourceString("Arg_MustBeUInt64"); internal static string Arg_MustBeUIntPtr => GetResourceString("Arg_MustBeUIntPtr"); internal static string Arg_MustBeVersion => GetResourceString("Arg_MustBeVersion"); internal static string Arg_MustContainEnumInfo => GetResourceString("Arg_MustContainEnumInfo"); internal static string Arg_NamedParamNull => GetResourceString("Arg_NamedParamNull"); internal static string Arg_NamedParamTooBig => GetResourceString("Arg_NamedParamTooBig"); internal static string Arg_NDirectBadObject => GetResourceString("Arg_NDirectBadObject"); internal static string Arg_Need1DArray => GetResourceString("Arg_Need1DArray"); internal static string Arg_Need2DArray => GetResourceString("Arg_Need2DArray"); internal static string Arg_Need3DArray => GetResourceString("Arg_Need3DArray"); internal static string Arg_NeedAtLeast1Rank => GetResourceString("Arg_NeedAtLeast1Rank"); internal static string Arg_NegativeArgCount => GetResourceString("Arg_NegativeArgCount"); internal static string Arg_NoAccessSpec => GetResourceString("Arg_NoAccessSpec"); internal static string Arg_NoDefCTor => GetResourceString("Arg_NoDefCTor"); internal static string Arg_NonZeroLowerBound => GetResourceString("Arg_NonZeroLowerBound"); internal static string Arg_NoStaticVirtual => GetResourceString("Arg_NoStaticVirtual"); internal static string Arg_NotFiniteNumberException => GetResourceString("Arg_NotFiniteNumberException"); internal static string Arg_NotGenericMethodDefinition => GetResourceString("Arg_NotGenericMethodDefinition"); internal static string Arg_NotGenericParameter => GetResourceString("Arg_NotGenericParameter"); internal static string Arg_NotGenericTypeDefinition => GetResourceString("Arg_NotGenericTypeDefinition"); internal static string Arg_NotImplementedException => GetResourceString("Arg_NotImplementedException"); internal static string Arg_NotSupportedException => GetResourceString("Arg_NotSupportedException"); internal static string Arg_NullReferenceException => GetResourceString("Arg_NullReferenceException"); internal static string Arg_ObjObjEx => GetResourceString("Arg_ObjObjEx"); internal static string Arg_OleAutDateInvalid => GetResourceString("Arg_OleAutDateInvalid"); internal static string Arg_OleAutDateScale => GetResourceString("Arg_OleAutDateScale"); internal static string Arg_OverflowException => GetResourceString("Arg_OverflowException"); internal static string Arg_ParamName_Name => GetResourceString("Arg_ParamName_Name"); internal static string Arg_ParmArraySize => GetResourceString("Arg_ParmArraySize"); internal static string Arg_ParmCnt => GetResourceString("Arg_ParmCnt"); internal static string Arg_PathEmpty => GetResourceString("Arg_PathEmpty"); internal static string Arg_PlatformNotSupported => GetResourceString("Arg_PlatformNotSupported"); internal static string Arg_PropSetGet => GetResourceString("Arg_PropSetGet"); internal static string Arg_PropSetInvoke => GetResourceString("Arg_PropSetInvoke"); internal static string Arg_RankException => GetResourceString("Arg_RankException"); internal static string Arg_RankIndices => GetResourceString("Arg_RankIndices"); internal static string Arg_RankMultiDimNotSupported => GetResourceString("Arg_RankMultiDimNotSupported"); internal static string Arg_RanksAndBounds => GetResourceString("Arg_RanksAndBounds"); internal static string Arg_RegGetOverflowBug => GetResourceString("Arg_RegGetOverflowBug"); internal static string Arg_RegKeyNotFound => GetResourceString("Arg_RegKeyNotFound"); internal static string Arg_RegSubKeyValueAbsent => GetResourceString("Arg_RegSubKeyValueAbsent"); internal static string Arg_RegValStrLenBug => GetResourceString("Arg_RegValStrLenBug"); internal static string Arg_ResMgrNotResSet => GetResourceString("Arg_ResMgrNotResSet"); internal static string Arg_ResourceFileUnsupportedVersion => GetResourceString("Arg_ResourceFileUnsupportedVersion"); internal static string Arg_ResourceNameNotExist => GetResourceString("Arg_ResourceNameNotExist"); internal static string Arg_SafeArrayRankMismatchException => GetResourceString("Arg_SafeArrayRankMismatchException"); internal static string Arg_SafeArrayTypeMismatchException => GetResourceString("Arg_SafeArrayTypeMismatchException"); internal static string Arg_SecurityException => GetResourceString("Arg_SecurityException"); internal static string SerializationException => GetResourceString("SerializationException"); internal static string Arg_SetMethNotFnd => GetResourceString("Arg_SetMethNotFnd"); internal static string Arg_StackOverflowException => GetResourceString("Arg_StackOverflowException"); internal static string Arg_SurrogatesNotAllowedAsSingleChar => GetResourceString("Arg_SurrogatesNotAllowedAsSingleChar"); internal static string Arg_SynchronizationLockException => GetResourceString("Arg_SynchronizationLockException"); internal static string Arg_SystemException => GetResourceString("Arg_SystemException"); internal static string Arg_TargetInvocationException => GetResourceString("Arg_TargetInvocationException"); internal static string Arg_TargetParameterCountException => GetResourceString("Arg_TargetParameterCountException"); internal static string Arg_ThreadStartException => GetResourceString("Arg_ThreadStartException"); internal static string Arg_ThreadStateException => GetResourceString("Arg_ThreadStateException"); internal static string Arg_TimeoutException => GetResourceString("Arg_TimeoutException"); internal static string Arg_TypeAccessException => GetResourceString("Arg_TypeAccessException"); internal static string Arg_TypedReference_Null => GetResourceString("Arg_TypedReference_Null"); internal static string Arg_TypeLoadException => GetResourceString("Arg_TypeLoadException"); internal static string Arg_TypeLoadNullStr => GetResourceString("Arg_TypeLoadNullStr"); internal static string Arg_TypeRefPrimitve => GetResourceString("Arg_TypeRefPrimitve"); internal static string Arg_TypeUnloadedException => GetResourceString("Arg_TypeUnloadedException"); internal static string Arg_UnauthorizedAccessException => GetResourceString("Arg_UnauthorizedAccessException"); internal static string Arg_UnboundGenField => GetResourceString("Arg_UnboundGenField"); internal static string Arg_UnboundGenParam => GetResourceString("Arg_UnboundGenParam"); internal static string Arg_UnknownTypeCode => GetResourceString("Arg_UnknownTypeCode"); internal static string Arg_VarMissNull => GetResourceString("Arg_VarMissNull"); internal static string Arg_VersionString => GetResourceString("Arg_VersionString"); internal static string Arg_WrongType => GetResourceString("Arg_WrongType"); internal static string Argument_AbsolutePathRequired => GetResourceString("Argument_AbsolutePathRequired"); internal static string Argument_AddingDuplicate => GetResourceString("Argument_AddingDuplicate"); internal static string Argument_AddingDuplicate__ => GetResourceString("Argument_AddingDuplicate__"); internal static string Argument_AddingDuplicateWithKey => GetResourceString("Argument_AddingDuplicateWithKey"); internal static string Argument_AdjustmentRulesNoNulls => GetResourceString("Argument_AdjustmentRulesNoNulls"); internal static string Argument_AdjustmentRulesOutOfOrder => GetResourceString("Argument_AdjustmentRulesOutOfOrder"); internal static string Argument_AlignmentMustBePow2 => GetResourceString("Argument_AlignmentMustBePow2"); internal static string Argument_AlreadyBoundOrSyncHandle => GetResourceString("Argument_AlreadyBoundOrSyncHandle"); internal static string Argument_ArrayGetInterfaceMap => GetResourceString("Argument_ArrayGetInterfaceMap"); internal static string Argument_ArraysInvalid => GetResourceString("Argument_ArraysInvalid"); internal static string Argument_AttributeNamesMustBeUnique => GetResourceString("Argument_AttributeNamesMustBeUnique"); internal static string Argument_BadConstructor => GetResourceString("Argument_BadConstructor"); internal static string Argument_BadConstructorCallConv => GetResourceString("Argument_BadConstructorCallConv"); internal static string Argument_BadExceptionCodeGen => GetResourceString("Argument_BadExceptionCodeGen"); internal static string Argument_BadFieldForConstructorBuilder => GetResourceString("Argument_BadFieldForConstructorBuilder"); internal static string Argument_BadFieldSig => GetResourceString("Argument_BadFieldSig"); internal static string Argument_BadFieldType => GetResourceString("Argument_BadFieldType"); internal static string Argument_BadFormatSpecifier => GetResourceString("Argument_BadFormatSpecifier"); internal static string Argument_BadImageFormatExceptionResolve => GetResourceString("Argument_BadImageFormatExceptionResolve"); internal static string Argument_BadLabel => GetResourceString("Argument_BadLabel"); internal static string Argument_BadLabelContent => GetResourceString("Argument_BadLabelContent"); internal static string Argument_BadNestedTypeFlags => GetResourceString("Argument_BadNestedTypeFlags"); internal static string Argument_BadParameterCountsForConstructor => GetResourceString("Argument_BadParameterCountsForConstructor"); internal static string Argument_BadParameterTypeForCAB => GetResourceString("Argument_BadParameterTypeForCAB"); internal static string Argument_BadPropertyForConstructorBuilder => GetResourceString("Argument_BadPropertyForConstructorBuilder"); internal static string Argument_BadSigFormat => GetResourceString("Argument_BadSigFormat"); internal static string Argument_BadSizeForData => GetResourceString("Argument_BadSizeForData"); internal static string Argument_BadTypeAttrInvalidLayout => GetResourceString("Argument_BadTypeAttrInvalidLayout"); internal static string Argument_BadTypeAttrNestedVisibilityOnNonNestedType => GetResourceString("Argument_BadTypeAttrNestedVisibilityOnNonNestedType"); internal static string Argument_BadTypeAttrNonNestedVisibilityNestedType => GetResourceString("Argument_BadTypeAttrNonNestedVisibilityNestedType"); internal static string Argument_BadTypeAttrReservedBitsSet => GetResourceString("Argument_BadTypeAttrReservedBitsSet"); internal static string Argument_BadTypeInCustomAttribute => GetResourceString("Argument_BadTypeInCustomAttribute"); internal static string Argument_CannotGetTypeTokenForByRef => GetResourceString("Argument_CannotGetTypeTokenForByRef"); internal static string Argument_CannotSetParentToInterface => GetResourceString("Argument_CannotSetParentToInterface"); internal static string Argument_CodepageNotSupported => GetResourceString("Argument_CodepageNotSupported"); internal static string Argument_CompareOptionOrdinal => GetResourceString("Argument_CompareOptionOrdinal"); internal static string Argument_ConflictingDateTimeRoundtripStyles => GetResourceString("Argument_ConflictingDateTimeRoundtripStyles"); internal static string Argument_ConflictingDateTimeStyles => GetResourceString("Argument_ConflictingDateTimeStyles"); internal static string Argument_ConstantDoesntMatch => GetResourceString("Argument_ConstantDoesntMatch"); internal static string Argument_ConstantNotSupported => GetResourceString("Argument_ConstantNotSupported"); internal static string Argument_ConstantNull => GetResourceString("Argument_ConstantNull"); internal static string Argument_ConstructorNeedGenericDeclaringType => GetResourceString("Argument_ConstructorNeedGenericDeclaringType"); internal static string Argument_ConversionOverflow => GetResourceString("Argument_ConversionOverflow"); internal static string Argument_ConvertMismatch => GetResourceString("Argument_ConvertMismatch"); internal static string Argument_CultureIetfNotSupported => GetResourceString("Argument_CultureIetfNotSupported"); internal static string Argument_CultureInvalidIdentifier => GetResourceString("Argument_CultureInvalidIdentifier"); internal static string Argument_CultureIsNeutral => GetResourceString("Argument_CultureIsNeutral"); internal static string Argument_CultureNotSupported => GetResourceString("Argument_CultureNotSupported"); internal static string Argument_CultureNotSupportedInInvariantMode => GetResourceString("Argument_CultureNotSupportedInInvariantMode"); internal static string Argument_CustomAssemblyLoadContextRequestedNameMismatch => GetResourceString("Argument_CustomAssemblyLoadContextRequestedNameMismatch"); internal static string Argument_CustomCultureCannotBePassedByNumber => GetResourceString("Argument_CustomCultureCannotBePassedByNumber"); internal static string Argument_DateTimeBadBinaryData => GetResourceString("Argument_DateTimeBadBinaryData"); internal static string Argument_DateTimeHasTicks => GetResourceString("Argument_DateTimeHasTicks"); internal static string Argument_DateTimeHasTimeOfDay => GetResourceString("Argument_DateTimeHasTimeOfDay"); internal static string Argument_DateTimeIsInvalid => GetResourceString("Argument_DateTimeIsInvalid"); internal static string Argument_DateTimeIsNotAmbiguous => GetResourceString("Argument_DateTimeIsNotAmbiguous"); internal static string Argument_DateTimeKindMustBeUnspecified => GetResourceString("Argument_DateTimeKindMustBeUnspecified"); internal static string Argument_DateTimeKindMustBeUnspecifiedOrUtc => GetResourceString("Argument_DateTimeKindMustBeUnspecifiedOrUtc"); internal static string Argument_DateTimeOffsetInvalidDateTimeStyles => GetResourceString("Argument_DateTimeOffsetInvalidDateTimeStyles"); internal static string Argument_DateTimeOffsetIsNotAmbiguous => GetResourceString("Argument_DateTimeOffsetIsNotAmbiguous"); internal static string Argument_DestinationTooShort => GetResourceString("Argument_DestinationTooShort"); internal static string Argument_DuplicateTypeName => GetResourceString("Argument_DuplicateTypeName"); internal static string Argument_EmitWriteLineType => GetResourceString("Argument_EmitWriteLineType"); internal static string Argument_EmptyDecString => GetResourceString("Argument_EmptyDecString"); internal static string Argument_EmptyFileName => GetResourceString("Argument_EmptyFileName"); internal static string Argument_EmptyName => GetResourceString("Argument_EmptyName"); internal static string Argument_EmptyPath => GetResourceString("Argument_EmptyPath"); internal static string Argument_EmptyWaithandleArray => GetResourceString("Argument_EmptyWaithandleArray"); internal static string Argument_EncoderFallbackNotEmpty => GetResourceString("Argument_EncoderFallbackNotEmpty"); internal static string Argument_EncodingConversionOverflowBytes => GetResourceString("Argument_EncodingConversionOverflowBytes"); internal static string Argument_EncodingConversionOverflowChars => GetResourceString("Argument_EncodingConversionOverflowChars"); internal static string Argument_EncodingNotSupported => GetResourceString("Argument_EncodingNotSupported"); internal static string Argument_EnumTypeDoesNotMatch => GetResourceString("Argument_EnumTypeDoesNotMatch"); internal static string Argument_FallbackBufferNotEmpty => GetResourceString("Argument_FallbackBufferNotEmpty"); internal static string Argument_FieldDeclaringTypeGeneric => GetResourceString("Argument_FieldDeclaringTypeGeneric"); internal static string Argument_FieldNeedGenericDeclaringType => GetResourceString("Argument_FieldNeedGenericDeclaringType"); internal static string Argument_GenConstraintViolation => GetResourceString("Argument_GenConstraintViolation"); internal static string Argument_GenericArgsCount => GetResourceString("Argument_GenericArgsCount"); internal static string Argument_GenericsInvalid => GetResourceString("Argument_GenericsInvalid"); internal static string Argument_GlobalFunctionHasToBeStatic => GetResourceString("Argument_GlobalFunctionHasToBeStatic"); internal static string Argument_HasToBeArrayClass => GetResourceString("Argument_HasToBeArrayClass"); internal static string Argument_IdnBadBidi => GetResourceString("Argument_IdnBadBidi"); internal static string Argument_IdnBadLabelSize => GetResourceString("Argument_IdnBadLabelSize"); internal static string Argument_IdnBadNameSize => GetResourceString("Argument_IdnBadNameSize"); internal static string Argument_IdnBadPunycode => GetResourceString("Argument_IdnBadPunycode"); internal static string Argument_IdnBadStd3 => GetResourceString("Argument_IdnBadStd3"); internal static string Argument_IdnIllegalName => GetResourceString("Argument_IdnIllegalName"); internal static string Argument_IllegalEnvVarName => GetResourceString("Argument_IllegalEnvVarName"); internal static string Argument_IllegalName => GetResourceString("Argument_IllegalName"); internal static string Argument_ImplementIComparable => GetResourceString("Argument_ImplementIComparable"); internal static string Argument_InvalidAppendMode => GetResourceString("Argument_InvalidAppendMode"); internal static string Argument_InvalidPreallocateAccess => GetResourceString("Argument_InvalidPreallocateAccess"); internal static string Argument_InvalidPreallocateMode => GetResourceString("Argument_InvalidPreallocateMode"); internal static string Argument_InvalidArgumentForComparison => GetResourceString("Argument_InvalidArgumentForComparison"); internal static string Argument_InvalidArrayLength => GetResourceString("Argument_InvalidArrayLength"); internal static string Argument_InvalidArrayType => GetResourceString("Argument_InvalidArrayType"); internal static string Argument_InvalidCalendar => GetResourceString("Argument_InvalidCalendar"); internal static string Argument_InvalidCharSequence => GetResourceString("Argument_InvalidCharSequence"); internal static string Argument_InvalidCharSequenceNoIndex => GetResourceString("Argument_InvalidCharSequenceNoIndex"); internal static string Argument_InvalidCodePageBytesIndex => GetResourceString("Argument_InvalidCodePageBytesIndex"); internal static string Argument_InvalidCodePageConversionIndex => GetResourceString("Argument_InvalidCodePageConversionIndex"); internal static string Argument_InvalidConstructorDeclaringType => GetResourceString("Argument_InvalidConstructorDeclaringType"); internal static string Argument_InvalidConstructorInfo => GetResourceString("Argument_InvalidConstructorInfo"); internal static string Argument_InvalidCultureName => GetResourceString("Argument_InvalidCultureName"); internal static string Argument_InvalidPredefinedCultureName => GetResourceString("Argument_InvalidPredefinedCultureName"); internal static string Argument_InvalidDateTimeKind => GetResourceString("Argument_InvalidDateTimeKind"); internal static string Argument_InvalidDateTimeStyles => GetResourceString("Argument_InvalidDateTimeStyles"); internal static string Argument_InvalidDateStyles => GetResourceString("Argument_InvalidDateStyles"); internal static string Argument_InvalidDigitSubstitution => GetResourceString("Argument_InvalidDigitSubstitution"); internal static string Argument_InvalidElementName => GetResourceString("Argument_InvalidElementName"); internal static string Argument_InvalidElementTag => GetResourceString("Argument_InvalidElementTag"); internal static string Argument_InvalidElementText => GetResourceString("Argument_InvalidElementText"); internal static string Argument_InvalidElementValue => GetResourceString("Argument_InvalidElementValue"); internal static string Argument_InvalidEnum => GetResourceString("Argument_InvalidEnum"); internal static string Argument_InvalidEnumValue => GetResourceString("Argument_InvalidEnumValue"); internal static string Argument_InvalidFieldDeclaringType => GetResourceString("Argument_InvalidFieldDeclaringType"); internal static string Argument_InvalidFileModeAndAccessCombo => GetResourceString("Argument_InvalidFileModeAndAccessCombo"); internal static string Argument_InvalidFlag => GetResourceString("Argument_InvalidFlag"); internal static string Argument_InvalidGenericInstArray => GetResourceString("Argument_InvalidGenericInstArray"); internal static string Argument_InvalidGroupSize => GetResourceString("Argument_InvalidGroupSize"); internal static string Argument_InvalidHandle => GetResourceString("Argument_InvalidHandle"); internal static string Argument_InvalidHighSurrogate => GetResourceString("Argument_InvalidHighSurrogate"); internal static string Argument_InvalidId => GetResourceString("Argument_InvalidId"); internal static string Argument_InvalidKindOfTypeForCA => GetResourceString("Argument_InvalidKindOfTypeForCA"); internal static string Argument_InvalidLabel => GetResourceString("Argument_InvalidLabel"); internal static string Argument_InvalidLowSurrogate => GetResourceString("Argument_InvalidLowSurrogate"); internal static string Argument_InvalidMemberForNamedArgument => GetResourceString("Argument_InvalidMemberForNamedArgument"); internal static string Argument_InvalidMethodDeclaringType => GetResourceString("Argument_InvalidMethodDeclaringType"); internal static string Argument_InvalidName => GetResourceString("Argument_InvalidName"); internal static string Argument_InvalidNativeDigitCount => GetResourceString("Argument_InvalidNativeDigitCount"); internal static string Argument_InvalidNativeDigitValue => GetResourceString("Argument_InvalidNativeDigitValue"); internal static string Argument_InvalidNeutralRegionName => GetResourceString("Argument_InvalidNeutralRegionName"); internal static string Argument_InvalidNormalizationForm => GetResourceString("Argument_InvalidNormalizationForm"); internal static string Argument_InvalidNumberStyles => GetResourceString("Argument_InvalidNumberStyles"); internal static string Argument_InvalidOffLen => GetResourceString("Argument_InvalidOffLen"); internal static string Argument_InvalidOpCodeOnDynamicMethod => GetResourceString("Argument_InvalidOpCodeOnDynamicMethod"); internal static string Argument_InvalidParameterInfo => GetResourceString("Argument_InvalidParameterInfo"); internal static string Argument_InvalidParamInfo => GetResourceString("Argument_InvalidParamInfo"); internal static string Argument_InvalidPathChars => GetResourceString("Argument_InvalidPathChars"); internal static string Argument_InvalidResourceCultureName => GetResourceString("Argument_InvalidResourceCultureName"); internal static string Argument_InvalidSafeBufferOffLen => GetResourceString("Argument_InvalidSafeBufferOffLen"); internal static string Argument_InvalidSeekOrigin => GetResourceString("Argument_InvalidSeekOrigin"); internal static string Argument_InvalidSerializedString => GetResourceString("Argument_InvalidSerializedString"); internal static string Argument_InvalidStartupHookSignature => GetResourceString("Argument_InvalidStartupHookSignature"); internal static string Argument_InvalidTimeSpanStyles => GetResourceString("Argument_InvalidTimeSpanStyles"); internal static string Argument_InvalidToken => GetResourceString("Argument_InvalidToken"); internal static string Argument_InvalidTypeForCA => GetResourceString("Argument_InvalidTypeForCA"); internal static string Argument_InvalidTypeForDynamicMethod => GetResourceString("Argument_InvalidTypeForDynamicMethod"); internal static string Argument_InvalidTypeName => GetResourceString("Argument_InvalidTypeName"); internal static string Argument_InvalidTypeWithPointersNotSupported => GetResourceString("Argument_InvalidTypeWithPointersNotSupported"); internal static string Argument_InvalidUnity => GetResourceString("Argument_InvalidUnity"); internal static string Argument_LargeInteger => GetResourceString("Argument_LargeInteger"); internal static string Argument_LongEnvVarValue => GetResourceString("Argument_LongEnvVarValue"); internal static string Argument_MethodDeclaringTypeGeneric => GetResourceString("Argument_MethodDeclaringTypeGeneric"); internal static string Argument_MethodDeclaringTypeGenericLcg => GetResourceString("Argument_MethodDeclaringTypeGenericLcg"); internal static string Argument_MethodNeedGenericDeclaringType => GetResourceString("Argument_MethodNeedGenericDeclaringType"); internal static string Argument_MinMaxValue => GetResourceString("Argument_MinMaxValue"); internal static string Argument_MismatchedArrays => GetResourceString("Argument_MismatchedArrays"); internal static string Argument_MissingDefaultConstructor => GetResourceString("Argument_MissingDefaultConstructor"); internal static string Argument_MustBeFalse => GetResourceString("Argument_MustBeFalse"); internal static string Argument_MustBeRuntimeAssembly => GetResourceString("Argument_MustBeRuntimeAssembly"); internal static string Argument_MustBeRuntimeFieldInfo => GetResourceString("Argument_MustBeRuntimeFieldInfo"); internal static string Argument_MustBeRuntimeMethodInfo => GetResourceString("Argument_MustBeRuntimeMethodInfo"); internal static string Argument_MustBeRuntimeReflectionObject => GetResourceString("Argument_MustBeRuntimeReflectionObject"); internal static string Argument_MustBeRuntimeType => GetResourceString("Argument_MustBeRuntimeType"); internal static string Argument_MustBeTypeBuilder => GetResourceString("Argument_MustBeTypeBuilder"); internal static string Argument_MustHaveAttributeBaseClass => GetResourceString("Argument_MustHaveAttributeBaseClass"); internal static string Argument_NativeOverlappedAlreadyFree => GetResourceString("Argument_NativeOverlappedAlreadyFree"); internal static string Argument_NativeOverlappedWrongBoundHandle => GetResourceString("Argument_NativeOverlappedWrongBoundHandle"); internal static string Argument_NeedGenericMethodDefinition => GetResourceString("Argument_NeedGenericMethodDefinition"); internal static string Argument_NeedNonGenericType => GetResourceString("Argument_NeedNonGenericType"); internal static string Argument_NeedStructWithNoRefs => GetResourceString("Argument_NeedStructWithNoRefs"); internal static string Argument_NeverValidGenericArgument => GetResourceString("Argument_NeverValidGenericArgument"); internal static string Argument_NoEra => GetResourceString("Argument_NoEra"); internal static string Argument_NoRegionInvariantCulture => GetResourceString("Argument_NoRegionInvariantCulture"); internal static string Argument_NotAWritableProperty => GetResourceString("Argument_NotAWritableProperty"); internal static string Argument_NotEnoughBytesToRead => GetResourceString("Argument_NotEnoughBytesToRead"); internal static string Argument_NotEnoughBytesToWrite => GetResourceString("Argument_NotEnoughBytesToWrite"); internal static string Argument_NotEnoughGenArguments => GetResourceString("Argument_NotEnoughGenArguments"); internal static string Argument_NotExceptionType => GetResourceString("Argument_NotExceptionType"); internal static string Argument_NotInExceptionBlock => GetResourceString("Argument_NotInExceptionBlock"); internal static string Argument_NotMethodCallOpcode => GetResourceString("Argument_NotMethodCallOpcode"); internal static string Argument_NotSerializable => GetResourceString("Argument_NotSerializable"); internal static string Argument_ObjNotComObject => GetResourceString("Argument_ObjNotComObject"); internal static string Argument_OffsetAndCapacityOutOfBounds => GetResourceString("Argument_OffsetAndCapacityOutOfBounds"); internal static string Argument_OffsetLocalMismatch => GetResourceString("Argument_OffsetLocalMismatch"); internal static string Argument_OffsetOfFieldNotFound => GetResourceString("Argument_OffsetOfFieldNotFound"); internal static string Argument_OffsetOutOfRange => GetResourceString("Argument_OffsetOutOfRange"); internal static string Argument_OffsetPrecision => GetResourceString("Argument_OffsetPrecision"); internal static string Argument_OffsetUtcMismatch => GetResourceString("Argument_OffsetUtcMismatch"); internal static string Argument_OneOfCulturesNotSupported => GetResourceString("Argument_OneOfCulturesNotSupported"); internal static string Argument_OnlyMscorlib => GetResourceString("Argument_OnlyMscorlib"); internal static string Argument_OutOfOrderDateTimes => GetResourceString("Argument_OutOfOrderDateTimes"); internal static string Argument_PathEmpty => GetResourceString("Argument_PathEmpty"); internal static string Argument_PreAllocatedAlreadyAllocated => GetResourceString("Argument_PreAllocatedAlreadyAllocated"); internal static string Argument_RecursiveFallback => GetResourceString("Argument_RecursiveFallback"); internal static string Argument_RecursiveFallbackBytes => GetResourceString("Argument_RecursiveFallbackBytes"); internal static string Argument_RedefinedLabel => GetResourceString("Argument_RedefinedLabel"); internal static string Argument_ResolveField => GetResourceString("Argument_ResolveField"); internal static string Argument_ResolveFieldHandle => GetResourceString("Argument_ResolveFieldHandle"); internal static string Argument_ResolveMember => GetResourceString("Argument_ResolveMember"); internal static string Argument_ResolveMethod => GetResourceString("Argument_ResolveMethod"); internal static string Argument_ResolveMethodHandle => GetResourceString("Argument_ResolveMethodHandle"); internal static string Argument_ResolveModuleType => GetResourceString("Argument_ResolveModuleType"); internal static string Argument_ResolveString => GetResourceString("Argument_ResolveString"); internal static string Argument_ResolveType => GetResourceString("Argument_ResolveType"); internal static string Argument_ResultCalendarRange => GetResourceString("Argument_ResultCalendarRange"); internal static string Argument_SemaphoreInitialMaximum => GetResourceString("Argument_SemaphoreInitialMaximum"); internal static string Argument_ShouldNotSpecifyExceptionType => GetResourceString("Argument_ShouldNotSpecifyExceptionType"); internal static string Argument_ShouldOnlySetVisibilityFlags => GetResourceString("Argument_ShouldOnlySetVisibilityFlags"); internal static string Argument_SigIsFinalized => GetResourceString("Argument_SigIsFinalized"); internal static string Argument_StreamNotReadable => GetResourceString("Argument_StreamNotReadable"); internal static string Argument_StreamNotWritable => GetResourceString("Argument_StreamNotWritable"); internal static string Argument_StringFirstCharIsZero => GetResourceString("Argument_StringFirstCharIsZero"); internal static string Argument_StringZeroLength => GetResourceString("Argument_StringZeroLength"); internal static string Argument_TimeSpanHasSeconds => GetResourceString("Argument_TimeSpanHasSeconds"); internal static string Argument_ToExclusiveLessThanFromExclusive => GetResourceString("Argument_ToExclusiveLessThanFromExclusive"); internal static string Argument_TooManyFinallyClause => GetResourceString("Argument_TooManyFinallyClause"); internal static string Argument_TransitionTimesAreIdentical => GetResourceString("Argument_TransitionTimesAreIdentical"); internal static string Argument_TypedReferenceInvalidField => GetResourceString("Argument_TypedReferenceInvalidField"); internal static string Argument_TypeMustNotBeComImport => GetResourceString("Argument_TypeMustNotBeComImport"); internal static string Argument_TypeNameTooLong => GetResourceString("Argument_TypeNameTooLong"); internal static string Argument_TypeNotComObject => GetResourceString("Argument_TypeNotComObject"); internal static string Argument_TypeNotValid => GetResourceString("Argument_TypeNotValid"); internal static string Argument_UnclosedExceptionBlock => GetResourceString("Argument_UnclosedExceptionBlock"); internal static string Argument_UnknownUnmanagedCallConv => GetResourceString("Argument_UnknownUnmanagedCallConv"); internal static string Argument_UnmanagedMemAccessorWrapAround => GetResourceString("Argument_UnmanagedMemAccessorWrapAround"); internal static string Argument_UnmatchedMethodForLocal => GetResourceString("Argument_UnmatchedMethodForLocal"); internal static string Argument_UnmatchingSymScope => GetResourceString("Argument_UnmatchingSymScope"); internal static string Argument_UTCOutOfRange => GetResourceString("Argument_UTCOutOfRange"); internal static string ArgumentException_BadMethodImplBody => GetResourceString("ArgumentException_BadMethodImplBody"); internal static string ArgumentException_BufferNotFromPool => GetResourceString("ArgumentException_BufferNotFromPool"); internal static string ArgumentException_OtherNotArrayOfCorrectLength => GetResourceString("ArgumentException_OtherNotArrayOfCorrectLength"); internal static string ArgumentException_NotIsomorphic => GetResourceString("ArgumentException_NotIsomorphic"); internal static string ArgumentException_TupleIncorrectType => GetResourceString("ArgumentException_TupleIncorrectType"); internal static string ArgumentException_TupleLastArgumentNotATuple => GetResourceString("ArgumentException_TupleLastArgumentNotATuple"); internal static string ArgumentException_ValueTupleIncorrectType => GetResourceString("ArgumentException_ValueTupleIncorrectType"); internal static string ArgumentException_ValueTupleLastArgumentNotAValueTuple => GetResourceString("ArgumentException_ValueTupleLastArgumentNotAValueTuple"); internal static string ArgumentNull_Array => GetResourceString("ArgumentNull_Array"); internal static string ArgumentNull_ArrayElement => GetResourceString("ArgumentNull_ArrayElement"); internal static string ArgumentNull_ArrayValue => GetResourceString("ArgumentNull_ArrayValue"); internal static string ArgumentNull_Assembly => GetResourceString("ArgumentNull_Assembly"); internal static string ArgumentNull_AssemblyNameName => GetResourceString("ArgumentNull_AssemblyNameName"); internal static string ArgumentNull_Buffer => GetResourceString("ArgumentNull_Buffer"); internal static string ArgumentNull_Child => GetResourceString("ArgumentNull_Child"); internal static string ArgumentNull_Collection => GetResourceString("ArgumentNull_Collection"); internal static string ArgumentNull_Dictionary => GetResourceString("ArgumentNull_Dictionary"); internal static string ArgumentNull_FileName => GetResourceString("ArgumentNull_FileName"); internal static string ArgumentNull_Generic => GetResourceString("ArgumentNull_Generic"); internal static string ArgumentNull_Key => GetResourceString("ArgumentNull_Key"); internal static string ArgumentNull_Path => GetResourceString("ArgumentNull_Path"); internal static string ArgumentNull_SafeHandle => GetResourceString("ArgumentNull_SafeHandle"); internal static string ArgumentNull_Stream => GetResourceString("ArgumentNull_Stream"); internal static string ArgumentNull_String => GetResourceString("ArgumentNull_String"); internal static string ArgumentNull_Type => GetResourceString("ArgumentNull_Type"); internal static string ArgumentNull_Waithandles => GetResourceString("ArgumentNull_Waithandles"); internal static string ArgumentOutOfRange_ActualValue => GetResourceString("ArgumentOutOfRange_ActualValue"); internal static string ArgumentOutOfRange_AddressSpace => GetResourceString("ArgumentOutOfRange_AddressSpace"); internal static string ArgumentOutOfRange_AddValue => GetResourceString("ArgumentOutOfRange_AddValue"); internal static string ArgumentOutOfRange_ArrayLB => GetResourceString("ArgumentOutOfRange_ArrayLB"); internal static string ArgumentOutOfRange_BadHourMinuteSecond => GetResourceString("ArgumentOutOfRange_BadHourMinuteSecond"); internal static string ArgumentOutOfRange_BadYearMonthDay => GetResourceString("ArgumentOutOfRange_BadYearMonthDay"); internal static string ArgumentOutOfRange_BiggerThanCollection => GetResourceString("ArgumentOutOfRange_BiggerThanCollection"); internal static string ArgumentOutOfRange_BinaryReaderFillBuffer => GetResourceString("ArgumentOutOfRange_BinaryReaderFillBuffer"); internal static string ArgumentOutOfRange_Bounds_Lower_Upper => GetResourceString("ArgumentOutOfRange_Bounds_Lower_Upper"); internal static string ArgumentOutOfRange_CalendarRange => GetResourceString("ArgumentOutOfRange_CalendarRange"); internal static string ArgumentOutOfRange_Capacity => GetResourceString("ArgumentOutOfRange_Capacity"); internal static string ArgumentOutOfRange_Count => GetResourceString("ArgumentOutOfRange_Count"); internal static string ArgumentOutOfRange_DateArithmetic => GetResourceString("ArgumentOutOfRange_DateArithmetic"); internal static string ArgumentOutOfRange_DateTimeBadMonths => GetResourceString("ArgumentOutOfRange_DateTimeBadMonths"); internal static string ArgumentOutOfRange_DateTimeBadTicks => GetResourceString("ArgumentOutOfRange_DateTimeBadTicks"); internal static string ArgumentOutOfRange_TimeOnlyBadTicks => GetResourceString("ArgumentOutOfRange_TimeOnlyBadTicks"); internal static string ArgumentOutOfRange_DateTimeBadYears => GetResourceString("ArgumentOutOfRange_DateTimeBadYears"); internal static string ArgumentOutOfRange_Day => GetResourceString("ArgumentOutOfRange_Day"); internal static string ArgumentOutOfRange_DayOfWeek => GetResourceString("ArgumentOutOfRange_DayOfWeek"); internal static string ArgumentOutOfRange_DayParam => GetResourceString("ArgumentOutOfRange_DayParam"); internal static string ArgumentOutOfRange_DecimalRound => GetResourceString("ArgumentOutOfRange_DecimalRound"); internal static string ArgumentOutOfRange_DecimalScale => GetResourceString("ArgumentOutOfRange_DecimalScale"); internal static string ArgumentOutOfRange_EndIndexStartIndex => GetResourceString("ArgumentOutOfRange_EndIndexStartIndex"); internal static string ArgumentOutOfRange_Enum => GetResourceString("ArgumentOutOfRange_Enum"); internal static string ArgumentOutOfRange_Era => GetResourceString("ArgumentOutOfRange_Era"); internal static string ArgumentOutOfRange_FileLengthTooBig => GetResourceString("ArgumentOutOfRange_FileLengthTooBig"); internal static string ArgumentOutOfRange_FileTimeInvalid => GetResourceString("ArgumentOutOfRange_FileTimeInvalid"); internal static string ArgumentOutOfRange_GenericPositive => GetResourceString("ArgumentOutOfRange_GenericPositive"); internal static string ArgumentOutOfRange_GetByteCountOverflow => GetResourceString("ArgumentOutOfRange_GetByteCountOverflow"); internal static string ArgumentOutOfRange_GetCharCountOverflow => GetResourceString("ArgumentOutOfRange_GetCharCountOverflow"); internal static string ArgumentOutOfRange_HashtableLoadFactor => GetResourceString("ArgumentOutOfRange_HashtableLoadFactor"); internal static string ArgumentOutOfRange_HugeArrayNotSupported => GetResourceString("ArgumentOutOfRange_HugeArrayNotSupported"); internal static string ArgumentOutOfRange_Index => GetResourceString("ArgumentOutOfRange_Index"); internal static string ArgumentOutOfRange_IndexCount => GetResourceString("ArgumentOutOfRange_IndexCount"); internal static string ArgumentOutOfRange_IndexCountBuffer => GetResourceString("ArgumentOutOfRange_IndexCountBuffer"); internal static string ArgumentOutOfRange_IndexLength => GetResourceString("ArgumentOutOfRange_IndexLength"); internal static string ArgumentOutOfRange_IndexString => GetResourceString("ArgumentOutOfRange_IndexString"); internal static string ArgumentOutOfRange_InputTooLarge => GetResourceString("ArgumentOutOfRange_InputTooLarge"); internal static string ArgumentOutOfRange_InvalidEraValue => GetResourceString("ArgumentOutOfRange_InvalidEraValue"); internal static string ArgumentOutOfRange_InvalidHighSurrogate => GetResourceString("ArgumentOutOfRange_InvalidHighSurrogate"); internal static string ArgumentOutOfRange_InvalidLowSurrogate => GetResourceString("ArgumentOutOfRange_InvalidLowSurrogate"); internal static string ArgumentOutOfRange_InvalidUTF32 => GetResourceString("ArgumentOutOfRange_InvalidUTF32"); internal static string ArgumentOutOfRange_Length => GetResourceString("ArgumentOutOfRange_Length"); internal static string ArgumentOutOfRange_LengthGreaterThanCapacity => GetResourceString("ArgumentOutOfRange_LengthGreaterThanCapacity"); internal static string ArgumentOutOfRange_LengthTooLarge => GetResourceString("ArgumentOutOfRange_LengthTooLarge"); internal static string ArgumentOutOfRange_LessEqualToIntegerMaxVal => GetResourceString("ArgumentOutOfRange_LessEqualToIntegerMaxVal"); internal static string ArgumentOutOfRange_ListInsert => GetResourceString("ArgumentOutOfRange_ListInsert"); internal static string ArgumentOutOfRange_Month => GetResourceString("ArgumentOutOfRange_Month"); internal static string ArgumentOutOfRange_DayNumber => GetResourceString("ArgumentOutOfRange_DayNumber"); internal static string ArgumentOutOfRange_MonthParam => GetResourceString("ArgumentOutOfRange_MonthParam"); internal static string ArgumentOutOfRange_MustBeNonNegInt32 => GetResourceString("ArgumentOutOfRange_MustBeNonNegInt32"); internal static string ArgumentOutOfRange_MustBeNonNegNum => GetResourceString("ArgumentOutOfRange_MustBeNonNegNum"); internal static string ArgumentOutOfRange_MustBePositive => GetResourceString("ArgumentOutOfRange_MustBePositive"); internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum"); internal static string ArgumentOutOfRange_NeedNonNegOrNegative1 => GetResourceString("ArgumentOutOfRange_NeedNonNegOrNegative1"); internal static string ArgumentOutOfRange_NeedPosNum => GetResourceString("ArgumentOutOfRange_NeedPosNum"); internal static string ArgumentOutOfRange_NeedValidId => GetResourceString("ArgumentOutOfRange_NeedValidId"); internal static string ArgumentOutOfRange_NegativeCapacity => GetResourceString("ArgumentOutOfRange_NegativeCapacity"); internal static string ArgumentOutOfRange_NegativeCount => GetResourceString("ArgumentOutOfRange_NegativeCount"); internal static string ArgumentOutOfRange_NegativeLength => GetResourceString("ArgumentOutOfRange_NegativeLength"); internal static string ArgumentOutOfRange_OffsetLength => GetResourceString("ArgumentOutOfRange_OffsetLength"); internal static string ArgumentOutOfRange_OffsetOut => GetResourceString("ArgumentOutOfRange_OffsetOut"); internal static string ArgumentOutOfRange_ParamSequence => GetResourceString("ArgumentOutOfRange_ParamSequence"); internal static string ArgumentOutOfRange_PartialWCHAR => GetResourceString("ArgumentOutOfRange_PartialWCHAR"); internal static string ArgumentOutOfRange_PeriodTooLarge => GetResourceString("ArgumentOutOfRange_PeriodTooLarge"); internal static string ArgumentOutOfRange_PositionLessThanCapacityRequired => GetResourceString("ArgumentOutOfRange_PositionLessThanCapacityRequired"); internal static string ArgumentOutOfRange_Range => GetResourceString("ArgumentOutOfRange_Range"); internal static string ArgumentOutOfRange_RoundingDigits => GetResourceString("ArgumentOutOfRange_RoundingDigits"); internal static string ArgumentOutOfRange_RoundingDigits_MathF => GetResourceString("ArgumentOutOfRange_RoundingDigits_MathF"); internal static string ArgumentOutOfRange_SmallCapacity => GetResourceString("ArgumentOutOfRange_SmallCapacity"); internal static string ArgumentOutOfRange_SmallMaxCapacity => GetResourceString("ArgumentOutOfRange_SmallMaxCapacity"); internal static string ArgumentOutOfRange_StartIndex => GetResourceString("ArgumentOutOfRange_StartIndex"); internal static string ArgumentOutOfRange_StartIndexLargerThanLength => GetResourceString("ArgumentOutOfRange_StartIndexLargerThanLength"); internal static string ArgumentOutOfRange_StreamLength => GetResourceString("ArgumentOutOfRange_StreamLength"); internal static string ArgumentOutOfRange_TimeoutTooLarge => GetResourceString("ArgumentOutOfRange_TimeoutTooLarge"); internal static string ArgumentOutOfRange_UIntPtrMax => GetResourceString("ArgumentOutOfRange_UIntPtrMax"); internal static string ArgumentOutOfRange_UnmanagedMemStreamLength => GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamLength"); internal static string ArgumentOutOfRange_UnmanagedMemStreamWrapAround => GetResourceString("ArgumentOutOfRange_UnmanagedMemStreamWrapAround"); internal static string ArgumentOutOfRange_UtcOffset => GetResourceString("ArgumentOutOfRange_UtcOffset"); internal static string ArgumentOutOfRange_UtcOffsetAndDaylightDelta => GetResourceString("ArgumentOutOfRange_UtcOffsetAndDaylightDelta"); internal static string ArgumentOutOfRange_Version => GetResourceString("ArgumentOutOfRange_Version"); internal static string ArgumentOutOfRange_Week => GetResourceString("ArgumentOutOfRange_Week"); internal static string ArgumentOutOfRange_Year => GetResourceString("ArgumentOutOfRange_Year"); internal static string Arithmetic_NaN => GetResourceString("Arithmetic_NaN"); internal static string ArrayTypeMismatch_ConstrainedCopy => GetResourceString("ArrayTypeMismatch_ConstrainedCopy"); internal static string AssemblyLoadContext_Unload_CannotUnloadIfNotCollectible => GetResourceString("AssemblyLoadContext_Unload_CannotUnloadIfNotCollectible"); internal static string AssemblyLoadContext_Verify_NotUnloading => GetResourceString("AssemblyLoadContext_Verify_NotUnloading"); internal static string AssertionFailed => GetResourceString("AssertionFailed"); internal static string AssertionFailed_Cnd => GetResourceString("AssertionFailed_Cnd"); internal static string AssumptionFailed => GetResourceString("AssumptionFailed"); internal static string AssumptionFailed_Cnd => GetResourceString("AssumptionFailed_Cnd"); internal static string AsyncMethodBuilder_InstanceNotInitialized => GetResourceString("AsyncMethodBuilder_InstanceNotInitialized"); internal static string BadImageFormat_BadILFormat => GetResourceString("BadImageFormat_BadILFormat"); internal static string BadImageFormat_InvalidType => GetResourceString("BadImageFormat_InvalidType"); internal static string BadImageFormat_NegativeStringLength => GetResourceString("BadImageFormat_NegativeStringLength"); internal static string BadImageFormat_ParameterSignatureMismatch => GetResourceString("BadImageFormat_ParameterSignatureMismatch"); internal static string BadImageFormat_ResType_SerBlobMismatch => GetResourceString("BadImageFormat_ResType_SerBlobMismatch"); internal static string BadImageFormat_ResourceDataLengthInvalid => GetResourceString("BadImageFormat_ResourceDataLengthInvalid"); internal static string BadImageFormat_ResourceNameCorrupted => GetResourceString("BadImageFormat_ResourceNameCorrupted"); internal static string BadImageFormat_ResourceNameCorrupted_NameIndex => GetResourceString("BadImageFormat_ResourceNameCorrupted_NameIndex"); internal static string BadImageFormat_ResourcesDataInvalidOffset => GetResourceString("BadImageFormat_ResourcesDataInvalidOffset"); internal static string BadImageFormat_ResourcesHeaderCorrupted => GetResourceString("BadImageFormat_ResourcesHeaderCorrupted"); internal static string BadImageFormat_ResourcesIndexTooLong => GetResourceString("BadImageFormat_ResourcesIndexTooLong"); internal static string BadImageFormat_ResourcesNameInvalidOffset => GetResourceString("BadImageFormat_ResourcesNameInvalidOffset"); internal static string BadImageFormat_ResourcesNameTooLong => GetResourceString("BadImageFormat_ResourcesNameTooLong"); internal static string BadImageFormat_TypeMismatch => GetResourceString("BadImageFormat_TypeMismatch"); internal static string CancellationToken_CreateLinkedToken_TokensIsEmpty => GetResourceString("CancellationToken_CreateLinkedToken_TokensIsEmpty"); internal static string CancellationTokenSource_Disposed => GetResourceString("CancellationTokenSource_Disposed"); internal static string ConcurrentCollection_SyncRoot_NotSupported => GetResourceString("ConcurrentCollection_SyncRoot_NotSupported"); internal static string EventSource_AbstractMustNotDeclareEventMethods => GetResourceString("EventSource_AbstractMustNotDeclareEventMethods"); internal static string EventSource_AbstractMustNotDeclareKTOC => GetResourceString("EventSource_AbstractMustNotDeclareKTOC"); internal static string EventSource_AddScalarOutOfRange => GetResourceString("EventSource_AddScalarOutOfRange"); internal static string EventSource_BadHexDigit => GetResourceString("EventSource_BadHexDigit"); internal static string EventSource_ChannelTypeDoesNotMatchEventChannelValue => GetResourceString("EventSource_ChannelTypeDoesNotMatchEventChannelValue"); internal static string EventSource_DataDescriptorsOutOfRange => GetResourceString("EventSource_DataDescriptorsOutOfRange"); internal static string EventSource_DuplicateStringKey => GetResourceString("EventSource_DuplicateStringKey"); internal static string EventSource_EnumKindMismatch => GetResourceString("EventSource_EnumKindMismatch"); internal static string EventSource_EvenHexDigits => GetResourceString("EventSource_EvenHexDigits"); internal static string EventSource_EventChannelOutOfRange => GetResourceString("EventSource_EventChannelOutOfRange"); internal static string EventSource_EventIdReused => GetResourceString("EventSource_EventIdReused"); internal static string EventSource_EventMustHaveTaskIfNonDefaultOpcode => GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode"); internal static string EventSource_EventMustNotBeExplicitImplementation => GetResourceString("EventSource_EventMustNotBeExplicitImplementation"); internal static string EventSource_EventNameReused => GetResourceString("EventSource_EventNameReused"); internal static string EventSource_EventParametersMismatch => GetResourceString("EventSource_EventParametersMismatch"); internal static string EventSource_EventSourceGuidInUse => GetResourceString("EventSource_EventSourceGuidInUse"); internal static string EventSource_EventTooBig => GetResourceString("EventSource_EventTooBig"); internal static string EventSource_EventWithAdminChannelMustHaveMessage => GetResourceString("EventSource_EventWithAdminChannelMustHaveMessage"); internal static string EventSource_IllegalKeywordsValue => GetResourceString("EventSource_IllegalKeywordsValue"); internal static string EventSource_IllegalOpcodeValue => GetResourceString("EventSource_IllegalOpcodeValue"); internal static string EventSource_IllegalTaskValue => GetResourceString("EventSource_IllegalTaskValue"); internal static string EventSource_IllegalValue => GetResourceString("EventSource_IllegalValue"); internal static string EventSource_IncorrentlyAuthoredTypeInfo => GetResourceString("EventSource_IncorrentlyAuthoredTypeInfo"); internal static string EventSource_InvalidCommand => GetResourceString("EventSource_InvalidCommand"); internal static string EventSource_InvalidEventFormat => GetResourceString("EventSource_InvalidEventFormat"); internal static string EventSource_KeywordCollision => GetResourceString("EventSource_KeywordCollision"); internal static string EventSource_KeywordNeedPowerOfTwo => GetResourceString("EventSource_KeywordNeedPowerOfTwo"); internal static string EventSource_ListenerCreatedInsideCallback => GetResourceString("EventSource_ListenerCreatedInsideCallback"); internal static string EventSource_ListenerNotFound => GetResourceString("EventSource_ListenerNotFound"); internal static string EventSource_ListenerWriteFailure => GetResourceString("EventSource_ListenerWriteFailure"); internal static string EventSource_MaxChannelExceeded => GetResourceString("EventSource_MaxChannelExceeded"); internal static string EventSource_MismatchIdToWriteEvent => GetResourceString("EventSource_MismatchIdToWriteEvent"); internal static string EventSource_NeedGuid => GetResourceString("EventSource_NeedGuid"); internal static string EventSource_NeedName => GetResourceString("EventSource_NeedName"); internal static string EventSource_NeedPositiveId => GetResourceString("EventSource_NeedPositiveId"); internal static string EventSource_NoFreeBuffers => GetResourceString("EventSource_NoFreeBuffers"); internal static string EventSource_NonCompliantTypeError => GetResourceString("EventSource_NonCompliantTypeError"); internal static string EventSource_NoRelatedActivityId => GetResourceString("EventSource_NoRelatedActivityId"); internal static string EventSource_NotSupportedArrayOfBinary => GetResourceString("EventSource_NotSupportedArrayOfBinary"); internal static string EventSource_NotSupportedArrayOfNil => GetResourceString("EventSource_NotSupportedArrayOfNil"); internal static string EventSource_NotSupportedArrayOfNullTerminatedString => GetResourceString("EventSource_NotSupportedArrayOfNullTerminatedString"); internal static string EventSource_NotSupportedNestedArraysEnums => GetResourceString("EventSource_NotSupportedNestedArraysEnums"); internal static string EventSource_NullInput => GetResourceString("EventSource_NullInput"); internal static string EventSource_OpcodeCollision => GetResourceString("EventSource_OpcodeCollision"); internal static string EventSource_PinArrayOutOfRange => GetResourceString("EventSource_PinArrayOutOfRange"); internal static string EventSource_RecursiveTypeDefinition => GetResourceString("EventSource_RecursiveTypeDefinition"); internal static string EventSource_StopsFollowStarts => GetResourceString("EventSource_StopsFollowStarts"); internal static string EventSource_TaskCollision => GetResourceString("EventSource_TaskCollision"); internal static string EventSource_TaskOpcodePairReused => GetResourceString("EventSource_TaskOpcodePairReused"); internal static string EventSource_TooManyArgs => GetResourceString("EventSource_TooManyArgs"); internal static string EventSource_TooManyFields => GetResourceString("EventSource_TooManyFields"); internal static string EventSource_ToString => GetResourceString("EventSource_ToString"); internal static string EventSource_TraitEven => GetResourceString("EventSource_TraitEven"); internal static string EventSource_TypeMustBeSealedOrAbstract => GetResourceString("EventSource_TypeMustBeSealedOrAbstract"); internal static string EventSource_TypeMustDeriveFromEventSource => GetResourceString("EventSource_TypeMustDeriveFromEventSource"); internal static string EventSource_UndefinedChannel => GetResourceString("EventSource_UndefinedChannel"); internal static string EventSource_UndefinedKeyword => GetResourceString("EventSource_UndefinedKeyword"); internal static string EventSource_UndefinedOpcode => GetResourceString("EventSource_UndefinedOpcode"); internal static string EventSource_UnknownEtwTrait => GetResourceString("EventSource_UnknownEtwTrait"); internal static string EventSource_UnsupportedEventTypeInManifest => GetResourceString("EventSource_UnsupportedEventTypeInManifest"); internal static string EventSource_UnsupportedMessageProperty => GetResourceString("EventSource_UnsupportedMessageProperty"); internal static string EventSource_VarArgsParameterMismatch => GetResourceString("EventSource_VarArgsParameterMismatch"); internal static string Exception_EndOfInnerExceptionStack => GetResourceString("Exception_EndOfInnerExceptionStack"); internal static string Exception_EndStackTraceFromPreviousThrow => GetResourceString("Exception_EndStackTraceFromPreviousThrow"); internal static string Exception_WasThrown => GetResourceString("Exception_WasThrown"); internal static string ExecutionContext_ExceptionInAsyncLocalNotification => GetResourceString("ExecutionContext_ExceptionInAsyncLocalNotification"); internal static string FileNotFound_ResolveAssembly => GetResourceString("FileNotFound_ResolveAssembly"); internal static string Format_AttributeUsage => GetResourceString("Format_AttributeUsage"); internal static string Format_Bad7BitInt => GetResourceString("Format_Bad7BitInt"); internal static string Format_BadBase64Char => GetResourceString("Format_BadBase64Char"); internal static string Format_BadBoolean => GetResourceString("Format_BadBoolean"); internal static string Format_BadDateOnly => GetResourceString("Format_BadDateOnly"); internal static string Format_BadTimeOnly => GetResourceString("Format_BadTimeOnly"); internal static string Format_DateTimeOnlyContainsNoneDateParts => GetResourceString("Format_DateTimeOnlyContainsNoneDateParts"); internal static string Format_BadFormatSpecifier => GetResourceString("Format_BadFormatSpecifier"); internal static string Format_NoFormatSpecifier => GetResourceString("Format_NoFormatSpecifier"); internal static string Format_BadHexChar => GetResourceString("Format_BadHexChar"); internal static string Format_BadHexLength => GetResourceString("Format_BadHexLength"); internal static string Format_BadQuote => GetResourceString("Format_BadQuote"); internal static string Format_BadTimeSpan => GetResourceString("Format_BadTimeSpan"); internal static string Format_EmptyInputString => GetResourceString("Format_EmptyInputString"); internal static string Format_ExtraJunkAtEnd => GetResourceString("Format_ExtraJunkAtEnd"); internal static string Format_GuidUnrecognized => GetResourceString("Format_GuidUnrecognized"); internal static string Format_IndexOutOfRange => GetResourceString("Format_IndexOutOfRange"); internal static string Format_InvalidEnumFormatSpecification => GetResourceString("Format_InvalidEnumFormatSpecification"); internal static string Format_InvalidGuidFormatSpecification => GetResourceString("Format_InvalidGuidFormatSpecification"); internal static string Format_InvalidString => GetResourceString("Format_InvalidString"); internal static string Format_NeedSingleChar => GetResourceString("Format_NeedSingleChar"); internal static string Format_NoParsibleDigits => GetResourceString("Format_NoParsibleDigits"); internal static string Format_StringZeroLength => GetResourceString("Format_StringZeroLength"); internal static string IndexOutOfRange_ArrayRankIndex => GetResourceString("IndexOutOfRange_ArrayRankIndex"); internal static string IndexOutOfRange_UMSPosition => GetResourceString("IndexOutOfRange_UMSPosition"); internal static string InsufficientMemory_MemFailPoint => GetResourceString("InsufficientMemory_MemFailPoint"); internal static string InsufficientMemory_MemFailPoint_TooBig => GetResourceString("InsufficientMemory_MemFailPoint_TooBig"); internal static string InsufficientMemory_MemFailPoint_VAFrag => GetResourceString("InsufficientMemory_MemFailPoint_VAFrag"); internal static string Interop_COM_TypeMismatch => GetResourceString("Interop_COM_TypeMismatch"); internal static string Interop_Marshal_Unmappable_Char => GetResourceString("Interop_Marshal_Unmappable_Char"); internal static string Interop_Marshal_SafeHandle_InvalidOperation => GetResourceString("Interop_Marshal_SafeHandle_InvalidOperation"); internal static string Interop_Marshal_CannotCreateSafeHandleField => GetResourceString("Interop_Marshal_CannotCreateSafeHandleField"); internal static string Interop_Marshal_CannotCreateCriticalHandleField => GetResourceString("Interop_Marshal_CannotCreateCriticalHandleField"); internal static string InvalidCast_CannotCastNullToValueType => GetResourceString("InvalidCast_CannotCastNullToValueType"); internal static string InvalidCast_CannotCoerceByRefVariant => GetResourceString("InvalidCast_CannotCoerceByRefVariant"); internal static string InvalidCast_DBNull => GetResourceString("InvalidCast_DBNull"); internal static string InvalidCast_Empty => GetResourceString("InvalidCast_Empty"); internal static string InvalidCast_FromDBNull => GetResourceString("InvalidCast_FromDBNull"); internal static string InvalidCast_FromTo => GetResourceString("InvalidCast_FromTo"); internal static string InvalidCast_IConvertible => GetResourceString("InvalidCast_IConvertible"); internal static string InvalidOperation_AsyncFlowCtrlCtxMismatch => GetResourceString("InvalidOperation_AsyncFlowCtrlCtxMismatch"); internal static string InvalidOperation_AsyncIOInProgress => GetResourceString("InvalidOperation_AsyncIOInProgress"); internal static string InvalidOperation_BadEmptyMethodBody => GetResourceString("InvalidOperation_BadEmptyMethodBody"); internal static string InvalidOperation_BadILGeneratorUsage => GetResourceString("InvalidOperation_BadILGeneratorUsage"); internal static string InvalidOperation_BadInstructionOrIndexOutOfBound => GetResourceString("InvalidOperation_BadInstructionOrIndexOutOfBound"); internal static string InvalidOperation_BadInterfaceNotAbstract => GetResourceString("InvalidOperation_BadInterfaceNotAbstract"); internal static string InvalidOperation_BadMethodBody => GetResourceString("InvalidOperation_BadMethodBody"); internal static string InvalidOperation_BadTypeAttributesNotAbstract => GetResourceString("InvalidOperation_BadTypeAttributesNotAbstract"); internal static string InvalidOperation_CalledTwice => GetResourceString("InvalidOperation_CalledTwice"); internal static string InvalidOperation_CannotImportGlobalFromDifferentModule => GetResourceString("InvalidOperation_CannotImportGlobalFromDifferentModule"); internal static string InvalidOperation_CannotRegisterSecondResolver => GetResourceString("InvalidOperation_CannotRegisterSecondResolver"); internal static string InvalidOperation_CannotRestoreUnsupressedFlow => GetResourceString("InvalidOperation_CannotRestoreUnsupressedFlow"); internal static string InvalidOperation_CannotSupressFlowMultipleTimes => GetResourceString("InvalidOperation_CannotSupressFlowMultipleTimes"); internal static string InvalidOperation_CannotUseAFCMultiple => GetResourceString("InvalidOperation_CannotUseAFCMultiple"); internal static string InvalidOperation_CannotUseAFCOtherThread => GetResourceString("InvalidOperation_CannotUseAFCOtherThread"); internal static string InvalidOperation_CollectionCorrupted => GetResourceString("InvalidOperation_CollectionCorrupted"); internal static string InvalidOperation_ComputerName => GetResourceString("InvalidOperation_ComputerName"); internal static string InvalidOperation_ConcurrentOperationsNotSupported => GetResourceString("InvalidOperation_ConcurrentOperationsNotSupported"); internal static string InvalidOperation_ConstructorNotAllowedOnInterface => GetResourceString("InvalidOperation_ConstructorNotAllowedOnInterface"); internal static string InvalidOperation_DateTimeParsing => GetResourceString("InvalidOperation_DateTimeParsing"); internal static string InvalidOperation_DefaultConstructorILGen => GetResourceString("InvalidOperation_DefaultConstructorILGen"); internal static string InvalidOperation_EnumEnded => GetResourceString("InvalidOperation_EnumEnded"); internal static string InvalidOperation_EnumFailedVersion => GetResourceString("InvalidOperation_EnumFailedVersion"); internal static string InvalidOperation_EnumNotStarted => GetResourceString("InvalidOperation_EnumNotStarted"); internal static string InvalidOperation_EnumOpCantHappen => GetResourceString("InvalidOperation_EnumOpCantHappen"); internal static string InvalidOperation_EventInfoNotAvailable => GetResourceString("InvalidOperation_EventInfoNotAvailable"); internal static string InvalidOperation_GenericParametersAlreadySet => GetResourceString("InvalidOperation_GenericParametersAlreadySet"); internal static string InvalidOperation_GetVersion => GetResourceString("InvalidOperation_GetVersion"); internal static string InvalidOperation_GlobalsHaveBeenCreated => GetResourceString("InvalidOperation_GlobalsHaveBeenCreated"); internal static string InvalidOperation_HandleIsNotInitialized => GetResourceString("InvalidOperation_HandleIsNotInitialized"); internal static string InvalidOperation_HandleIsNotPinned => GetResourceString("InvalidOperation_HandleIsNotPinned"); internal static string InvalidOperation_HashInsertFailed => GetResourceString("InvalidOperation_HashInsertFailed"); internal static string InvalidOperation_IComparerFailed => GetResourceString("InvalidOperation_IComparerFailed"); internal static string InvalidOperation_MethodBaked => GetResourceString("InvalidOperation_MethodBaked"); internal static string InvalidOperation_MethodBuilderBaked => GetResourceString("InvalidOperation_MethodBuilderBaked"); internal static string InvalidOperation_MethodHasBody => GetResourceString("InvalidOperation_MethodHasBody"); internal static string InvalidOperation_MustCallInitialize => GetResourceString("InvalidOperation_MustCallInitialize"); internal static string InvalidOperation_NativeOverlappedReused => GetResourceString("InvalidOperation_NativeOverlappedReused"); internal static string InvalidOperation_NoMultiModuleAssembly => GetResourceString("InvalidOperation_NoMultiModuleAssembly"); internal static string InvalidOperation_NoPublicAddMethod => GetResourceString("InvalidOperation_NoPublicAddMethod"); internal static string InvalidOperation_NoPublicRemoveMethod => GetResourceString("InvalidOperation_NoPublicRemoveMethod"); internal static string InvalidOperation_NotADebugModule => GetResourceString("InvalidOperation_NotADebugModule"); internal static string InvalidOperation_NotAllowedInDynamicMethod => GetResourceString("InvalidOperation_NotAllowedInDynamicMethod"); internal static string InvalidOperation_NotAVarArgCallingConvention => GetResourceString("InvalidOperation_NotAVarArgCallingConvention"); internal static string InvalidOperation_NotGenericType => GetResourceString("InvalidOperation_NotGenericType"); internal static string InvalidOperation_NotWithConcurrentGC => GetResourceString("InvalidOperation_NotWithConcurrentGC"); internal static string InvalidOperation_NoUnderlyingTypeOnEnum => GetResourceString("InvalidOperation_NoUnderlyingTypeOnEnum"); internal static string InvalidOperation_NoValue => GetResourceString("InvalidOperation_NoValue"); internal static string InvalidOperation_NullArray => GetResourceString("InvalidOperation_NullArray"); internal static string InvalidOperation_NullContext => GetResourceString("InvalidOperation_NullContext"); internal static string InvalidOperation_NullModuleHandle => GetResourceString("InvalidOperation_NullModuleHandle"); internal static string InvalidOperation_OpenLocalVariableScope => GetResourceString("InvalidOperation_OpenLocalVariableScope"); internal static string InvalidOperation_Overlapped_Pack => GetResourceString("InvalidOperation_Overlapped_Pack"); internal static string InvalidOperation_PropertyInfoNotAvailable => GetResourceString("InvalidOperation_PropertyInfoNotAvailable"); internal static string InvalidOperation_ReadOnly => GetResourceString("InvalidOperation_ReadOnly"); internal static string InvalidOperation_ResMgrBadResSet_Type => GetResourceString("InvalidOperation_ResMgrBadResSet_Type"); internal static string InvalidOperation_ResourceNotStream_Name => GetResourceString("InvalidOperation_ResourceNotStream_Name"); internal static string InvalidOperation_ResourceNotString_Name => GetResourceString("InvalidOperation_ResourceNotString_Name"); internal static string InvalidOperation_ResourceNotString_Type => GetResourceString("InvalidOperation_ResourceNotString_Type"); internal static string InvalidOperation_SetLatencyModeNoGC => GetResourceString("InvalidOperation_SetLatencyModeNoGC"); internal static string InvalidOperation_ShouldNotHaveMethodBody => GetResourceString("InvalidOperation_ShouldNotHaveMethodBody"); internal static string InvalidOperation_ThreadWrongThreadStart => GetResourceString("InvalidOperation_ThreadWrongThreadStart"); internal static string InvalidOperation_TimeoutsNotSupported => GetResourceString("InvalidOperation_TimeoutsNotSupported"); internal static string InvalidOperation_TimerAlreadyClosed => GetResourceString("InvalidOperation_TimerAlreadyClosed"); internal static string InvalidOperation_TypeHasBeenCreated => GetResourceString("InvalidOperation_TypeHasBeenCreated"); internal static string InvalidOperation_TypeNotCreated => GetResourceString("InvalidOperation_TypeNotCreated"); internal static string InvalidOperation_UnderlyingArrayListChanged => GetResourceString("InvalidOperation_UnderlyingArrayListChanged"); internal static string InvalidOperation_UnknownEnumType => GetResourceString("InvalidOperation_UnknownEnumType"); internal static string InvalidOperation_WrongAsyncResultOrEndCalledMultiple => GetResourceString("InvalidOperation_WrongAsyncResultOrEndCalledMultiple"); internal static string InvalidProgram_Default => GetResourceString("InvalidProgram_Default"); internal static string InvalidTimeZone_InvalidRegistryData => GetResourceString("InvalidTimeZone_InvalidRegistryData"); internal static string InvariantFailed => GetResourceString("InvariantFailed"); internal static string InvariantFailed_Cnd => GetResourceString("InvariantFailed_Cnd"); internal static string IO_NoFileTableInInMemoryAssemblies => GetResourceString("IO_NoFileTableInInMemoryAssemblies"); internal static string IO_EOF_ReadBeyondEOF => GetResourceString("IO_EOF_ReadBeyondEOF"); internal static string IO_FileLoad => GetResourceString("IO_FileLoad"); internal static string IO_FileName_Name => GetResourceString("IO_FileName_Name"); internal static string IO_FileNotFound => GetResourceString("IO_FileNotFound"); internal static string IO_FileNotFound_FileName => GetResourceString("IO_FileNotFound_FileName"); internal static string IO_AlreadyExists_Name => GetResourceString("IO_AlreadyExists_Name"); internal static string IO_DiskFull_Path_AllocationSize => GetResourceString("IO_DiskFull_Path_AllocationSize"); internal static string IO_FileTooLarge_Path_AllocationSize => GetResourceString("IO_FileTooLarge_Path_AllocationSize"); internal static string IO_BindHandleFailed => GetResourceString("IO_BindHandleFailed"); internal static string IO_FileExists_Name => GetResourceString("IO_FileExists_Name"); internal static string IO_FileStreamHandlePosition => GetResourceString("IO_FileStreamHandlePosition"); internal static string IO_FileTooLong2GB => GetResourceString("IO_FileTooLong2GB"); internal static string IO_FileTooLong => GetResourceString("IO_FileTooLong"); internal static string IO_FileTooLongOrHandleNotSync => GetResourceString("IO_FileTooLongOrHandleNotSync"); internal static string IO_FixedCapacity => GetResourceString("IO_FixedCapacity"); internal static string IO_InvalidStringLen_Len => GetResourceString("IO_InvalidStringLen_Len"); internal static string IO_SeekAppendOverwrite => GetResourceString("IO_SeekAppendOverwrite"); internal static string IO_SeekBeforeBegin => GetResourceString("IO_SeekBeforeBegin"); internal static string IO_SetLengthAppendTruncate => GetResourceString("IO_SetLengthAppendTruncate"); internal static string IO_SharingViolation_File => GetResourceString("IO_SharingViolation_File"); internal static string IO_SharingViolation_NoFileName => GetResourceString("IO_SharingViolation_NoFileName"); internal static string IO_StreamTooLong => GetResourceString("IO_StreamTooLong"); internal static string IO_PathNotFound_NoPathName => GetResourceString("IO_PathNotFound_NoPathName"); internal static string IO_PathNotFound_Path => GetResourceString("IO_PathNotFound_Path"); internal static string IO_PathTooLong => GetResourceString("IO_PathTooLong"); internal static string IO_PathTooLong_Path => GetResourceString("IO_PathTooLong_Path"); internal static string IO_UnknownFileName => GetResourceString("IO_UnknownFileName"); internal static string Lazy_CreateValue_NoParameterlessCtorForT => GetResourceString("Lazy_CreateValue_NoParameterlessCtorForT"); internal static string Lazy_ctor_ModeInvalid => GetResourceString("Lazy_ctor_ModeInvalid"); internal static string Lazy_StaticInit_InvalidOperation => GetResourceString("Lazy_StaticInit_InvalidOperation"); internal static string Lazy_ToString_ValueNotCreated => GetResourceString("Lazy_ToString_ValueNotCreated"); internal static string Lazy_Value_RecursiveCallsToValue => GetResourceString("Lazy_Value_RecursiveCallsToValue"); internal static string ManualResetEventSlim_ctor_SpinCountOutOfRange => GetResourceString("ManualResetEventSlim_ctor_SpinCountOutOfRange"); internal static string ManualResetEventSlim_ctor_TooManyWaiters => GetResourceString("ManualResetEventSlim_ctor_TooManyWaiters"); internal static string ManualResetEventSlim_Disposed => GetResourceString("ManualResetEventSlim_Disposed"); internal static string Marshaler_StringTooLong => GetResourceString("Marshaler_StringTooLong"); internal static string MissingConstructor_Name => GetResourceString("MissingConstructor_Name"); internal static string MissingField => GetResourceString("MissingField"); internal static string MissingField_Name => GetResourceString("MissingField_Name"); internal static string MissingManifestResource_MultipleBlobs => GetResourceString("MissingManifestResource_MultipleBlobs"); internal static string MissingManifestResource_NoNeutralAsm => GetResourceString("MissingManifestResource_NoNeutralAsm"); internal static string MissingManifestResource_NoNeutralDisk => GetResourceString("MissingManifestResource_NoNeutralDisk"); internal static string MissingMember => GetResourceString("MissingMember"); internal static string MissingMember_Name => GetResourceString("MissingMember_Name"); internal static string MissingMemberNestErr => GetResourceString("MissingMemberNestErr"); internal static string MissingMemberTypeRef => GetResourceString("MissingMemberTypeRef"); internal static string MissingMethod_Name => GetResourceString("MissingMethod_Name"); internal static string MissingSatelliteAssembly_Culture_Name => GetResourceString("MissingSatelliteAssembly_Culture_Name"); internal static string MissingSatelliteAssembly_Default => GetResourceString("MissingSatelliteAssembly_Default"); internal static string Multicast_Combine => GetResourceString("Multicast_Combine"); internal static string MustUseCCRewrite => GetResourceString("MustUseCCRewrite"); internal static string NotSupported_AbstractNonCLS => GetResourceString("NotSupported_AbstractNonCLS"); internal static string NotSupported_ActivAttr => GetResourceString("NotSupported_ActivAttr"); internal static string NotSupported_AssemblyLoadFromHash => GetResourceString("NotSupported_AssemblyLoadFromHash"); internal static string NotSupported_ByRefToByRefLikeReturn => GetResourceString("NotSupported_ByRefToByRefLikeReturn"); internal static string NotSupported_ByRefToVoidReturn => GetResourceString("NotSupported_ByRefToVoidReturn"); internal static string NotSupported_CallToVarArg => GetResourceString("NotSupported_CallToVarArg"); internal static string NotSupported_CannotCallEqualsOnSpan => GetResourceString("NotSupported_CannotCallEqualsOnSpan"); internal static string NotSupported_CannotCallGetHashCodeOnSpan => GetResourceString("NotSupported_CannotCallGetHashCodeOnSpan"); internal static string NotSupported_ChangeType => GetResourceString("NotSupported_ChangeType"); internal static string NotSupported_CreateInstanceWithTypeBuilder => GetResourceString("NotSupported_CreateInstanceWithTypeBuilder"); internal static string NotSupported_DBNullSerial => GetResourceString("NotSupported_DBNullSerial"); internal static string NotSupported_DynamicAssembly => GetResourceString("NotSupported_DynamicAssembly"); internal static string NotSupported_DynamicMethodFlags => GetResourceString("NotSupported_DynamicMethodFlags"); internal static string NotSupported_DynamicModule => GetResourceString("NotSupported_DynamicModule"); internal static string NotSupported_FixedSizeCollection => GetResourceString("NotSupported_FixedSizeCollection"); internal static string InvalidOperation_SpanOverlappedOperation => GetResourceString("InvalidOperation_SpanOverlappedOperation"); internal static string NotSupported_IllegalOneByteBranch => GetResourceString("NotSupported_IllegalOneByteBranch"); internal static string NotSupported_KeyCollectionSet => GetResourceString("NotSupported_KeyCollectionSet"); internal static string NotSupported_MaxWaitHandles => GetResourceString("NotSupported_MaxWaitHandles"); internal static string NotSupported_MemStreamNotExpandable => GetResourceString("NotSupported_MemStreamNotExpandable"); internal static string NotSupported_MustBeModuleBuilder => GetResourceString("NotSupported_MustBeModuleBuilder"); internal static string NotSupported_NoCodepageData => GetResourceString("NotSupported_NoCodepageData"); internal static string InvalidOperation_FunctionMissingUnmanagedCallersOnly => GetResourceString("InvalidOperation_FunctionMissingUnmanagedCallersOnly"); internal static string NotSupported_NonReflectedType => GetResourceString("NotSupported_NonReflectedType"); internal static string NotSupported_NoParentDefaultConstructor => GetResourceString("NotSupported_NoParentDefaultConstructor"); internal static string NotSupported_NoTypeInfo => GetResourceString("NotSupported_NoTypeInfo"); internal static string NotSupported_NYI => GetResourceString("NotSupported_NYI"); internal static string NotSupported_ObsoleteResourcesFile => GetResourceString("NotSupported_ObsoleteResourcesFile"); internal static string NotSupported_OutputStreamUsingTypeBuilder => GetResourceString("NotSupported_OutputStreamUsingTypeBuilder"); internal static string NotSupported_RangeCollection => GetResourceString("NotSupported_RangeCollection"); internal static string NotSupported_Reading => GetResourceString("NotSupported_Reading"); internal static string NotSupported_ReadOnlyCollection => GetResourceString("NotSupported_ReadOnlyCollection"); internal static string NotSupported_ResourceObjectSerialization => GetResourceString("NotSupported_ResourceObjectSerialization"); internal static string NotSupported_StringComparison => GetResourceString("NotSupported_StringComparison"); internal static string NotSupported_SubclassOverride => GetResourceString("NotSupported_SubclassOverride"); internal static string NotSupported_SymbolMethod => GetResourceString("NotSupported_SymbolMethod"); internal static string NotSupported_Type => GetResourceString("NotSupported_Type"); internal static string NotSupported_TypeNotYetCreated => GetResourceString("NotSupported_TypeNotYetCreated"); internal static string NotSupported_UmsSafeBuffer => GetResourceString("NotSupported_UmsSafeBuffer"); internal static string NotSupported_UnitySerHolder => GetResourceString("NotSupported_UnitySerHolder"); internal static string NotSupported_UnknownTypeCode => GetResourceString("NotSupported_UnknownTypeCode"); internal static string NotSupported_UnreadableStream => GetResourceString("NotSupported_UnreadableStream"); internal static string NotSupported_UnseekableStream => GetResourceString("NotSupported_UnseekableStream"); internal static string NotSupported_UnwritableStream => GetResourceString("NotSupported_UnwritableStream"); internal static string NotSupported_ValueCollectionSet => GetResourceString("NotSupported_ValueCollectionSet"); internal static string NotSupported_Writing => GetResourceString("NotSupported_Writing"); internal static string NotSupported_WrongResourceReader_Type => GetResourceString("NotSupported_WrongResourceReader_Type"); internal static string ObjectDisposed_FileClosed => GetResourceString("ObjectDisposed_FileClosed"); internal static string ObjectDisposed_Generic => GetResourceString("ObjectDisposed_Generic"); internal static string ObjectDisposed_ObjectName_Name => GetResourceString("ObjectDisposed_ObjectName_Name"); internal static string ObjectDisposed_WriterClosed => GetResourceString("ObjectDisposed_WriterClosed"); internal static string ObjectDisposed_ReaderClosed => GetResourceString("ObjectDisposed_ReaderClosed"); internal static string ObjectDisposed_ResourceSet => GetResourceString("ObjectDisposed_ResourceSet"); internal static string ObjectDisposed_StreamClosed => GetResourceString("ObjectDisposed_StreamClosed"); internal static string ObjectDisposed_ViewAccessorClosed => GetResourceString("ObjectDisposed_ViewAccessorClosed"); internal static string ObjectDisposed_SafeHandleClosed => GetResourceString("ObjectDisposed_SafeHandleClosed"); internal static string OperationCanceled => GetResourceString("OperationCanceled"); internal static string Overflow_Byte => GetResourceString("Overflow_Byte"); internal static string Overflow_Char => GetResourceString("Overflow_Char"); internal static string Overflow_Currency => GetResourceString("Overflow_Currency"); internal static string Overflow_Decimal => GetResourceString("Overflow_Decimal"); internal static string Overflow_Duration => GetResourceString("Overflow_Duration"); internal static string Overflow_Int16 => GetResourceString("Overflow_Int16"); internal static string Overflow_Int32 => GetResourceString("Overflow_Int32"); internal static string Overflow_Int64 => GetResourceString("Overflow_Int64"); internal static string Overflow_NegateTwosCompNum => GetResourceString("Overflow_NegateTwosCompNum"); internal static string Overflow_NegativeUnsigned => GetResourceString("Overflow_NegativeUnsigned"); internal static string Overflow_SByte => GetResourceString("Overflow_SByte"); internal static string Overflow_TimeSpanElementTooLarge => GetResourceString("Overflow_TimeSpanElementTooLarge"); internal static string Overflow_TimeSpanTooLong => GetResourceString("Overflow_TimeSpanTooLong"); internal static string Overflow_UInt16 => GetResourceString("Overflow_UInt16"); internal static string Overflow_UInt32 => GetResourceString("Overflow_UInt32"); internal static string Overflow_UInt64 => GetResourceString("Overflow_UInt64"); internal static string PlatformNotSupported_ReflectionOnly => GetResourceString("PlatformNotSupported_ReflectionOnly"); internal static string PlatformNotSupported_Remoting => GetResourceString("PlatformNotSupported_Remoting"); internal static string PlatformNotSupported_SecureBinarySerialization => GetResourceString("PlatformNotSupported_SecureBinarySerialization"); internal static string PlatformNotSupported_StrongNameSigning => GetResourceString("PlatformNotSupported_StrongNameSigning"); internal static string PlatformNotSupported_ITypeInfo => GetResourceString("PlatformNotSupported_ITypeInfo"); internal static string PlatformNotSupported_IExpando => GetResourceString("PlatformNotSupported_IExpando"); internal static string PlatformNotSupported_AppDomains => GetResourceString("PlatformNotSupported_AppDomains"); internal static string PlatformNotSupported_CAS => GetResourceString("PlatformNotSupported_CAS"); internal static string PlatformNotSupported_Principal => GetResourceString("PlatformNotSupported_Principal"); internal static string PlatformNotSupported_ThreadAbort => GetResourceString("PlatformNotSupported_ThreadAbort"); internal static string PlatformNotSupported_ThreadSuspend => GetResourceString("PlatformNotSupported_ThreadSuspend"); internal static string PostconditionFailed => GetResourceString("PostconditionFailed"); internal static string PostconditionFailed_Cnd => GetResourceString("PostconditionFailed_Cnd"); internal static string PostconditionOnExceptionFailed => GetResourceString("PostconditionOnExceptionFailed"); internal static string PostconditionOnExceptionFailed_Cnd => GetResourceString("PostconditionOnExceptionFailed_Cnd"); internal static string PreconditionFailed => GetResourceString("PreconditionFailed"); internal static string PreconditionFailed_Cnd => GetResourceString("PreconditionFailed_Cnd"); internal static string Rank_MultiDimNotSupported => GetResourceString("Rank_MultiDimNotSupported"); internal static string Rank_MustMatch => GetResourceString("Rank_MustMatch"); internal static string ResourceReaderIsClosed => GetResourceString("ResourceReaderIsClosed"); internal static string Resources_StreamNotValid => GetResourceString("Resources_StreamNotValid"); internal static string RFLCT_AmbigCust => GetResourceString("RFLCT_AmbigCust"); internal static string RFLCT_Ambiguous => GetResourceString("RFLCT_Ambiguous"); internal static string InvalidFilterCriteriaException_CritInt => GetResourceString("InvalidFilterCriteriaException_CritInt"); internal static string InvalidFilterCriteriaException_CritString => GetResourceString("InvalidFilterCriteriaException_CritString"); internal static string RFLCT_InvalidFieldFail => GetResourceString("RFLCT_InvalidFieldFail"); internal static string RFLCT_InvalidPropFail => GetResourceString("RFLCT_InvalidPropFail"); internal static string RFLCT_Targ_ITargMismatch => GetResourceString("RFLCT_Targ_ITargMismatch"); internal static string RFLCT_Targ_StatFldReqTarg => GetResourceString("RFLCT_Targ_StatFldReqTarg"); internal static string RFLCT_Targ_StatMethReqTarg => GetResourceString("RFLCT_Targ_StatMethReqTarg"); internal static string RuntimeWrappedException => GetResourceString("RuntimeWrappedException"); internal static string StandardOleMarshalObjectGetMarshalerFailed => GetResourceString("StandardOleMarshalObjectGetMarshalerFailed"); internal static string Security_CannotReadRegistryData => GetResourceString("Security_CannotReadRegistryData"); internal static string Security_RegistryPermission => GetResourceString("Security_RegistryPermission"); internal static string SemaphoreSlim_ctor_InitialCountWrong => GetResourceString("SemaphoreSlim_ctor_InitialCountWrong"); internal static string SemaphoreSlim_ctor_MaxCountWrong => GetResourceString("SemaphoreSlim_ctor_MaxCountWrong"); internal static string SemaphoreSlim_Disposed => GetResourceString("SemaphoreSlim_Disposed"); internal static string SemaphoreSlim_Release_CountWrong => GetResourceString("SemaphoreSlim_Release_CountWrong"); internal static string SemaphoreSlim_Wait_TimeoutWrong => GetResourceString("SemaphoreSlim_Wait_TimeoutWrong"); internal static string Serialization_BadParameterInfo => GetResourceString("Serialization_BadParameterInfo"); internal static string Serialization_CorruptField => GetResourceString("Serialization_CorruptField"); internal static string Serialization_DateTimeTicksOutOfRange => GetResourceString("Serialization_DateTimeTicksOutOfRange"); internal static string Serialization_DelegatesNotSupported => GetResourceString("Serialization_DelegatesNotSupported"); internal static string Serialization_InsufficientState => GetResourceString("Serialization_InsufficientState"); internal static string Serialization_InvalidData => GetResourceString("Serialization_InvalidData"); internal static string Serialization_InvalidEscapeSequence => GetResourceString("Serialization_InvalidEscapeSequence"); internal static string Serialization_InvalidOnDeser => GetResourceString("Serialization_InvalidOnDeser"); internal static string Serialization_InvalidPtrValue => GetResourceString("Serialization_InvalidPtrValue"); internal static string Serialization_InvalidType => GetResourceString("Serialization_InvalidType"); internal static string Serialization_KeyValueDifferentSizes => GetResourceString("Serialization_KeyValueDifferentSizes"); internal static string Serialization_MissingDateTimeData => GetResourceString("Serialization_MissingDateTimeData"); internal static string Serialization_MissingKeys => GetResourceString("Serialization_MissingKeys"); internal static string Serialization_MissingValues => GetResourceString("Serialization_MissingValues"); internal static string Serialization_NoParameterInfo => GetResourceString("Serialization_NoParameterInfo"); internal static string Serialization_NotFound => GetResourceString("Serialization_NotFound"); internal static string Serialization_NullKey => GetResourceString("Serialization_NullKey"); internal static string Serialization_OptionalFieldVersionValue => GetResourceString("Serialization_OptionalFieldVersionValue"); internal static string Serialization_SameNameTwice => GetResourceString("Serialization_SameNameTwice"); internal static string Serialization_StringBuilderCapacity => GetResourceString("Serialization_StringBuilderCapacity"); internal static string Serialization_StringBuilderMaxCapacity => GetResourceString("Serialization_StringBuilderMaxCapacity"); internal static string SpinLock_Exit_SynchronizationLockException => GetResourceString("SpinLock_Exit_SynchronizationLockException"); internal static string SpinLock_IsHeldByCurrentThread => GetResourceString("SpinLock_IsHeldByCurrentThread"); internal static string SpinLock_TryEnter_ArgumentOutOfRange => GetResourceString("SpinLock_TryEnter_ArgumentOutOfRange"); internal static string SpinLock_TryEnter_LockRecursionException => GetResourceString("SpinLock_TryEnter_LockRecursionException"); internal static string SpinLock_TryReliableEnter_ArgumentException => GetResourceString("SpinLock_TryReliableEnter_ArgumentException"); internal static string SpinWait_SpinUntil_ArgumentNull => GetResourceString("SpinWait_SpinUntil_ArgumentNull"); internal static string SpinWait_SpinUntil_TimeoutWrong => GetResourceString("SpinWait_SpinUntil_TimeoutWrong"); internal static string Task_ContinueWith_ESandLR => GetResourceString("Task_ContinueWith_ESandLR"); internal static string Task_ContinueWith_NotOnAnything => GetResourceString("Task_ContinueWith_NotOnAnything"); internal static string Task_InvalidTimerTimeSpan => GetResourceString("Task_InvalidTimerTimeSpan"); internal static string Task_Delay_InvalidMillisecondsDelay => GetResourceString("Task_Delay_InvalidMillisecondsDelay"); internal static string Task_Dispose_NotCompleted => GetResourceString("Task_Dispose_NotCompleted"); internal static string Task_FromAsync_LongRunning => GetResourceString("Task_FromAsync_LongRunning"); internal static string Task_FromAsync_PreferFairness => GetResourceString("Task_FromAsync_PreferFairness"); internal static string Task_MultiTaskContinuation_EmptyTaskList => GetResourceString("Task_MultiTaskContinuation_EmptyTaskList"); internal static string Task_MultiTaskContinuation_FireOptions => GetResourceString("Task_MultiTaskContinuation_FireOptions"); internal static string Task_MultiTaskContinuation_NullTask => GetResourceString("Task_MultiTaskContinuation_NullTask"); internal static string Task_RunSynchronously_AlreadyStarted => GetResourceString("Task_RunSynchronously_AlreadyStarted"); internal static string Task_RunSynchronously_Continuation => GetResourceString("Task_RunSynchronously_Continuation"); internal static string Task_RunSynchronously_Promise => GetResourceString("Task_RunSynchronously_Promise"); internal static string Task_RunSynchronously_TaskCompleted => GetResourceString("Task_RunSynchronously_TaskCompleted"); internal static string Task_Start_AlreadyStarted => GetResourceString("Task_Start_AlreadyStarted"); internal static string Task_Start_ContinuationTask => GetResourceString("Task_Start_ContinuationTask"); internal static string Task_Start_Promise => GetResourceString("Task_Start_Promise"); internal static string Task_Start_TaskCompleted => GetResourceString("Task_Start_TaskCompleted"); internal static string Task_ThrowIfDisposed => GetResourceString("Task_ThrowIfDisposed"); internal static string Task_WaitMulti_NullTask => GetResourceString("Task_WaitMulti_NullTask"); internal static string TaskCanceledException_ctor_DefaultMessage => GetResourceString("TaskCanceledException_ctor_DefaultMessage"); internal static string TaskCompletionSourceT_TrySetException_NoExceptions => GetResourceString("TaskCompletionSourceT_TrySetException_NoExceptions"); internal static string TaskCompletionSourceT_TrySetException_NullException => GetResourceString("TaskCompletionSourceT_TrySetException_NullException"); internal static string TaskExceptionHolder_UnhandledException => GetResourceString("TaskExceptionHolder_UnhandledException"); internal static string TaskExceptionHolder_UnknownExceptionType => GetResourceString("TaskExceptionHolder_UnknownExceptionType"); internal static string TaskScheduler_ExecuteTask_WrongTaskScheduler => GetResourceString("TaskScheduler_ExecuteTask_WrongTaskScheduler"); internal static string TaskScheduler_FromCurrentSynchronizationContext_NoCurrent => GetResourceString("TaskScheduler_FromCurrentSynchronizationContext_NoCurrent"); internal static string TaskScheduler_InconsistentStateAfterTryExecuteTaskInline => GetResourceString("TaskScheduler_InconsistentStateAfterTryExecuteTaskInline"); internal static string TaskSchedulerException_ctor_DefaultMessage => GetResourceString("TaskSchedulerException_ctor_DefaultMessage"); internal static string TaskT_DebuggerNoResult => GetResourceString("TaskT_DebuggerNoResult"); internal static string TaskT_TransitionToFinal_AlreadyCompleted => GetResourceString("TaskT_TransitionToFinal_AlreadyCompleted"); internal static string Thread_ApartmentState_ChangeFailed => GetResourceString("Thread_ApartmentState_ChangeFailed"); internal static string Thread_GetSetCompressedStack_NotSupported => GetResourceString("Thread_GetSetCompressedStack_NotSupported"); internal static string Thread_Operation_RequiresCurrentThread => GetResourceString("Thread_Operation_RequiresCurrentThread"); internal static string Threading_AbandonedMutexException => GetResourceString("Threading_AbandonedMutexException"); internal static string Threading_WaitHandleCannotBeOpenedException => GetResourceString("Threading_WaitHandleCannotBeOpenedException"); internal static string Threading_WaitHandleCannotBeOpenedException_InvalidHandle => GetResourceString("Threading_WaitHandleCannotBeOpenedException_InvalidHandle"); internal static string Threading_WaitHandleTooManyPosts => GetResourceString("Threading_WaitHandleTooManyPosts"); internal static string Threading_SemaphoreFullException => GetResourceString("Threading_SemaphoreFullException"); internal static string ThreadLocal_Disposed => GetResourceString("ThreadLocal_Disposed"); internal static string ThreadLocal_Value_RecursiveCallsToValue => GetResourceString("ThreadLocal_Value_RecursiveCallsToValue"); internal static string ThreadLocal_ValuesNotAvailable => GetResourceString("ThreadLocal_ValuesNotAvailable"); internal static string TimeZoneNotFound_MissingData => GetResourceString("TimeZoneNotFound_MissingData"); internal static string TypeInitialization_Default => GetResourceString("TypeInitialization_Default"); internal static string TypeInitialization_Type => GetResourceString("TypeInitialization_Type"); internal static string TypeLoad_ResolveNestedType => GetResourceString("TypeLoad_ResolveNestedType"); internal static string TypeLoad_ResolveType => GetResourceString("TypeLoad_ResolveType"); internal static string TypeLoad_ResolveTypeFromAssembly => GetResourceString("TypeLoad_ResolveTypeFromAssembly"); internal static string UnauthorizedAccess_IODenied_NoPathName => GetResourceString("UnauthorizedAccess_IODenied_NoPathName"); internal static string UnauthorizedAccess_IODenied_Path => GetResourceString("UnauthorizedAccess_IODenied_Path"); internal static string UnauthorizedAccess_MemStreamBuffer => GetResourceString("UnauthorizedAccess_MemStreamBuffer"); internal static string UnauthorizedAccess_RegistryKeyGeneric_Key => GetResourceString("UnauthorizedAccess_RegistryKeyGeneric_Key"); internal static string UnknownError_Num => GetResourceString("UnknownError_Num"); internal static string Verification_Exception => GetResourceString("Verification_Exception"); internal static string DebugAssertBanner => GetResourceString("DebugAssertBanner"); internal static string DebugAssertLongMessage => GetResourceString("DebugAssertLongMessage"); internal static string DebugAssertShortMessage => GetResourceString("DebugAssertShortMessage"); internal static string LockRecursionException_ReadAfterWriteNotAllowed => GetResourceString("LockRecursionException_ReadAfterWriteNotAllowed"); internal static string LockRecursionException_RecursiveReadNotAllowed => GetResourceString("LockRecursionException_RecursiveReadNotAllowed"); internal static string LockRecursionException_RecursiveWriteNotAllowed => GetResourceString("LockRecursionException_RecursiveWriteNotAllowed"); internal static string LockRecursionException_RecursiveUpgradeNotAllowed => GetResourceString("LockRecursionException_RecursiveUpgradeNotAllowed"); internal static string LockRecursionException_WriteAfterReadNotAllowed => GetResourceString("LockRecursionException_WriteAfterReadNotAllowed"); internal static string SynchronizationLockException_MisMatchedUpgrade => GetResourceString("SynchronizationLockException_MisMatchedUpgrade"); internal static string SynchronizationLockException_MisMatchedRead => GetResourceString("SynchronizationLockException_MisMatchedRead"); internal static string SynchronizationLockException_IncorrectDispose => GetResourceString("SynchronizationLockException_IncorrectDispose"); internal static string LockRecursionException_UpgradeAfterReadNotAllowed => GetResourceString("LockRecursionException_UpgradeAfterReadNotAllowed"); internal static string LockRecursionException_UpgradeAfterWriteNotAllowed => GetResourceString("LockRecursionException_UpgradeAfterWriteNotAllowed"); internal static string SynchronizationLockException_MisMatchedWrite => GetResourceString("SynchronizationLockException_MisMatchedWrite"); internal static string NotSupported_SignatureType => GetResourceString("NotSupported_SignatureType"); internal static string HashCode_HashCodeNotSupported => GetResourceString("HashCode_HashCodeNotSupported"); internal static string HashCode_EqualityNotSupported => GetResourceString("HashCode_EqualityNotSupported"); internal static string Arg_TypeNotSupported => GetResourceString("Arg_TypeNotSupported"); internal static string IO_InvalidReadLength => GetResourceString("IO_InvalidReadLength"); internal static string Arg_BasePathNotFullyQualified => GetResourceString("Arg_BasePathNotFullyQualified"); internal static string Arg_ElementsInSourceIsGreaterThanDestination => GetResourceString("Arg_ElementsInSourceIsGreaterThanDestination"); internal static string Arg_NullArgumentNullRef => GetResourceString("Arg_NullArgumentNullRef"); internal static string Argument_OverlapAlignmentMismatch => GetResourceString("Argument_OverlapAlignmentMismatch"); internal static string Arg_InsufficientNumberOfElements => GetResourceString("Arg_InsufficientNumberOfElements"); internal static string Arg_MustBeNullTerminatedString => GetResourceString("Arg_MustBeNullTerminatedString"); internal static string ArgumentOutOfRange_Week_ISO => GetResourceString("ArgumentOutOfRange_Week_ISO"); internal static string Argument_BadPInvokeMethod => GetResourceString("Argument_BadPInvokeMethod"); internal static string Argument_BadPInvokeOnInterface => GetResourceString("Argument_BadPInvokeOnInterface"); internal static string Argument_MethodRedefined => GetResourceString("Argument_MethodRedefined"); internal static string Argument_CannotExtractScalar => GetResourceString("Argument_CannotExtractScalar"); internal static string Argument_CannotParsePrecision => GetResourceString("Argument_CannotParsePrecision"); internal static string Argument_GWithPrecisionNotSupported => GetResourceString("Argument_GWithPrecisionNotSupported"); internal static string Argument_PrecisionTooLarge => GetResourceString("Argument_PrecisionTooLarge"); internal static string AssemblyDependencyResolver_FailedToLoadHostpolicy => GetResourceString("AssemblyDependencyResolver_FailedToLoadHostpolicy"); internal static string AssemblyDependencyResolver_FailedToResolveDependencies => GetResourceString("AssemblyDependencyResolver_FailedToResolveDependencies"); internal static string Arg_EnumNotCloneable => GetResourceString("Arg_EnumNotCloneable"); internal static string InvalidOp_InvalidNewEnumVariant => GetResourceString("InvalidOp_InvalidNewEnumVariant"); internal static string Argument_StructArrayTooLarge => GetResourceString("Argument_StructArrayTooLarge"); internal static string IndexOutOfRange_ArrayWithOffset => GetResourceString("IndexOutOfRange_ArrayWithOffset"); internal static string Serialization_DangerousDeserialization => GetResourceString("Serialization_DangerousDeserialization"); internal static string Serialization_DangerousDeserialization_Switch => GetResourceString("Serialization_DangerousDeserialization_Switch"); internal static string Argument_InvalidStartupHookSimpleAssemblyName => GetResourceString("Argument_InvalidStartupHookSimpleAssemblyName"); internal static string Argument_StartupHookAssemblyLoadFailed => GetResourceString("Argument_StartupHookAssemblyLoadFailed"); internal static string InvalidOperation_NonStaticComRegFunction => GetResourceString("InvalidOperation_NonStaticComRegFunction"); internal static string InvalidOperation_NonStaticComUnRegFunction => GetResourceString("InvalidOperation_NonStaticComUnRegFunction"); internal static string InvalidOperation_InvalidComRegFunctionSig => GetResourceString("InvalidOperation_InvalidComRegFunctionSig"); internal static string InvalidOperation_InvalidComUnRegFunctionSig => GetResourceString("InvalidOperation_InvalidComUnRegFunctionSig"); internal static string InvalidOperation_MultipleComRegFunctions => GetResourceString("InvalidOperation_MultipleComRegFunctions"); internal static string InvalidOperation_MultipleComUnRegFunctions => GetResourceString("InvalidOperation_MultipleComUnRegFunctions"); internal static string InvalidOperation_ResetGlobalComWrappersInstance => GetResourceString("InvalidOperation_ResetGlobalComWrappersInstance"); internal static string InvalidOperation_SuppliedInnerMustBeMarkedAggregation => GetResourceString("InvalidOperation_SuppliedInnerMustBeMarkedAggregation"); internal static string Argument_SpansMustHaveSameLength => GetResourceString("Argument_SpansMustHaveSameLength"); internal static string NotSupported_CannotWriteToBufferedStreamIfReadBufferCannotBeFlushed => GetResourceString("NotSupported_CannotWriteToBufferedStreamIfReadBufferCannotBeFlushed"); internal static string GenericInvalidData => GetResourceString("GenericInvalidData"); internal static string Argument_ResourceScopeWrongDirection => GetResourceString("Argument_ResourceScopeWrongDirection"); internal static string ArgumentNull_TypeRequiredByResourceScope => GetResourceString("ArgumentNull_TypeRequiredByResourceScope"); internal static string Argument_BadResourceScopeTypeBits => GetResourceString("Argument_BadResourceScopeTypeBits"); internal static string Argument_BadResourceScopeVisibilityBits => GetResourceString("Argument_BadResourceScopeVisibilityBits"); internal static string net_emptystringcall => GetResourceString("net_emptystringcall"); internal static string Argument_EmptyApplicationName => GetResourceString("Argument_EmptyApplicationName"); internal static string Argument_FrameworkNameInvalid => GetResourceString("Argument_FrameworkNameInvalid"); internal static string Argument_FrameworkNameInvalidVersion => GetResourceString("Argument_FrameworkNameInvalidVersion"); internal static string Argument_FrameworkNameMissingVersion => GetResourceString("Argument_FrameworkNameMissingVersion"); internal static string Argument_FrameworkNameTooShort => GetResourceString("Argument_FrameworkNameTooShort"); internal static string Arg_SwitchExpressionException => GetResourceString("Arg_SwitchExpressionException"); internal static string Arg_ContextMarshalException => GetResourceString("Arg_ContextMarshalException"); internal static string Arg_AppDomainUnloadedException => GetResourceString("Arg_AppDomainUnloadedException"); internal static string SwitchExpressionException_UnmatchedValue => GetResourceString("SwitchExpressionException_UnmatchedValue"); internal static string Encoding_UTF7_Disabled => GetResourceString("Encoding_UTF7_Disabled"); internal static string IDynamicInterfaceCastable_DoesNotImplementRequested => GetResourceString("IDynamicInterfaceCastable_DoesNotImplementRequested"); internal static string IDynamicInterfaceCastable_MissingImplementationAttribute => GetResourceString("IDynamicInterfaceCastable_MissingImplementationAttribute"); internal static string IDynamicInterfaceCastable_NotInterface => GetResourceString("IDynamicInterfaceCastable_NotInterface"); internal static string Arg_MustBeHalf => GetResourceString("Arg_MustBeHalf"); internal static string Arg_MustBeRune => GetResourceString("Arg_MustBeRune"); internal static string BinaryFormatter_SerializationDisallowed => GetResourceString("BinaryFormatter_SerializationDisallowed"); internal static string NotSupported_CodeBase => GetResourceString("NotSupported_CodeBase"); internal static string Activator_CannotCreateInstance => GetResourceString("Activator_CannotCreateInstance"); internal static string Argv_IncludeDoubleQuote => GetResourceString("Argv_IncludeDoubleQuote"); internal static string ResourceManager_ReflectionNotAllowed => GetResourceString("ResourceManager_ReflectionNotAllowed"); internal static string NotSupported_COM => GetResourceString("NotSupported_COM"); internal static string InvalidOperation_EmptyQueue => GetResourceString("InvalidOperation_EmptyQueue"); internal static string Arg_FileIsDirectory_Name => GetResourceString("Arg_FileIsDirectory_Name"); internal static string Arg_InvalidFileAttrs => GetResourceString("Arg_InvalidFileAttrs"); internal static string Arg_Path2IsRooted => GetResourceString("Arg_Path2IsRooted"); internal static string Arg_PathIsVolume => GetResourceString("Arg_PathIsVolume"); internal static string Argument_InvalidSubPath => GetResourceString("Argument_InvalidSubPath"); internal static string IO_SourceDestMustBeDifferent => GetResourceString("IO_SourceDestMustBeDifferent"); internal static string IO_SourceDestMustHaveSameRoot => GetResourceString("IO_SourceDestMustHaveSameRoot"); internal static string PlatformNotSupported_FileEncryption => GetResourceString("PlatformNotSupported_FileEncryption"); internal static string Arg_MemberInfoNotFound => GetResourceString("Arg_MemberInfoNotFound"); internal static string NullabilityInfoContext_NotSupported => GetResourceString("NullabilityInfoContext_NotSupported"); private static string InternalGetResourceString(string key) { if (key.Length == 0) { return key; } bool lockTaken = false; try { Monitor.Enter(_lock, ref lockTaken); if (_currentlyLoading != null && _currentlyLoading.Count > 0 && _currentlyLoading.LastIndexOf(key) != -1) { if (_infinitelyRecursingCount > 0) { return key; } _infinitelyRecursingCount++; string message = $"Infinite recursion during resource lookup within {"System.Private.CoreLib"}. This may be a bug in {"System.Private.CoreLib"}, or potentially in certain extensibility points such as assembly resolve events or CultureInfo names. Resource name: {key}"; Environment.FailFast(message); } if (_currentlyLoading == null) { _currentlyLoading = new List(); } if (!_resourceManagerInited) { RuntimeHelpers.RunClassConstructor(typeof(ResourceManager).TypeHandle); RuntimeHelpers.RunClassConstructor(typeof(ResourceReader).TypeHandle); RuntimeHelpers.RunClassConstructor(typeof(RuntimeResourceSet).TypeHandle); RuntimeHelpers.RunClassConstructor(typeof(BinaryReader).TypeHandle); _resourceManagerInited = true; } _currentlyLoading.Add(key); string @string = ResourceManager.GetString(key, null); _currentlyLoading.RemoveAt(_currentlyLoading.Count - 1); return @string ?? key; } catch { if (lockTaken) { s_resourceManager = null; _currentlyLoading = null; } throw; } finally { if (lockTaken) { Monitor.Exit(_lock); } } } private static bool UsingResourceKeys() { return s_usingResourceKeys; } internal static string GetResourceString(string resourceKey) { if (UsingResourceKeys()) { return resourceKey; } string result = null; try { result = InternalGetResourceString(resourceKey); } catch (MissingManifestResourceException) { } return result; } internal static string GetResourceString(string resourceKey, string defaultString) { string resourceString = GetResourceString(resourceKey); if (!(resourceKey == resourceString) && resourceString != null) { return resourceString; } return defaultString; } internal static string Format(string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(resourceFormat, p1); } internal static string Format(string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(resourceFormat, p1, p2); } internal static string Format(string resourceFormat, object p1, object p2, object p3) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2, p3); } return string.Format(resourceFormat, p1, p2, p3); } internal static string Format(string resourceFormat, params object[] args) { if (args != null) { if (UsingResourceKeys()) { return resourceFormat + ", " + string.Join(", ", args); } return string.Format(resourceFormat, args); } return resourceFormat; } internal static string Format(IFormatProvider provider, string resourceFormat, object p1) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1); } return string.Format(provider, resourceFormat, p1); } internal static string Format(IFormatProvider provider, string resourceFormat, object p1, object p2) { if (UsingResourceKeys()) { return string.Join(", ", resourceFormat, p1, p2); } return string.Format(provider, resourceFormat, p1, p2); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class StackOverflowException : SystemException { public StackOverflowException() : base(SR.Arg_StackOverflowException) { base.HResult = -2147023895; } public StackOverflowException(string? message) : base(message) { base.HResult = -2147023895; } public StackOverflowException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2147023895; } private StackOverflowException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class StringComparer : IComparer, IEqualityComparer, IComparer, IEqualityComparer { public static StringComparer InvariantCulture => CultureAwareComparer.InvariantCaseSensitiveInstance; public static StringComparer InvariantCultureIgnoreCase => CultureAwareComparer.InvariantIgnoreCaseInstance; public static StringComparer CurrentCulture => new CultureAwareComparer(CultureInfo.CurrentCulture, CompareOptions.None); public static StringComparer CurrentCultureIgnoreCase => new CultureAwareComparer(CultureInfo.CurrentCulture, CompareOptions.IgnoreCase); public static StringComparer Ordinal => OrdinalCaseSensitiveComparer.Instance; public static StringComparer OrdinalIgnoreCase => OrdinalIgnoreCaseComparer.Instance; public static StringComparer FromComparison(StringComparison comparisonType) { return comparisonType switch { StringComparison.CurrentCulture => CurrentCulture, StringComparison.CurrentCultureIgnoreCase => CurrentCultureIgnoreCase, StringComparison.InvariantCulture => InvariantCulture, StringComparison.InvariantCultureIgnoreCase => InvariantCultureIgnoreCase, StringComparison.Ordinal => Ordinal, StringComparison.OrdinalIgnoreCase => OrdinalIgnoreCase, _ => throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType"), }; } public static StringComparer Create(CultureInfo culture, bool ignoreCase) { if (culture == null) { throw new ArgumentNullException("culture"); } return new CultureAwareComparer(culture, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None); } public static StringComparer Create(CultureInfo culture, CompareOptions options) { if (culture == null) { throw new ArgumentNullException("culture"); } return new CultureAwareComparer(culture, options); } public static bool IsWellKnownOrdinalComparer(IEqualityComparer? comparer, out bool ignoreCase) { if (comparer is IInternalStringEqualityComparer internalStringEqualityComparer) { comparer = internalStringEqualityComparer.GetUnderlyingEqualityComparer(); } if (!(comparer is StringComparer stringComparer)) { if (comparer is GenericEqualityComparer) { ignoreCase = false; return true; } ignoreCase = false; return false; } return stringComparer.IsWellKnownOrdinalComparerCore(out ignoreCase); } private protected virtual bool IsWellKnownOrdinalComparerCore(out bool ignoreCase) { ignoreCase = false; return false; } public static bool IsWellKnownCultureAwareComparer(IEqualityComparer? comparer, [NotNullWhen(true)] out CompareInfo? compareInfo, out CompareOptions compareOptions) { if (comparer is IInternalStringEqualityComparer internalStringEqualityComparer) { comparer = internalStringEqualityComparer.GetUnderlyingEqualityComparer(); } if (comparer is StringComparer stringComparer) { return stringComparer.IsWellKnownCultureAwareComparerCore(out compareInfo, out compareOptions); } compareInfo = null; compareOptions = CompareOptions.None; return false; } private protected virtual bool IsWellKnownCultureAwareComparerCore([NotNullWhen(true)] out CompareInfo compareInfo, out CompareOptions compareOptions) { compareInfo = null; compareOptions = CompareOptions.None; return false; } public int Compare(object? x, object? y) { if (x == y) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } if (x is string x2 && y is string y2) { return Compare(x2, y2); } if (x is IComparable comparable) { return comparable.CompareTo(y); } throw new ArgumentException(SR.Argument_ImplementIComparable); } public new bool Equals(object? x, object? y) { if (x == y) { return true; } if (x == null || y == null) { return false; } if (x is string x2 && y is string y2) { return Equals(x2, y2); } return x.Equals(y); } public int GetHashCode(object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } if (obj is string obj2) { return GetHashCode(obj2); } return obj.GetHashCode(); } public abstract int Compare(string? x, string? y); public abstract bool Equals(string? x, string? y); public abstract int GetHashCode(string obj); } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class CultureAwareComparer : StringComparer, ISerializable { internal static readonly CultureAwareComparer InvariantCaseSensitiveInstance = new CultureAwareComparer(CompareInfo.Invariant, CompareOptions.None); internal static readonly CultureAwareComparer InvariantIgnoreCaseInstance = new CultureAwareComparer(CompareInfo.Invariant, CompareOptions.IgnoreCase); private readonly CompareInfo _compareInfo; private readonly CompareOptions _options; internal CultureAwareComparer(CultureInfo culture, CompareOptions options) : this(culture.CompareInfo, options) { } internal CultureAwareComparer(CompareInfo compareInfo, CompareOptions options) { _compareInfo = compareInfo; if (((uint)options & 0xDFFFFFE0u) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, "options"); } _options = options; } private CultureAwareComparer(SerializationInfo info, StreamingContext context) { _compareInfo = (CompareInfo)info.GetValue("_compareInfo", typeof(CompareInfo)); bool boolean = info.GetBoolean("_ignoreCase"); object valueNoThrow = info.GetValueNoThrow("_options", typeof(CompareOptions)); if (valueNoThrow != null) { _options = (CompareOptions)valueNoThrow; } _options |= (CompareOptions)(boolean ? 1 : 0); } public override int Compare(string? x, string? y) { if ((object)x == y) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } return _compareInfo.Compare(x, y, _options); } public override bool Equals(string? x, string? y) { if ((object)x == y) { return true; } if (x == null || y == null) { return false; } return _compareInfo.Compare(x, y, _options) == 0; } public override int GetHashCode(string obj) { if (obj == null) { throw new ArgumentNullException("obj"); } return _compareInfo.GetHashCode(obj, _options); } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is CultureAwareComparer cultureAwareComparer && _options == cultureAwareComparer._options) { return _compareInfo.Equals(cultureAwareComparer._compareInfo); } return false; } public override int GetHashCode() { return _compareInfo.GetHashCode() ^ (int)(_options & (CompareOptions)2147483647); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("_compareInfo", _compareInfo); info.AddValue("_options", _options); info.AddValue("_ignoreCase", (_options & CompareOptions.IgnoreCase) != 0); } private protected override bool IsWellKnownCultureAwareComparerCore([NotNullWhen(true)] out CompareInfo compareInfo, out CompareOptions compareOptions) { compareInfo = _compareInfo; compareOptions = _options; return true; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class OrdinalComparer : StringComparer { private readonly bool _ignoreCase; internal OrdinalComparer(bool ignoreCase) { _ignoreCase = ignoreCase; } public override int Compare(string? x, string? y) { if ((object)x == y) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } if (_ignoreCase) { return string.Compare(x, y, StringComparison.OrdinalIgnoreCase); } return string.CompareOrdinal(x, y); } public override bool Equals(string? x, string? y) { if ((object)x == y) { return true; } if (x == null || y == null) { return false; } if (_ignoreCase) { if (x.Length != y.Length) { return false; } return System.Globalization.Ordinal.EqualsIgnoreCase(ref x.GetRawStringData(), ref y.GetRawStringData(), x.Length); } return x.Equals(y); } public override int GetHashCode(string obj) { if (obj == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); } if (_ignoreCase) { return obj.GetHashCodeOrdinalIgnoreCase(); } return obj.GetHashCode(); } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is OrdinalComparer ordinalComparer)) { return false; } return _ignoreCase == ordinalComparer._ignoreCase; } public override int GetHashCode() { int hashCode = "OrdinalComparer".GetHashCode(); if (!_ignoreCase) { return hashCode; } return ~hashCode; } private protected override bool IsWellKnownOrdinalComparerCore(out bool ignoreCase) { ignoreCase = _ignoreCase; return true; } } [Serializable] internal sealed class OrdinalCaseSensitiveComparer : OrdinalComparer, ISerializable { internal static readonly OrdinalCaseSensitiveComparer Instance = new OrdinalCaseSensitiveComparer(); private OrdinalCaseSensitiveComparer() : base(ignoreCase: false) { } public override int Compare(string x, string y) { return string.CompareOrdinal(x, y); } public override bool Equals(string x, string y) { return string.Equals(x, y); } public override int GetHashCode(string obj) { if (obj == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); } return obj.GetHashCode(); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.SetType(typeof(OrdinalComparer)); info.AddValue("_ignoreCase", value: false); } } [Serializable] internal sealed class OrdinalIgnoreCaseComparer : OrdinalComparer, ISerializable { internal static readonly OrdinalIgnoreCaseComparer Instance = new OrdinalIgnoreCaseComparer(); private OrdinalIgnoreCaseComparer() : base(ignoreCase: true) { } public override int Compare(string x, string y) { return string.Compare(x, y, StringComparison.OrdinalIgnoreCase); } public override bool Equals(string x, string y) { if ((object)x == y) { return true; } if (x == null || y == null) { return false; } if (x.Length != y.Length) { return false; } return System.Globalization.Ordinal.EqualsIgnoreCase(ref x.GetRawStringData(), ref y.GetRawStringData(), x.Length); } public override int GetHashCode(string obj) { if (obj == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); } return obj.GetHashCodeOrdinalIgnoreCase(); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.SetType(typeof(OrdinalComparer)); info.AddValue("_ignoreCase", value: true); } } public enum StringComparison { CurrentCulture, CurrentCultureIgnoreCase, InvariantCulture, InvariantCultureIgnoreCase, Ordinal, OrdinalIgnoreCase } public static class StringNormalizationExtensions { public static bool IsNormalized(this string strInput) { return IsNormalized(strInput, NormalizationForm.FormC); } public static bool IsNormalized(this string strInput, NormalizationForm normalizationForm) { if (strInput == null) { throw new ArgumentNullException("strInput"); } return strInput.IsNormalized(normalizationForm); } public static string Normalize(this string strInput) { return Normalize(strInput, NormalizationForm.FormC); } public static string Normalize(this string strInput, NormalizationForm normalizationForm) { if (strInput == null) { throw new ArgumentNullException("strInput"); } return strInput.Normalize(normalizationForm); } } [Flags] public enum StringSplitOptions { None = 0, RemoveEmptyEntries = 1, TrimEntries = 2 } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SystemException : Exception { public SystemException() : base(SR.Arg_SystemException) { base.HResult = -2146233087; } public SystemException(string? message) : base(message) { base.HResult = -2146233087; } public SystemException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233087; } protected SystemException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [AttributeUsage(AttributeTargets.Method)] public sealed class STAThreadAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method)] public sealed class MTAThreadAttribute : Attribute { } [AttributeUsage(AttributeTargets.Field, Inherited = false)] public class ThreadStaticAttribute : Attribute { } [StackTraceHidden] internal static class ThrowHelper { [DoesNotReturn] internal static void ThrowArrayTypeMismatchException() { throw new ArrayTypeMismatchException(); } [DoesNotReturn] internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType) { throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeWithPointersNotSupported, targetType)); } [DoesNotReturn] internal static void ThrowIndexOutOfRangeException() { throw new IndexOutOfRangeException(); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException() { throw new ArgumentOutOfRangeException(); } [DoesNotReturn] internal static void ThrowArgumentException_DestinationTooShort() { throw new ArgumentException(SR.Argument_DestinationTooShort, "destination"); } [DoesNotReturn] internal static void ThrowArgumentException_OverlapAlignmentMismatch() { throw new ArgumentException(SR.Argument_OverlapAlignmentMismatch); } [DoesNotReturn] internal static void ThrowArgumentException_CannotExtractScalar(ExceptionArgument argument) { throw GetArgumentException(ExceptionResource.Argument_CannotExtractScalar, argument); } [DoesNotReturn] internal static void ThrowArgumentException_TupleIncorrectType(object obj) { throw new ArgumentException(SR.Format(SR.ArgumentException_ValueTupleIncorrectType, obj.GetType()), "other"); } [DoesNotReturn] internal static void ThrowArgumentOutOfRange_IndexException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); } [DoesNotReturn] internal static void ThrowArgumentException_BadComparer(object comparer) { throw new ArgumentException(SR.Format(SR.Arg_BogusIComparer, comparer)); } [DoesNotReturn] internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } [DoesNotReturn] internal static void ThrowValueArgumentOutOfRange_NeedNonNegNumException() { throw GetArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } [DoesNotReturn] internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum() { throw GetArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } [DoesNotReturn] internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index() { throw GetArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } [DoesNotReturn] internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count() { throw GetArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } [DoesNotReturn] internal static void ThrowArgumentOutOfRange_Year() { throw GetArgumentOutOfRangeException(ExceptionArgument.year, ExceptionResource.ArgumentOutOfRange_Year); } [DoesNotReturn] internal static void ThrowArgumentOutOfRange_Month(int month) { throw new ArgumentOutOfRangeException("month", month, SR.ArgumentOutOfRange_Month); } [DoesNotReturn] internal static void ThrowArgumentOutOfRange_DayNumber(int dayNumber) { throw new ArgumentOutOfRangeException("dayNumber", dayNumber, SR.ArgumentOutOfRange_DayNumber); } [DoesNotReturn] internal static void ThrowArgumentOutOfRange_BadYearMonthDay() { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } [DoesNotReturn] internal static void ThrowArgumentOutOfRange_BadHourMinuteSecond() { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } [DoesNotReturn] internal static void ThrowArgumentOutOfRange_TimeSpanTooLong() { throw new ArgumentOutOfRangeException(null, SR.Overflow_TimeSpanTooLong); } [DoesNotReturn] internal static void ThrowWrongKeyTypeArgumentException(T key, Type targetType) { throw GetWrongKeyTypeArgumentException(key, targetType); } [DoesNotReturn] internal static void ThrowWrongValueTypeArgumentException(T value, Type targetType) { throw GetWrongValueTypeArgumentException(value, targetType); } private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key) { return new ArgumentException(SR.Format(SR.Argument_AddingDuplicateWithKey, key)); } [DoesNotReturn] internal static void ThrowAddingDuplicateWithKeyArgumentException(T key) { throw GetAddingDuplicateWithKeyArgumentException(key); } [DoesNotReturn] internal static void ThrowKeyNotFoundException(T key) { throw GetKeyNotFoundException(key); } [DoesNotReturn] internal static void ThrowArgumentException(ExceptionResource resource) { throw GetArgumentException(resource); } [DoesNotReturn] internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument) { throw GetArgumentException(resource, argument); } [DoesNotReturn] internal static void ThrowArgumentException_HandleNotSync(string paramName) { throw new ArgumentException(SR.Arg_HandleNotSync, paramName); } [DoesNotReturn] internal static void ThrowArgumentException_HandleNotAsync(string paramName) { throw new ArgumentException(SR.Arg_HandleNotAsync, paramName); } [DoesNotReturn] internal static void ThrowArgumentNullException(ExceptionArgument argument) { throw new ArgumentNullException(GetArgumentName(argument)); } [DoesNotReturn] internal static void ThrowArgumentNullException(ExceptionArgument argument, ExceptionResource resource) { throw new ArgumentNullException(GetArgumentName(argument), GetResourceString(resource)); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { throw new ArgumentOutOfRangeException(GetArgumentName(argument)); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { throw GetArgumentOutOfRangeException(argument, resource); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource) { throw GetArgumentOutOfRangeException(argument, paramNumber, resource); } [DoesNotReturn] internal static void ThrowEndOfFileException() { throw CreateEndOfFileException(); } internal static Exception CreateEndOfFileException() { return new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF); } [DoesNotReturn] internal static void ThrowInvalidOperationException() { throw new InvalidOperationException(); } [DoesNotReturn] internal static void ThrowInvalidOperationException(ExceptionResource resource) { throw GetInvalidOperationException(resource); } [DoesNotReturn] internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e) { throw new InvalidOperationException(GetResourceString(resource), e); } [DoesNotReturn] internal static void ThrowSerializationException(ExceptionResource resource) { throw new SerializationException(GetResourceString(resource)); } [DoesNotReturn] internal static void ThrowRankException(ExceptionResource resource) { throw new RankException(GetResourceString(resource)); } [DoesNotReturn] internal static void ThrowNotSupportedException(ExceptionResource resource) { throw new NotSupportedException(GetResourceString(resource)); } [DoesNotReturn] internal static void ThrowNotSupportedException_UnseekableStream() { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } [DoesNotReturn] internal static void ThrowNotSupportedException_UnreadableStream() { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } [DoesNotReturn] internal static void ThrowNotSupportedException_UnwritableStream() { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } [DoesNotReturn] internal static void ThrowObjectDisposedException_StreamClosed(string objectName) { throw new ObjectDisposedException(objectName, SR.ObjectDisposed_StreamClosed); } [DoesNotReturn] internal static void ThrowObjectDisposedException_FileClosed() { throw new ObjectDisposedException(null, SR.ObjectDisposed_FileClosed); } [DoesNotReturn] internal static void ThrowObjectDisposedException(ExceptionResource resource) { throw new ObjectDisposedException(null, GetResourceString(resource)); } [DoesNotReturn] internal static void ThrowNotSupportedException() { throw new NotSupportedException(); } [DoesNotReturn] internal static void ThrowAggregateException(List exceptions) { throw new AggregateException(exceptions); } [DoesNotReturn] internal static void ThrowOutOfMemoryException() { throw new OutOfMemoryException(); } [DoesNotReturn] internal static void ThrowArgumentException_Argument_InvalidArrayType() { throw new ArgumentException(SR.Argument_InvalidArrayType); } [DoesNotReturn] internal static void ThrowArgumentException_InvalidHandle(string paramName) { throw new ArgumentException(SR.Arg_InvalidHandle, paramName); } [DoesNotReturn] internal static void ThrowInvalidOperationException_InvalidOperation_EnumNotStarted() { throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); } [DoesNotReturn] internal static void ThrowInvalidOperationException_InvalidOperation_EnumEnded() { throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } [DoesNotReturn] internal static void ThrowInvalidOperationException_EnumCurrent(int index) { throw GetInvalidOperationException_EnumCurrent(index); } [DoesNotReturn] internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion() { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } [DoesNotReturn] internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen() { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } [DoesNotReturn] internal static void ThrowInvalidOperationException_InvalidOperation_NoValue() { throw new InvalidOperationException(SR.InvalidOperation_NoValue); } [DoesNotReturn] internal static void ThrowInvalidOperationException_ConcurrentOperationsNotSupported() { throw new InvalidOperationException(SR.InvalidOperation_ConcurrentOperationsNotSupported); } [DoesNotReturn] internal static void ThrowInvalidOperationException_HandleIsNotInitialized() { throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotInitialized); } [DoesNotReturn] internal static void ThrowInvalidOperationException_HandleIsNotPinned() { throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotPinned); } [DoesNotReturn] internal static void ThrowArraySegmentCtorValidationFailedExceptions(Array array, int offset, int count) { throw GetArraySegmentCtorValidationFailedException(array, offset, count); } [DoesNotReturn] internal static void ThrowFormatException_BadFormatSpecifier() { throw new FormatException(SR.Argument_BadFormatSpecifier); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException_PrecisionTooLarge() { throw new ArgumentOutOfRangeException("precision", SR.Format(SR.Argument_PrecisionTooLarge, (byte)99)); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException_SymbolDoesNotFit() { throw new ArgumentOutOfRangeException("symbol", SR.Argument_BadFormatSpecifier); } [DoesNotReturn] internal static void ThrowArgumentOutOfRangeException_NeedNonNegNum(string paramName) { throw new ArgumentOutOfRangeException(paramName, SR.ArgumentOutOfRange_NeedNonNegNum); } [DoesNotReturn] internal static void ArgumentOutOfRangeException_Enum_Value() { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_Enum); } private static Exception GetArraySegmentCtorValidationFailedException(Array array, int offset, int count) { if (array == null) { return new ArgumentNullException("array"); } if (offset < 0) { return new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { return new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } return new ArgumentException(SR.Argument_InvalidOffLen); } private static ArgumentException GetArgumentException(ExceptionResource resource) { return new ArgumentException(GetResourceString(resource)); } private static InvalidOperationException GetInvalidOperationException(ExceptionResource resource) { return new InvalidOperationException(GetResourceString(resource)); } private static ArgumentException GetWrongKeyTypeArgumentException(object key, Type targetType) { return new ArgumentException(SR.Format(SR.Arg_WrongType, key, targetType), "key"); } private static ArgumentException GetWrongValueTypeArgumentException(object value, Type targetType) { return new ArgumentException(SR.Format(SR.Arg_WrongType, value, targetType), "value"); } private static KeyNotFoundException GetKeyNotFoundException(object key) { return new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key)); } private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource)); } private static ArgumentException GetArgumentException(ExceptionResource resource, ExceptionArgument argument) { return new ArgumentException(GetResourceString(resource), GetArgumentName(argument)); } private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource) { return new ArgumentOutOfRangeException(GetArgumentName(argument) + "[" + paramNumber + "]", GetResourceString(resource)); } private static InvalidOperationException GetInvalidOperationException_EnumCurrent(int index) { return new InvalidOperationException((index < 0) ? SR.InvalidOperation_EnumNotStarted : SR.InvalidOperation_EnumEnded); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void IfNullAndNullsAreIllegalThenThrow(object value, ExceptionArgument argName) { if (default(T) != null && value == null) { ThrowArgumentNullException(argName); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void ThrowForUnsupportedNumericsVectorBaseType() where T : struct { if (typeof(T) != typeof(byte) && typeof(T) != typeof(sbyte) && typeof(T) != typeof(short) && typeof(T) != typeof(ushort) && typeof(T) != typeof(int) && typeof(T) != typeof(uint) && typeof(T) != typeof(long) && typeof(T) != typeof(ulong) && typeof(T) != typeof(float) && typeof(T) != typeof(double) && typeof(T) != typeof(IntPtr) && typeof(T) != typeof(UIntPtr)) { ThrowNotSupportedException(ExceptionResource.Arg_TypeNotSupported); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void ThrowForUnsupportedIntrinsicsVectorBaseType() where T : struct { if (typeof(T) != typeof(byte) && typeof(T) != typeof(sbyte) && typeof(T) != typeof(short) && typeof(T) != typeof(ushort) && typeof(T) != typeof(int) && typeof(T) != typeof(uint) && typeof(T) != typeof(long) && typeof(T) != typeof(ulong) && typeof(T) != typeof(float) && typeof(T) != typeof(double)) { ThrowNotSupportedException(ExceptionResource.Arg_TypeNotSupported); } } private static string GetArgumentName(ExceptionArgument argument) { return argument switch { ExceptionArgument.obj => "obj", ExceptionArgument.dictionary => "dictionary", ExceptionArgument.array => "array", ExceptionArgument.info => "info", ExceptionArgument.key => "key", ExceptionArgument.text => "text", ExceptionArgument.values => "values", ExceptionArgument.value => "value", ExceptionArgument.startIndex => "startIndex", ExceptionArgument.task => "task", ExceptionArgument.bytes => "bytes", ExceptionArgument.byteIndex => "byteIndex", ExceptionArgument.byteCount => "byteCount", ExceptionArgument.ch => "ch", ExceptionArgument.chars => "chars", ExceptionArgument.charIndex => "charIndex", ExceptionArgument.charCount => "charCount", ExceptionArgument.s => "s", ExceptionArgument.input => "input", ExceptionArgument.ownedMemory => "ownedMemory", ExceptionArgument.list => "list", ExceptionArgument.index => "index", ExceptionArgument.capacity => "capacity", ExceptionArgument.collection => "collection", ExceptionArgument.item => "item", ExceptionArgument.converter => "converter", ExceptionArgument.match => "match", ExceptionArgument.count => "count", ExceptionArgument.action => "action", ExceptionArgument.comparison => "comparison", ExceptionArgument.exceptions => "exceptions", ExceptionArgument.exception => "exception", ExceptionArgument.pointer => "pointer", ExceptionArgument.start => "start", ExceptionArgument.format => "format", ExceptionArgument.formats => "formats", ExceptionArgument.culture => "culture", ExceptionArgument.comparer => "comparer", ExceptionArgument.comparable => "comparable", ExceptionArgument.source => "source", ExceptionArgument.state => "state", ExceptionArgument.length => "length", ExceptionArgument.comparisonType => "comparisonType", ExceptionArgument.manager => "manager", ExceptionArgument.sourceBytesToCopy => "sourceBytesToCopy", ExceptionArgument.callBack => "callBack", ExceptionArgument.creationOptions => "creationOptions", ExceptionArgument.function => "function", ExceptionArgument.scheduler => "scheduler", ExceptionArgument.continuationAction => "continuationAction", ExceptionArgument.continuationFunction => "continuationFunction", ExceptionArgument.tasks => "tasks", ExceptionArgument.asyncResult => "asyncResult", ExceptionArgument.beginMethod => "beginMethod", ExceptionArgument.endMethod => "endMethod", ExceptionArgument.endFunction => "endFunction", ExceptionArgument.cancellationToken => "cancellationToken", ExceptionArgument.continuationOptions => "continuationOptions", ExceptionArgument.delay => "delay", ExceptionArgument.millisecondsDelay => "millisecondsDelay", ExceptionArgument.millisecondsTimeout => "millisecondsTimeout", ExceptionArgument.stateMachine => "stateMachine", ExceptionArgument.timeout => "timeout", ExceptionArgument.type => "type", ExceptionArgument.sourceIndex => "sourceIndex", ExceptionArgument.sourceArray => "sourceArray", ExceptionArgument.destinationIndex => "destinationIndex", ExceptionArgument.destinationArray => "destinationArray", ExceptionArgument.pHandle => "pHandle", ExceptionArgument.handle => "handle", ExceptionArgument.other => "other", ExceptionArgument.newSize => "newSize", ExceptionArgument.lowerBounds => "lowerBounds", ExceptionArgument.lengths => "lengths", ExceptionArgument.len => "len", ExceptionArgument.keys => "keys", ExceptionArgument.indices => "indices", ExceptionArgument.index1 => "index1", ExceptionArgument.index2 => "index2", ExceptionArgument.index3 => "index3", ExceptionArgument.length1 => "length1", ExceptionArgument.length2 => "length2", ExceptionArgument.length3 => "length3", ExceptionArgument.endIndex => "endIndex", ExceptionArgument.elementType => "elementType", ExceptionArgument.arrayIndex => "arrayIndex", ExceptionArgument.year => "year", ExceptionArgument.codePoint => "codePoint", ExceptionArgument.str => "str", ExceptionArgument.options => "options", ExceptionArgument.prefix => "prefix", ExceptionArgument.suffix => "suffix", ExceptionArgument.buffer => "buffer", ExceptionArgument.buffers => "buffers", ExceptionArgument.offset => "offset", ExceptionArgument.stream => "stream", _ => "", }; } private static string GetResourceString(ExceptionResource resource) { return resource switch { ExceptionResource.ArgumentOutOfRange_Index => SR.ArgumentOutOfRange_Index, ExceptionResource.ArgumentOutOfRange_IndexCount => SR.ArgumentOutOfRange_IndexCount, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer => SR.ArgumentOutOfRange_IndexCountBuffer, ExceptionResource.ArgumentOutOfRange_Count => SR.ArgumentOutOfRange_Count, ExceptionResource.ArgumentOutOfRange_Year => SR.ArgumentOutOfRange_Year, ExceptionResource.Arg_ArrayPlusOffTooSmall => SR.Arg_ArrayPlusOffTooSmall, ExceptionResource.NotSupported_ReadOnlyCollection => SR.NotSupported_ReadOnlyCollection, ExceptionResource.Arg_RankMultiDimNotSupported => SR.Arg_RankMultiDimNotSupported, ExceptionResource.Arg_NonZeroLowerBound => SR.Arg_NonZeroLowerBound, ExceptionResource.ArgumentOutOfRange_GetCharCountOverflow => SR.ArgumentOutOfRange_GetCharCountOverflow, ExceptionResource.ArgumentOutOfRange_ListInsert => SR.ArgumentOutOfRange_ListInsert, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum => SR.ArgumentOutOfRange_NeedNonNegNum, ExceptionResource.ArgumentOutOfRange_SmallCapacity => SR.ArgumentOutOfRange_SmallCapacity, ExceptionResource.Argument_InvalidOffLen => SR.Argument_InvalidOffLen, ExceptionResource.Argument_CannotExtractScalar => SR.Argument_CannotExtractScalar, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection => SR.ArgumentOutOfRange_BiggerThanCollection, ExceptionResource.Serialization_MissingKeys => SR.Serialization_MissingKeys, ExceptionResource.Serialization_NullKey => SR.Serialization_NullKey, ExceptionResource.NotSupported_KeyCollectionSet => SR.NotSupported_KeyCollectionSet, ExceptionResource.NotSupported_ValueCollectionSet => SR.NotSupported_ValueCollectionSet, ExceptionResource.InvalidOperation_NullArray => SR.InvalidOperation_NullArray, ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted => SR.TaskT_TransitionToFinal_AlreadyCompleted, ExceptionResource.TaskCompletionSourceT_TrySetException_NullException => SR.TaskCompletionSourceT_TrySetException_NullException, ExceptionResource.TaskCompletionSourceT_TrySetException_NoExceptions => SR.TaskCompletionSourceT_TrySetException_NoExceptions, ExceptionResource.NotSupported_StringComparison => SR.NotSupported_StringComparison, ExceptionResource.ConcurrentCollection_SyncRoot_NotSupported => SR.ConcurrentCollection_SyncRoot_NotSupported, ExceptionResource.Task_MultiTaskContinuation_NullTask => SR.Task_MultiTaskContinuation_NullTask, ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple => SR.InvalidOperation_WrongAsyncResultOrEndCalledMultiple, ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList => SR.Task_MultiTaskContinuation_EmptyTaskList, ExceptionResource.Task_Start_TaskCompleted => SR.Task_Start_TaskCompleted, ExceptionResource.Task_Start_Promise => SR.Task_Start_Promise, ExceptionResource.Task_Start_ContinuationTask => SR.Task_Start_ContinuationTask, ExceptionResource.Task_Start_AlreadyStarted => SR.Task_Start_AlreadyStarted, ExceptionResource.Task_RunSynchronously_Continuation => SR.Task_RunSynchronously_Continuation, ExceptionResource.Task_RunSynchronously_Promise => SR.Task_RunSynchronously_Promise, ExceptionResource.Task_RunSynchronously_TaskCompleted => SR.Task_RunSynchronously_TaskCompleted, ExceptionResource.Task_RunSynchronously_AlreadyStarted => SR.Task_RunSynchronously_AlreadyStarted, ExceptionResource.AsyncMethodBuilder_InstanceNotInitialized => SR.AsyncMethodBuilder_InstanceNotInitialized, ExceptionResource.Task_ContinueWith_ESandLR => SR.Task_ContinueWith_ESandLR, ExceptionResource.Task_ContinueWith_NotOnAnything => SR.Task_ContinueWith_NotOnAnything, ExceptionResource.Task_InvalidTimerTimeSpan => SR.Task_InvalidTimerTimeSpan, ExceptionResource.Task_Delay_InvalidMillisecondsDelay => SR.Task_Delay_InvalidMillisecondsDelay, ExceptionResource.Task_Dispose_NotCompleted => SR.Task_Dispose_NotCompleted, ExceptionResource.Task_ThrowIfDisposed => SR.Task_ThrowIfDisposed, ExceptionResource.Task_WaitMulti_NullTask => SR.Task_WaitMulti_NullTask, ExceptionResource.ArgumentException_OtherNotArrayOfCorrectLength => SR.ArgumentException_OtherNotArrayOfCorrectLength, ExceptionResource.ArgumentNull_Array => SR.ArgumentNull_Array, ExceptionResource.ArgumentNull_SafeHandle => SR.ArgumentNull_SafeHandle, ExceptionResource.ArgumentOutOfRange_EndIndexStartIndex => SR.ArgumentOutOfRange_EndIndexStartIndex, ExceptionResource.ArgumentOutOfRange_Enum => SR.ArgumentOutOfRange_Enum, ExceptionResource.ArgumentOutOfRange_HugeArrayNotSupported => SR.ArgumentOutOfRange_HugeArrayNotSupported, ExceptionResource.Argument_AddingDuplicate => SR.Argument_AddingDuplicate, ExceptionResource.Argument_InvalidArgumentForComparison => SR.Argument_InvalidArgumentForComparison, ExceptionResource.Arg_LowerBoundsMustMatch => SR.Arg_LowerBoundsMustMatch, ExceptionResource.Arg_MustBeType => SR.Arg_MustBeType, ExceptionResource.Arg_Need1DArray => SR.Arg_Need1DArray, ExceptionResource.Arg_Need2DArray => SR.Arg_Need2DArray, ExceptionResource.Arg_Need3DArray => SR.Arg_Need3DArray, ExceptionResource.Arg_NeedAtLeast1Rank => SR.Arg_NeedAtLeast1Rank, ExceptionResource.Arg_RankIndices => SR.Arg_RankIndices, ExceptionResource.Arg_RanksAndBounds => SR.Arg_RanksAndBounds, ExceptionResource.InvalidOperation_IComparerFailed => SR.InvalidOperation_IComparerFailed, ExceptionResource.NotSupported_FixedSizeCollection => SR.NotSupported_FixedSizeCollection, ExceptionResource.Rank_MultiDimNotSupported => SR.Rank_MultiDimNotSupported, ExceptionResource.Arg_TypeNotSupported => SR.Arg_TypeNotSupported, ExceptionResource.Argument_SpansMustHaveSameLength => SR.Argument_SpansMustHaveSameLength, ExceptionResource.Argument_InvalidFlag => SR.Argument_InvalidFlag, ExceptionResource.CancellationTokenSource_Disposed => SR.CancellationTokenSource_Disposed, ExceptionResource.Argument_AlignmentMustBePow2 => SR.Argument_AlignmentMustBePow2, _ => "", }; } } internal enum ExceptionArgument { obj, dictionary, array, info, key, text, values, value, startIndex, task, bytes, byteIndex, byteCount, ch, chars, charIndex, charCount, s, input, ownedMemory, list, index, capacity, collection, item, converter, match, count, action, comparison, exceptions, exception, pointer, start, format, formats, culture, comparer, comparable, source, state, length, comparisonType, manager, sourceBytesToCopy, callBack, creationOptions, function, scheduler, continuationAction, continuationFunction, tasks, asyncResult, beginMethod, endMethod, endFunction, cancellationToken, continuationOptions, delay, millisecondsDelay, millisecondsTimeout, stateMachine, timeout, type, sourceIndex, sourceArray, destinationIndex, destinationArray, pHandle, handle, other, newSize, lowerBounds, lengths, len, keys, indices, index1, index2, index3, length1, length2, length3, endIndex, elementType, arrayIndex, year, codePoint, str, options, prefix, suffix, buffer, buffers, offset, stream } internal enum ExceptionResource { ArgumentOutOfRange_Index, ArgumentOutOfRange_IndexCount, ArgumentOutOfRange_IndexCountBuffer, ArgumentOutOfRange_Count, ArgumentOutOfRange_Year, Arg_ArrayPlusOffTooSmall, NotSupported_ReadOnlyCollection, Arg_RankMultiDimNotSupported, Arg_NonZeroLowerBound, ArgumentOutOfRange_GetCharCountOverflow, ArgumentOutOfRange_ListInsert, ArgumentOutOfRange_NeedNonNegNum, ArgumentOutOfRange_SmallCapacity, Argument_InvalidOffLen, Argument_CannotExtractScalar, ArgumentOutOfRange_BiggerThanCollection, Serialization_MissingKeys, Serialization_NullKey, NotSupported_KeyCollectionSet, NotSupported_ValueCollectionSet, InvalidOperation_NullArray, TaskT_TransitionToFinal_AlreadyCompleted, TaskCompletionSourceT_TrySetException_NullException, TaskCompletionSourceT_TrySetException_NoExceptions, NotSupported_StringComparison, ConcurrentCollection_SyncRoot_NotSupported, Task_MultiTaskContinuation_NullTask, InvalidOperation_WrongAsyncResultOrEndCalledMultiple, Task_MultiTaskContinuation_EmptyTaskList, Task_Start_TaskCompleted, Task_Start_Promise, Task_Start_ContinuationTask, Task_Start_AlreadyStarted, Task_RunSynchronously_Continuation, Task_RunSynchronously_Promise, Task_RunSynchronously_TaskCompleted, Task_RunSynchronously_AlreadyStarted, AsyncMethodBuilder_InstanceNotInitialized, Task_ContinueWith_ESandLR, Task_ContinueWith_NotOnAnything, Task_InvalidTimerTimeSpan, Task_Delay_InvalidMillisecondsDelay, Task_Dispose_NotCompleted, Task_ThrowIfDisposed, Task_WaitMulti_NullTask, ArgumentException_OtherNotArrayOfCorrectLength, ArgumentNull_Array, ArgumentNull_SafeHandle, ArgumentOutOfRange_EndIndexStartIndex, ArgumentOutOfRange_Enum, ArgumentOutOfRange_HugeArrayNotSupported, Argument_AddingDuplicate, Argument_InvalidArgumentForComparison, Arg_LowerBoundsMustMatch, Arg_MustBeType, Arg_Need1DArray, Arg_Need2DArray, Arg_Need3DArray, Arg_NeedAtLeast1Rank, Arg_RankIndices, Arg_RanksAndBounds, InvalidOperation_IComparerFailed, NotSupported_FixedSizeCollection, Rank_MultiDimNotSupported, Arg_TypeNotSupported, Argument_SpansMustHaveSameLength, Argument_InvalidFlag, CancellationTokenSource_Disposed, Argument_AlignmentMustBePow2 } public readonly struct TimeOnly : IComparable, IComparable, IEquatable, ISpanFormattable, IFormattable, IComparisonOperators, IEqualityOperators, IMinMaxValue, ISpanParseable, IParseable, ISubtractionOperators { private readonly long _ticks; public static TimeOnly MinValue => new TimeOnly(0uL); public static TimeOnly MaxValue => new TimeOnly(863999999999uL); public int Hour => new TimeSpan(_ticks).Hours; public int Minute => new TimeSpan(_ticks).Minutes; public int Second => new TimeSpan(_ticks).Seconds; public int Millisecond => new TimeSpan(_ticks).Milliseconds; public long Ticks => _ticks; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeOnly IMinMaxValue.MinValue => MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeOnly IMinMaxValue.MaxValue => MaxValue; public TimeOnly(int hour, int minute) : this(DateTime.TimeToTicks(hour, minute, 0, 0)) { } public TimeOnly(int hour, int minute, int second) : this(DateTime.TimeToTicks(hour, minute, second, 0)) { } public TimeOnly(int hour, int minute, int second, int millisecond) : this(DateTime.TimeToTicks(hour, minute, second, millisecond)) { } public TimeOnly(long ticks) { if ((ulong)ticks > 863999999999uL) { throw new ArgumentOutOfRangeException("ticks", SR.ArgumentOutOfRange_TimeOnlyBadTicks); } _ticks = ticks; } internal TimeOnly(ulong ticks) { _ticks = (long)ticks; } private TimeOnly AddTicks(long ticks) { return new TimeOnly((_ticks + 864000000000L + ticks % 864000000000L) % 864000000000L); } private TimeOnly AddTicks(long ticks, out int wrappedDays) { wrappedDays = (int)(ticks / 864000000000L); long num = _ticks + ticks % 864000000000L; if (num < 0) { wrappedDays--; num += 864000000000L; } else if (num >= 864000000000L) { wrappedDays++; num -= 864000000000L; } return new TimeOnly(num); } public TimeOnly Add(TimeSpan value) { return AddTicks(value.Ticks); } public TimeOnly Add(TimeSpan value, out int wrappedDays) { return AddTicks(value.Ticks, out wrappedDays); } public TimeOnly AddHours(double value) { return AddTicks((long)(value * 36000000000.0)); } public TimeOnly AddHours(double value, out int wrappedDays) { return AddTicks((long)(value * 36000000000.0), out wrappedDays); } public TimeOnly AddMinutes(double value) { return AddTicks((long)(value * 600000000.0)); } public TimeOnly AddMinutes(double value, out int wrappedDays) { return AddTicks((long)(value * 600000000.0), out wrappedDays); } public bool IsBetween(TimeOnly start, TimeOnly end) { long ticks = start._ticks; long ticks2 = end._ticks; if (ticks > ticks2) { if (ticks > _ticks) { return ticks2 > _ticks; } return true; } if (ticks <= _ticks) { return ticks2 > _ticks; } return false; } public static bool operator ==(TimeOnly left, TimeOnly right) { return left._ticks == right._ticks; } public static bool operator !=(TimeOnly left, TimeOnly right) { return left._ticks != right._ticks; } public static bool operator >(TimeOnly left, TimeOnly right) { return left._ticks > right._ticks; } public static bool operator >=(TimeOnly left, TimeOnly right) { return left._ticks >= right._ticks; } public static bool operator <(TimeOnly left, TimeOnly right) { return left._ticks < right._ticks; } public static bool operator <=(TimeOnly left, TimeOnly right) { return left._ticks <= right._ticks; } public static TimeSpan operator -(TimeOnly t1, TimeOnly t2) { return new TimeSpan((t1._ticks - t2._ticks + 864000000000L) % 864000000000L); } public static TimeOnly FromTimeSpan(TimeSpan timeSpan) { return new TimeOnly(timeSpan._ticks); } public static TimeOnly FromDateTime(DateTime dateTime) { return new TimeOnly(dateTime.TimeOfDay.Ticks); } public TimeSpan ToTimeSpan() { return new TimeSpan(_ticks); } internal DateTime ToDateTime() { return new DateTime(_ticks); } public int CompareTo(TimeOnly value) { return _ticks.CompareTo(value._ticks); } public int CompareTo(object? value) { if (value == null) { return 1; } if (!(value is TimeOnly value2)) { throw new ArgumentException(SR.Arg_MustBeTimeOnly); } return CompareTo(value2); } public bool Equals(TimeOnly value) { return _ticks == value._ticks; } public override bool Equals([NotNullWhen(true)] object? value) { if (value is TimeOnly timeOnly) { return _ticks == timeOnly._ticks; } return false; } public override int GetHashCode() { long ticks = _ticks; return (int)ticks ^ (int)(ticks >> 32); } public static TimeOnly Parse(ReadOnlySpan s, IFormatProvider? provider = null, DateTimeStyles style = DateTimeStyles.None) { TimeOnly result; ParseFailureKind parseFailureKind = TryParseInternal(s, provider, style, out result); if (parseFailureKind != 0) { ThrowOnError(parseFailureKind, s); } return result; } public static TimeOnly ParseExact(ReadOnlySpan s, ReadOnlySpan format, IFormatProvider? provider = null, DateTimeStyles style = DateTimeStyles.None) { TimeOnly result; ParseFailureKind parseFailureKind = TryParseExactInternal(s, format, provider, style, out result); if (parseFailureKind != 0) { ThrowOnError(parseFailureKind, s); } return result; } public static TimeOnly ParseExact(ReadOnlySpan s, string[] formats) { return ParseExact(s, formats, null); } public static TimeOnly ParseExact(ReadOnlySpan s, string[] formats, IFormatProvider? provider, DateTimeStyles style = DateTimeStyles.None) { TimeOnly result; ParseFailureKind parseFailureKind = TryParseExactInternal(s, formats, provider, style, out result); if (parseFailureKind != 0) { ThrowOnError(parseFailureKind, s); } return result; } public static TimeOnly Parse(string s) { return Parse(s, null); } public static TimeOnly Parse(string s, IFormatProvider? provider, DateTimeStyles style = DateTimeStyles.None) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse(s.AsSpan(), provider, style); } public static TimeOnly ParseExact(string s, string format) { return ParseExact(s, format, null); } public static TimeOnly ParseExact(string s, string format, IFormatProvider? provider, DateTimeStyles style = DateTimeStyles.None) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if (format == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); } return ParseExact(s.AsSpan(), format.AsSpan(), provider, style); } public static TimeOnly ParseExact(string s, string[] formats) { return ParseExact(s, formats, null); } public static TimeOnly ParseExact(string s, string[] formats, IFormatProvider? provider, DateTimeStyles style = DateTimeStyles.None) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return ParseExact(s.AsSpan(), formats, provider, style); } public static bool TryParse(ReadOnlySpan s, out TimeOnly result) { return TryParse(s, null, DateTimeStyles.None, out result); } public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, DateTimeStyles style, out TimeOnly result) { return TryParseInternal(s, provider, style, out result) == ParseFailureKind.None; } private static ParseFailureKind TryParseInternal(ReadOnlySpan s, IFormatProvider provider, DateTimeStyles style, out TimeOnly result) { if (((uint)style & 0xFFFFFFF8u) != 0) { result = default(TimeOnly); return ParseFailureKind.FormatWithParameter; } DateTimeResult result2 = default(DateTimeResult); result2.Init(s); if (!DateTimeParse.TryParse(s, DateTimeFormatInfo.GetInstance(provider), style, ref result2)) { result = default(TimeOnly); return ParseFailureKind.FormatWithOriginalDateTime; } if ((result2.flags & (ParseFlags.HaveYear | ParseFlags.HaveMonth | ParseFlags.HaveDay | ParseFlags.HaveDate | ParseFlags.TimeZoneUsed | ParseFlags.TimeZoneUtc | ParseFlags.ParsedMonthName | ParseFlags.CaptureOffset | ParseFlags.UtcSortPattern)) != 0) { result = default(TimeOnly); return ParseFailureKind.WrongParts; } result = new TimeOnly(result2.parsedDate.TimeOfDay.Ticks); return ParseFailureKind.None; } public static bool TryParseExact(ReadOnlySpan s, ReadOnlySpan format, out TimeOnly result) { return TryParseExact(s, format, null, DateTimeStyles.None, out result); } public static bool TryParseExact(ReadOnlySpan s, ReadOnlySpan format, IFormatProvider? provider, DateTimeStyles style, out TimeOnly result) { return TryParseExactInternal(s, format, provider, style, out result) == ParseFailureKind.None; } private static ParseFailureKind TryParseExactInternal(ReadOnlySpan s, ReadOnlySpan format, IFormatProvider provider, DateTimeStyles style, out TimeOnly result) { if (((uint)style & 0xFFFFFFF8u) != 0) { result = default(TimeOnly); return ParseFailureKind.FormatWithParameter; } if (format.Length == 1) { switch (format[0]) { case 'O': case 'o': format = "HH':'mm':'ss'.'fffffff"; provider = CultureInfo.InvariantCulture.DateTimeFormat; break; case 'R': case 'r': format = "HH':'mm':'ss"; provider = CultureInfo.InvariantCulture.DateTimeFormat; break; } } DateTimeResult result2 = default(DateTimeResult); result2.Init(s); if (!DateTimeParse.TryParseExact(s, format, DateTimeFormatInfo.GetInstance(provider), style, ref result2)) { result = default(TimeOnly); return ParseFailureKind.FormatWithOriginalDateTime; } if ((result2.flags & (ParseFlags.HaveYear | ParseFlags.HaveMonth | ParseFlags.HaveDay | ParseFlags.HaveDate | ParseFlags.TimeZoneUsed | ParseFlags.TimeZoneUtc | ParseFlags.ParsedMonthName | ParseFlags.CaptureOffset | ParseFlags.UtcSortPattern)) != 0) { result = default(TimeOnly); return ParseFailureKind.WrongParts; } result = new TimeOnly(result2.parsedDate.TimeOfDay.Ticks); return ParseFailureKind.None; } public static bool TryParseExact(ReadOnlySpan s, [NotNullWhen(true)] string?[]? formats, out TimeOnly result) { return TryParseExact(s, formats, null, DateTimeStyles.None, out result); } public static bool TryParseExact(ReadOnlySpan s, [NotNullWhen(true)] string?[]? formats, IFormatProvider? provider, DateTimeStyles style, out TimeOnly result) { return TryParseExactInternal(s, formats, provider, style, out result) == ParseFailureKind.None; } private static ParseFailureKind TryParseExactInternal(ReadOnlySpan s, string[] formats, IFormatProvider provider, DateTimeStyles style, out TimeOnly result) { if (((uint)style & 0xFFFFFFF8u) != 0 || formats == null) { result = default(TimeOnly); return ParseFailureKind.FormatWithParameter; } DateTimeFormatInfo instance = DateTimeFormatInfo.GetInstance(provider); for (int i = 0; i < formats.Length; i++) { DateTimeFormatInfo dtfi = instance; string text = formats[i]; if (string.IsNullOrEmpty(text)) { result = default(TimeOnly); return ParseFailureKind.FormatWithFormatSpecifier; } if (text.Length == 1) { switch (text[0]) { case 'O': case 'o': text = "HH':'mm':'ss'.'fffffff"; dtfi = CultureInfo.InvariantCulture.DateTimeFormat; break; case 'R': case 'r': text = "HH':'mm':'ss"; dtfi = CultureInfo.InvariantCulture.DateTimeFormat; break; } } DateTimeResult result2 = default(DateTimeResult); result2.Init(s); if (DateTimeParse.TryParseExact(s, text, dtfi, style, ref result2) && (result2.flags & (ParseFlags.HaveYear | ParseFlags.HaveMonth | ParseFlags.HaveDay | ParseFlags.HaveDate | ParseFlags.TimeZoneUsed | ParseFlags.TimeZoneUtc | ParseFlags.ParsedMonthName | ParseFlags.CaptureOffset | ParseFlags.UtcSortPattern)) == 0) { result = new TimeOnly(result2.parsedDate.TimeOfDay.Ticks); return ParseFailureKind.None; } } result = default(TimeOnly); return ParseFailureKind.FormatWithOriginalDateTime; } public static bool TryParse([NotNullWhen(true)] string? s, out TimeOnly result) { return TryParse(s, null, DateTimeStyles.None, out result); } public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, DateTimeStyles style, out TimeOnly result) { if (s == null) { result = default(TimeOnly); return false; } return TryParse(s.AsSpan(), provider, style, out result); } public static bool TryParseExact([NotNullWhen(true)] string? s, [NotNullWhen(true)] string? format, out TimeOnly result) { return TryParseExact(s, format, null, DateTimeStyles.None, out result); } public static bool TryParseExact([NotNullWhen(true)] string? s, [NotNullWhen(true)] string? format, IFormatProvider? provider, DateTimeStyles style, out TimeOnly result) { if (s == null || format == null) { result = default(TimeOnly); return false; } return TryParseExact(s.AsSpan(), format.AsSpan(), provider, style, out result); } public static bool TryParseExact([NotNullWhen(true)] string? s, [NotNullWhen(true)] string?[]? formats, out TimeOnly result) { return TryParseExact(s, formats, null, DateTimeStyles.None, out result); } public static bool TryParseExact([NotNullWhen(true)] string? s, [NotNullWhen(true)] string?[]? formats, IFormatProvider? provider, DateTimeStyles style, out TimeOnly result) { if (s == null) { result = default(TimeOnly); return false; } return TryParseExact(s.AsSpan(), formats, provider, style, out result); } private static void ThrowOnError(ParseFailureKind result, ReadOnlySpan s) { switch (result) { case ParseFailureKind.FormatWithParameter: throw new ArgumentException(SR.Argument_InvalidDateStyles, "style"); case ParseFailureKind.FormatWithOriginalDateTime: throw new FormatException(SR.Format(SR.Format_BadTimeOnly, s.ToString())); case ParseFailureKind.FormatWithFormatSpecifier: throw new FormatException(SR.Argument_BadFormatSpecifier); default: throw new FormatException(SR.Format(SR.Format_DateTimeOnlyContainsNoneDateParts, s.ToString(), "TimeOnly")); } } public string ToLongTimeString() { return ToString("T"); } public string ToShortTimeString() { return ToString(); } public override string ToString() { return ToString("t"); } public string ToString(string? format) { return ToString(format, null); } public string ToString(IFormatProvider? provider) { return ToString("t", provider); } public string ToString(string? format, IFormatProvider? provider) { if (format == null || format.Length == 0) { format = "t"; } if (format.Length == 1) { switch (format[0]) { case 'O': case 'o': return string.Create(16, this, delegate(Span destination, TimeOnly value) { bool flag = DateTimeFormat.TryFormatTimeOnlyO(value.Hour, value.Minute, value.Second, value._ticks % 10000000, destination); }); case 'R': case 'r': return string.Create(8, this, delegate(Span destination, TimeOnly value) { bool flag2 = DateTimeFormat.TryFormatTimeOnlyR(value.Hour, value.Minute, value.Second, destination); }); case 'T': case 't': return DateTimeFormat.Format(ToDateTime(), format, provider); default: throw new FormatException(SR.Format_InvalidString); } } DateTimeFormat.IsValidCustomTimeFormat(format.AsSpan(), throwOnError: true); return DateTimeFormat.Format(ToDateTime(), format, provider); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { if (format.Length == 0) { format = "t"; } if (format.Length == 1) { switch (format[0]) { case 'O': case 'o': if (!DateTimeFormat.TryFormatTimeOnlyO(Hour, Minute, Second, _ticks % 10000000, destination)) { charsWritten = 0; return false; } charsWritten = 16; return true; case 'R': case 'r': if (!DateTimeFormat.TryFormatTimeOnlyR(Hour, Minute, Second, destination)) { charsWritten = 0; return false; } charsWritten = 8; return true; case 'T': case 't': return DateTimeFormat.TryFormat(ToDateTime(), destination, out charsWritten, format, provider); default: throw new FormatException(SR.Argument_BadFormatSpecifier); } } if (!DateTimeFormat.IsValidCustomTimeFormat(format, throwOnError: false)) { throw new FormatException(SR.Format(SR.Format_DateTimeOnlyContainsNoneDateParts, format.ToString(), "TimeOnly")); } return DateTimeFormat.TryFormat(ToDateTime(), destination, out charsWritten, format, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(TimeOnly left, TimeOnly right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(TimeOnly left, TimeOnly right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(TimeOnly left, TimeOnly right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(TimeOnly left, TimeOnly right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(TimeOnly left, TimeOnly right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(TimeOnly left, TimeOnly right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeOnly IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out TimeOnly result) { return TryParse(s, provider, DateTimeStyles.None, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeOnly ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out TimeOnly result) { return TryParse(s, provider, DateTimeStyles.None, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan ISubtractionOperators.op_Subtraction(TimeOnly left, TimeOnly right) { return left - right; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class TimeoutException : SystemException { public TimeoutException() : base(SR.Arg_TimeoutException) { base.HResult = -2146233083; } public TimeoutException(string? message) : base(message) { base.HResult = -2146233083; } public TimeoutException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233083; } protected TimeoutException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] public readonly struct TimeSpan : IComparable, IComparable, IEquatable, ISpanFormattable, IFormattable, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDivisionOperators, IDivisionOperators, IMinMaxValue, IMultiplyOperators, IMultiplicativeIdentity, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators { public const long TicksPerMillisecond = 10000L; public const long TicksPerSecond = 10000000L; public const long TicksPerMinute = 600000000L; public const long TicksPerHour = 36000000000L; public const long TicksPerDay = 864000000000L; public static readonly TimeSpan Zero = new TimeSpan(0L); public static readonly TimeSpan MaxValue = new TimeSpan(long.MaxValue); public static readonly TimeSpan MinValue = new TimeSpan(long.MinValue); internal readonly long _ticks; public long Ticks => _ticks; public int Days => (int)(_ticks / 864000000000L); public int Hours => (int)(_ticks / 36000000000L % 24); public int Milliseconds => (int)(_ticks / 10000 % 1000); public int Minutes => (int)(_ticks / 600000000 % 60); public int Seconds => (int)(_ticks / 10000000 % 60); public double TotalDays => (double)_ticks / 864000000000.0; public double TotalHours => (double)_ticks / 36000000000.0; public double TotalMilliseconds { get { double num = (double)_ticks / 10000.0; if (num > 922337203685477.0) { return 922337203685477.0; } if (num < -922337203685477.0) { return -922337203685477.0; } return num; } } public double TotalMinutes => (double)_ticks / 600000000.0; public double TotalSeconds => (double)_ticks / 10000000.0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan IAdditiveIdentity.AdditiveIdentity => default(TimeSpan); [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan IMinMaxValue.MinValue => MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan IMinMaxValue.MaxValue => MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IMultiplicativeIdentity.MultiplicativeIdentity => 1.0; public TimeSpan(long ticks) { _ticks = ticks; } public TimeSpan(int hours, int minutes, int seconds) { _ticks = TimeToTicks(hours, minutes, seconds); } public TimeSpan(int days, int hours, int minutes, int seconds) : this(days, hours, minutes, seconds, 0) { } public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) { long num = ((long)days * 3600L * 24 + (long)hours * 3600L + (long)minutes * 60L + seconds) * 1000 + milliseconds; if (num > 922337203685477L || num < -922337203685477L) { throw new ArgumentOutOfRangeException(null, SR.Overflow_TimeSpanTooLong); } _ticks = num * 10000; } public TimeSpan Add(TimeSpan ts) { long num = _ticks + ts._ticks; if (_ticks >> 63 == ts._ticks >> 63 && _ticks >> 63 != num >> 63) { throw new OverflowException(SR.Overflow_TimeSpanTooLong); } return new TimeSpan(num); } public static int Compare(TimeSpan t1, TimeSpan t2) { if (t1._ticks > t2._ticks) { return 1; } if (t1._ticks < t2._ticks) { return -1; } return 0; } public int CompareTo(object? value) { if (value == null) { return 1; } if (!(value is TimeSpan)) { throw new ArgumentException(SR.Arg_MustBeTimeSpan); } long ticks = ((TimeSpan)value)._ticks; if (_ticks > ticks) { return 1; } if (_ticks < ticks) { return -1; } return 0; } public int CompareTo(TimeSpan value) { long ticks = value._ticks; if (_ticks > ticks) { return 1; } if (_ticks < ticks) { return -1; } return 0; } public static TimeSpan FromDays(double value) { return Interval(value, 864000000000.0); } public TimeSpan Duration() { if (Ticks == MinValue.Ticks) { throw new OverflowException(SR.Overflow_Duration); } return new TimeSpan((_ticks >= 0) ? _ticks : (-_ticks)); } public override bool Equals([NotNullWhen(true)] object? value) { if (value is TimeSpan) { return _ticks == ((TimeSpan)value)._ticks; } return false; } public bool Equals(TimeSpan obj) { return _ticks == obj._ticks; } public static bool Equals(TimeSpan t1, TimeSpan t2) { return t1._ticks == t2._ticks; } public override int GetHashCode() { return (int)_ticks ^ (int)(_ticks >> 32); } public static TimeSpan FromHours(double value) { return Interval(value, 36000000000.0); } private static TimeSpan Interval(double value, double scale) { if (double.IsNaN(value)) { throw new ArgumentException(SR.Arg_CannotBeNaN); } double ticks = value * scale; return IntervalFromDoubleTicks(ticks); } private static TimeSpan IntervalFromDoubleTicks(double ticks) { if (ticks > 9.223372036854776E+18 || ticks < -9.223372036854776E+18 || double.IsNaN(ticks)) { throw new OverflowException(SR.Overflow_TimeSpanTooLong); } if (ticks == 9.223372036854776E+18) { return MaxValue; } return new TimeSpan((long)ticks); } public static TimeSpan FromMilliseconds(double value) { return Interval(value, 10000.0); } public static TimeSpan FromMinutes(double value) { return Interval(value, 600000000.0); } public TimeSpan Negate() { if (Ticks == MinValue.Ticks) { throw new OverflowException(SR.Overflow_NegateTwosCompNum); } return new TimeSpan(-_ticks); } public static TimeSpan FromSeconds(double value) { return Interval(value, 10000000.0); } public TimeSpan Subtract(TimeSpan ts) { long num = _ticks - ts._ticks; if (_ticks >> 63 != ts._ticks >> 63 && _ticks >> 63 != num >> 63) { throw new OverflowException(SR.Overflow_TimeSpanTooLong); } return new TimeSpan(num); } public TimeSpan Multiply(double factor) { return this * factor; } public TimeSpan Divide(double divisor) { return this / divisor; } public double Divide(TimeSpan ts) { return this / ts; } public static TimeSpan FromTicks(long value) { return new TimeSpan(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static long TimeToTicks(int hour, int minute, int second) { long num = (long)hour * 3600L + (long)minute * 60L + second; if (num > 922337203685L || num < -922337203685L) { ThrowHelper.ThrowArgumentOutOfRange_TimeSpanTooLong(); } return num * 10000000; } private static void ValidateStyles(TimeSpanStyles style, string parameterName) { if (style != 0 && style != TimeSpanStyles.AssumeNegative) { throw new ArgumentException(SR.Argument_InvalidTimeSpanStyles, parameterName); } } public static TimeSpan Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); } return TimeSpanParse.Parse(s, null); } public static TimeSpan Parse(string input, IFormatProvider? formatProvider) { if (input == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); } return TimeSpanParse.Parse(input, formatProvider); } public static TimeSpan Parse(ReadOnlySpan input, IFormatProvider? formatProvider = null) { return TimeSpanParse.Parse(input, formatProvider); } public static TimeSpan ParseExact(string input, string format, IFormatProvider? formatProvider) { if (input == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); } if (format == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); } return TimeSpanParse.ParseExact(input, format, formatProvider, TimeSpanStyles.None); } public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider? formatProvider) { if (input == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); } return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None); } public static TimeSpan ParseExact(string input, string format, IFormatProvider? formatProvider, TimeSpanStyles styles) { ValidateStyles(styles, "styles"); if (input == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); } if (format == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.format); } return TimeSpanParse.ParseExact(input, format, formatProvider, styles); } public static TimeSpan ParseExact(ReadOnlySpan input, ReadOnlySpan format, IFormatProvider? formatProvider, TimeSpanStyles styles = TimeSpanStyles.None) { ValidateStyles(styles, "styles"); return TimeSpanParse.ParseExact(input, format, formatProvider, styles); } public static TimeSpan ParseExact(string input, string[] formats, IFormatProvider? formatProvider, TimeSpanStyles styles) { ValidateStyles(styles, "styles"); if (input == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); } return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles); } public static TimeSpan ParseExact(ReadOnlySpan input, string[] formats, IFormatProvider? formatProvider, TimeSpanStyles styles = TimeSpanStyles.None) { ValidateStyles(styles, "styles"); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles); } public static bool TryParse([NotNullWhen(true)] string? s, out TimeSpan result) { if (s == null) { result = default(TimeSpan); return false; } return TimeSpanParse.TryParse(s, null, out result); } public static bool TryParse(ReadOnlySpan s, out TimeSpan result) { return TimeSpanParse.TryParse(s, null, out result); } public static bool TryParse([NotNullWhen(true)] string? input, IFormatProvider? formatProvider, out TimeSpan result) { if (input == null) { result = default(TimeSpan); return false; } return TimeSpanParse.TryParse(input, formatProvider, out result); } public static bool TryParse(ReadOnlySpan input, IFormatProvider? formatProvider, out TimeSpan result) { return TimeSpanParse.TryParse(input, formatProvider, out result); } public static bool TryParseExact([NotNullWhen(true)] string? input, [NotNullWhen(true)] string? format, IFormatProvider? formatProvider, out TimeSpan result) { if (input == null || format == null) { result = default(TimeSpan); return false; } return TimeSpanParse.TryParseExact(input, format, formatProvider, TimeSpanStyles.None, out result); } public static bool TryParseExact(ReadOnlySpan input, ReadOnlySpan format, IFormatProvider? formatProvider, out TimeSpan result) { return TimeSpanParse.TryParseExact(input, format, formatProvider, TimeSpanStyles.None, out result); } public static bool TryParseExact([NotNullWhen(true)] string? input, [NotNullWhen(true)] string?[]? formats, IFormatProvider? formatProvider, out TimeSpan result) { if (input == null) { result = default(TimeSpan); return false; } return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result); } public static bool TryParseExact(ReadOnlySpan input, [NotNullWhen(true)] string?[]? formats, IFormatProvider? formatProvider, out TimeSpan result) { return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result); } public static bool TryParseExact([NotNullWhen(true)] string? input, [NotNullWhen(true)] string? format, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, "styles"); if (input == null || format == null) { result = default(TimeSpan); return false; } return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result); } public static bool TryParseExact(ReadOnlySpan input, ReadOnlySpan format, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, "styles"); return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result); } public static bool TryParseExact([NotNullWhen(true)] string? input, [NotNullWhen(true)] string?[]? formats, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, "styles"); if (input == null) { result = default(TimeSpan); return false; } return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result); } public static bool TryParseExact(ReadOnlySpan input, [NotNullWhen(true)] string?[]? formats, IFormatProvider? formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, "styles"); return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result); } public override string ToString() { return TimeSpanFormat.FormatC(this); } public string ToString(string? format) { return TimeSpanFormat.Format(this, format, null); } public string ToString(string? format, IFormatProvider? formatProvider) { return TimeSpanFormat.Format(this, format, formatProvider); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? formatProvider = null) { return TimeSpanFormat.TryFormat(this, destination, out charsWritten, format, formatProvider); } public static TimeSpan operator -(TimeSpan t) { if (t._ticks == MinValue._ticks) { throw new OverflowException(SR.Overflow_NegateTwosCompNum); } return new TimeSpan(-t._ticks); } public static TimeSpan operator -(TimeSpan t1, TimeSpan t2) { return t1.Subtract(t2); } public static TimeSpan operator +(TimeSpan t) { return t; } public static TimeSpan operator +(TimeSpan t1, TimeSpan t2) { return t1.Add(t2); } public static TimeSpan operator *(TimeSpan timeSpan, double factor) { if (double.IsNaN(factor)) { throw new ArgumentException(SR.Arg_CannotBeNaN, "factor"); } double ticks = Math.Round((double)timeSpan.Ticks * factor); return IntervalFromDoubleTicks(ticks); } public static TimeSpan operator *(double factor, TimeSpan timeSpan) { return timeSpan * factor; } public static TimeSpan operator /(TimeSpan timeSpan, double divisor) { if (double.IsNaN(divisor)) { throw new ArgumentException(SR.Arg_CannotBeNaN, "divisor"); } double ticks = Math.Round((double)timeSpan.Ticks / divisor); return IntervalFromDoubleTicks(ticks); } public static double operator /(TimeSpan t1, TimeSpan t2) { return (double)t1.Ticks / (double)t2.Ticks; } public static bool operator ==(TimeSpan t1, TimeSpan t2) { return t1._ticks == t2._ticks; } public static bool operator !=(TimeSpan t1, TimeSpan t2) { return t1._ticks != t2._ticks; } public static bool operator <(TimeSpan t1, TimeSpan t2) { return t1._ticks < t2._ticks; } public static bool operator <=(TimeSpan t1, TimeSpan t2) { return t1._ticks <= t2._ticks; } public static bool operator >(TimeSpan t1, TimeSpan t2) { return t1._ticks > t2._ticks; } public static bool operator >=(TimeSpan t1, TimeSpan t2) { return t1._ticks >= t2._ticks; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan IAdditionOperators.op_Addition(TimeSpan left, TimeSpan right) { return left + right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(TimeSpan left, TimeSpan right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(TimeSpan left, TimeSpan right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(TimeSpan left, TimeSpan right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(TimeSpan left, TimeSpan right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan IDivisionOperators.op_Division(TimeSpan left, double right) { return left / right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static double IDivisionOperators.op_Division(TimeSpan left, TimeSpan right) { return left / right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(TimeSpan left, TimeSpan right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(TimeSpan left, TimeSpan right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan IMultiplyOperators.op_Multiply(TimeSpan left, double right) { return left * right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out TimeSpan result) { return TryParse(s, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out TimeSpan result) { return TryParse(s, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan ISubtractionOperators.op_Subtraction(TimeSpan left, TimeSpan right) { return left - right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan IUnaryNegationOperators.op_UnaryNegation(TimeSpan value) { return -value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static TimeSpan IUnaryPlusOperators.op_UnaryPlus(TimeSpan value) { return +value; } } [Obsolete("System.TimeZone has been deprecated. Investigate the use of System.TimeZoneInfo instead.")] public abstract class TimeZone { private static volatile TimeZone currentTimeZone; private static object s_InternalSyncObject; private static object InternalSyncObject { get { if (s_InternalSyncObject == null) { object value = new object(); Interlocked.CompareExchange(ref s_InternalSyncObject, value, (object)null); } return s_InternalSyncObject; } } public static TimeZone CurrentTimeZone { get { TimeZone timeZone = currentTimeZone; if (timeZone == null) { lock (InternalSyncObject) { if (currentTimeZone == null) { currentTimeZone = new CurrentSystemTimeZone(); } timeZone = currentTimeZone; } } return timeZone; } } public abstract string StandardName { get; } public abstract string DaylightName { get; } internal static void ResetTimeZone() { if (currentTimeZone != null) { lock (InternalSyncObject) { currentTimeZone = null; } } } public abstract TimeSpan GetUtcOffset(DateTime time); public virtual DateTime ToUniversalTime(DateTime time) { if (time.Kind == DateTimeKind.Utc) { return time; } long num = time.Ticks - GetUtcOffset(time).Ticks; if (num > 3155378975999999999L) { return new DateTime(3155378975999999999L, DateTimeKind.Utc); } if (num < 0) { return new DateTime(0L, DateTimeKind.Utc); } return new DateTime(num, DateTimeKind.Utc); } public virtual DateTime ToLocalTime(DateTime time) { if (time.Kind == DateTimeKind.Local) { return time; } bool isAmbiguousLocalDst = false; long utcOffsetFromUniversalTime = ((CurrentSystemTimeZone)CurrentTimeZone).GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst); return new DateTime(time.Ticks + utcOffsetFromUniversalTime, DateTimeKind.Local, isAmbiguousLocalDst); } public abstract DaylightTime GetDaylightChanges(int year); public virtual bool IsDaylightSavingTime(DateTime time) { return IsDaylightSavingTime(time, GetDaylightChanges(time.Year)); } public static bool IsDaylightSavingTime(DateTime time, DaylightTime daylightTimes) { return CalculateUtcOffset(time, daylightTimes) != TimeSpan.Zero; } internal static TimeSpan CalculateUtcOffset(DateTime time, DaylightTime daylightTimes) { if (daylightTimes == null) { return TimeSpan.Zero; } DateTimeKind kind = time.Kind; if (kind == DateTimeKind.Utc) { return TimeSpan.Zero; } DateTime dateTime = daylightTimes.Start + daylightTimes.Delta; DateTime end = daylightTimes.End; DateTime dateTime2; DateTime dateTime3; if (daylightTimes.Delta.Ticks > 0) { dateTime2 = end - daylightTimes.Delta; dateTime3 = end; } else { dateTime2 = dateTime; dateTime3 = dateTime - daylightTimes.Delta; } bool flag = false; if (dateTime > end) { if (time >= dateTime || time < end) { flag = true; } } else if (time >= dateTime && time < end) { flag = true; } if (flag && time >= dateTime2 && time < dateTime3) { flag = time.IsAmbiguousDaylightSavingTime(); } if (flag) { return daylightTimes.Delta; } return TimeSpan.Zero; } } [Serializable] [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class TimeZoneInfo : IEquatable, ISerializable, IDeserializationCallback { [Serializable] public sealed class AdjustmentRule : IEquatable, ISerializable, IDeserializationCallback { private static readonly TimeSpan DaylightDeltaAdjustment = TimeSpan.FromHours(24.0); private static readonly TimeSpan MaxDaylightDelta = TimeSpan.FromHours(12.0); private readonly DateTime _dateStart; private readonly DateTime _dateEnd; private readonly TimeSpan _daylightDelta; private readonly TransitionTime _daylightTransitionStart; private readonly TransitionTime _daylightTransitionEnd; private readonly TimeSpan _baseUtcOffsetDelta; private readonly bool _noDaylightTransitions; public DateTime DateStart => _dateStart; public DateTime DateEnd => _dateEnd; public TimeSpan DaylightDelta => _daylightDelta; public TransitionTime DaylightTransitionStart => _daylightTransitionStart; public TransitionTime DaylightTransitionEnd => _daylightTransitionEnd; public TimeSpan BaseUtcOffsetDelta => _baseUtcOffsetDelta; internal bool NoDaylightTransitions => _noDaylightTransitions; internal bool HasDaylightSaving { get { if (!(DaylightDelta != TimeSpan.Zero) && (!(DaylightTransitionStart != default(TransitionTime)) || !(DaylightTransitionStart.TimeOfDay != DateTime.MinValue))) { if (DaylightTransitionEnd != default(TransitionTime)) { return DaylightTransitionEnd.TimeOfDay != DateTime.MinValue.AddMilliseconds(1.0); } return false; } return true; } } public bool Equals([NotNullWhen(true)] AdjustmentRule? other) { if (other != null && _dateStart == other._dateStart && _dateEnd == other._dateEnd && _daylightDelta == other._daylightDelta && _baseUtcOffsetDelta == other._baseUtcOffsetDelta && _daylightTransitionEnd.Equals(other._daylightTransitionEnd)) { return _daylightTransitionStart.Equals(other._daylightTransitionStart); } return false; } public override int GetHashCode() { return _dateStart.GetHashCode(); } private AdjustmentRule(DateTime dateStart, DateTime dateEnd, TimeSpan daylightDelta, TransitionTime daylightTransitionStart, TransitionTime daylightTransitionEnd, TimeSpan baseUtcOffsetDelta, bool noDaylightTransitions) { ValidateAdjustmentRule(dateStart, dateEnd, daylightDelta, daylightTransitionStart, daylightTransitionEnd, noDaylightTransitions); _dateStart = dateStart; _dateEnd = dateEnd; _daylightDelta = daylightDelta; _daylightTransitionStart = daylightTransitionStart; _daylightTransitionEnd = daylightTransitionEnd; _baseUtcOffsetDelta = baseUtcOffsetDelta; _noDaylightTransitions = noDaylightTransitions; } public static AdjustmentRule CreateAdjustmentRule(DateTime dateStart, DateTime dateEnd, TimeSpan daylightDelta, TransitionTime daylightTransitionStart, TransitionTime daylightTransitionEnd, TimeSpan baseUtcOffsetDelta) { return new AdjustmentRule(dateStart, dateEnd, daylightDelta, daylightTransitionStart, daylightTransitionEnd, baseUtcOffsetDelta, noDaylightTransitions: false); } public static AdjustmentRule CreateAdjustmentRule(DateTime dateStart, DateTime dateEnd, TimeSpan daylightDelta, TransitionTime daylightTransitionStart, TransitionTime daylightTransitionEnd) { return new AdjustmentRule(dateStart, dateEnd, daylightDelta, daylightTransitionStart, daylightTransitionEnd, TimeSpan.Zero, noDaylightTransitions: false); } internal static AdjustmentRule CreateAdjustmentRule(DateTime dateStart, DateTime dateEnd, TimeSpan daylightDelta, TransitionTime daylightTransitionStart, TransitionTime daylightTransitionEnd, TimeSpan baseUtcOffsetDelta, bool noDaylightTransitions) { AdjustDaylightDeltaToExpectedRange(ref daylightDelta, ref baseUtcOffsetDelta); return new AdjustmentRule(dateStart, dateEnd, daylightDelta, daylightTransitionStart, daylightTransitionEnd, baseUtcOffsetDelta, noDaylightTransitions); } internal bool IsStartDateMarkerForBeginningOfYear() { if (!NoDaylightTransitions && DaylightTransitionStart.Month == 1 && DaylightTransitionStart.Day == 1) { return DaylightTransitionStart.TimeOfDay.TimeOfDay.Ticks < 10000000; } return false; } internal bool IsEndDateMarkerForEndOfYear() { if (!NoDaylightTransitions && DaylightTransitionEnd.Month == 1 && DaylightTransitionEnd.Day == 1) { return DaylightTransitionEnd.TimeOfDay.TimeOfDay.Ticks < 10000000; } return false; } private static void ValidateAdjustmentRule(DateTime dateStart, DateTime dateEnd, TimeSpan daylightDelta, TransitionTime daylightTransitionStart, TransitionTime daylightTransitionEnd, bool noDaylightTransitions) { if (dateStart.Kind != 0 && dateStart.Kind != DateTimeKind.Utc) { throw new ArgumentException(SR.Argument_DateTimeKindMustBeUnspecifiedOrUtc, "dateStart"); } if (dateEnd.Kind != 0 && dateEnd.Kind != DateTimeKind.Utc) { throw new ArgumentException(SR.Argument_DateTimeKindMustBeUnspecifiedOrUtc, "dateEnd"); } if (daylightTransitionStart.Equals(daylightTransitionEnd) && !noDaylightTransitions) { throw new ArgumentException(SR.Argument_TransitionTimesAreIdentical, "daylightTransitionEnd"); } if (dateStart > dateEnd) { throw new ArgumentException(SR.Argument_OutOfOrderDateTimes, "dateStart"); } if (daylightDelta.TotalHours < -23.0 || daylightDelta.TotalHours > 14.0) { throw new ArgumentOutOfRangeException("daylightDelta", daylightDelta, SR.ArgumentOutOfRange_UtcOffset); } if (daylightDelta.Ticks % 600000000 != 0L) { throw new ArgumentException(SR.Argument_TimeSpanHasSeconds, "daylightDelta"); } if (dateStart != DateTime.MinValue && dateStart.Kind == DateTimeKind.Unspecified && dateStart.TimeOfDay != TimeSpan.Zero) { throw new ArgumentException(SR.Argument_DateTimeHasTimeOfDay, "dateStart"); } if (dateEnd != DateTime.MaxValue && dateEnd.Kind == DateTimeKind.Unspecified && dateEnd.TimeOfDay != TimeSpan.Zero) { throw new ArgumentException(SR.Argument_DateTimeHasTimeOfDay, "dateEnd"); } } private static void AdjustDaylightDeltaToExpectedRange(ref TimeSpan daylightDelta, ref TimeSpan baseUtcOffsetDelta) { if (daylightDelta > MaxDaylightDelta) { daylightDelta -= DaylightDeltaAdjustment; baseUtcOffsetDelta += DaylightDeltaAdjustment; } else if (daylightDelta < -MaxDaylightDelta) { daylightDelta += DaylightDeltaAdjustment; baseUtcOffsetDelta -= DaylightDeltaAdjustment; } } void IDeserializationCallback.OnDeserialization(object sender) { try { ValidateAdjustmentRule(_dateStart, _dateEnd, _daylightDelta, _daylightTransitionStart, _daylightTransitionEnd, _noDaylightTransitions); } catch (ArgumentException innerException) { throw new SerializationException(SR.Serialization_InvalidData, innerException); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("DateStart", _dateStart); info.AddValue("DateEnd", _dateEnd); info.AddValue("DaylightDelta", _daylightDelta); info.AddValue("DaylightTransitionStart", _daylightTransitionStart); info.AddValue("DaylightTransitionEnd", _daylightTransitionEnd); info.AddValue("BaseUtcOffsetDelta", _baseUtcOffsetDelta); info.AddValue("NoDaylightTransitions", _noDaylightTransitions); } private AdjustmentRule(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } _dateStart = (DateTime)info.GetValue("DateStart", typeof(DateTime)); _dateEnd = (DateTime)info.GetValue("DateEnd", typeof(DateTime)); _daylightDelta = (TimeSpan)info.GetValue("DaylightDelta", typeof(TimeSpan)); _daylightTransitionStart = (TransitionTime)info.GetValue("DaylightTransitionStart", typeof(TransitionTime)); _daylightTransitionEnd = (TransitionTime)info.GetValue("DaylightTransitionEnd", typeof(TransitionTime)); object valueNoThrow = info.GetValueNoThrow("BaseUtcOffsetDelta", typeof(TimeSpan)); if (valueNoThrow != null) { _baseUtcOffsetDelta = (TimeSpan)valueNoThrow; } valueNoThrow = info.GetValueNoThrow("NoDaylightTransitions", typeof(bool)); if (valueNoThrow != null) { _noDaylightTransitions = (bool)valueNoThrow; } } } private enum TimeZoneInfoResult { Success, TimeZoneNotFoundException, InvalidTimeZoneException, SecurityException } private sealed class CachedData { private volatile TimeZoneInfo _localTimeZone; public Dictionary _systemTimeZones; public ReadOnlyCollection _readOnlySystemTimeZones; public bool _allSystemTimeZonesRead; private volatile OffsetAndRule _oneYearLocalFromUtc; public TimeZoneInfo Local => _localTimeZone ?? CreateLocal(); private TimeZoneInfo CreateLocal() { lock (this) { TimeZoneInfo timeZoneInfo = _localTimeZone; if (timeZoneInfo == null) { timeZoneInfo = GetLocalTimeZone(this); timeZoneInfo = (_localTimeZone = new TimeZoneInfo(timeZoneInfo._id, timeZoneInfo._baseUtcOffset, timeZoneInfo._displayName, timeZoneInfo._standardDisplayName, timeZoneInfo._daylightDisplayName, timeZoneInfo._adjustmentRules, disableDaylightSavingTime: false, timeZoneInfo.HasIanaId)); } return timeZoneInfo; } } public DateTimeKind GetCorrespondingKind(TimeZoneInfo timeZone) { if (timeZone != s_utcTimeZone) { if (timeZone != _localTimeZone) { return DateTimeKind.Unspecified; } return DateTimeKind.Local; } return DateTimeKind.Utc; } private static TimeZoneInfo GetCurrentOneYearLocal() { Interop.Kernel32.TIME_ZONE_INFORMATION lpTimeZoneInformation; uint timeZoneInformation = Interop.Kernel32.GetTimeZoneInformation(out lpTimeZoneInformation); if (timeZoneInformation != uint.MaxValue) { return GetLocalTimeZoneFromWin32Data(in lpTimeZoneInformation, dstDisabled: false); } return CreateCustomTimeZone("Local", TimeSpan.Zero, "Local", "Local"); } public OffsetAndRule GetOneYearLocalFromUtc(int year) { OffsetAndRule offsetAndRule = _oneYearLocalFromUtc; if (offsetAndRule == null || offsetAndRule.Year != year) { TimeZoneInfo currentOneYearLocal = GetCurrentOneYearLocal(); AdjustmentRule[] adjustmentRules = currentOneYearLocal._adjustmentRules; AdjustmentRule rule = ((adjustmentRules != null) ? adjustmentRules[0] : null); offsetAndRule = (_oneYearLocalFromUtc = new OffsetAndRule(year, currentOneYearLocal.BaseUtcOffset, rule)); } return offsetAndRule; } } private struct StringSerializer { private enum State { Escaped, NotEscaped, StartOfToken, EndOfLine } private readonly string _serializedText; private int _currentTokenStartIndex; private State _state; public static string GetSerializedString(TimeZoneInfo zone) { Span initialBuffer = stackalloc char[64]; ValueStringBuilder serializedText = new ValueStringBuilder(initialBuffer); SerializeSubstitute(zone.Id, ref serializedText); serializedText.Append(';'); serializedText.AppendSpanFormattable(zone.BaseUtcOffset.TotalMinutes, null, CultureInfo.InvariantCulture); serializedText.Append(';'); SerializeSubstitute(zone.DisplayName, ref serializedText); serializedText.Append(';'); SerializeSubstitute(zone.StandardName, ref serializedText); serializedText.Append(';'); SerializeSubstitute(zone.DaylightName, ref serializedText); serializedText.Append(';'); AdjustmentRule[] adjustmentRules = zone.GetAdjustmentRules(); AdjustmentRule[] array = adjustmentRules; foreach (AdjustmentRule adjustmentRule in array) { serializedText.Append('['); serializedText.AppendSpanFormattable(adjustmentRule.DateStart, "MM:dd:yyyy", DateTimeFormatInfo.InvariantInfo); serializedText.Append(';'); serializedText.AppendSpanFormattable(adjustmentRule.DateEnd, "MM:dd:yyyy", DateTimeFormatInfo.InvariantInfo); serializedText.Append(';'); serializedText.AppendSpanFormattable(adjustmentRule.DaylightDelta.TotalMinutes, null, CultureInfo.InvariantCulture); serializedText.Append(';'); SerializeTransitionTime(adjustmentRule.DaylightTransitionStart, ref serializedText); serializedText.Append(';'); SerializeTransitionTime(adjustmentRule.DaylightTransitionEnd, ref serializedText); serializedText.Append(';'); if (adjustmentRule.BaseUtcOffsetDelta != TimeSpan.Zero) { serializedText.AppendSpanFormattable(adjustmentRule.BaseUtcOffsetDelta.TotalMinutes, null, CultureInfo.InvariantCulture); serializedText.Append(';'); } if (adjustmentRule.NoDaylightTransitions) { serializedText.Append('1'); serializedText.Append(';'); } serializedText.Append(']'); } serializedText.Append(';'); return serializedText.ToString(); } public static TimeZoneInfo GetDeserializedTimeZoneInfo(string source) { StringSerializer stringSerializer = new StringSerializer(source); string nextStringValue = stringSerializer.GetNextStringValue(); TimeSpan nextTimeSpanValue = stringSerializer.GetNextTimeSpanValue(); string nextStringValue2 = stringSerializer.GetNextStringValue(); string nextStringValue3 = stringSerializer.GetNextStringValue(); string nextStringValue4 = stringSerializer.GetNextStringValue(); AdjustmentRule[] nextAdjustmentRuleArrayValue = stringSerializer.GetNextAdjustmentRuleArrayValue(); try { return new TimeZoneInfo(nextStringValue, nextTimeSpanValue, nextStringValue2, nextStringValue3, nextStringValue4, nextAdjustmentRuleArrayValue, disableDaylightSavingTime: false); } catch (ArgumentException innerException) { throw new SerializationException(SR.Serialization_InvalidData, innerException); } catch (InvalidTimeZoneException innerException2) { throw new SerializationException(SR.Serialization_InvalidData, innerException2); } } private StringSerializer(string str) { _serializedText = str; _currentTokenStartIndex = 0; _state = State.StartOfToken; } private static void SerializeSubstitute(string text, ref ValueStringBuilder serializedText) { foreach (char c in text) { if (c == '\\' || c == '[' || c == ']' || c == ';') { serializedText.Append('\\'); } serializedText.Append(c); } } private static void SerializeTransitionTime(TransitionTime time, ref ValueStringBuilder serializedText) { serializedText.Append('['); serializedText.Append(time.IsFixedDateRule ? '1' : '0'); serializedText.Append(';'); serializedText.AppendSpanFormattable(time.TimeOfDay, "HH:mm:ss.FFF", DateTimeFormatInfo.InvariantInfo); serializedText.Append(';'); serializedText.AppendSpanFormattable(time.Month, null, CultureInfo.InvariantCulture); serializedText.Append(';'); if (time.IsFixedDateRule) { serializedText.AppendSpanFormattable(time.Day, null, CultureInfo.InvariantCulture); serializedText.Append(';'); } else { serializedText.AppendSpanFormattable(time.Week, null, CultureInfo.InvariantCulture); serializedText.Append(';'); serializedText.AppendSpanFormattable((int)time.DayOfWeek, null, CultureInfo.InvariantCulture); serializedText.Append(';'); } serializedText.Append(']'); } private static void VerifyIsEscapableCharacter(char c) { if (c != '\\' && c != ';' && c != '[' && c != ']') { throw new SerializationException(SR.Format(SR.Serialization_InvalidEscapeSequence, c)); } } private void SkipVersionNextDataFields(int depth) { if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length) { throw new SerializationException(SR.Serialization_InvalidData); } State state = State.NotEscaped; for (int i = _currentTokenStartIndex; i < _serializedText.Length; i++) { switch (state) { case State.Escaped: VerifyIsEscapableCharacter(_serializedText[i]); state = State.NotEscaped; break; case State.NotEscaped: switch (_serializedText[i]) { case '\\': state = State.Escaped; break; case '[': depth++; break; case ']': depth--; if (depth == 0) { _currentTokenStartIndex = i + 1; if (_currentTokenStartIndex >= _serializedText.Length) { _state = State.EndOfLine; } else { _state = State.StartOfToken; } return; } break; case '\0': throw new SerializationException(SR.Serialization_InvalidData); } break; } } throw new SerializationException(SR.Serialization_InvalidData); } private string GetNextStringValue() { if (_state == State.EndOfLine) { throw new SerializationException(SR.Serialization_InvalidData); } if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length) { throw new SerializationException(SR.Serialization_InvalidData); } State state = State.NotEscaped; Span initialBuffer = stackalloc char[64]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); for (int i = _currentTokenStartIndex; i < _serializedText.Length; i++) { switch (state) { case State.Escaped: VerifyIsEscapableCharacter(_serializedText[i]); valueStringBuilder.Append(_serializedText[i]); state = State.NotEscaped; break; case State.NotEscaped: switch (_serializedText[i]) { case '\\': state = State.Escaped; break; case '[': throw new SerializationException(SR.Serialization_InvalidData); case ']': throw new SerializationException(SR.Serialization_InvalidData); case ';': _currentTokenStartIndex = i + 1; if (_currentTokenStartIndex >= _serializedText.Length) { _state = State.EndOfLine; } else { _state = State.StartOfToken; } return valueStringBuilder.ToString(); case '\0': throw new SerializationException(SR.Serialization_InvalidData); default: valueStringBuilder.Append(_serializedText[i]); break; } break; } } if (state == State.Escaped) { throw new SerializationException(SR.Format(SR.Serialization_InvalidEscapeSequence, string.Empty)); } throw new SerializationException(SR.Serialization_InvalidData); } private DateTime GetNextDateTimeValue(string format) { string nextStringValue = GetNextStringValue(); if (!DateTime.TryParseExact(nextStringValue, format, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out var result)) { throw new SerializationException(SR.Serialization_InvalidData); } return result; } private TimeSpan GetNextTimeSpanValue() { int nextInt32Value = GetNextInt32Value(); try { return new TimeSpan(0, nextInt32Value, 0); } catch (ArgumentOutOfRangeException innerException) { throw new SerializationException(SR.Serialization_InvalidData, innerException); } } private int GetNextInt32Value() { string nextStringValue = GetNextStringValue(); if (!int.TryParse(nextStringValue, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var result)) { throw new SerializationException(SR.Serialization_InvalidData); } return result; } private AdjustmentRule[] GetNextAdjustmentRuleArrayValue() { List list = new List(1); int num = 0; for (AdjustmentRule nextAdjustmentRuleValue = GetNextAdjustmentRuleValue(); nextAdjustmentRuleValue != null; nextAdjustmentRuleValue = GetNextAdjustmentRuleValue()) { list.Add(nextAdjustmentRuleValue); num++; } if (_state == State.EndOfLine) { throw new SerializationException(SR.Serialization_InvalidData); } if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length) { throw new SerializationException(SR.Serialization_InvalidData); } if (num == 0) { return null; } return list.ToArray(); } private AdjustmentRule GetNextAdjustmentRuleValue() { if (_state == State.EndOfLine) { return null; } if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length) { throw new SerializationException(SR.Serialization_InvalidData); } if (_serializedText[_currentTokenStartIndex] == ';') { return null; } if (_serializedText[_currentTokenStartIndex] != '[') { throw new SerializationException(SR.Serialization_InvalidData); } _currentTokenStartIndex++; DateTime nextDateTimeValue = GetNextDateTimeValue("MM:dd:yyyy"); DateTime nextDateTimeValue2 = GetNextDateTimeValue("MM:dd:yyyy"); TimeSpan nextTimeSpanValue = GetNextTimeSpanValue(); TransitionTime nextTransitionTimeValue = GetNextTransitionTimeValue(); TransitionTime nextTransitionTimeValue2 = GetNextTransitionTimeValue(); TimeSpan baseUtcOffsetDelta = TimeSpan.Zero; int num = 0; if (_state == State.EndOfLine || _currentTokenStartIndex >= _serializedText.Length) { throw new SerializationException(SR.Serialization_InvalidData); } if ((_serializedText[_currentTokenStartIndex] >= '0' && _serializedText[_currentTokenStartIndex] <= '9') || _serializedText[_currentTokenStartIndex] == '-' || _serializedText[_currentTokenStartIndex] == '+') { baseUtcOffsetDelta = GetNextTimeSpanValue(); } if (_serializedText[_currentTokenStartIndex] >= '0' && _serializedText[_currentTokenStartIndex] <= '1') { num = GetNextInt32Value(); } if (_state == State.EndOfLine || _currentTokenStartIndex >= _serializedText.Length) { throw new SerializationException(SR.Serialization_InvalidData); } if (_serializedText[_currentTokenStartIndex] != ']') { SkipVersionNextDataFields(1); } else { _currentTokenStartIndex++; } AdjustmentRule result; try { result = AdjustmentRule.CreateAdjustmentRule(nextDateTimeValue, nextDateTimeValue2, nextTimeSpanValue, nextTransitionTimeValue, nextTransitionTimeValue2, baseUtcOffsetDelta, num > 0); } catch (ArgumentException innerException) { throw new SerializationException(SR.Serialization_InvalidData, innerException); } if (_currentTokenStartIndex >= _serializedText.Length) { _state = State.EndOfLine; } else { _state = State.StartOfToken; } return result; } private TransitionTime GetNextTransitionTimeValue() { if (_state == State.EndOfLine || (_currentTokenStartIndex < _serializedText.Length && _serializedText[_currentTokenStartIndex] == ']')) { throw new SerializationException(SR.Serialization_InvalidData); } if (_currentTokenStartIndex < 0 || _currentTokenStartIndex >= _serializedText.Length) { throw new SerializationException(SR.Serialization_InvalidData); } if (_serializedText[_currentTokenStartIndex] != '[') { throw new SerializationException(SR.Serialization_InvalidData); } _currentTokenStartIndex++; int nextInt32Value = GetNextInt32Value(); if (nextInt32Value != 0 && nextInt32Value != 1) { throw new SerializationException(SR.Serialization_InvalidData); } DateTime nextDateTimeValue = GetNextDateTimeValue("HH:mm:ss.FFF"); nextDateTimeValue = new DateTime(1, 1, 1, nextDateTimeValue.Hour, nextDateTimeValue.Minute, nextDateTimeValue.Second, nextDateTimeValue.Millisecond); int nextInt32Value2 = GetNextInt32Value(); TransitionTime result; if (nextInt32Value == 1) { int nextInt32Value3 = GetNextInt32Value(); try { result = TransitionTime.CreateFixedDateRule(nextDateTimeValue, nextInt32Value2, nextInt32Value3); } catch (ArgumentException innerException) { throw new SerializationException(SR.Serialization_InvalidData, innerException); } } else { int nextInt32Value4 = GetNextInt32Value(); int nextInt32Value5 = GetNextInt32Value(); try { result = TransitionTime.CreateFloatingDateRule(nextDateTimeValue, nextInt32Value2, nextInt32Value4, (DayOfWeek)nextInt32Value5); } catch (ArgumentException innerException2) { throw new SerializationException(SR.Serialization_InvalidData, innerException2); } } if (_state == State.EndOfLine || _currentTokenStartIndex >= _serializedText.Length) { throw new SerializationException(SR.Serialization_InvalidData); } if (_serializedText[_currentTokenStartIndex] != ']') { SkipVersionNextDataFields(1); } else { _currentTokenStartIndex++; } bool flag = false; if (_currentTokenStartIndex < _serializedText.Length && _serializedText[_currentTokenStartIndex] == ';') { _currentTokenStartIndex++; flag = true; } if (!flag) { throw new SerializationException(SR.Serialization_InvalidData); } if (_currentTokenStartIndex >= _serializedText.Length) { _state = State.EndOfLine; } else { _state = State.StartOfToken; } return result; } } [Serializable] public readonly struct TransitionTime : IEquatable, ISerializable, IDeserializationCallback { private readonly DateTime _timeOfDay; private readonly byte _month; private readonly byte _week; private readonly byte _day; private readonly DayOfWeek _dayOfWeek; private readonly bool _isFixedDateRule; public DateTime TimeOfDay => _timeOfDay; public int Month => _month; public int Week => _week; public int Day => _day; public DayOfWeek DayOfWeek => _dayOfWeek; public bool IsFixedDateRule => _isFixedDateRule; public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is TransitionTime) { return Equals((TransitionTime)obj); } return false; } public static bool operator ==(TransitionTime t1, TransitionTime t2) { return t1.Equals(t2); } public static bool operator !=(TransitionTime t1, TransitionTime t2) { return !t1.Equals(t2); } public bool Equals(TransitionTime other) { if (_isFixedDateRule == other._isFixedDateRule && _timeOfDay == other._timeOfDay && _month == other._month) { if (!other._isFixedDateRule) { if (_week == other._week) { return _dayOfWeek == other._dayOfWeek; } return false; } return _day == other._day; } return false; } public override int GetHashCode() { return _month ^ (_week << 8); } private TransitionTime(DateTime timeOfDay, int month, int week, int day, DayOfWeek dayOfWeek, bool isFixedDateRule) { ValidateTransitionTime(timeOfDay, month, week, day, dayOfWeek); _timeOfDay = timeOfDay; _month = (byte)month; _week = (byte)week; _day = (byte)day; _dayOfWeek = dayOfWeek; _isFixedDateRule = isFixedDateRule; } public static TransitionTime CreateFixedDateRule(DateTime timeOfDay, int month, int day) { return new TransitionTime(timeOfDay, month, 1, day, DayOfWeek.Sunday, isFixedDateRule: true); } public static TransitionTime CreateFloatingDateRule(DateTime timeOfDay, int month, int week, DayOfWeek dayOfWeek) { return new TransitionTime(timeOfDay, month, week, 1, dayOfWeek, isFixedDateRule: false); } private static void ValidateTransitionTime(DateTime timeOfDay, int month, int week, int day, DayOfWeek dayOfWeek) { if (timeOfDay.Kind != 0) { throw new ArgumentException(SR.Argument_DateTimeKindMustBeUnspecified, "timeOfDay"); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", SR.ArgumentOutOfRange_MonthParam); } if (day < 1 || day > 31) { throw new ArgumentOutOfRangeException("day", SR.ArgumentOutOfRange_DayParam); } if (week < 1 || week > 5) { throw new ArgumentOutOfRangeException("week", SR.ArgumentOutOfRange_Week); } if (dayOfWeek < DayOfWeek.Sunday || dayOfWeek > DayOfWeek.Saturday) { throw new ArgumentOutOfRangeException("dayOfWeek", SR.ArgumentOutOfRange_DayOfWeek); } timeOfDay.GetDate(out var year, out var month2, out var day2); if (year != 1 || month2 != 1 || day2 != 1 || timeOfDay.Ticks % 10000 != 0L) { throw new ArgumentException(SR.Argument_DateTimeHasTicks, "timeOfDay"); } } void IDeserializationCallback.OnDeserialization(object sender) { if (this != default(TransitionTime)) { try { ValidateTransitionTime(_timeOfDay, _month, _week, _day, _dayOfWeek); } catch (ArgumentException innerException) { throw new SerializationException(SR.Serialization_InvalidData, innerException); } } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("TimeOfDay", _timeOfDay); info.AddValue("Month", _month); info.AddValue("Week", _week); info.AddValue("Day", _day); info.AddValue("DayOfWeek", _dayOfWeek); info.AddValue("IsFixedDateRule", _isFixedDateRule); } private TransitionTime(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } _timeOfDay = (DateTime)info.GetValue("TimeOfDay", typeof(DateTime)); _month = (byte)info.GetValue("Month", typeof(byte)); _week = (byte)info.GetValue("Week", typeof(byte)); _day = (byte)info.GetValue("Day", typeof(byte)); _dayOfWeek = (DayOfWeek)info.GetValue("DayOfWeek", typeof(DayOfWeek)); _isFixedDateRule = (bool)info.GetValue("IsFixedDateRule", typeof(bool)); } } private sealed class OffsetAndRule { public readonly int Year; public readonly TimeSpan Offset; public readonly AdjustmentRule Rule; public OffsetAndRule(int year, TimeSpan offset, AdjustmentRule rule) { Year = year; Offset = offset; Rule = rule; } } private readonly string _id; private readonly string _displayName; private readonly string _standardDisplayName; private readonly string _daylightDisplayName; private readonly TimeSpan _baseUtcOffset; private readonly bool _supportsDaylightSavingTime; private readonly AdjustmentRule[] _adjustmentRules; private List _equivalentZones; private static readonly TimeZoneInfo s_utcTimeZone = CreateUtcTimeZone(); private static CachedData s_cachedData = new CachedData(); private static readonly DateTime s_maxDateOnly = new DateTime(9999, 12, 31); private static readonly DateTime s_minDateOnly = new DateTime(1, 1, 2); private static readonly TimeSpan MaxOffset = TimeSpan.FromHours(14.0); private static readonly TimeSpan MinOffset = -MaxOffset; public string Id => _id; public bool HasIanaId { get; } public string DisplayName => _displayName ?? string.Empty; public string StandardName => _standardDisplayName ?? string.Empty; public string DaylightName => _daylightDisplayName ?? string.Empty; public TimeSpan BaseUtcOffset => _baseUtcOffset; public bool SupportsDaylightSavingTime => _supportsDaylightSavingTime; public static TimeZoneInfo Local => s_cachedData.Local; public static TimeZoneInfo Utc => s_utcTimeZone; public TimeSpan[] GetAmbiguousTimeOffsets(DateTimeOffset dateTimeOffset) { if (!SupportsDaylightSavingTime) { throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, "dateTimeOffset"); } DateTime dateTime = ConvertTime(dateTimeOffset, this).DateTime; bool flag = false; int? ruleIndex; AdjustmentRule adjustmentRuleForAmbiguousOffsets = GetAdjustmentRuleForAmbiguousOffsets(dateTime, out ruleIndex); if (adjustmentRuleForAmbiguousOffsets != null && adjustmentRuleForAmbiguousOffsets.HasDaylightSaving) { DaylightTimeStruct daylightTime = GetDaylightTime(dateTime.Year, adjustmentRuleForAmbiguousOffsets, ruleIndex); flag = GetIsAmbiguousTime(dateTime, adjustmentRuleForAmbiguousOffsets, daylightTime); } if (!flag) { throw new ArgumentException(SR.Argument_DateTimeOffsetIsNotAmbiguous, "dateTimeOffset"); } TimeSpan[] array = new TimeSpan[2]; TimeSpan timeSpan = _baseUtcOffset + adjustmentRuleForAmbiguousOffsets.BaseUtcOffsetDelta; if (adjustmentRuleForAmbiguousOffsets.DaylightDelta > TimeSpan.Zero) { array[0] = timeSpan; array[1] = timeSpan + adjustmentRuleForAmbiguousOffsets.DaylightDelta; } else { array[0] = timeSpan + adjustmentRuleForAmbiguousOffsets.DaylightDelta; array[1] = timeSpan; } return array; } public TimeSpan[] GetAmbiguousTimeOffsets(DateTime dateTime) { if (!SupportsDaylightSavingTime) { throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, "dateTime"); } DateTime dateTime2; if (dateTime.Kind == DateTimeKind.Local) { CachedData cachedData = s_cachedData; dateTime2 = ConvertTime(dateTime, cachedData.Local, this, TimeZoneInfoOptions.None, cachedData); } else if (dateTime.Kind == DateTimeKind.Utc) { CachedData cachedData2 = s_cachedData; dateTime2 = ConvertTime(dateTime, s_utcTimeZone, this, TimeZoneInfoOptions.None, cachedData2); } else { dateTime2 = dateTime; } bool flag = false; int? ruleIndex; AdjustmentRule adjustmentRuleForAmbiguousOffsets = GetAdjustmentRuleForAmbiguousOffsets(dateTime2, out ruleIndex); if (adjustmentRuleForAmbiguousOffsets != null && adjustmentRuleForAmbiguousOffsets.HasDaylightSaving) { DaylightTimeStruct daylightTime = GetDaylightTime(dateTime2.Year, adjustmentRuleForAmbiguousOffsets, ruleIndex); flag = GetIsAmbiguousTime(dateTime2, adjustmentRuleForAmbiguousOffsets, daylightTime); } if (!flag) { throw new ArgumentException(SR.Argument_DateTimeIsNotAmbiguous, "dateTime"); } TimeSpan[] array = new TimeSpan[2]; TimeSpan timeSpan = _baseUtcOffset + adjustmentRuleForAmbiguousOffsets.BaseUtcOffsetDelta; if (adjustmentRuleForAmbiguousOffsets.DaylightDelta > TimeSpan.Zero) { array[0] = timeSpan; array[1] = timeSpan + adjustmentRuleForAmbiguousOffsets.DaylightDelta; } else { array[0] = timeSpan + adjustmentRuleForAmbiguousOffsets.DaylightDelta; array[1] = timeSpan; } return array; } private AdjustmentRule GetAdjustmentRuleForAmbiguousOffsets(DateTime adjustedTime, out int? ruleIndex) { AdjustmentRule adjustmentRuleForTime = GetAdjustmentRuleForTime(adjustedTime, out ruleIndex); if (adjustmentRuleForTime != null && adjustmentRuleForTime.NoDaylightTransitions && !adjustmentRuleForTime.HasDaylightSaving) { return GetPreviousAdjustmentRule(adjustmentRuleForTime, ruleIndex); } return adjustmentRuleForTime; } private AdjustmentRule GetPreviousAdjustmentRule(AdjustmentRule rule, int? ruleIndex) { if (ruleIndex.HasValue && 0 < ruleIndex.GetValueOrDefault() && ruleIndex.GetValueOrDefault() < _adjustmentRules.Length) { return _adjustmentRules[ruleIndex.GetValueOrDefault() - 1]; } AdjustmentRule result = rule; for (int i = 1; i < _adjustmentRules.Length; i++) { if (rule == _adjustmentRules[i]) { result = _adjustmentRules[i - 1]; break; } } return result; } public TimeSpan GetUtcOffset(DateTimeOffset dateTimeOffset) { return GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this); } public TimeSpan GetUtcOffset(DateTime dateTime) { return GetUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData); } internal static TimeSpan GetLocalUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags) { CachedData cachedData = s_cachedData; return cachedData.Local.GetUtcOffset(dateTime, flags, cachedData); } internal TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags) { return GetUtcOffset(dateTime, flags, s_cachedData); } private TimeSpan GetUtcOffset(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData) { if (dateTime.Kind == DateTimeKind.Local) { if (cachedData.GetCorrespondingKind(this) != DateTimeKind.Local) { DateTime time = ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags); return GetUtcOffsetFromUtc(time, this); } } else if (dateTime.Kind == DateTimeKind.Utc) { if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc) { return _baseUtcOffset; } return GetUtcOffsetFromUtc(dateTime, this); } return GetUtcOffset(dateTime, this); } public bool IsAmbiguousTime(DateTimeOffset dateTimeOffset) { if (!_supportsDaylightSavingTime) { return false; } return IsAmbiguousTime(ConvertTime(dateTimeOffset, this).DateTime); } public bool IsAmbiguousTime(DateTime dateTime) { return IsAmbiguousTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime); } internal bool IsAmbiguousTime(DateTime dateTime, TimeZoneInfoOptions flags) { if (!_supportsDaylightSavingTime) { return false; } CachedData cachedData = s_cachedData; DateTime dateTime2 = ((dateTime.Kind == DateTimeKind.Local) ? ConvertTime(dateTime, cachedData.Local, this, flags, cachedData) : ((dateTime.Kind == DateTimeKind.Utc) ? ConvertTime(dateTime, s_utcTimeZone, this, flags, cachedData) : dateTime)); int? ruleIndex; AdjustmentRule adjustmentRuleForTime = GetAdjustmentRuleForTime(dateTime2, out ruleIndex); if (adjustmentRuleForTime != null && adjustmentRuleForTime.HasDaylightSaving) { DaylightTimeStruct daylightTime = GetDaylightTime(dateTime2.Year, adjustmentRuleForTime, ruleIndex); return GetIsAmbiguousTime(dateTime2, adjustmentRuleForTime, daylightTime); } return false; } public bool IsDaylightSavingTime(DateTimeOffset dateTimeOffset) { GetUtcOffsetFromUtc(dateTimeOffset.UtcDateTime, this, out var isDaylightSavings); return isDaylightSavings; } public bool IsDaylightSavingTime(DateTime dateTime) { return IsDaylightSavingTime(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime, s_cachedData); } internal bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags) { return IsDaylightSavingTime(dateTime, flags, s_cachedData); } private bool IsDaylightSavingTime(DateTime dateTime, TimeZoneInfoOptions flags, CachedData cachedData) { if (!_supportsDaylightSavingTime || _adjustmentRules == null) { return false; } DateTime dateTime2; if (dateTime.Kind == DateTimeKind.Local) { dateTime2 = ConvertTime(dateTime, cachedData.Local, this, flags, cachedData); } else { if (dateTime.Kind == DateTimeKind.Utc) { if (cachedData.GetCorrespondingKind(this) == DateTimeKind.Utc) { return false; } GetUtcOffsetFromUtc(dateTime, this, out var isDaylightSavings); return isDaylightSavings; } dateTime2 = dateTime; } int? ruleIndex; AdjustmentRule adjustmentRuleForTime = GetAdjustmentRuleForTime(dateTime2, out ruleIndex); if (adjustmentRuleForTime != null && adjustmentRuleForTime.HasDaylightSaving) { DaylightTimeStruct daylightTime = GetDaylightTime(dateTime2.Year, adjustmentRuleForTime, ruleIndex); return GetIsDaylightSavings(dateTime2, adjustmentRuleForTime, daylightTime); } return false; } public bool IsInvalidTime(DateTime dateTime) { bool result = false; if (dateTime.Kind == DateTimeKind.Unspecified || (dateTime.Kind == DateTimeKind.Local && s_cachedData.GetCorrespondingKind(this) == DateTimeKind.Local)) { int? ruleIndex; AdjustmentRule adjustmentRuleForTime = GetAdjustmentRuleForTime(dateTime, out ruleIndex); if (adjustmentRuleForTime != null && adjustmentRuleForTime.HasDaylightSaving) { DaylightTimeStruct daylightTime = GetDaylightTime(dateTime.Year, adjustmentRuleForTime, ruleIndex); result = GetIsInvalidTime(dateTime, adjustmentRuleForTime, daylightTime); } else { result = false; } } return result; } public static void ClearCachedData() { s_cachedData = new CachedData(); } public static DateTimeOffset ConvertTimeBySystemTimeZoneId(DateTimeOffset dateTimeOffset, string destinationTimeZoneId) { return ConvertTime(dateTimeOffset, FindSystemTimeZoneById(destinationTimeZoneId)); } public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string destinationTimeZoneId) { return ConvertTime(dateTime, FindSystemTimeZoneById(destinationTimeZoneId)); } public static DateTime ConvertTimeBySystemTimeZoneId(DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId) { if (dateTime.Kind == DateTimeKind.Local && string.Equals(sourceTimeZoneId, Local.Id, StringComparison.OrdinalIgnoreCase)) { CachedData cachedData = s_cachedData; return ConvertTime(dateTime, cachedData.Local, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, cachedData); } if (dateTime.Kind == DateTimeKind.Utc && string.Equals(sourceTimeZoneId, Utc.Id, StringComparison.OrdinalIgnoreCase)) { return ConvertTime(dateTime, s_utcTimeZone, FindSystemTimeZoneById(destinationTimeZoneId), TimeZoneInfoOptions.None, s_cachedData); } return ConvertTime(dateTime, FindSystemTimeZoneById(sourceTimeZoneId), FindSystemTimeZoneById(destinationTimeZoneId)); } public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone) { if (destinationTimeZone == null) { throw new ArgumentNullException("destinationTimeZone"); } DateTime utcDateTime = dateTimeOffset.UtcDateTime; TimeSpan utcOffsetFromUtc = GetUtcOffsetFromUtc(utcDateTime, destinationTimeZone); long num = utcDateTime.Ticks + utcOffsetFromUtc.Ticks; if (num <= DateTimeOffset.MaxValue.Ticks) { if (num >= DateTimeOffset.MinValue.Ticks) { return new DateTimeOffset(num, utcOffsetFromUtc); } return DateTimeOffset.MinValue; } return DateTimeOffset.MaxValue; } public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo destinationTimeZone) { if (destinationTimeZone == null) { throw new ArgumentNullException("destinationTimeZone"); } if (dateTime.Ticks == 0L) { ClearCachedData(); } CachedData cachedData = s_cachedData; TimeZoneInfo sourceTimeZone = ((dateTime.Kind == DateTimeKind.Utc) ? s_utcTimeZone : cachedData.Local); return ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, cachedData); } public static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone) { return ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData); } internal static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags) { return ConvertTime(dateTime, sourceTimeZone, destinationTimeZone, flags, s_cachedData); } private static DateTime ConvertTime(DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone, TimeZoneInfoOptions flags, CachedData cachedData) { if (sourceTimeZone == null) { throw new ArgumentNullException("sourceTimeZone"); } if (destinationTimeZone == null) { throw new ArgumentNullException("destinationTimeZone"); } DateTimeKind correspondingKind = cachedData.GetCorrespondingKind(sourceTimeZone); if ((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0 && dateTime.Kind != 0 && dateTime.Kind != correspondingKind) { throw new ArgumentException(SR.Argument_ConvertMismatch, "sourceTimeZone"); } int? ruleIndex; AdjustmentRule adjustmentRuleForTime = sourceTimeZone.GetAdjustmentRuleForTime(dateTime, out ruleIndex); TimeSpan baseUtcOffset = sourceTimeZone.BaseUtcOffset; if (adjustmentRuleForTime != null) { baseUtcOffset += adjustmentRuleForTime.BaseUtcOffsetDelta; if (adjustmentRuleForTime.HasDaylightSaving) { bool flag = false; DaylightTimeStruct daylightTime = sourceTimeZone.GetDaylightTime(dateTime.Year, adjustmentRuleForTime, ruleIndex); if ((flags & TimeZoneInfoOptions.NoThrowOnInvalidTime) == 0 && GetIsInvalidTime(dateTime, adjustmentRuleForTime, daylightTime)) { throw new ArgumentException(SR.Argument_DateTimeIsInvalid, "dateTime"); } flag = GetIsDaylightSavings(dateTime, adjustmentRuleForTime, daylightTime); baseUtcOffset += (flag ? adjustmentRuleForTime.DaylightDelta : TimeSpan.Zero); } } DateTimeKind correspondingKind2 = cachedData.GetCorrespondingKind(destinationTimeZone); if (dateTime.Kind != 0 && correspondingKind != 0 && correspondingKind == correspondingKind2) { return dateTime; } long ticks = dateTime.Ticks - baseUtcOffset.Ticks; bool isAmbiguousLocalDst; DateTime dateTime2 = ConvertUtcToTimeZone(ticks, destinationTimeZone, out isAmbiguousLocalDst); if (correspondingKind2 == DateTimeKind.Local) { return new DateTime(dateTime2.Ticks, DateTimeKind.Local, isAmbiguousLocalDst); } return new DateTime(dateTime2.Ticks, correspondingKind2); } public static DateTime ConvertTimeFromUtc(DateTime dateTime, TimeZoneInfo destinationTimeZone) { return ConvertTime(dateTime, s_utcTimeZone, destinationTimeZone, TimeZoneInfoOptions.None, s_cachedData); } public static DateTime ConvertTimeToUtc(DateTime dateTime) { if (dateTime.Kind == DateTimeKind.Utc) { return dateTime; } CachedData cachedData = s_cachedData; return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, TimeZoneInfoOptions.None, cachedData); } internal static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfoOptions flags) { if (dateTime.Kind == DateTimeKind.Utc) { return dateTime; } CachedData cachedData = s_cachedData; return ConvertTime(dateTime, cachedData.Local, s_utcTimeZone, flags, cachedData); } public static DateTime ConvertTimeToUtc(DateTime dateTime, TimeZoneInfo sourceTimeZone) { return ConvertTime(dateTime, sourceTimeZone, s_utcTimeZone, TimeZoneInfoOptions.None, s_cachedData); } public bool Equals([NotNullWhen(true)] TimeZoneInfo? other) { if (other != null && string.Equals(_id, other._id, StringComparison.OrdinalIgnoreCase)) { return HasSameRules(other); } return false; } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj as TimeZoneInfo); } public static TimeZoneInfo FromSerializedString(string source) { if (source == null) { throw new ArgumentNullException("source"); } if (source.Length == 0) { throw new ArgumentException(SR.Format(SR.Argument_InvalidSerializedString, source), "source"); } return StringSerializer.GetDeserializedTimeZoneInfo(source); } public override int GetHashCode() { return StringComparer.OrdinalIgnoreCase.GetHashCode(_id); } public static ReadOnlyCollection GetSystemTimeZones() { CachedData cachedData = s_cachedData; lock (cachedData) { if (cachedData._readOnlySystemTimeZones == null) { PopulateAllSystemTimeZones(cachedData); cachedData._allSystemTimeZonesRead = true; List list = ((cachedData._systemTimeZones == null) ? new List() : new List(cachedData._systemTimeZones.Values)); list.Sort(delegate(TimeZoneInfo x, TimeZoneInfo y) { int num = x.BaseUtcOffset.CompareTo(y.BaseUtcOffset); return (num != 0) ? num : string.CompareOrdinal(x.DisplayName, y.DisplayName); }); cachedData._readOnlySystemTimeZones = new ReadOnlyCollection(list); } } return cachedData._readOnlySystemTimeZones; } public bool HasSameRules(TimeZoneInfo other) { if (other == null) { throw new ArgumentNullException("other"); } if (_baseUtcOffset != other._baseUtcOffset || _supportsDaylightSavingTime != other._supportsDaylightSavingTime) { return false; } AdjustmentRule[] adjustmentRules = _adjustmentRules; AdjustmentRule[] adjustmentRules2 = other._adjustmentRules; if (adjustmentRules == null || adjustmentRules2 == null) { return adjustmentRules == adjustmentRules2; } return adjustmentRules.AsSpan().SequenceEqual(adjustmentRules2); } public string ToSerializedString() { return StringSerializer.GetSerializedString(this); } public override string ToString() { return DisplayName; } private TimeZoneInfo(string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, AdjustmentRule[] adjustmentRules, bool disableDaylightSavingTime, bool hasIanaId = false) { ValidateTimeZoneInfo(id, baseUtcOffset, adjustmentRules, out var adjustmentRulesSupportDst); _id = id; _baseUtcOffset = baseUtcOffset; _displayName = displayName; _standardDisplayName = standardDisplayName; _daylightDisplayName = (disableDaylightSavingTime ? null : daylightDisplayName); _supportsDaylightSavingTime = adjustmentRulesSupportDst && !disableDaylightSavingTime; _adjustmentRules = adjustmentRules; HasIanaId = _id.Equals("UTC", StringComparison.OrdinalIgnoreCase) || hasIanaId; } public static TimeZoneInfo CreateCustomTimeZone(string id, TimeSpan baseUtcOffset, string? displayName, string? standardDisplayName) { string windowsId; bool hasIanaId = TryConvertIanaIdToWindowsId(id, allocate: false, out windowsId); return new TimeZoneInfo(id, baseUtcOffset, displayName, standardDisplayName, standardDisplayName, null, disableDaylightSavingTime: false, hasIanaId); } public static TimeZoneInfo CreateCustomTimeZone(string id, TimeSpan baseUtcOffset, string? displayName, string? standardDisplayName, string? daylightDisplayName, AdjustmentRule[]? adjustmentRules) { return CreateCustomTimeZone(id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime: false); } public static TimeZoneInfo CreateCustomTimeZone(string id, TimeSpan baseUtcOffset, string? displayName, string? standardDisplayName, string? daylightDisplayName, AdjustmentRule[]? adjustmentRules, bool disableDaylightSavingTime) { if (!disableDaylightSavingTime && adjustmentRules != null && adjustmentRules.Length != 0) { adjustmentRules = (AdjustmentRule[])adjustmentRules.Clone(); } string windowsId; bool hasIanaId = TryConvertIanaIdToWindowsId(id, allocate: false, out windowsId); return new TimeZoneInfo(id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime, hasIanaId); } public static bool TryConvertIanaIdToWindowsId(string ianaId, [NotNullWhen(true)] out string? windowsId) { return TryConvertIanaIdToWindowsId(ianaId, allocate: true, out windowsId); } public static bool TryConvertWindowsIdToIanaId(string windowsId, [NotNullWhen(true)] out string? ianaId) { return TryConvertWindowsIdToIanaId(windowsId, null, allocate: true, out ianaId); } public static bool TryConvertWindowsIdToIanaId(string windowsId, string? region, [NotNullWhen(true)] out string? ianaId) { return TryConvertWindowsIdToIanaId(windowsId, region, allocate: true, out ianaId); } void IDeserializationCallback.OnDeserialization(object sender) { try { ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out var adjustmentRulesSupportDst); if (adjustmentRulesSupportDst != _supportsDaylightSavingTime) { throw new SerializationException(SR.Format(SR.Serialization_CorruptField, "SupportsDaylightSavingTime")); } } catch (ArgumentException innerException) { throw new SerializationException(SR.Serialization_InvalidData, innerException); } catch (InvalidTimeZoneException innerException2) { throw new SerializationException(SR.Serialization_InvalidData, innerException2); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("Id", _id); info.AddValue("DisplayName", _displayName); info.AddValue("StandardName", _standardDisplayName); info.AddValue("DaylightName", _daylightDisplayName); info.AddValue("BaseUtcOffset", _baseUtcOffset); info.AddValue("AdjustmentRules", _adjustmentRules); info.AddValue("SupportsDaylightSavingTime", _supportsDaylightSavingTime); } private TimeZoneInfo(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } _id = (string)info.GetValue("Id", typeof(string)); _displayName = (string)info.GetValue("DisplayName", typeof(string)); _standardDisplayName = (string)info.GetValue("StandardName", typeof(string)); _daylightDisplayName = (string)info.GetValue("DaylightName", typeof(string)); _baseUtcOffset = (TimeSpan)info.GetValue("BaseUtcOffset", typeof(TimeSpan)); _adjustmentRules = (AdjustmentRule[])info.GetValue("AdjustmentRules", typeof(AdjustmentRule[])); _supportsDaylightSavingTime = (bool)info.GetValue("SupportsDaylightSavingTime", typeof(bool)); } private AdjustmentRule GetAdjustmentRuleForTime(DateTime dateTime, out int? ruleIndex) { return GetAdjustmentRuleForTime(dateTime, dateTimeisUtc: false, out ruleIndex); } private AdjustmentRule GetAdjustmentRuleForTime(DateTime dateTime, bool dateTimeisUtc, out int? ruleIndex) { if (_adjustmentRules == null || _adjustmentRules.Length == 0) { ruleIndex = null; return null; } DateTime dateOnly = (dateTimeisUtc ? (dateTime + BaseUtcOffset).Date : dateTime.Date); int num = 0; int num2 = _adjustmentRules.Length - 1; while (num <= num2) { int num3 = num + (num2 - num >> 1); AdjustmentRule adjustmentRule = _adjustmentRules[num3]; AdjustmentRule previousRule = ((num3 > 0) ? _adjustmentRules[num3 - 1] : adjustmentRule); int num4 = CompareAdjustmentRuleToDateTime(adjustmentRule, previousRule, dateTime, dateOnly, dateTimeisUtc); if (num4 == 0) { ruleIndex = num3; return adjustmentRule; } if (num4 < 0) { num = num3 + 1; } else { num2 = num3 - 1; } } ruleIndex = null; return null; } private int CompareAdjustmentRuleToDateTime(AdjustmentRule rule, AdjustmentRule previousRule, DateTime dateTime, DateTime dateOnly, bool dateTimeisUtc) { bool flag; if (rule.DateStart.Kind == DateTimeKind.Utc) { DateTime dateTime2 = (dateTimeisUtc ? dateTime : ConvertToUtc(dateTime, previousRule.DaylightDelta, previousRule.BaseUtcOffsetDelta)); flag = dateTime2 >= rule.DateStart; } else { flag = dateOnly >= rule.DateStart; } if (!flag) { return 1; } bool flag2; if (rule.DateEnd.Kind == DateTimeKind.Utc) { DateTime dateTime3 = (dateTimeisUtc ? dateTime : ConvertToUtc(dateTime, rule.DaylightDelta, rule.BaseUtcOffsetDelta)); flag2 = dateTime3 <= rule.DateEnd; } else { flag2 = dateOnly <= rule.DateEnd; } if (!flag2) { return -1; } return 0; } private DateTime ConvertToUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta) { return ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: true); } private DateTime ConvertFromUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta) { return ConvertToFromUtc(dateTime, daylightDelta, baseUtcOffsetDelta, convertToUtc: false); } private DateTime ConvertToFromUtc(DateTime dateTime, TimeSpan daylightDelta, TimeSpan baseUtcOffsetDelta, bool convertToUtc) { TimeSpan timeSpan = BaseUtcOffset + daylightDelta + baseUtcOffsetDelta; if (convertToUtc) { timeSpan = timeSpan.Negate(); } long num = dateTime.Ticks + timeSpan.Ticks; if (num <= DateTime.MaxValue.Ticks) { if (num >= DateTime.MinValue.Ticks) { return new DateTime(num); } return DateTime.MinValue; } return DateTime.MaxValue; } private static DateTime ConvertUtcToTimeZone(long ticks, TimeZoneInfo destinationTimeZone, out bool isAmbiguousLocalDst) { DateTime time = ((ticks > DateTime.MaxValue.Ticks) ? DateTime.MaxValue : ((ticks < DateTime.MinValue.Ticks) ? DateTime.MinValue : new DateTime(ticks))); ticks += GetUtcOffsetFromUtc(time, destinationTimeZone, out isAmbiguousLocalDst).Ticks; if (ticks <= DateTime.MaxValue.Ticks) { if (ticks >= DateTime.MinValue.Ticks) { return new DateTime(ticks); } return DateTime.MinValue; } return DateTime.MaxValue; } private DaylightTimeStruct GetDaylightTime(int year, AdjustmentRule rule, int? ruleIndex) { TimeSpan daylightDelta = rule.DaylightDelta; DateTime start; DateTime end; if (rule.NoDaylightTransitions) { AdjustmentRule previousAdjustmentRule = GetPreviousAdjustmentRule(rule, ruleIndex); start = ConvertFromUtc(rule.DateStart, previousAdjustmentRule.DaylightDelta, previousAdjustmentRule.BaseUtcOffsetDelta); end = ConvertFromUtc(rule.DateEnd, rule.DaylightDelta, rule.BaseUtcOffsetDelta); } else { start = TransitionTimeToDateTime(year, rule.DaylightTransitionStart); end = TransitionTimeToDateTime(year, rule.DaylightTransitionEnd); } return new DaylightTimeStruct(start, end, daylightDelta); } private static bool GetIsDaylightSavings(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime) { if (rule == null) { return false; } DateTime startTime; DateTime endTime; if (time.Kind == DateTimeKind.Local) { startTime = (rule.IsStartDateMarkerForBeginningOfYear() ? new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) : (daylightTime.Start + daylightTime.Delta)); endTime = (rule.IsEndDateMarkerForEndOfYear() ? new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1L) : daylightTime.End); } else { bool flag = rule.DaylightDelta > TimeSpan.Zero; startTime = (rule.IsStartDateMarkerForBeginningOfYear() ? new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) : (daylightTime.Start + (flag ? rule.DaylightDelta : TimeSpan.Zero))); endTime = (rule.IsEndDateMarkerForEndOfYear() ? new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1L) : (daylightTime.End + (flag ? (-rule.DaylightDelta) : TimeSpan.Zero))); } bool flag2 = CheckIsDst(startTime, time, endTime, ignoreYearAdjustment: false, rule); if (flag2 && time.Kind == DateTimeKind.Local && GetIsAmbiguousTime(time, rule, daylightTime)) { flag2 = time.IsAmbiguousDaylightSavingTime(); } return flag2; } private TimeSpan GetDaylightSavingsStartOffsetFromUtc(TimeSpan baseUtcOffset, AdjustmentRule rule, int? ruleIndex) { if (rule.NoDaylightTransitions) { AdjustmentRule previousAdjustmentRule = GetPreviousAdjustmentRule(rule, ruleIndex); return baseUtcOffset + previousAdjustmentRule.BaseUtcOffsetDelta + previousAdjustmentRule.DaylightDelta; } return baseUtcOffset + rule.BaseUtcOffsetDelta; } private static TimeSpan GetDaylightSavingsEndOffsetFromUtc(TimeSpan baseUtcOffset, AdjustmentRule rule) { return baseUtcOffset + rule.BaseUtcOffsetDelta + rule.DaylightDelta; } private static bool GetIsDaylightSavingsFromUtc(DateTime time, int year, TimeSpan utc, AdjustmentRule rule, int? ruleIndex, out bool isAmbiguousLocalDst, TimeZoneInfo zone) { isAmbiguousLocalDst = false; if (rule == null) { return false; } DaylightTimeStruct daylightTime = zone.GetDaylightTime(year, rule, ruleIndex); bool ignoreYearAdjustment = false; TimeSpan daylightSavingsStartOffsetFromUtc = zone.GetDaylightSavingsStartOffsetFromUtc(utc, rule, ruleIndex); DateTime dateTime; if (rule.IsStartDateMarkerForBeginningOfYear() && daylightTime.Start.Year > DateTime.MinValue.Year) { int? ruleIndex2; AdjustmentRule adjustmentRuleForTime = zone.GetAdjustmentRuleForTime(new DateTime(daylightTime.Start.Year - 1, 12, 31), out ruleIndex2); if (adjustmentRuleForTime != null && adjustmentRuleForTime.IsEndDateMarkerForEndOfYear()) { dateTime = zone.GetDaylightTime(daylightTime.Start.Year - 1, adjustmentRuleForTime, ruleIndex2).Start - utc - adjustmentRuleForTime.BaseUtcOffsetDelta; ignoreYearAdjustment = true; } else { dateTime = new DateTime(daylightTime.Start.Year, 1, 1, 0, 0, 0) - daylightSavingsStartOffsetFromUtc; } } else { dateTime = daylightTime.Start - daylightSavingsStartOffsetFromUtc; } TimeSpan daylightSavingsEndOffsetFromUtc = GetDaylightSavingsEndOffsetFromUtc(utc, rule); DateTime dateTime2; if (rule.IsEndDateMarkerForEndOfYear() && daylightTime.End.Year < DateTime.MaxValue.Year) { int? ruleIndex3; AdjustmentRule adjustmentRuleForTime2 = zone.GetAdjustmentRuleForTime(new DateTime(daylightTime.End.Year + 1, 1, 1), out ruleIndex3); if (adjustmentRuleForTime2 != null && adjustmentRuleForTime2.IsStartDateMarkerForBeginningOfYear()) { dateTime2 = ((!adjustmentRuleForTime2.IsEndDateMarkerForEndOfYear()) ? (zone.GetDaylightTime(daylightTime.End.Year + 1, adjustmentRuleForTime2, ruleIndex3).End - utc - adjustmentRuleForTime2.BaseUtcOffsetDelta - adjustmentRuleForTime2.DaylightDelta) : (new DateTime(daylightTime.End.Year + 1, 12, 31) - utc - adjustmentRuleForTime2.BaseUtcOffsetDelta - adjustmentRuleForTime2.DaylightDelta)); ignoreYearAdjustment = true; } else { dateTime2 = new DateTime(daylightTime.End.Year + 1, 1, 1, 0, 0, 0).AddTicks(-1L) - daylightSavingsEndOffsetFromUtc; } } else { dateTime2 = daylightTime.End - daylightSavingsEndOffsetFromUtc; } DateTime dateTime3; DateTime dateTime4; if (daylightTime.Delta.Ticks > 0) { dateTime3 = dateTime2 - daylightTime.Delta; dateTime4 = dateTime2; } else { dateTime3 = dateTime; dateTime4 = dateTime - daylightTime.Delta; } bool flag = CheckIsDst(dateTime, time, dateTime2, ignoreYearAdjustment, rule); if (flag) { isAmbiguousLocalDst = time >= dateTime3 && time < dateTime4; if (!isAmbiguousLocalDst && dateTime3.Year != dateTime4.Year) { try { DateTime dateTime5 = dateTime3.AddYears(1); DateTime dateTime6 = dateTime4.AddYears(1); isAmbiguousLocalDst = time >= dateTime5 && time < dateTime6; } catch (ArgumentOutOfRangeException) { } if (!isAmbiguousLocalDst) { try { DateTime dateTime5 = dateTime3.AddYears(-1); DateTime dateTime6 = dateTime4.AddYears(-1); isAmbiguousLocalDst = time >= dateTime5 && time < dateTime6; } catch (ArgumentOutOfRangeException) { } } } } return flag; } private static bool CheckIsDst(DateTime startTime, DateTime time, DateTime endTime, bool ignoreYearAdjustment, AdjustmentRule rule) { if (!ignoreYearAdjustment && !rule.NoDaylightTransitions) { int year = startTime.Year; int year2 = endTime.Year; if (year != year2) { endTime = endTime.AddYears(year - year2); } int year3 = time.Year; if (year != year3) { time = time.AddYears(year - year3); } } if (startTime > endTime) { if (!(time < endTime)) { return time >= startTime; } return true; } if (rule.NoDaylightTransitions) { if (time >= startTime) { return time <= endTime; } return false; } if (time >= startTime) { return time < endTime; } return false; } private static bool GetIsAmbiguousTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime) { bool result = false; if (rule == null || rule.DaylightDelta == TimeSpan.Zero) { return result; } DateTime dateTime; DateTime dateTime2; if (rule.DaylightDelta > TimeSpan.Zero) { if (rule.IsEndDateMarkerForEndOfYear()) { return false; } dateTime = daylightTime.End; dateTime2 = daylightTime.End - rule.DaylightDelta; } else { if (rule.IsStartDateMarkerForBeginningOfYear()) { return false; } dateTime = daylightTime.Start; dateTime2 = daylightTime.Start + rule.DaylightDelta; } result = time >= dateTime2 && time < dateTime; if (!result && dateTime.Year != dateTime2.Year) { try { DateTime dateTime3 = dateTime.AddYears(1); DateTime dateTime4 = dateTime2.AddYears(1); result = time >= dateTime4 && time < dateTime3; } catch (ArgumentOutOfRangeException) { } if (!result) { try { DateTime dateTime3 = dateTime.AddYears(-1); DateTime dateTime4 = dateTime2.AddYears(-1); result = time >= dateTime4 && time < dateTime3; } catch (ArgumentOutOfRangeException) { } } } return result; } private static bool GetIsInvalidTime(DateTime time, AdjustmentRule rule, DaylightTimeStruct daylightTime) { bool result = false; if (rule == null || rule.DaylightDelta == TimeSpan.Zero) { return result; } DateTime dateTime; DateTime dateTime2; if (rule.DaylightDelta < TimeSpan.Zero) { if (rule.IsEndDateMarkerForEndOfYear()) { return false; } dateTime = daylightTime.End; dateTime2 = daylightTime.End - rule.DaylightDelta; } else { if (rule.IsStartDateMarkerForBeginningOfYear()) { return false; } dateTime = daylightTime.Start; dateTime2 = daylightTime.Start + rule.DaylightDelta; } result = time >= dateTime && time < dateTime2; if (!result && dateTime.Year != dateTime2.Year) { try { DateTime dateTime3 = dateTime.AddYears(1); DateTime dateTime4 = dateTime2.AddYears(1); result = time >= dateTime3 && time < dateTime4; } catch (ArgumentOutOfRangeException) { } if (!result) { try { DateTime dateTime3 = dateTime.AddYears(-1); DateTime dateTime4 = dateTime2.AddYears(-1); result = time >= dateTime3 && time < dateTime4; } catch (ArgumentOutOfRangeException) { } } } return result; } private static TimeSpan GetUtcOffset(DateTime time, TimeZoneInfo zone) { TimeSpan baseUtcOffset = zone.BaseUtcOffset; int? ruleIndex; AdjustmentRule adjustmentRuleForTime = zone.GetAdjustmentRuleForTime(time, out ruleIndex); if (adjustmentRuleForTime != null) { baseUtcOffset += adjustmentRuleForTime.BaseUtcOffsetDelta; if (adjustmentRuleForTime.HasDaylightSaving) { DaylightTimeStruct daylightTime = zone.GetDaylightTime(time.Year, adjustmentRuleForTime, ruleIndex); bool isDaylightSavings = GetIsDaylightSavings(time, adjustmentRuleForTime, daylightTime); baseUtcOffset += (isDaylightSavings ? adjustmentRuleForTime.DaylightDelta : TimeSpan.Zero); } } return baseUtcOffset; } private static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone) { bool isDaylightSavings; return GetUtcOffsetFromUtc(time, zone, out isDaylightSavings); } private static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out bool isDaylightSavings) { bool isAmbiguousLocalDst; return GetUtcOffsetFromUtc(time, zone, out isDaylightSavings, out isAmbiguousLocalDst); } internal static TimeSpan GetUtcOffsetFromUtc(DateTime time, TimeZoneInfo zone, out bool isDaylightSavings, out bool isAmbiguousLocalDst) { isDaylightSavings = false; isAmbiguousLocalDst = false; TimeSpan baseUtcOffset = zone.BaseUtcOffset; AdjustmentRule adjustmentRuleForTime; int? ruleIndex; int year; if (time > s_maxDateOnly) { adjustmentRuleForTime = zone.GetAdjustmentRuleForTime(DateTime.MaxValue, out ruleIndex); year = 9999; } else if (time < s_minDateOnly) { adjustmentRuleForTime = zone.GetAdjustmentRuleForTime(DateTime.MinValue, out ruleIndex); year = 1; } else { adjustmentRuleForTime = zone.GetAdjustmentRuleForTime(time, dateTimeisUtc: true, out ruleIndex); year = (time + baseUtcOffset).Year; } if (adjustmentRuleForTime != null) { baseUtcOffset += adjustmentRuleForTime.BaseUtcOffsetDelta; if (adjustmentRuleForTime.HasDaylightSaving) { isDaylightSavings = GetIsDaylightSavingsFromUtc(time, year, zone._baseUtcOffset, adjustmentRuleForTime, ruleIndex, out isAmbiguousLocalDst, zone); baseUtcOffset += (isDaylightSavings ? adjustmentRuleForTime.DaylightDelta : TimeSpan.Zero); } } return baseUtcOffset; } internal static DateTime TransitionTimeToDateTime(int year, TransitionTime transitionTime) { TimeSpan timeOfDay = transitionTime.TimeOfDay.TimeOfDay; DateTime result; if (transitionTime.IsFixedDateRule) { int num = transitionTime.Day; if (num > 28) { int num2 = DateTime.DaysInMonth(year, transitionTime.Month); if (num > num2) { num = num2; } } result = new DateTime(year, transitionTime.Month, num) + timeOfDay; } else if (transitionTime.Week <= 4) { result = new DateTime(year, transitionTime.Month, 1) + timeOfDay; int dayOfWeek = (int)result.DayOfWeek; int num3 = (int)(transitionTime.DayOfWeek - dayOfWeek); if (num3 < 0) { num3 += 7; } num3 += 7 * (transitionTime.Week - 1); if (num3 > 0) { result = result.AddDays(num3); } } else { int day = DateTime.DaysInMonth(year, transitionTime.Month); result = new DateTime(year, transitionTime.Month, day) + timeOfDay; int dayOfWeek2 = (int)result.DayOfWeek; int num4 = (int)(dayOfWeek2 - transitionTime.DayOfWeek); if (num4 < 0) { num4 += 7; } if (num4 > 0) { result = result.AddDays(-num4); } } return result; } private static TimeZoneInfoResult TryGetTimeZone(string id, bool dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData, bool alwaysFallbackToLocalMachine = false) { TimeZoneInfoResult timeZoneInfoResult = TryGetTimeZoneUsingId(id, dstDisabled, out value, out e, cachedData, alwaysFallbackToLocalMachine); if (timeZoneInfoResult != 0) { bool idIsIana; string alternativeId = GetAlternativeId(id, out idIsIana); if (alternativeId != null) { timeZoneInfoResult = TryGetTimeZoneUsingId(alternativeId, dstDisabled, out value, out e, cachedData, alwaysFallbackToLocalMachine); if (timeZoneInfoResult == TimeZoneInfoResult.Success) { TimeZoneInfo timeZoneInfo = null; if (value._equivalentZones == null) { timeZoneInfo = new TimeZoneInfo(id, value._baseUtcOffset, value._displayName, value._standardDisplayName, value._daylightDisplayName, value._adjustmentRules, dstDisabled && value._supportsDaylightSavingTime, idIsIana); value._equivalentZones = new List(); lock (value._equivalentZones) { value._equivalentZones.Add(timeZoneInfo); } } else { foreach (TimeZoneInfo equivalentZone in value._equivalentZones) { if (equivalentZone.Id == id) { timeZoneInfo = equivalentZone; break; } } if (timeZoneInfo == null) { timeZoneInfo = new TimeZoneInfo(id, value._baseUtcOffset, value._displayName, value._standardDisplayName, value._daylightDisplayName, value._adjustmentRules, dstDisabled && value._supportsDaylightSavingTime, idIsIana); lock (value._equivalentZones) { value._equivalentZones.Add(timeZoneInfo); } } } value = timeZoneInfo; } } } return timeZoneInfoResult; } private static TimeZoneInfoResult TryGetTimeZoneUsingId(string id, bool dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData, bool alwaysFallbackToLocalMachine) { TimeZoneInfoResult result = TimeZoneInfoResult.Success; e = null; if (cachedData._systemTimeZones != null && cachedData._systemTimeZones.TryGetValue(id, out var value2)) { if (dstDisabled && value2._supportsDaylightSavingTime) { value = CreateCustomTimeZone(value2._id, value2._baseUtcOffset, value2._displayName, value2._standardDisplayName); } else { value = new TimeZoneInfo(value2._id, value2._baseUtcOffset, value2._displayName, value2._standardDisplayName, value2._daylightDisplayName, value2._adjustmentRules, disableDaylightSavingTime: false, value2.HasIanaId); } return result; } if (!cachedData._allSystemTimeZonesRead || alwaysFallbackToLocalMachine) { result = TryGetTimeZoneFromLocalMachine(id, dstDisabled, out value, out e, cachedData); } else { result = TimeZoneInfoResult.TimeZoneNotFoundException; value = null; } return result; } private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, bool dstDisabled, out TimeZoneInfo value, out Exception e, CachedData cachedData) { TimeZoneInfo value2; TimeZoneInfoResult timeZoneInfoResult = TryGetTimeZoneFromLocalMachine(id, out value2, out e); if (timeZoneInfoResult == TimeZoneInfoResult.Success) { if (cachedData._systemTimeZones == null) { cachedData._systemTimeZones = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "UTC", s_utcTimeZone } }; } if (!id.Equals("UTC", StringComparison.OrdinalIgnoreCase)) { cachedData._systemTimeZones.Add(id, value2); } if (dstDisabled && value2._supportsDaylightSavingTime) { value = CreateCustomTimeZone(value2._id, value2._baseUtcOffset, value2._displayName, value2._standardDisplayName); } else { value = new TimeZoneInfo(value2._id, value2._baseUtcOffset, value2._displayName, value2._standardDisplayName, value2._daylightDisplayName, value2._adjustmentRules, disableDaylightSavingTime: false, value2.HasIanaId); } } else { value = null; } return timeZoneInfoResult; } private static void ValidateTimeZoneInfo(string id, TimeSpan baseUtcOffset, AdjustmentRule[] adjustmentRules, out bool adjustmentRulesSupportDst) { if (id == null) { throw new ArgumentNullException("id"); } if (id.Length == 0) { throw new ArgumentException(SR.Format(SR.Argument_InvalidId, id), "id"); } if (UtcOffsetOutOfRange(baseUtcOffset)) { throw new ArgumentOutOfRangeException("baseUtcOffset", SR.ArgumentOutOfRange_UtcOffset); } if (baseUtcOffset.Ticks % 600000000 != 0L) { throw new ArgumentException(SR.Argument_TimeSpanHasSeconds, "baseUtcOffset"); } adjustmentRulesSupportDst = false; if (adjustmentRules == null || adjustmentRules.Length == 0) { return; } adjustmentRulesSupportDst = true; AdjustmentRule adjustmentRule = null; AdjustmentRule adjustmentRule2 = null; for (int i = 0; i < adjustmentRules.Length; i++) { adjustmentRule = adjustmentRule2; adjustmentRule2 = adjustmentRules[i]; if (adjustmentRule2 == null) { throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesNoNulls); } if (!IsValidAdjustmentRuleOffset(baseUtcOffset, adjustmentRule2)) { throw new InvalidTimeZoneException(SR.ArgumentOutOfRange_UtcOffsetAndDaylightDelta); } if (adjustmentRule != null && adjustmentRule2.DateStart <= adjustmentRule.DateEnd) { throw new InvalidTimeZoneException(SR.Argument_AdjustmentRulesOutOfOrder); } } } internal static bool UtcOffsetOutOfRange(TimeSpan offset) { if (!(offset < MinOffset)) { return offset > MaxOffset; } return true; } private static TimeSpan GetUtcOffset(TimeSpan baseUtcOffset, AdjustmentRule adjustmentRule) { return baseUtcOffset + adjustmentRule.BaseUtcOffsetDelta + (adjustmentRule.HasDaylightSaving ? adjustmentRule.DaylightDelta : TimeSpan.Zero); } private static bool IsValidAdjustmentRuleOffset(TimeSpan baseUtcOffset, AdjustmentRule adjustmentRule) { TimeSpan utcOffset = GetUtcOffset(baseUtcOffset, adjustmentRule); return !UtcOffsetOutOfRange(utcOffset); } private static TimeZoneInfo CreateUtcTimeZone() { string utcStandardDisplayName = GetUtcStandardDisplayName(); string utcFullDisplayName = GetUtcFullDisplayName("UTC", utcStandardDisplayName); return CreateCustomTimeZone("UTC", TimeSpan.Zero, utcFullDisplayName, utcStandardDisplayName); } private unsafe static bool TryConvertIanaIdToWindowsId(string ianaId, bool allocate, out string windowsId) { if (GlobalizationMode.Invariant || GlobalizationMode.UseNls || ianaId == null) { windowsId = null; return false; } foreach (char c in ianaId) { if (c == '\\' || c == '\n' || c == '\r') { windowsId = null; return false; } } char* ptr = stackalloc char[100]; int num = Interop.Globalization.IanaIdToWindowsId(ianaId, ptr, 100); if (num > 0) { windowsId = (allocate ? new string(ptr, 0, num) : null); return true; } windowsId = null; return false; } private unsafe static bool TryConvertWindowsIdToIanaId(string windowsId, string region, bool allocate, out string ianaId) { if (GlobalizationMode.Invariant || GlobalizationMode.UseNls || windowsId == null) { ianaId = null; return false; } if (windowsId.Equals("utc", StringComparison.OrdinalIgnoreCase)) { ianaId = "Etc/UTC"; return true; } foreach (char c in windowsId) { if (c == '\\' || c == '\n' || c == '\r') { ianaId = null; return false; } } IntPtr region2 = IntPtr.Zero; if (region != null && region.Length < 11) { byte* ptr = stackalloc byte[(int)(uint)(region.Length + 1)]; int j; for (j = 0; j < region.Length && region[j] <= '\u007f'; j++) { ptr[j] = (((uint)(region[j] - 97) <= 25u) ? ((byte)(region[j] - 97 + 65)) : ((byte)region[j])); } if (j >= region.Length) { ptr[region.Length] = 0; region2 = new IntPtr(ptr); } } char* ptr2 = stackalloc char[100]; int num = Interop.Globalization.WindowsIdToIanaId(windowsId, region2, ptr2, 100); if (num > 0) { ianaId = (allocate ? new string(ptr2, 0, num) : null); return true; } ianaId = null; return false; } public AdjustmentRule[] GetAdjustmentRules() { if (_adjustmentRules == null) { return Array.Empty(); } return (AdjustmentRule[])_adjustmentRules.Clone(); } private static void PopulateAllSystemTimeZones(CachedData cachedData) { using RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones", writable: false); if (registryKey != null) { string[] subKeyNames = registryKey.GetSubKeyNames(); foreach (string id in subKeyNames) { TryGetTimeZone(id, dstDisabled: false, out var _, out var _, cachedData); } } } private static string GetAlternativeId(string id, out bool idIsIana) { idIsIana = true; if (!TryConvertIanaIdToWindowsId(id, out string windowsId)) { return null; } return windowsId; } private TimeZoneInfo(in Interop.Kernel32.TIME_ZONE_INFORMATION zone, bool dstDisabled) { string standardName = zone.GetStandardName(); if (standardName.Length == 0) { _id = "Local"; } else { _id = standardName; } _baseUtcOffset = new TimeSpan(0, -zone.Bias, 0); if (!dstDisabled) { Interop.Kernel32.REG_TZI_FORMAT timeZoneInformation = new Interop.Kernel32.REG_TZI_FORMAT(in zone); AdjustmentRule adjustmentRule = CreateAdjustmentRuleFromTimeZoneInformation(in timeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, zone.Bias); if (adjustmentRule != null) { _adjustmentRules = new AdjustmentRule[1] { adjustmentRule }; } } ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime); _displayName = standardName; _standardDisplayName = standardName; _daylightDisplayName = zone.GetDaylightName(); } private static bool CheckDaylightSavingTimeNotSupported(in Interop.Kernel32.TIME_ZONE_INFORMATION timeZone) { return timeZone.DaylightDate.Equals(in timeZone.StandardDate); } private static AdjustmentRule CreateAdjustmentRuleFromTimeZoneInformation(in Interop.Kernel32.REG_TZI_FORMAT timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset) { if (timeZoneInformation.StandardDate.Month == 0) { if (timeZoneInformation.Bias == defaultBaseUtcOffset) { return null; } return AdjustmentRule.CreateAdjustmentRule(startDate, endDate, TimeSpan.Zero, TransitionTime.CreateFixedDateRule(DateTime.MinValue, 1, 1), TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(1.0), 1, 1), new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), noDaylightTransitions: false); } if (!TransitionTimeFromTimeZoneInformation(in timeZoneInformation, out var transitionTime, readStartDate: true)) { return null; } if (!TransitionTimeFromTimeZoneInformation(in timeZoneInformation, out var transitionTime2, readStartDate: false)) { return null; } if (transitionTime.Equals(transitionTime2)) { return null; } return AdjustmentRule.CreateAdjustmentRule(startDate, endDate, new TimeSpan(0, -timeZoneInformation.DaylightBias, 0), transitionTime, transitionTime2, new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), noDaylightTransitions: false); } private static string FindIdFromTimeZoneInformation(in Interop.Kernel32.TIME_ZONE_INFORMATION timeZone, out bool dstDisabled) { dstDisabled = false; using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones", writable: false)) { if (registryKey == null) { return null; } string[] subKeyNames = registryKey.GetSubKeyNames(); foreach (string text in subKeyNames) { if (TryCompareTimeZoneInformationToRegistry(in timeZone, text, out dstDisabled)) { return text; } } } return null; } private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData) { Interop.Kernel32.TIME_DYNAMIC_ZONE_INFORMATION pTimeZoneInformation; uint dynamicTimeZoneInformation = Interop.Kernel32.GetDynamicTimeZoneInformation(out pTimeZoneInformation); if (dynamicTimeZoneInformation == uint.MaxValue) { return CreateCustomTimeZone("Local", TimeSpan.Zero, "Local", "Local"); } string timeZoneKeyName = pTimeZoneInformation.GetTimeZoneKeyName(); if (timeZoneKeyName.Length != 0 && TryGetTimeZone(timeZoneKeyName, pTimeZoneInformation.DynamicDaylightTimeDisabled != 0, out var value, out var e, cachedData) == TimeZoneInfoResult.Success) { return value; } Interop.Kernel32.TIME_ZONE_INFORMATION timeZone = new Interop.Kernel32.TIME_ZONE_INFORMATION(in pTimeZoneInformation); bool dstDisabled; string text = FindIdFromTimeZoneInformation(in timeZone, out dstDisabled); if (text != null && TryGetTimeZone(text, dstDisabled, out var value2, out e, cachedData) == TimeZoneInfoResult.Success) { return value2; } return GetLocalTimeZoneFromWin32Data(in timeZone, dstDisabled); } private static TimeZoneInfo GetLocalTimeZoneFromWin32Data(in Interop.Kernel32.TIME_ZONE_INFORMATION timeZoneInformation, bool dstDisabled) { try { return new TimeZoneInfo(in timeZoneInformation, dstDisabled); } catch (ArgumentException) { } catch (InvalidTimeZoneException) { } if (!dstDisabled) { try { return new TimeZoneInfo(in timeZoneInformation, dstDisabled: true); } catch (ArgumentException) { } catch (InvalidTimeZoneException) { } } return CreateCustomTimeZone("Local", TimeSpan.Zero, "Local", "Local"); } public static TimeZoneInfo FindSystemTimeZoneById(string id) { if (string.Equals(id, "UTC", StringComparison.OrdinalIgnoreCase)) { return Utc; } if (id == null) { throw new ArgumentNullException("id"); } if (id.Length == 0 || id.Length > 255 || id.Contains('\0')) { throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id)); } CachedData cachedData = s_cachedData; TimeZoneInfoResult timeZoneInfoResult; TimeZoneInfo value; Exception e; lock (cachedData) { timeZoneInfoResult = TryGetTimeZone(id, dstDisabled: false, out value, out e, cachedData); } return timeZoneInfoResult switch { TimeZoneInfoResult.Success => value, TimeZoneInfoResult.InvalidTimeZoneException => throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidRegistryData, id), e), TimeZoneInfoResult.SecurityException => throw new SecurityException(SR.Format(SR.Security_CannotReadRegistryData, id), e), _ => throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e), }; } internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst) { isAmbiguousLocalDst = false; int year = time.Year; OffsetAndRule oneYearLocalFromUtc = s_cachedData.GetOneYearLocalFromUtc(year); TimeSpan offset = oneYearLocalFromUtc.Offset; if (oneYearLocalFromUtc.Rule != null) { offset += oneYearLocalFromUtc.Rule.BaseUtcOffsetDelta; if (oneYearLocalFromUtc.Rule.HasDaylightSaving) { bool isDaylightSavingsFromUtc = GetIsDaylightSavingsFromUtc(time, year, oneYearLocalFromUtc.Offset, oneYearLocalFromUtc.Rule, null, out isAmbiguousLocalDst, Local); offset += (isDaylightSavingsFromUtc ? oneYearLocalFromUtc.Rule.DaylightDelta : TimeSpan.Zero); } } return offset; } private static bool TransitionTimeFromTimeZoneInformation(in Interop.Kernel32.REG_TZI_FORMAT timeZoneInformation, out TransitionTime transitionTime, bool readStartDate) { if (timeZoneInformation.StandardDate.Month == 0) { transitionTime = default(TransitionTime); return false; } if (readStartDate) { if (timeZoneInformation.DaylightDate.Year == 0) { transitionTime = TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, timeZoneInformation.DaylightDate.Hour, timeZoneInformation.DaylightDate.Minute, timeZoneInformation.DaylightDate.Second, timeZoneInformation.DaylightDate.Milliseconds), timeZoneInformation.DaylightDate.Month, timeZoneInformation.DaylightDate.Day, (DayOfWeek)timeZoneInformation.DaylightDate.DayOfWeek); } else { transitionTime = TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, timeZoneInformation.DaylightDate.Hour, timeZoneInformation.DaylightDate.Minute, timeZoneInformation.DaylightDate.Second, timeZoneInformation.DaylightDate.Milliseconds), timeZoneInformation.DaylightDate.Month, timeZoneInformation.DaylightDate.Day); } } else if (timeZoneInformation.StandardDate.Year == 0) { transitionTime = TransitionTime.CreateFloatingDateRule(new DateTime(1, 1, 1, timeZoneInformation.StandardDate.Hour, timeZoneInformation.StandardDate.Minute, timeZoneInformation.StandardDate.Second, timeZoneInformation.StandardDate.Milliseconds), timeZoneInformation.StandardDate.Month, timeZoneInformation.StandardDate.Day, (DayOfWeek)timeZoneInformation.StandardDate.DayOfWeek); } else { transitionTime = TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, timeZoneInformation.StandardDate.Hour, timeZoneInformation.StandardDate.Minute, timeZoneInformation.StandardDate.Second, timeZoneInformation.StandardDate.Milliseconds), timeZoneInformation.StandardDate.Month, timeZoneInformation.StandardDate.Day); } return true; } private static bool TryCreateAdjustmentRules(string id, in Interop.Kernel32.REG_TZI_FORMAT defaultTimeZoneInformation, out AdjustmentRule[] rules, out Exception e, int defaultBaseUtcOffset) { rules = null; e = null; try { using RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\" + id + "\\Dynamic DST", writable: false); if (registryKey == null) { AdjustmentRule adjustmentRule = CreateAdjustmentRuleFromTimeZoneInformation(in defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset); if (adjustmentRule != null) { rules = new AdjustmentRule[1] { adjustmentRule }; } return true; } int num = (int)registryKey.GetValue("FirstEntry", -1); int num2 = (int)registryKey.GetValue("LastEntry", -1); if (num == -1 || num2 == -1 || num > num2) { return false; } if (!TryGetTimeZoneEntryFromRegistry(registryKey, num.ToString(CultureInfo.InvariantCulture), out var dtzi)) { return false; } if (num == num2) { AdjustmentRule adjustmentRule2 = CreateAdjustmentRuleFromTimeZoneInformation(in dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset); if (adjustmentRule2 != null) { rules = new AdjustmentRule[1] { adjustmentRule2 }; } return true; } List list = new List(1); AdjustmentRule adjustmentRule3 = CreateAdjustmentRuleFromTimeZoneInformation(in dtzi, DateTime.MinValue.Date, new DateTime(num, 12, 31), defaultBaseUtcOffset); if (adjustmentRule3 != null) { list.Add(adjustmentRule3); } for (int i = num + 1; i < num2; i++) { if (!TryGetTimeZoneEntryFromRegistry(registryKey, i.ToString(CultureInfo.InvariantCulture), out dtzi)) { return false; } AdjustmentRule adjustmentRule4 = CreateAdjustmentRuleFromTimeZoneInformation(in dtzi, new DateTime(i, 1, 1), new DateTime(i, 12, 31), defaultBaseUtcOffset); if (adjustmentRule4 != null) { list.Add(adjustmentRule4); } } if (!TryGetTimeZoneEntryFromRegistry(registryKey, num2.ToString(CultureInfo.InvariantCulture), out dtzi)) { return false; } AdjustmentRule adjustmentRule5 = CreateAdjustmentRuleFromTimeZoneInformation(in dtzi, new DateTime(num2, 1, 1), DateTime.MaxValue.Date, defaultBaseUtcOffset); if (adjustmentRule5 != null) { list.Add(adjustmentRule5); } if (list.Count != 0) { rules = list.ToArray(); } } catch (InvalidCastException ex) { e = ex; return false; } catch (ArgumentOutOfRangeException ex2) { e = ex2; return false; } catch (ArgumentException ex3) { e = ex3; return false; } return true; } private unsafe static bool TryGetTimeZoneEntryFromRegistry(RegistryKey key, string name, out Interop.Kernel32.REG_TZI_FORMAT dtzi) { if (!(key.GetValue(name, null) is byte[] array) || array.Length != sizeof(Interop.Kernel32.REG_TZI_FORMAT)) { dtzi = default(Interop.Kernel32.REG_TZI_FORMAT); return false; } fixed (byte* ptr = &array[0]) { dtzi = *(Interop.Kernel32.REG_TZI_FORMAT*)ptr; } return true; } private static bool TryCompareStandardDate(in Interop.Kernel32.TIME_ZONE_INFORMATION timeZone, in Interop.Kernel32.REG_TZI_FORMAT registryTimeZoneInfo) { if (timeZone.Bias == registryTimeZoneInfo.Bias && timeZone.StandardBias == registryTimeZoneInfo.StandardBias) { return timeZone.StandardDate.Equals(in registryTimeZoneInfo.StandardDate); } return false; } private static bool TryCompareTimeZoneInformationToRegistry(in Interop.Kernel32.TIME_ZONE_INFORMATION timeZone, string id, out bool dstDisabled) { dstDisabled = false; using RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\" + id, writable: false); if (registryKey == null) { return false; } if (!TryGetTimeZoneEntryFromRegistry(registryKey, "TZI", out var dtzi)) { return false; } if (!TryCompareStandardDate(in timeZone, in dtzi)) { return false; } bool flag = dstDisabled || CheckDaylightSavingTimeNotSupported(in timeZone) || (timeZone.DaylightBias == dtzi.DaylightBias && timeZone.DaylightDate.Equals(in dtzi.DaylightDate)); if (flag) { string a = registryKey.GetValue("Std", string.Empty) as string; flag = string.Equals(a, timeZone.GetStandardName(), StringComparison.Ordinal); } return flag; } private static string GetLocalizedNameByMuiNativeResource(string resource) { if (string.IsNullOrEmpty(resource) || (GlobalizationMode.Invariant && GlobalizationMode.PredefinedCulturesOnly)) { return string.Empty; } string[] array = resource.Split(','); if (array.Length != 2) { return string.Empty; } if (!int.TryParse(array[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return string.Empty; } result = -result; CultureInfo cultureInfo = CultureInfo.CurrentUICulture; string systemDirectory = Environment.SystemDirectory; string path = $"{array[0].AsSpan().TrimStart('@')}.mui"; try { while (cultureInfo.Name.Length != 0) { string text = Path.Join(systemDirectory, cultureInfo.Name, path); if (File.Exists(text)) { return GetLocalizedNameByNativeResource(text, result); } cultureInfo = cultureInfo.Parent; } } catch (ArgumentException) { } return string.Empty; } private unsafe static string GetLocalizedNameByNativeResource(string filePath, int resource) { IntPtr intPtr = IntPtr.Zero; try { intPtr = Interop.Kernel32.LoadLibraryEx(filePath, IntPtr.Zero, 2); if (intPtr != IntPtr.Zero) { char* ptr = stackalloc char[500]; int num = Interop.User32.LoadString(intPtr, (uint)resource, ptr, 500); if (num != 0) { return new string(ptr, 0, num); } } } finally { if (intPtr != IntPtr.Zero) { Interop.Kernel32.FreeLibrary(intPtr); } } return string.Empty; } private static void GetLocalizedNamesByRegistryKey(RegistryKey key, out string displayName, out string standardName, out string daylightName) { displayName = string.Empty; standardName = string.Empty; daylightName = string.Empty; string text = key.GetValue("MUI_Display", string.Empty) as string; string text2 = key.GetValue("MUI_Std", string.Empty) as string; string text3 = key.GetValue("MUI_Dlt", string.Empty) as string; if (!string.IsNullOrEmpty(text)) { displayName = GetLocalizedNameByMuiNativeResource(text); } if (!string.IsNullOrEmpty(text2)) { standardName = GetLocalizedNameByMuiNativeResource(text2); } if (!string.IsNullOrEmpty(text3)) { daylightName = GetLocalizedNameByMuiNativeResource(text3); } if (string.IsNullOrEmpty(displayName)) { displayName = key.GetValue("Display", string.Empty) as string; } if (string.IsNullOrEmpty(standardName)) { standardName = key.GetValue("Std", string.Empty) as string; } if (string.IsNullOrEmpty(daylightName)) { daylightName = key.GetValue("Dlt", string.Empty) as string; } } private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo value, out Exception e) { e = null; using RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\" + id, writable: false); if (registryKey == null) { value = null; return TimeZoneInfoResult.TimeZoneNotFoundException; } if (!TryGetTimeZoneEntryFromRegistry(registryKey, "TZI", out var dtzi)) { value = null; return TimeZoneInfoResult.InvalidTimeZoneException; } if (!TryCreateAdjustmentRules(id, in dtzi, out var rules, out e, dtzi.Bias)) { value = null; return TimeZoneInfoResult.InvalidTimeZoneException; } GetLocalizedNamesByRegistryKey(registryKey, out var displayName, out var standardName, out var daylightName); try { value = new TimeZoneInfo(id, new TimeSpan(0, -dtzi.Bias, 0), displayName, standardName, daylightName, rules, disableDaylightSavingTime: false); return TimeZoneInfoResult.Success; } catch (ArgumentException ex) { value = null; e = ex; return TimeZoneInfoResult.InvalidTimeZoneException; } catch (InvalidTimeZoneException ex2) { value = null; e = ex2; return TimeZoneInfoResult.InvalidTimeZoneException; } } private static string GetUtcStandardDisplayName() { CultureInfo currentUICulture = CultureInfo.CurrentUICulture; if (currentUICulture.Name.Length == 0 || currentUICulture.TwoLetterISOLanguageName == "en") { return "Coordinated Universal Time"; } string text = null; using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones\\UTC", writable: false)) { if (registryKey != null) { string text2 = registryKey.GetValue("MUI_Std", string.Empty) as string; if (!string.IsNullOrEmpty(text2)) { text = GetLocalizedNameByMuiNativeResource(text2); } if (string.IsNullOrEmpty(text)) { text = registryKey.GetValue("Std", string.Empty) as string; } } } switch (text) { case null: case "GMT": case "UTC": text = "Coordinated Universal Time"; break; } return text; } private static string GetUtcFullDisplayName(string timeZoneId, string standardDisplayName) { return "(UTC) " + standardDisplayName; } } [Flags] internal enum TimeZoneInfoOptions { None = 1, NoThrowOnInvalidTime = 2 } [Serializable] [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class TimeZoneNotFoundException : Exception { public TimeZoneNotFoundException() { } public TimeZoneNotFoundException(string? message) : base(message) { } public TimeZoneNotFoundException(string? message, Exception? innerException) : base(message, innerException) { } protected TimeZoneNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } } internal interface ITupleInternal : ITuple { string ToString(StringBuilder sb); int GetHashCode(IEqualityComparer comparer); } public static class Tuple { public static Tuple Create(T1 item1) { return new Tuple(item1); } public static Tuple Create(T1 item1, T2 item2) { return new Tuple(item1, item2); } public static Tuple Create(T1 item1, T2 item2, T3 item3) { return new Tuple(item1, item2, item3); } public static Tuple Create(T1 item1, T2 item2, T3 item3, T4 item4) { return new Tuple(item1, item2, item3, item4); } public static Tuple Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { return new Tuple(item1, item2, item3, item4, item5); } public static Tuple Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { return new Tuple(item1, item2, item3, item4, item5, item6); } public static Tuple Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { return new Tuple(item1, item2, item3, item4, item5, item6, item7); } public static Tuple> Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) { return new Tuple>(item1, item2, item3, item4, item5, item6, item7, new Tuple(item8)); } internal static int CombineHashCodes(int h1, int h2) { return ((h1 << 5) + h1) ^ h2; } internal static int CombineHashCodes(int h1, int h2, int h3) { return CombineHashCodes(CombineHashCodes(h1, h2), h3); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4) { return CombineHashCodes(CombineHashCodes(h1, h2), CombineHashCodes(h3, h4)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), h5); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7)); } internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int h6, int h7, int h8) { return CombineHashCodes(CombineHashCodes(h1, h2, h3, h4), CombineHashCodes(h5, h6, h7, h8)); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; public T1 Item1 => m_Item1; int ITuple.Length => 1; object? ITuple.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return Item1; } } public Tuple(T1 item1) { m_Item1 = item1; } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj, EqualityComparer.Default); } bool IStructuralEquatable.Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { return Equals(other, comparer); } private bool Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple tuple)) { return false; } return comparer.Equals(m_Item1, tuple.m_Item1); } int IComparable.CompareTo(object obj) { return CompareTo(obj, Comparer.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { return CompareTo(other, comparer); } private int CompareTo(object other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple tuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), "other"); } return comparer.Compare(m_Item1, tuple.m_Item1); } public override int GetHashCode() { return GetHashCode(EqualityComparer.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { return comparer.GetHashCode(m_Item1); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(')'); return sb.ToString(); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; private readonly T2 m_Item2; public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; int ITuple.Length => 2; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, _ => throw new IndexOutOfRangeException(), }; public Tuple(T1 item1, T2 item2) { m_Item1 = item1; m_Item2 = item2; } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj, EqualityComparer.Default); } bool IStructuralEquatable.Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { return Equals(other, comparer); } private bool Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple tuple)) { return false; } if (comparer.Equals(m_Item1, tuple.m_Item1)) { return comparer.Equals(m_Item2, tuple.m_Item2); } return false; } int IComparable.CompareTo(object obj) { return CompareTo(obj, Comparer.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { return CompareTo(other, comparer); } private int CompareTo(object other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple tuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), "other"); } int num = comparer.Compare(m_Item1, tuple.m_Item1); if (num != 0) { return num; } return comparer.Compare(m_Item2, tuple.m_Item2); } public override int GetHashCode() { return GetHashCode(EqualityComparer.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2)); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(')'); return sb.ToString(); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; private readonly T2 m_Item2; private readonly T3 m_Item3; public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; int ITuple.Length => 3; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, _ => throw new IndexOutOfRangeException(), }; public Tuple(T1 item1, T2 item2, T3 item3) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj, EqualityComparer.Default); } bool IStructuralEquatable.Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { return Equals(other, comparer); } private bool Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple tuple)) { return false; } if (comparer.Equals(m_Item1, tuple.m_Item1) && comparer.Equals(m_Item2, tuple.m_Item2)) { return comparer.Equals(m_Item3, tuple.m_Item3); } return false; } int IComparable.CompareTo(object obj) { return CompareTo(obj, Comparer.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { return CompareTo(other, comparer); } private int CompareTo(object other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple tuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), "other"); } int num = comparer.Compare(m_Item1, tuple.m_Item1); if (num != 0) { return num; } num = comparer.Compare(m_Item2, tuple.m_Item2); if (num != 0) { return num; } return comparer.Compare(m_Item3, tuple.m_Item3); } public override int GetHashCode() { return GetHashCode(EqualityComparer.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3)); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(')'); return sb.ToString(); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; private readonly T2 m_Item2; private readonly T3 m_Item3; private readonly T4 m_Item4; public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; int ITuple.Length => 4; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, _ => throw new IndexOutOfRangeException(), }; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj, EqualityComparer.Default); } bool IStructuralEquatable.Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { return Equals(other, comparer); } private bool Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple tuple)) { return false; } if (comparer.Equals(m_Item1, tuple.m_Item1) && comparer.Equals(m_Item2, tuple.m_Item2) && comparer.Equals(m_Item3, tuple.m_Item3)) { return comparer.Equals(m_Item4, tuple.m_Item4); } return false; } int IComparable.CompareTo(object obj) { return CompareTo(obj, Comparer.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { return CompareTo(other, comparer); } private int CompareTo(object other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple tuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), "other"); } int num = comparer.Compare(m_Item1, tuple.m_Item1); if (num != 0) { return num; } num = comparer.Compare(m_Item2, tuple.m_Item2); if (num != 0) { return num; } num = comparer.Compare(m_Item3, tuple.m_Item3); if (num != 0) { return num; } return comparer.Compare(m_Item4, tuple.m_Item4); } public override int GetHashCode() { return GetHashCode(EqualityComparer.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4)); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(')'); return sb.ToString(); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; private readonly T2 m_Item2; private readonly T3 m_Item3; private readonly T4 m_Item4; private readonly T5 m_Item5; public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; public T5 Item5 => m_Item5; int ITuple.Length => 5; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, _ => throw new IndexOutOfRangeException(), }; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj, EqualityComparer.Default); } bool IStructuralEquatable.Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { return Equals(other, comparer); } private bool Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple tuple)) { return false; } if (comparer.Equals(m_Item1, tuple.m_Item1) && comparer.Equals(m_Item2, tuple.m_Item2) && comparer.Equals(m_Item3, tuple.m_Item3) && comparer.Equals(m_Item4, tuple.m_Item4)) { return comparer.Equals(m_Item5, tuple.m_Item5); } return false; } int IComparable.CompareTo(object obj) { return CompareTo(obj, Comparer.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { return CompareTo(other, comparer); } private int CompareTo(object other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple tuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), "other"); } int num = comparer.Compare(m_Item1, tuple.m_Item1); if (num != 0) { return num; } num = comparer.Compare(m_Item2, tuple.m_Item2); if (num != 0) { return num; } num = comparer.Compare(m_Item3, tuple.m_Item3); if (num != 0) { return num; } num = comparer.Compare(m_Item4, tuple.m_Item4); if (num != 0) { return num; } return comparer.Compare(m_Item5, tuple.m_Item5); } public override int GetHashCode() { return GetHashCode(EqualityComparer.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5)); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(')'); return sb.ToString(); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; private readonly T2 m_Item2; private readonly T3 m_Item3; private readonly T4 m_Item4; private readonly T5 m_Item5; private readonly T6 m_Item6; public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; public T5 Item5 => m_Item5; public T6 Item6 => m_Item6; int ITuple.Length => 6; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, 5 => Item6, _ => throw new IndexOutOfRangeException(), }; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj, EqualityComparer.Default); } bool IStructuralEquatable.Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { return Equals(other, comparer); } private bool Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple tuple)) { return false; } if (comparer.Equals(m_Item1, tuple.m_Item1) && comparer.Equals(m_Item2, tuple.m_Item2) && comparer.Equals(m_Item3, tuple.m_Item3) && comparer.Equals(m_Item4, tuple.m_Item4) && comparer.Equals(m_Item5, tuple.m_Item5)) { return comparer.Equals(m_Item6, tuple.m_Item6); } return false; } int IComparable.CompareTo(object obj) { return CompareTo(obj, Comparer.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { return CompareTo(other, comparer); } private int CompareTo(object other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple tuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), "other"); } int num = comparer.Compare(m_Item1, tuple.m_Item1); if (num != 0) { return num; } num = comparer.Compare(m_Item2, tuple.m_Item2); if (num != 0) { return num; } num = comparer.Compare(m_Item3, tuple.m_Item3); if (num != 0) { return num; } num = comparer.Compare(m_Item4, tuple.m_Item4); if (num != 0) { return num; } num = comparer.Compare(m_Item5, tuple.m_Item5); if (num != 0) { return num; } return comparer.Compare(m_Item6, tuple.m_Item6); } public override int GetHashCode() { return GetHashCode(EqualityComparer.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6)); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(')'); return sb.ToString(); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple { private readonly T1 m_Item1; private readonly T2 m_Item2; private readonly T3 m_Item3; private readonly T4 m_Item4; private readonly T5 m_Item5; private readonly T6 m_Item6; private readonly T7 m_Item7; public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; public T5 Item5 => m_Item5; public T6 Item6 => m_Item6; public T7 Item7 => m_Item7; int ITuple.Length => 7; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, 5 => Item6, 6 => Item7, _ => throw new IndexOutOfRangeException(), }; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; m_Item7 = item7; } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj, EqualityComparer.Default); } bool IStructuralEquatable.Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { return Equals(other, comparer); } private bool Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple tuple)) { return false; } if (comparer.Equals(m_Item1, tuple.m_Item1) && comparer.Equals(m_Item2, tuple.m_Item2) && comparer.Equals(m_Item3, tuple.m_Item3) && comparer.Equals(m_Item4, tuple.m_Item4) && comparer.Equals(m_Item5, tuple.m_Item5) && comparer.Equals(m_Item6, tuple.m_Item6)) { return comparer.Equals(m_Item7, tuple.m_Item7); } return false; } int IComparable.CompareTo(object obj) { return ((IStructuralComparable)this).CompareTo(obj, (IComparer)Comparer.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { return CompareTo(other, comparer); } private int CompareTo(object other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple tuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), "other"); } int num = comparer.Compare(m_Item1, tuple.m_Item1); if (num != 0) { return num; } num = comparer.Compare(m_Item2, tuple.m_Item2); if (num != 0) { return num; } num = comparer.Compare(m_Item3, tuple.m_Item3); if (num != 0) { return num; } num = comparer.Compare(m_Item4, tuple.m_Item4); if (num != 0) { return num; } num = comparer.Compare(m_Item5, tuple.m_Item5); if (num != 0) { return num; } num = comparer.Compare(m_Item6, tuple.m_Item6); if (num != 0) { return num; } return comparer.Compare(m_Item7, tuple.m_Item7); } public override int GetHashCode() { return GetHashCode(EqualityComparer.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { return Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7)); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(", "); sb.Append(m_Item7); sb.Append(')'); return sb.ToString(); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class Tuple : IStructuralEquatable, IStructuralComparable, IComparable, ITupleInternal, ITuple where TRest : notnull { private readonly T1 m_Item1; private readonly T2 m_Item2; private readonly T3 m_Item3; private readonly T4 m_Item4; private readonly T5 m_Item5; private readonly T6 m_Item6; private readonly T7 m_Item7; private readonly TRest m_Rest; public T1 Item1 => m_Item1; public T2 Item2 => m_Item2; public T3 Item3 => m_Item3; public T4 Item4 => m_Item4; public T5 Item5 => m_Item5; public T6 Item6 => m_Item6; public T7 Item7 => m_Item7; public TRest Rest => m_Rest; int ITuple.Length => 7 + ((ITupleInternal)(object)Rest).Length; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, 5 => Item6, 6 => Item7, _ => ((ITupleInternal)(object)Rest)[index - 7], }; public Tuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { if (!(rest is ITupleInternal)) { throw new ArgumentException(SR.ArgumentException_TupleLastArgumentNotATuple); } m_Item1 = item1; m_Item2 = item2; m_Item3 = item3; m_Item4 = item4; m_Item5 = item5; m_Item6 = item6; m_Item7 = item7; m_Rest = rest; } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj, EqualityComparer.Default); } bool IStructuralEquatable.Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { return Equals(other, comparer); } private bool Equals([NotNullWhen(true)] object other, IEqualityComparer comparer) { if (other == null) { return false; } if (!(other is Tuple tuple)) { return false; } if (comparer.Equals(m_Item1, tuple.m_Item1) && comparer.Equals(m_Item2, tuple.m_Item2) && comparer.Equals(m_Item3, tuple.m_Item3) && comparer.Equals(m_Item4, tuple.m_Item4) && comparer.Equals(m_Item5, tuple.m_Item5) && comparer.Equals(m_Item6, tuple.m_Item6) && comparer.Equals(m_Item7, tuple.m_Item7)) { return comparer.Equals(m_Rest, tuple.m_Rest); } return false; } int IComparable.CompareTo(object obj) { return CompareTo(obj, Comparer.Default); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { return CompareTo(other, comparer); } private int CompareTo(object other, IComparer comparer) { if (other == null) { return 1; } if (!(other is Tuple tuple)) { throw new ArgumentException(SR.Format(SR.ArgumentException_TupleIncorrectType, GetType()), "other"); } int num = comparer.Compare(m_Item1, tuple.m_Item1); if (num != 0) { return num; } num = comparer.Compare(m_Item2, tuple.m_Item2); if (num != 0) { return num; } num = comparer.Compare(m_Item3, tuple.m_Item3); if (num != 0) { return num; } num = comparer.Compare(m_Item4, tuple.m_Item4); if (num != 0) { return num; } num = comparer.Compare(m_Item5, tuple.m_Item5); if (num != 0) { return num; } num = comparer.Compare(m_Item6, tuple.m_Item6); if (num != 0) { return num; } num = comparer.Compare(m_Item7, tuple.m_Item7); if (num != 0) { return num; } return comparer.Compare(m_Rest, tuple.m_Rest); } public override int GetHashCode() { return GetHashCode(EqualityComparer.Default); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } private int GetHashCode(IEqualityComparer comparer) { ITupleInternal tupleInternal = (ITupleInternal)(object)m_Rest; if (tupleInternal.Length >= 8) { return tupleInternal.GetHashCode(comparer); } return (8 - tupleInternal.Length) switch { 1 => Tuple.CombineHashCodes(comparer.GetHashCode(m_Item7), tupleInternal.GetHashCode(comparer)), 2 => Tuple.CombineHashCodes(comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), tupleInternal.GetHashCode(comparer)), 3 => Tuple.CombineHashCodes(comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), tupleInternal.GetHashCode(comparer)), 4 => Tuple.CombineHashCodes(comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), tupleInternal.GetHashCode(comparer)), 5 => Tuple.CombineHashCodes(comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), tupleInternal.GetHashCode(comparer)), 6 => Tuple.CombineHashCodes(comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), tupleInternal.GetHashCode(comparer)), 7 => Tuple.CombineHashCodes(comparer.GetHashCode(m_Item1), comparer.GetHashCode(m_Item2), comparer.GetHashCode(m_Item3), comparer.GetHashCode(m_Item4), comparer.GetHashCode(m_Item5), comparer.GetHashCode(m_Item6), comparer.GetHashCode(m_Item7), tupleInternal.GetHashCode(comparer)), _ => -1, }; } int ITupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCode(comparer); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append('('); return ToString(stringBuilder); } string ITupleInternal.ToString(StringBuilder sb) { return ToString(sb); } private string ToString(StringBuilder sb) { sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(", "); sb.Append(m_Item3); sb.Append(", "); sb.Append(m_Item4); sb.Append(", "); sb.Append(m_Item5); sb.Append(", "); sb.Append(m_Item6); sb.Append(", "); sb.Append(m_Item7); sb.Append(", "); return ((ITupleInternal)(object)m_Rest).ToString(sb); } } internal sealed class TupleSlim { public readonly T1 Item1; public readonly T2 Item2; public TupleSlim(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } } internal sealed class TupleSlim { public readonly T1 Item1; public readonly T2 Item2; public readonly T3 Item3; public TupleSlim(T1 item1, T2 item2, T3 item3) { Item1 = item1; Item2 = item2; Item3 = item3; } } internal sealed class TupleSlim { public readonly T1 Item1; public readonly T2 Item2; public readonly T3 Item3; public readonly T4 Item4; public TupleSlim(T1 item1, T2 item2, T3 item3, T4 item4) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; } } public static class TupleExtensions { [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple value, out T1 item1) { item1 = value.Item1; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple value, out T1 item1, out T2 item2) { item1 = value.Item1; item2 = value.Item2; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple value, out T1 item1, out T2 item2, out T3 item3) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple value, out T1 item1, out T2 item2, out T3 item3, out T4 item4) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple> value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; item8 = value.Rest.Item1; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple> value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; item8 = value.Rest.Item1; item9 = value.Rest.Item2; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple> value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; item8 = value.Rest.Item1; item9 = value.Rest.Item2; item10 = value.Rest.Item3; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple> value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; item8 = value.Rest.Item1; item9 = value.Rest.Item2; item10 = value.Rest.Item3; item11 = value.Rest.Item4; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple> value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; item8 = value.Rest.Item1; item9 = value.Rest.Item2; item10 = value.Rest.Item3; item11 = value.Rest.Item4; item12 = value.Rest.Item5; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple> value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; item8 = value.Rest.Item1; item9 = value.Rest.Item2; item10 = value.Rest.Item3; item11 = value.Rest.Item4; item12 = value.Rest.Item5; item13 = value.Rest.Item6; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple> value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; item8 = value.Rest.Item1; item9 = value.Rest.Item2; item10 = value.Rest.Item3; item11 = value.Rest.Item4; item12 = value.Rest.Item5; item13 = value.Rest.Item6; item14 = value.Rest.Item7; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple>> value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; item8 = value.Rest.Item1; item9 = value.Rest.Item2; item10 = value.Rest.Item3; item11 = value.Rest.Item4; item12 = value.Rest.Item5; item13 = value.Rest.Item6; item14 = value.Rest.Item7; item15 = value.Rest.Rest.Item1; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple>> value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; item8 = value.Rest.Item1; item9 = value.Rest.Item2; item10 = value.Rest.Item3; item11 = value.Rest.Item4; item12 = value.Rest.Item5; item13 = value.Rest.Item6; item14 = value.Rest.Item7; item15 = value.Rest.Rest.Item1; item16 = value.Rest.Rest.Item2; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple>> value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; item8 = value.Rest.Item1; item9 = value.Rest.Item2; item10 = value.Rest.Item3; item11 = value.Rest.Item4; item12 = value.Rest.Item5; item13 = value.Rest.Item6; item14 = value.Rest.Item7; item15 = value.Rest.Rest.Item1; item16 = value.Rest.Rest.Item2; item17 = value.Rest.Rest.Item3; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple>> value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; item8 = value.Rest.Item1; item9 = value.Rest.Item2; item10 = value.Rest.Item3; item11 = value.Rest.Item4; item12 = value.Rest.Item5; item13 = value.Rest.Item6; item14 = value.Rest.Item7; item15 = value.Rest.Rest.Item1; item16 = value.Rest.Rest.Item2; item17 = value.Rest.Rest.Item3; item18 = value.Rest.Rest.Item4; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple>> value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18, out T19 item19) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; item8 = value.Rest.Item1; item9 = value.Rest.Item2; item10 = value.Rest.Item3; item11 = value.Rest.Item4; item12 = value.Rest.Item5; item13 = value.Rest.Item6; item14 = value.Rest.Item7; item15 = value.Rest.Rest.Item1; item16 = value.Rest.Rest.Item2; item17 = value.Rest.Rest.Item3; item18 = value.Rest.Rest.Item4; item19 = value.Rest.Rest.Item5; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple>> value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18, out T19 item19, out T20 item20) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; item8 = value.Rest.Item1; item9 = value.Rest.Item2; item10 = value.Rest.Item3; item11 = value.Rest.Item4; item12 = value.Rest.Item5; item13 = value.Rest.Item6; item14 = value.Rest.Item7; item15 = value.Rest.Rest.Item1; item16 = value.Rest.Rest.Item2; item17 = value.Rest.Rest.Item3; item18 = value.Rest.Rest.Item4; item19 = value.Rest.Rest.Item5; item20 = value.Rest.Rest.Item6; } [EditorBrowsable(EditorBrowsableState.Never)] public static void Deconstruct(this Tuple>> value, out T1 item1, out T2 item2, out T3 item3, out T4 item4, out T5 item5, out T6 item6, out T7 item7, out T8 item8, out T9 item9, out T10 item10, out T11 item11, out T12 item12, out T13 item13, out T14 item14, out T15 item15, out T16 item16, out T17 item17, out T18 item18, out T19 item19, out T20 item20, out T21 item21) { item1 = value.Item1; item2 = value.Item2; item3 = value.Item3; item4 = value.Item4; item5 = value.Item5; item6 = value.Item6; item7 = value.Item7; item8 = value.Rest.Item1; item9 = value.Rest.Item2; item10 = value.Rest.Item3; item11 = value.Rest.Item4; item12 = value.Rest.Item5; item13 = value.Rest.Item6; item14 = value.Rest.Item7; item15 = value.Rest.Rest.Item1; item16 = value.Rest.Rest.Item2; item17 = value.Rest.Rest.Item3; item18 = value.Rest.Rest.Item4; item19 = value.Rest.Rest.Item5; item20 = value.Rest.Rest.Item6; item21 = value.Rest.Rest.Item7; } public static ValueTuple ToValueTuple(this Tuple value) { return ValueTuple.Create(value.Item1); } public static (T1, T2) ToValueTuple(this Tuple value) { return ValueTuple.Create(value.Item1, value.Item2); } public static (T1, T2, T3) ToValueTuple(this Tuple value) { return ValueTuple.Create(value.Item1, value.Item2, value.Item3); } public static (T1, T2, T3, T4) ToValueTuple(this Tuple value) { return ValueTuple.Create(value.Item1, value.Item2, value.Item3, value.Item4); } public static (T1, T2, T3, T4, T5) ToValueTuple(this Tuple value) { return ValueTuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5); } public static (T1, T2, T3, T4, T5, T6) ToValueTuple(this Tuple value) { return ValueTuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6); } public static (T1, T2, T3, T4, T5, T6, T7) ToValueTuple(this Tuple value) { return ValueTuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7); } public static (T1, T2, T3, T4, T5, T6, T7, T8) ToValueTuple(this Tuple> value) { return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, ValueTuple.Create(value.Rest.Item1)); } public static (T1, T2, T3, T4, T5, T6, T7, T8, T9) ToValueTuple(this Tuple> value) { return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, ValueTuple.Create(value.Rest.Item1, value.Rest.Item2)); } public static (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) ToValueTuple(this Tuple> value) { return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3)); } public static (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) ToValueTuple(this Tuple> value) { return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4)); } public static (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) ToValueTuple(this Tuple> value) { return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5)); } public static (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) ToValueTuple(this Tuple> value) { return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6)); } public static (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) ToValueTuple(this Tuple> value) { return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, ValueTuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7)); } public static (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) ToValueTuple(this Tuple>> value) { return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7, ValueTuple.Create(value.Rest.Rest.Item1))); } public static (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16) ToValueTuple(this Tuple>> value) { return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7, ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2))); } public static (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17) ToValueTuple(this Tuple>> value) { return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7, ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3))); } public static (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18) ToValueTuple(this Tuple>> value) { return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7, ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4))); } public static (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19) ToValueTuple(this Tuple>> value) { return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7, ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5))); } public static (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20) ToValueTuple(this Tuple>> value) { return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7, ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5, value.Rest.Rest.Item6))); } public static (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21) ToValueTuple(this Tuple>> value) { return CreateLong(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, CreateLong(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7, ValueTuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5, value.Rest.Rest.Item6, value.Rest.Rest.Item7))); } public static Tuple ToTuple(this ValueTuple value) { return Tuple.Create(value.Item1); } public static Tuple ToTuple(this (T1, T2) value) { return Tuple.Create(value.Item1, value.Item2); } public static Tuple ToTuple(this (T1, T2, T3) value) { return Tuple.Create(value.Item1, value.Item2, value.Item3); } public static Tuple ToTuple(this (T1, T2, T3, T4) value) { return Tuple.Create(value.Item1, value.Item2, value.Item3, value.Item4); } public static Tuple ToTuple(this (T1, T2, T3, T4, T5) value) { return Tuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5); } public static Tuple ToTuple(this (T1, T2, T3, T4, T5, T6) value) { return Tuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6); } public static Tuple ToTuple(this (T1, T2, T3, T4, T5, T6, T7) value) { return Tuple.Create(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7); } public static Tuple> ToTuple(this (T1, T2, T3, T4, T5, T6, T7, T8) value) { return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, Tuple.Create(value.Rest.Item1)); } public static Tuple> ToTuple(this (T1, T2, T3, T4, T5, T6, T7, T8, T9) value) { return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, Tuple.Create(value.Rest.Item1, value.Rest.Item2)); } public static Tuple> ToTuple(this (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) value) { return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3)); } public static Tuple> ToTuple(this (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11) value) { return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4)); } public static Tuple> ToTuple(this (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12) value) { return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5)); } public static Tuple> ToTuple(this (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13) value) { return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6)); } public static Tuple> ToTuple(this (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14) value) { return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, Tuple.Create(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7)); } public static Tuple>> ToTuple(this (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15) value) { return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7, Tuple.Create(value.Rest.Rest.Item1))); } public static Tuple>> ToTuple(this (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16) value) { return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7, Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2))); } public static Tuple>> ToTuple(this (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17) value) { return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7, Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3))); } public static Tuple>> ToTuple(this (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18) value) { return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7, Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4))); } public static Tuple>> ToTuple(this (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19) value) { return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7, Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5))); } public static Tuple>> ToTuple(this (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20) value) { return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7, Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5, value.Rest.Rest.Item6))); } public static Tuple>> ToTuple(this (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21) value) { return CreateLongRef(value.Item1, value.Item2, value.Item3, value.Item4, value.Item5, value.Item6, value.Item7, CreateLongRef(value.Rest.Item1, value.Rest.Item2, value.Rest.Item3, value.Rest.Item4, value.Rest.Item5, value.Rest.Item6, value.Rest.Item7, Tuple.Create(value.Rest.Rest.Item1, value.Rest.Rest.Item2, value.Rest.Rest.Item3, value.Rest.Rest.Item4, value.Rest.Rest.Item5, value.Rest.Rest.Item6, value.Rest.Rest.Item7))); } private static ValueTuple CreateLong(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) where TRest : struct, ITuple? { return new ValueTuple(item1, item2, item3, item4, item5, item6, item7, rest); } private static Tuple CreateLongRef(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) where TRest : ITuple? { return new Tuple(item1, item2, item3, item4, item5, item6, item7, rest); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class TypeAccessException : TypeLoadException { public TypeAccessException() : base(SR.Arg_TypeAccessException) { base.HResult = -2146233021; } public TypeAccessException(string? message) : base(message) { base.HResult = -2146233021; } public TypeAccessException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233021; } protected TypeAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public enum TypeCode { Empty = 0, Object = 1, DBNull = 2, Boolean = 3, Char = 4, SByte = 5, Byte = 6, Int16 = 7, UInt16 = 8, Int32 = 9, UInt32 = 10, Int64 = 11, UInt64 = 12, Single = 13, Double = 14, Decimal = 15, DateTime = 16, String = 18 } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class TypeInitializationException : SystemException { private readonly string _typeName; public string TypeName => _typeName ?? string.Empty; private TypeInitializationException() : base(SR.TypeInitialization_Default) { base.HResult = -2146233036; } public TypeInitializationException(string? fullTypeName, Exception? innerException) : this(fullTypeName, SR.Format(SR.TypeInitialization_Type, fullTypeName), innerException) { } internal TypeInitializationException(string message) : base(message) { base.HResult = -2146233036; } internal TypeInitializationException(string fullTypeName, string message, Exception innerException) : base(message, innerException) { _typeName = fullTypeName; base.HResult = -2146233036; } private TypeInitializationException(SerializationInfo info, StreamingContext context) : base(info, context) { _typeName = info.GetString("TypeName"); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("TypeName", TypeName, typeof(string)); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class TypeUnloadedException : SystemException { public TypeUnloadedException() : base(SR.Arg_TypeUnloadedException) { base.HResult = -2146234349; } public TypeUnloadedException(string? message) : base(message) { base.HResult = -2146234349; } public TypeUnloadedException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146234349; } protected TypeUnloadedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [CLSCompliant(false)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct UInt16 : IComparable, IConvertible, ISpanFormattable, IFormattable, IComparable, IEquatable, IBinaryInteger, IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IShiftOperators, IMinMaxValue, IUnsignedNumber { private readonly ushort m_value; public const ushort MaxValue = 65535; public const ushort MinValue = 0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IAdditiveIdentity.AdditiveIdentity => 0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IMinMaxValue.MinValue => 0; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IMinMaxValue.MaxValue => ushort.MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IMultiplicativeIdentity.MultiplicativeIdentity => 1; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort INumber.One => 1; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort INumber.Zero => 0; public int CompareTo(object? value) { if (value == null) { return 1; } if (value is ushort) { return this - (ushort)value; } throw new ArgumentException(SR.Arg_MustBeUInt16); } public int CompareTo(ushort value) { return this - value; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is ushort)) { return false; } return this == (ushort)obj; } [NonVersionable] public bool Equals(ushort obj) { return this == obj; } public override int GetHashCode() { return this; } public override string ToString() { return Number.UInt32ToDecStr(this); } public string ToString(IFormatProvider? provider) { return Number.UInt32ToDecStr(this); } public string ToString(string? format) { return Number.FormatUInt32(this, format, null); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatUInt32(this, format, provider); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return Number.TryFormatUInt32(this, format, provider, destination, out charsWritten); } public static ushort Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static ushort Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, style, NumberFormatInfo.CurrentInfo); } public static ushort Parse(string s, IFormatProvider? provider) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static ushort Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Parse((ReadOnlySpan)s, style, NumberFormatInfo.GetInstance(provider)); } public static ushort Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static ushort Parse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info) { uint result; Number.ParsingStatus parsingStatus = Number.TryParseUInt32(s, style, info, out result); if (parsingStatus != 0) { Number.ThrowOverflowOrFormatException(parsingStatus, TypeCode.UInt16); } if (result > 65535) { Number.ThrowOverflowException(TypeCode.UInt16); } return (ushort)result; } public static bool TryParse([NotNullWhen(true)] string? s, out ushort result) { if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan s, out ushort result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out ushort result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan)s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out ushort result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan s, NumberStyles style, NumberFormatInfo info, out ushort result) { if (Number.TryParseUInt32(s, style, info, out var result2) != 0 || result2 > 65535) { result = 0; return false; } result = (ushort)result2; return true; } public TypeCode GetTypeCode() { return TypeCode.UInt16; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(this); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(this); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return this; } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt16", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IAdditionOperators.op_Addition(ushort left, ushort right) { return (ushort)(left + right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IBinaryInteger.LeadingZeroCount(ushort value) { return (ushort)(BitOperations.LeadingZeroCount(value) - 16); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IBinaryInteger.PopCount(ushort value) { return (ushort)BitOperations.PopCount(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IBinaryInteger.RotateLeft(ushort value, int rotateAmount) { return (ushort)((value << (rotateAmount & 0xF)) | (value >> ((16 - rotateAmount) & 0xF))); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IBinaryInteger.RotateRight(ushort value, int rotateAmount) { return (ushort)((value >> (rotateAmount & 0xF)) | (value << ((16 - rotateAmount) & 0xF))); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IBinaryInteger.TrailingZeroCount(ushort value) { return (ushort)(BitOperations.TrailingZeroCount(value << 16) - 16); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IBinaryNumber.IsPow2(ushort value) { return BitOperations.IsPow2((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IBinaryNumber.Log2(ushort value) { return (ushort)BitOperations.Log2(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IBitwiseOperators.op_BitwiseAnd(ushort left, ushort right) { return (ushort)(left & right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IBitwiseOperators.op_BitwiseOr(ushort left, ushort right) { return (ushort)(left | right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IBitwiseOperators.op_ExclusiveOr(ushort left, ushort right) { return (ushort)(left ^ right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IBitwiseOperators.op_OnesComplement(ushort value) { return (ushort)(~value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(ushort left, ushort right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(ushort left, ushort right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(ushort left, ushort right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(ushort left, ushort right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IDecrementOperators.op_Decrement(ushort value) { return --value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IDivisionOperators.op_Division(ushort left, ushort right) { return (ushort)(left / right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(ushort left, ushort right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(ushort left, ushort right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IIncrementOperators.op_Increment(ushort value) { return ++value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IModulusOperators.op_Modulus(ushort left, ushort right) { return (ushort)(left % right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IMultiplyOperators.op_Multiply(ushort left, ushort right) { return (ushort)(left * right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort INumber.Abs(ushort value) { return value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort INumber.Clamp(ushort value, ushort min, ushort max) { return Math.Clamp(value, min, max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort INumber.Create(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (ushort)(decimal)(object)value; } checked { if (typeof(TOther) == typeof(double)) { return (ushort)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (ushort)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (ushort)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (ushort)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (ushort)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (ushort)(sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (ushort)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (ushort)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (ushort)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (ushort)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (!(num > 65535m)) { if (!(num < 0m)) { return (ushort)num; } return 0; } return ushort.MaxValue; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (!(num2 > 65535.0)) { if (!(num2 < 0.0)) { return (ushort)num2; } return 0; } return ushort.MaxValue; } if (typeof(TOther) == typeof(short)) { short num3 = (short)(object)value; if (num3 >= 0) { return (ushort)num3; } return 0; } if (typeof(TOther) == typeof(int)) { int num4 = (int)(object)value; if (num4 <= 65535) { if (num4 >= 0) { return (ushort)num4; } return 0; } return ushort.MaxValue; } if (typeof(TOther) == typeof(long)) { long num5 = (long)(object)value; if (num5 <= 65535) { if (num5 >= 0) { return (ushort)num5; } return 0; } return ushort.MaxValue; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr <= 65535) { if ((nint)intPtr >= 0) { return (ushort)(nint)intPtr; } return 0; } return ushort.MaxValue; } if (typeof(TOther) == typeof(sbyte)) { sbyte b = (sbyte)(object)value; if (b >= 0) { return (ushort)b; } return 0; } if (typeof(TOther) == typeof(float)) { float num6 = (float)(object)value; if (!(num6 > 65535f)) { if (!(num6 < 0f)) { return (ushort)num6; } return 0; } return ushort.MaxValue; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { uint num7 = (uint)(object)value; if (num7 <= 65535) { return (ushort)num7; } return ushort.MaxValue; } if (typeof(TOther) == typeof(ulong)) { ulong num8 = (ulong)(object)value; if (num8 <= 65535) { return (ushort)num8; } return ushort.MaxValue; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr <= 65535) { return (ushort)(nuint)uIntPtr; } return ushort.MaxValue; } ThrowHelper.ThrowNotSupportedException(); return 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (ushort)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (ushort)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (ushort)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (ushort)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (ushort)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (ushort)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (ushort)(sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (ushort)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (ushort)(uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (ushort)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (ushort)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (ushort Quotient, ushort Remainder) INumber.DivRem(ushort left, ushort right) { return Math.DivRem(left, right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort INumber.Max(ushort x, ushort y) { return Math.Max(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort INumber.Min(ushort x, ushort y) { return Math.Min(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort INumber.Sign(ushort value) { return (ushort)((value != 0) ? 1u : 0u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out ushort result) { if (typeof(TOther) == typeof(byte)) { result = (byte)(object)value; return true; } if (typeof(TOther) == typeof(char)) { result = (char)(object)value; return true; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (num < 0m || num > 65535m) { result = 0; return false; } result = (ushort)num; return true; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (num2 < 0.0 || num2 > 65535.0) { result = 0; return false; } result = (ushort)num2; return true; } if (typeof(TOther) == typeof(short)) { short num3 = (short)(object)value; if (num3 < 0) { result = 0; return false; } result = (ushort)num3; return true; } if (typeof(TOther) == typeof(int)) { int num4 = (int)(object)value; if (num4 < 0 || num4 > 65535) { result = 0; return false; } result = (ushort)num4; return true; } if (typeof(TOther) == typeof(long)) { long num5 = (long)(object)value; if (num5 < 0 || num5 > 65535) { result = 0; return false; } result = (ushort)num5; return true; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr < 0 || (nint)intPtr > 65535) { result = 0; return false; } result = (ushort)(nint)intPtr; return true; } if (typeof(TOther) == typeof(sbyte)) { sbyte b = (sbyte)(object)value; if (b < 0) { result = 0; return false; } result = (ushort)b; return true; } if (typeof(TOther) == typeof(float)) { float num6 = (float)(object)value; if (num6 < 0f || num6 > 65535f) { result = 0; return false; } result = (ushort)num6; return true; } if (typeof(TOther) == typeof(ushort)) { result = (ushort)(object)value; return true; } if (typeof(TOther) == typeof(uint)) { uint num7 = (uint)(object)value; if (num7 > 65535) { result = 0; return false; } result = (ushort)num7; return true; } if (typeof(TOther) == typeof(ulong)) { ulong num8 = (ulong)(object)value; if (num8 > 65535) { result = 0; return false; } result = (ushort)num8; return true; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr > 65535) { result = 0; return false; } result = (ushort)(nuint)uIntPtr; return true; } ThrowHelper.ThrowNotSupportedException(); result = 0; return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out ushort result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out ushort result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out ushort result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IShiftOperators.op_LeftShift(ushort value, int shiftAmount) { return (ushort)(value << shiftAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IShiftOperators.op_RightShift(ushort value, int shiftAmount) { return (ushort)(value >> shiftAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out ushort result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort ISubtractionOperators.op_Subtraction(ushort left, ushort right) { return (ushort)(left - right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IUnaryNegationOperators.op_UnaryNegation(ushort value) { return (ushort)(-value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ushort IUnaryPlusOperators.op_UnaryPlus(ushort value) { return value; } } [Serializable] [CLSCompliant(false)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct UInt32 : IComparable, IConvertible, ISpanFormattable, IFormattable, IComparable, IEquatable, IBinaryInteger, IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IShiftOperators, IMinMaxValue, IUnsignedNumber { private readonly uint m_value; public const uint MaxValue = 4294967295u; public const uint MinValue = 0u; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IAdditiveIdentity.AdditiveIdentity => 0u; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IMinMaxValue.MinValue => 0u; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IMinMaxValue.MaxValue => uint.MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IMultiplicativeIdentity.MultiplicativeIdentity => 1u; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint INumber.One => 1u; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint INumber.Zero => 0u; public int CompareTo(object? value) { if (value == null) { return 1; } if (value is uint num) { if (this < num) { return -1; } if (this > num) { return 1; } return 0; } throw new ArgumentException(SR.Arg_MustBeUInt32); } public int CompareTo(uint value) { if (this < value) { return -1; } if (this > value) { return 1; } return 0; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is uint)) { return false; } return this == (uint)obj; } [NonVersionable] public bool Equals(uint obj) { return this == obj; } public override int GetHashCode() { return (int)this; } public override string ToString() { return Number.UInt32ToDecStr(this); } public string ToString(IFormatProvider? provider) { return Number.UInt32ToDecStr(this); } public string ToString(string? format) { return Number.FormatUInt32(this, format, null); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatUInt32(this, format, provider); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return Number.TryFormatUInt32(this, format, provider, destination, out charsWritten); } public static uint Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static uint Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseUInt32(s, style, NumberFormatInfo.CurrentInfo); } public static uint Parse(string s, IFormatProvider? provider) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static uint Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider)); } public static uint Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider)); } public static bool TryParse([NotNullWhen(true)] string? s, out uint result) { if (s == null) { result = 0u; return false; } return Number.TryParseUInt32IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } public static bool TryParse(ReadOnlySpan s, out uint result) { return Number.TryParseUInt32IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out uint result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0u; return false; } return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out uint result) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } public TypeCode GetTypeCode() { return TypeCode.UInt32; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(this); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(this); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this); } uint IConvertible.ToUInt32(IFormatProvider provider) { return this; } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(this); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt32", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IAdditionOperators.op_Addition(uint left, uint right) { return left + right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IBinaryInteger.LeadingZeroCount(uint value) { return (uint)BitOperations.LeadingZeroCount(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IBinaryInteger.PopCount(uint value) { return (uint)BitOperations.PopCount(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IBinaryInteger.RotateLeft(uint value, int rotateAmount) { return BitOperations.RotateLeft(value, rotateAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IBinaryInteger.RotateRight(uint value, int rotateAmount) { return BitOperations.RotateRight(value, rotateAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IBinaryInteger.TrailingZeroCount(uint value) { return (uint)BitOperations.TrailingZeroCount(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IBinaryNumber.IsPow2(uint value) { return BitOperations.IsPow2(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IBinaryNumber.Log2(uint value) { return (uint)BitOperations.Log2(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IBitwiseOperators.op_BitwiseAnd(uint left, uint right) { return left & right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IBitwiseOperators.op_BitwiseOr(uint left, uint right) { return left | right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IBitwiseOperators.op_ExclusiveOr(uint left, uint right) { return left ^ right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IBitwiseOperators.op_OnesComplement(uint value) { return ~value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(uint left, uint right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(uint left, uint right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(uint left, uint right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(uint left, uint right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IDecrementOperators.op_Decrement(uint value) { return --value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IDivisionOperators.op_Division(uint left, uint right) { return left / right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(uint left, uint right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(uint left, uint right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IIncrementOperators.op_Increment(uint value) { return ++value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IModulusOperators.op_Modulus(uint left, uint right) { return left % right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IMultiplyOperators.op_Multiply(uint left, uint right) { return left * right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint INumber.Abs(uint value) { return value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint INumber.Clamp(uint value, uint min, uint max) { return Math.Clamp(value, min, max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint INumber.Create(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (uint)(decimal)(object)value; } checked { if (typeof(TOther) == typeof(double)) { return (uint)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (uint)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (uint)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (uint)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (uint)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (uint)(sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (uint)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (uint)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (uint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0u; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (!(num > 4294967295m)) { if (!(num < 0m)) { return (uint)num; } return 0u; } return uint.MaxValue; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (!(num2 > 4294967295.0)) { if (!(num2 < 0.0)) { return (uint)num2; } return 0u; } return uint.MaxValue; } if (typeof(TOther) == typeof(short)) { short num3 = (short)(object)value; if (num3 >= 0) { return (uint)num3; } return 0u; } if (typeof(TOther) == typeof(int)) { int num4 = (int)(object)value; if (num4 >= 0) { return (uint)num4; } return 0u; } if (typeof(TOther) == typeof(long)) { long num5 = (long)(object)value; if (num5 <= uint.MaxValue) { if (num5 >= 0) { return (uint)num5; } return 0u; } return uint.MaxValue; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr <= uint.MaxValue) { if ((nint)intPtr >= 0) { return (uint)(nint)intPtr; } return 0u; } return uint.MaxValue; } if (typeof(TOther) == typeof(sbyte)) { sbyte b = (sbyte)(object)value; if (b >= 0) { return (uint)b; } return 0u; } if (typeof(TOther) == typeof(float)) { float num6 = (float)(object)value; if (!(num6 > 4.2949673E+09f)) { if (!(num6 < 0f)) { return (uint)num6; } return 0u; } return uint.MaxValue; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { ulong num7 = (ulong)(object)value; if (num7 <= uint.MaxValue) { return (uint)num7; } return uint.MaxValue; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr <= uint.MaxValue) { return (uint)(nuint)uIntPtr; } return uint.MaxValue; } ThrowHelper.ThrowNotSupportedException(); return 0u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (uint)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (uint)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (uint)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (uint)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (uint)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (uint)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (uint)(sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (uint)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (uint)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (uint)(nuint)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0u; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (uint Quotient, uint Remainder) INumber.DivRem(uint left, uint right) { return Math.DivRem(left, right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint INumber.Max(uint x, uint y) { return Math.Max(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint INumber.Min(uint x, uint y) { return Math.Min(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint INumber.Sign(uint value) { if (value != 0) { return 1u; } return 0u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out uint result) { if (typeof(TOther) == typeof(byte)) { result = (byte)(object)value; return true; } if (typeof(TOther) == typeof(char)) { result = (char)(object)value; return true; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (num < 0m || num > 4294967295m) { result = 0u; return false; } result = (uint)num; return true; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (num2 < 0.0 || num2 > 4294967295.0) { result = 0u; return false; } result = (uint)num2; return true; } if (typeof(TOther) == typeof(short)) { short num3 = (short)(object)value; if (num3 < 0) { result = 0u; return false; } result = (uint)num3; return true; } if (typeof(TOther) == typeof(int)) { int num4 = (int)(object)value; if (num4 < 0) { result = 0u; return false; } result = (uint)num4; return true; } if (typeof(TOther) == typeof(long)) { long num5 = (long)(object)value; if (num5 < 0 || num5 > uint.MaxValue) { result = 0u; return false; } result = (uint)num5; return true; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr < 0 || (nint)intPtr > uint.MaxValue) { result = 0u; return false; } result = (uint)(nint)intPtr; return true; } if (typeof(TOther) == typeof(sbyte)) { sbyte b = (sbyte)(object)value; if (b < 0) { result = 0u; return false; } result = (uint)b; return true; } if (typeof(TOther) == typeof(float)) { float num6 = (float)(object)value; if (num6 < 0f || num6 > 4.2949673E+09f) { result = 0u; return false; } result = (uint)num6; return true; } if (typeof(TOther) == typeof(ushort)) { result = (ushort)(object)value; return true; } if (typeof(TOther) == typeof(uint)) { result = (uint)(object)value; return true; } if (typeof(TOther) == typeof(ulong)) { ulong num7 = (ulong)(object)value; if (num7 > uint.MaxValue) { result = 0u; return false; } result = (uint)num7; return true; } if (typeof(TOther) == typeof(UIntPtr)) { UIntPtr uIntPtr = (UIntPtr)(object)value; if ((nuint)uIntPtr > uint.MaxValue) { result = 0u; return false; } result = (uint)(nuint)uIntPtr; return true; } ThrowHelper.ThrowNotSupportedException(); result = 0u; return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out uint result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out uint result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out uint result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IShiftOperators.op_LeftShift(uint value, int shiftAmount) { return value << shiftAmount; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IShiftOperators.op_RightShift(uint value, int shiftAmount) { return value >> shiftAmount; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out uint result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint ISubtractionOperators.op_Subtraction(uint left, uint right) { return left - right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IUnaryNegationOperators.op_UnaryNegation(uint value) { return 0 - value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static uint IUnaryPlusOperators.op_UnaryPlus(uint value) { return value; } } [Serializable] [CLSCompliant(false)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct UInt64 : IComparable, IConvertible, ISpanFormattable, IFormattable, IComparable, IEquatable, IBinaryInteger, IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IShiftOperators, IMinMaxValue, IUnsignedNumber { private readonly ulong m_value; public const ulong MaxValue = 18446744073709551615uL; public const ulong MinValue = 0uL; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IAdditiveIdentity.AdditiveIdentity => 0uL; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IMinMaxValue.MinValue => 0uL; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IMinMaxValue.MaxValue => ulong.MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IMultiplicativeIdentity.MultiplicativeIdentity => 1uL; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong INumber.One => 1uL; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong INumber.Zero => 0uL; public int CompareTo(object? value) { if (value == null) { return 1; } if (value is ulong num) { if (this < num) { return -1; } if (this > num) { return 1; } return 0; } throw new ArgumentException(SR.Arg_MustBeUInt64); } public int CompareTo(ulong value) { if (this < value) { return -1; } if (this > value) { return 1; } return 0; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is ulong)) { return false; } return this == (ulong)obj; } [NonVersionable] public bool Equals(ulong obj) { return this == obj; } public override int GetHashCode() { return (int)this ^ (int)(this >> 32); } public override string ToString() { return Number.UInt64ToDecStr(this, -1); } public string ToString(IFormatProvider? provider) { return Number.UInt64ToDecStr(this, -1); } public string ToString(string? format) { return Number.FormatUInt64(this, format, null); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatUInt64(this, format, provider); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return Number.TryFormatUInt64(this, format, provider, destination, out charsWritten); } public static ulong Parse(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static ulong Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseUInt64(s, style, NumberFormatInfo.CurrentInfo); } public static ulong Parse(string s, IFormatProvider? provider) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static ulong Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return Number.ParseUInt64(s, style, NumberFormatInfo.GetInstance(provider)); } public static ulong Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.ParseUInt64(s, style, NumberFormatInfo.GetInstance(provider)); } public static bool TryParse([NotNullWhen(true)] string? s, out ulong result) { if (s == null) { result = 0uL; return false; } return Number.TryParseUInt64IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } public static bool TryParse(ReadOnlySpan s, out ulong result) { return Number.TryParseUInt64IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK; } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out ulong result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0uL; return false; } return Number.TryParseUInt64(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out ulong result) { NumberFormatInfo.ValidateParseStyleInteger(style); return Number.TryParseUInt64(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK; } public TypeCode GetTypeCode() { return TypeCode.UInt64; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(this); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(this); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(this); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(this); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(this); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(this); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(this); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(this); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(this); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return this; } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(this); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(this); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(this); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt64", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType(this, type, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IAdditionOperators.op_Addition(ulong left, ulong right) { return left + right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IBinaryInteger.LeadingZeroCount(ulong value) { return (ulong)BitOperations.LeadingZeroCount(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IBinaryInteger.PopCount(ulong value) { return (ulong)BitOperations.PopCount(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IBinaryInteger.RotateLeft(ulong value, int rotateAmount) { return BitOperations.RotateLeft(value, rotateAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IBinaryInteger.RotateRight(ulong value, int rotateAmount) { return BitOperations.RotateRight(value, rotateAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IBinaryInteger.TrailingZeroCount(ulong value) { return (ulong)BitOperations.TrailingZeroCount(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IBinaryNumber.IsPow2(ulong value) { return BitOperations.IsPow2(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IBinaryNumber.Log2(ulong value) { return (ulong)BitOperations.Log2(value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IBitwiseOperators.op_BitwiseAnd(ulong left, ulong right) { return left & right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IBitwiseOperators.op_BitwiseOr(ulong left, ulong right) { return left | right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IBitwiseOperators.op_ExclusiveOr(ulong left, ulong right) { return left ^ right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IBitwiseOperators.op_OnesComplement(ulong value) { return ~value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(ulong left, ulong right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(ulong left, ulong right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(ulong left, ulong right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(ulong left, ulong right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IDecrementOperators.op_Decrement(ulong value) { return --value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IDivisionOperators.op_Division(ulong left, ulong right) { return left / right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(ulong left, ulong right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(ulong left, ulong right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IIncrementOperators.op_Increment(ulong value) { return ++value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IModulusOperators.op_Modulus(ulong left, ulong right) { return left % right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IMultiplyOperators.op_Multiply(ulong left, ulong right) { return left * right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong INumber.Abs(ulong value) { return value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong INumber.Clamp(ulong value, ulong min, ulong max) { return Math.Clamp(value, min, max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong INumber.Create(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (ulong)(decimal)(object)value; } checked { if (typeof(TOther) == typeof(double)) { return (ulong)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (ulong)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (ulong)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (ulong)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (ulong)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (ulong)(sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (ulong)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (ulong)(object)value; } } if (typeof(TOther) == typeof(UIntPtr)) { return (ulong)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0uL; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (!(num > 18446744073709551615m)) { if (!(num < 0m)) { return (ulong)num; } return 0uL; } return ulong.MaxValue; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (!(num2 > 1.8446744073709552E+19)) { if (!(num2 < 0.0)) { return (ulong)num2; } return 0uL; } return ulong.MaxValue; } if (typeof(TOther) == typeof(short)) { short num3 = (short)(object)value; if (num3 >= 0) { return (ulong)num3; } return 0uL; } if (typeof(TOther) == typeof(int)) { int num4 = (int)(object)value; if (num4 >= 0) { return (ulong)num4; } return 0uL; } if (typeof(TOther) == typeof(long)) { long num5 = (long)(object)value; if (num5 >= 0) { return (ulong)num5; } return 0uL; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr >= 0) { return (ulong)(nint)intPtr; } return 0uL; } if (typeof(TOther) == typeof(sbyte)) { sbyte b = (sbyte)(object)value; if (b >= 0) { return (ulong)b; } return 0uL; } if (typeof(TOther) == typeof(float)) { float num6 = (float)(object)value; if (!(num6 > 1.8446744E+19f)) { if (!(num6 < 0f)) { return (ulong)num6; } return 0uL; } return ulong.MaxValue; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (ulong)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0uL; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (ulong)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (ulong)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (ulong)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (ulong)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (ulong)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (ulong)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (ulong)(sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (ulong)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (ulong)(UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0uL; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (ulong Quotient, ulong Remainder) INumber.DivRem(ulong left, ulong right) { return Math.DivRem(left, right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong INumber.Max(ulong x, ulong y) { return Math.Max(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong INumber.Min(ulong x, ulong y) { return Math.Min(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong INumber.Sign(ulong value) { return (ulong)((value != 0L) ? 1 : 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out ulong result) { if (typeof(TOther) == typeof(byte)) { result = (byte)(object)value; return true; } if (typeof(TOther) == typeof(char)) { result = (char)(object)value; return true; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (num < 0m || num > 18446744073709551615m) { result = 0uL; return false; } result = (ulong)num; return true; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (num2 < 0.0 || num2 > 1.8446744073709552E+19) { result = 0uL; return false; } result = (ulong)num2; return true; } if (typeof(TOther) == typeof(short)) { short num3 = (short)(object)value; if (num3 < 0) { result = 0uL; return false; } result = (ulong)num3; return true; } if (typeof(TOther) == typeof(int)) { int num4 = (int)(object)value; if (num4 < 0) { result = 0uL; return false; } result = (ulong)num4; return true; } if (typeof(TOther) == typeof(long)) { long num5 = (long)(object)value; if (num5 < 0) { result = 0uL; return false; } result = (ulong)num5; return true; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr < 0) { result = 0uL; return false; } result = (ulong)(nint)intPtr; return true; } if (typeof(TOther) == typeof(sbyte)) { sbyte b = (sbyte)(object)value; if (b < 0) { result = 0uL; return false; } result = (ulong)b; return true; } if (typeof(TOther) == typeof(float)) { float num6 = (float)(object)value; if (num6 < 0f || num6 > 1.8446744E+19f) { result = 0uL; return false; } result = (ulong)num6; return true; } if (typeof(TOther) == typeof(ushort)) { result = (ushort)(object)value; return true; } if (typeof(TOther) == typeof(uint)) { result = (uint)(object)value; return true; } if (typeof(TOther) == typeof(ulong)) { result = (ulong)(object)value; return true; } if (typeof(TOther) == typeof(UIntPtr)) { result = (ulong)(UIntPtr)(object)value; return true; } ThrowHelper.ThrowNotSupportedException(); result = 0uL; return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out ulong result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out ulong result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out ulong result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IShiftOperators.op_LeftShift(ulong value, int shiftAmount) { return value << shiftAmount; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IShiftOperators.op_RightShift(ulong value, int shiftAmount) { return value >> shiftAmount; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out ulong result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong ISubtractionOperators.op_Subtraction(ulong left, ulong right) { return left - right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IUnaryNegationOperators.op_UnaryNegation(ulong value) { return 0 - value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static ulong IUnaryPlusOperators.op_UnaryPlus(ulong value) { return value; } } [Serializable] [CLSCompliant(false)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct UIntPtr : IEquatable, IComparable, IComparable, ISpanFormattable, IFormattable, ISerializable, IBinaryInteger, IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IEqualityOperators, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IShiftOperators, IMinMaxValue, IUnsignedNumber { private unsafe readonly void* _value; [Intrinsic] public static readonly UIntPtr Zero; public static int Size { [NonVersionable] get { return 4; } } public static UIntPtr MaxValue { [NonVersionable] get { return (UIntPtr)uint.MaxValue; } } public static UIntPtr MinValue { [NonVersionable] get { return (UIntPtr)0u; } } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IAdditiveIdentity.AdditiveIdentity => 0u; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IMinMaxValue.MinValue => MinValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IMinMaxValue.MaxValue => MaxValue; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IMultiplicativeIdentity.MultiplicativeIdentity => 1u; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint INumber.One => 1u; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint INumber.Zero => 0u; [NonVersionable] public unsafe UIntPtr(uint value) { _value = (void*)value; } [NonVersionable] public unsafe UIntPtr(ulong value) { _value = (void*)checked((uint)value); } [NonVersionable] public unsafe UIntPtr(void* value) { _value = value; } private unsafe UIntPtr(SerializationInfo info, StreamingContext context) { ulong uInt = info.GetUInt64("value"); _ = Size; if (uInt > uint.MaxValue) { throw new ArgumentException(SR.Serialization_InvalidPtrValue); } _value = (void*)uInt; } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("value", ToUInt64()); } public unsafe override bool Equals([NotNullWhen(true)] object? obj) { if (obj is UIntPtr) { return _value == ((UIntPtr)obj)._value; } return false; } public unsafe override int GetHashCode() { return (int)_value; } [NonVersionable] public unsafe uint ToUInt32() { return (uint)_value; } [NonVersionable] public unsafe ulong ToUInt64() { return (ulong)_value; } [NonVersionable] public static explicit operator UIntPtr(uint value) { return new UIntPtr(value); } [NonVersionable] public static explicit operator UIntPtr(ulong value) { return new UIntPtr(value); } [NonVersionable] public unsafe static explicit operator UIntPtr(void* value) { return new UIntPtr(value); } [NonVersionable] public unsafe static explicit operator void*(UIntPtr value) { return value._value; } [NonVersionable] public unsafe static explicit operator uint(UIntPtr value) { return (uint)value._value; } [NonVersionable] public unsafe static explicit operator ulong(UIntPtr value) { return (ulong)value._value; } [NonVersionable] public unsafe static bool operator ==(UIntPtr value1, UIntPtr value2) { return value1._value == value2._value; } [NonVersionable] public unsafe static bool operator !=(UIntPtr value1, UIntPtr value2) { return value1._value != value2._value; } [NonVersionable] public static UIntPtr Add(UIntPtr pointer, int offset) { return pointer + offset; } [NonVersionable] public unsafe static UIntPtr operator +(UIntPtr pointer, int offset) { return (UIntPtr)((byte*)pointer._value + offset); } [NonVersionable] public static UIntPtr Subtract(UIntPtr pointer, int offset) { return pointer - offset; } [NonVersionable] public unsafe static UIntPtr operator -(UIntPtr pointer, int offset) { return (UIntPtr)((byte*)pointer._value - offset); } [NonVersionable] public unsafe void* ToPointer() { return _value; } public unsafe int CompareTo(object? value) { if (value == null) { return 1; } if (value is UIntPtr uIntPtr) { if ((nuint)_value < (nuint)uIntPtr) { return -1; } if ((nuint)_value > (nuint)uIntPtr) { return 1; } return 0; } throw new ArgumentException(SR.Arg_MustBeUIntPtr); } public unsafe int CompareTo(UIntPtr value) { return ((uint)_value).CompareTo((uint)value); } [NonVersionable] public unsafe bool Equals(UIntPtr other) { return _value == (void*)other; } public unsafe override string ToString() { return ((uint)_value).ToString(); } public unsafe string ToString(string? format) { return ((uint)_value).ToString(format); } public unsafe string ToString(IFormatProvider? provider) { return ((uint)_value).ToString(provider); } public unsafe string ToString(string? format, IFormatProvider? provider) { return ((uint)_value).ToString(format, provider); } public unsafe bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return ((uint)_value).TryFormat(destination, out charsWritten, format, provider); } public static UIntPtr Parse(string s) { return (UIntPtr)uint.Parse(s); } public static UIntPtr Parse(string s, NumberStyles style) { return (UIntPtr)uint.Parse(s, style); } public static UIntPtr Parse(string s, IFormatProvider? provider) { return (UIntPtr)uint.Parse(s, provider); } public static UIntPtr Parse(string s, NumberStyles style, IFormatProvider? provider) { return (UIntPtr)uint.Parse(s, style, provider); } public static UIntPtr Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { return (UIntPtr)uint.Parse(s, style, provider); } public static bool TryParse([NotNullWhen(true)] string? s, out UIntPtr result) { Unsafe.SkipInit(out result); return uint.TryParse(s, out Unsafe.As(ref result)); } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out UIntPtr result) { Unsafe.SkipInit(out result); return uint.TryParse(s, style, provider, out Unsafe.As(ref result)); } public static bool TryParse(ReadOnlySpan s, out UIntPtr result) { Unsafe.SkipInit(out result); return uint.TryParse(s, out Unsafe.As(ref result)); } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out UIntPtr result) { Unsafe.SkipInit(out result); return uint.TryParse(s, style, provider, out Unsafe.As(ref result)); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IAdditionOperators.op_Addition(nuint left, nuint right) { return left + right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IBinaryInteger.LeadingZeroCount(nuint value) { if (Environment.Is64BitProcess) { } return (nuint)BitOperations.LeadingZeroCount((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IBinaryInteger.PopCount(nuint value) { if (Environment.Is64BitProcess) { } return (nuint)BitOperations.PopCount((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IBinaryInteger.RotateLeft(nuint value, int rotateAmount) { if (Environment.Is64BitProcess) { } return BitOperations.RotateLeft((uint)value, rotateAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IBinaryInteger.RotateRight(nuint value, int rotateAmount) { if (Environment.Is64BitProcess) { } return BitOperations.RotateRight((uint)value, rotateAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IBinaryInteger.TrailingZeroCount(nuint value) { if (Environment.Is64BitProcess) { } return (nuint)BitOperations.TrailingZeroCount((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IBinaryNumber.IsPow2(nuint value) { if (Environment.Is64BitProcess) { } return BitOperations.IsPow2((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IBinaryNumber.Log2(nuint value) { if (Environment.Is64BitProcess) { } return (nuint)BitOperations.Log2((uint)value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IBitwiseOperators.op_BitwiseAnd(nuint left, nuint right) { return left & right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IBitwiseOperators.op_BitwiseOr(nuint left, nuint right) { return left | right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IBitwiseOperators.op_ExclusiveOr(nuint left, nuint right) { return left ^ right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IBitwiseOperators.op_OnesComplement(nuint value) { return ~value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThan(nuint left, nuint right) { return left < right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_LessThanOrEqual(nuint left, nuint right) { return left <= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThan(nuint left, nuint right) { return left > right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IComparisonOperators.op_GreaterThanOrEqual(nuint left, nuint right) { return left >= right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IDecrementOperators.op_Decrement(nuint value) { return --value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IDivisionOperators.op_Division(nuint left, nuint right) { return left / right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Equality(nuint left, nuint right) { return left == right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IEqualityOperators.op_Inequality(nuint left, nuint right) { return left != right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IIncrementOperators.op_Increment(nuint value) { return ++value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IModulusOperators.op_Modulus(nuint left, nuint right) { return left % right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IMultiplyOperators.op_Multiply(nuint left, nuint right) { return left * right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint INumber.Abs(nuint value) { return value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint INumber.Clamp(nuint value, nuint min, nuint max) { return Math.Clamp(value, min, max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint INumber.Create(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } checked { if (typeof(TOther) == typeof(decimal)) { return (nuint)(ulong)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (nuint)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (nuint)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (nuint)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (nuint)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (nuint)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (nuint)(sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (nuint)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (nuint)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0u; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint INumber.CreateSaturating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (!(num > (decimal)(ulong)MaxValue)) { if (!(num < 0m)) { return (nuint)(ulong)num; } return MinValue; } return MaxValue; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (!(num2 > (double)(nint)(nuint)MaxValue)) { if (!(num2 < 0.0)) { return (nuint)num2; } return MinValue; } return MaxValue; } if (typeof(TOther) == typeof(short)) { short num3 = (short)(object)value; if (num3 >= 0) { return (nuint)num3; } return MinValue; } if (typeof(TOther) == typeof(int)) { int num4 = (int)(object)value; if (num4 >= 0) { return (nuint)num4; } return MinValue; } if (typeof(TOther) == typeof(long)) { long num5 = (long)(object)value; _ = Size; if (num5 <= uint.MaxValue) { if (num5 >= 0) { return (nuint)num5; } return MinValue; } return MaxValue; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr >= 0) { return (nuint)(nint)intPtr; } return MinValue; } if (typeof(TOther) == typeof(sbyte)) { sbyte b = (sbyte)(object)value; if (b >= 0) { return (nuint)b; } return MinValue; } if (typeof(TOther) == typeof(float)) { float num6 = (float)(object)value; if (!(num6 > (float)(nint)(nuint)MaxValue)) { if (!(num6 < 0f)) { return (nuint)num6; } return MinValue; } return MaxValue; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { ulong num7 = (ulong)(object)value; if (num7 <= (nuint)MaxValue) { return (nuint)num7; } return MaxValue; } if (typeof(TOther) == typeof(UIntPtr)) { return (UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint INumber.CreateTruncating(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } if (typeof(TOther) == typeof(char)) { return (char)(object)value; } if (typeof(TOther) == typeof(decimal)) { return (nuint)(ulong)(decimal)(object)value; } if (typeof(TOther) == typeof(double)) { return (nuint)(double)(object)value; } if (typeof(TOther) == typeof(short)) { return (nuint)(short)(object)value; } if (typeof(TOther) == typeof(int)) { return (nuint)(int)(object)value; } if (typeof(TOther) == typeof(long)) { return (nuint)(long)(object)value; } if (typeof(TOther) == typeof(IntPtr)) { return (nuint)(nint)(IntPtr)(object)value; } if (typeof(TOther) == typeof(sbyte)) { return (nuint)(sbyte)(object)value; } if (typeof(TOther) == typeof(float)) { return (nuint)(float)(object)value; } if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } if (typeof(TOther) == typeof(uint)) { return (uint)(object)value; } if (typeof(TOther) == typeof(ulong)) { return (nuint)(ulong)(object)value; } if (typeof(TOther) == typeof(UIntPtr)) { return (UIntPtr)(object)value; } ThrowHelper.ThrowNotSupportedException(); return 0u; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static (nuint Quotient, nuint Remainder) INumber.DivRem(nuint left, nuint right) { return Math.DivRem(left, right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint INumber.Max(nuint x, nuint y) { return Math.Max(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint INumber.Min(nuint x, nuint y) { return Math.Min(x, y); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint INumber.Parse(string s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint INumber.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider) { return Parse(s, style, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint INumber.Sign(nuint value) { return (nuint)(int)((value != 0) ? 1u : 0u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryCreate(TOther value, out nuint result) { if (typeof(TOther) == typeof(byte)) { result = (byte)(object)value; return true; } if (typeof(TOther) == typeof(char)) { result = (char)(object)value; return true; } if (typeof(TOther) == typeof(decimal)) { decimal num = (decimal)(object)value; if (num < 0m || num > (decimal)(ulong)MaxValue) { result = 0u; return false; } result = (nuint)(ulong)num; return true; } if (typeof(TOther) == typeof(double)) { double num2 = (double)(object)value; if (num2 < 0.0 || num2 > (double)(nint)(nuint)MaxValue) { result = 0u; return false; } result = (nuint)num2; return true; } if (typeof(TOther) == typeof(short)) { short num3 = (short)(object)value; if (num3 < 0) { result = 0u; return false; } result = (nuint)num3; return true; } if (typeof(TOther) == typeof(int)) { int num4 = (int)(object)value; if (num4 < 0) { result = 0u; return false; } result = (nuint)num4; return true; } if (typeof(TOther) == typeof(long)) { long num5 = (long)(object)value; if (num5 >= 0) { _ = Size; if (num5 <= uint.MaxValue) { result = (nuint)num5; return true; } } result = 0u; return false; } if (typeof(TOther) == typeof(IntPtr)) { IntPtr intPtr = (IntPtr)(object)value; if ((nint)intPtr < 0) { result = 0u; return false; } result = (nuint)(nint)intPtr; return true; } if (typeof(TOther) == typeof(sbyte)) { sbyte b = (sbyte)(object)value; if (b < 0) { result = 0u; return false; } result = (nuint)b; return true; } if (typeof(TOther) == typeof(float)) { float num6 = (float)(object)value; if (num6 < 0f || num6 > (float)(nint)(nuint)MaxValue) { result = 0u; return false; } result = (nuint)num6; return true; } if (typeof(TOther) == typeof(ushort)) { result = (ushort)(object)value; return true; } if (typeof(TOther) == typeof(uint)) { result = (uint)(object)value; return true; } if (typeof(TOther) == typeof(ulong)) { ulong num7 = (ulong)(object)value; if (num7 > (nuint)MaxValue) { result = 0u; return false; } result = (nuint)num7; return true; } if (typeof(TOther) == typeof(UIntPtr)) { result = (UIntPtr)(object)value; return true; } ThrowHelper.ThrowNotSupportedException(); result = 0u; return false; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse([NotNullWhen(true)] string s, NumberStyles style, IFormatProvider provider, out nuint result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool INumber.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider provider, out nuint result) { return TryParse(s, style, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IParseable.Parse(string s, IFormatProvider provider) { return Parse(s, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool IParseable.TryParse([NotNullWhen(true)] string s, IFormatProvider provider, out nuint result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IShiftOperators.op_LeftShift(nuint value, int shiftAmount) { return value << shiftAmount; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IShiftOperators.op_RightShift(nuint value, int shiftAmount) { return value >> shiftAmount; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint ISpanParseable.Parse(ReadOnlySpan s, IFormatProvider provider) { return Parse(s, NumberStyles.Integer, provider); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static bool ISpanParseable.TryParse(ReadOnlySpan s, IFormatProvider provider, out nuint result) { return TryParse(s, NumberStyles.Integer, provider, out result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint ISubtractionOperators.op_Subtraction(nuint left, nuint right) { return left - right; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IUnaryNegationOperators.op_UnaryNegation(nuint value) { return 0 - value; } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] static nuint IUnaryPlusOperators.op_UnaryPlus(nuint value) { return value; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class UnauthorizedAccessException : SystemException { public UnauthorizedAccessException() : base(SR.Arg_UnauthorizedAccessException) { base.HResult = -2147024891; } public UnauthorizedAccessException(string? message) : base(message) { base.HResult = -2147024891; } public UnauthorizedAccessException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2147024891; } protected UnauthorizedAccessException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class UnhandledExceptionEventArgs : EventArgs { private readonly object _exception; private readonly bool _isTerminating; public object ExceptionObject => _exception; public bool IsTerminating => _isTerminating; public UnhandledExceptionEventArgs(object exception, bool isTerminating) { _exception = exception; _isTerminating = isTerminating; } } public delegate void UnhandledExceptionEventHandler(object sender, UnhandledExceptionEventArgs e); [Serializable] public sealed class UnitySerializationHolder : ISerializable, IObjectReference { private readonly int _unityType; private readonly string _data; internal static void GetUnitySerializationInfo(SerializationInfo info, int unityType) { info.SetType(typeof(UnitySerializationHolder)); info.AddValue("Data", null, typeof(string)); info.AddValue("UnityType", unityType); info.AddValue("AssemblyName", string.Empty); } public UnitySerializationHolder(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } _unityType = info.GetInt32("UnityType"); _data = info.GetString("Data"); } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new NotSupportedException(SR.NotSupported_UnitySerHolder); } public object GetRealObject(StreamingContext context) { if (_unityType != 2) { throw new ArgumentException(SR.Format(SR.Argument_InvalidUnity, _data ?? "UnityType")); } return DBNull.Value; } } internal interface IValueTupleInternal : ITuple { int GetHashCode(IEqualityComparer comparer); string ToStringEnd(); } [Serializable] [StructLayout(LayoutKind.Sequential, Size = 1)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct ValueTuple : IEquatable, IStructuralEquatable, IStructuralComparable, IComparable, IComparable, IValueTupleInternal, ITuple { int ITuple.Length => 0; object? ITuple.this[int index] { get { throw new IndexOutOfRangeException(); } } public override bool Equals([NotNullWhen(true)] object? obj) { return obj is ValueTuple; } public bool Equals(ValueTuple other) { return true; } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { return other is ValueTuple; } int IComparable.CompareTo(object other) { if (other == null) { return 1; } if (!(other is ValueTuple)) { ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 0; } public int CompareTo(ValueTuple other) { return 0; } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other == null) { return 1; } if (!(other is ValueTuple)) { ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 0; } public override int GetHashCode() { return 0; } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return 0; } int IValueTupleInternal.GetHashCode(IEqualityComparer comparer) { return 0; } public override string ToString() { return "()"; } string IValueTupleInternal.ToStringEnd() { return ")"; } public static ValueTuple Create() { return default(ValueTuple); } public static ValueTuple Create(T1 item1) { return new ValueTuple(item1); } public static (T1, T2) Create(T1 item1, T2 item2) { return (item1, item2); } public static (T1, T2, T3) Create(T1 item1, T2 item2, T3 item3) { return (item1, item2, item3); } public static (T1, T2, T3, T4) Create(T1 item1, T2 item2, T3 item3, T4 item4) { return (item1, item2, item3, item4); } public static (T1, T2, T3, T4, T5) Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { return (item1, item2, item3, item4, item5); } public static (T1, T2, T3, T4, T5, T6) Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { return (item1, item2, item3, item4, item5, item6); } public static (T1, T2, T3, T4, T5, T6, T7) Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { return (item1, item2, item3, item4, item5, item6, item7); } public static (T1, T2, T3, T4, T5, T6, T7, T8) Create(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8) { return new ValueTuple>(item1, item2, item3, item4, item5, item6, item7, Create(item8)); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct ValueTuple : IEquatable>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable>, IValueTupleInternal, ITuple { public T1 Item1; int ITuple.Length => 1; object? ITuple.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return Item1; } } public ValueTuple(T1 item1) { Item1 = item1; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ValueTuple other) { return Equals(other); } return false; } public bool Equals(ValueTuple other) { return EqualityComparer.Default.Equals(Item1, other.Item1); } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other is ValueTuple valueTuple) { return comparer.Equals(Item1, valueTuple.Item1); } return false; } int IComparable.CompareTo(object other) { if (other != null) { if (other is ValueTuple valueTuple) { return Comparer.Default.Compare(Item1, valueTuple.Item1); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public int CompareTo(ValueTuple other) { return Comparer.Default.Compare(Item1, other.Item1); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other != null) { if (other is ValueTuple valueTuple) { return comparer.Compare(Item1, valueTuple.Item1); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public override int GetHashCode() { return Item1?.GetHashCode() ?? 0; } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return comparer.GetHashCode(Item1); } int IValueTupleInternal.GetHashCode(IEqualityComparer comparer) { return comparer.GetHashCode(Item1); } public override string ToString() { return "(" + Item1?.ToString() + ")"; } string IValueTupleInternal.ToStringEnd() { return Item1?.ToString() + ")"; } } [Serializable] [StructLayout(LayoutKind.Auto)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct ValueTuple : IEquatable<(T1, T2)>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<(T1, T2)>, IValueTupleInternal, ITuple { public T1 Item1; public T2 Item2; int ITuple.Length => 2; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, _ => throw new IndexOutOfRangeException(), }; public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is (T1, T2) other) { return Equals(other); } return false; } public bool Equals((T1, T2) other) { if (EqualityComparer.Default.Equals(Item1, other.Item1)) { return EqualityComparer.Default.Equals(Item2, other.Item2); } return false; } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other is (T1, T2) tuple && comparer.Equals(Item1, tuple.Item1)) { return comparer.Equals(Item2, tuple.Item2); } return false; } int IComparable.CompareTo(object other) { if (other != null) { if (other is (T1, T2) other2) { return CompareTo(other2); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public int CompareTo((T1, T2) other) { int num = Comparer.Default.Compare(Item1, other.Item1); if (num != 0) { return num; } return Comparer.Default.Compare(Item2, other.Item2); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other != null) { if (other is (T1, T2) tuple) { int num = comparer.Compare(Item1, tuple.Item1); if (num != 0) { return num; } return comparer.Compare(Item2, tuple.Item2); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public override int GetHashCode() { return HashCode.Combine(Item1?.GetHashCode() ?? 0, Item2?.GetHashCode() ?? 0); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCodeCore(comparer); } private int GetHashCodeCore(IEqualityComparer comparer) { return HashCode.Combine(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2)); } int IValueTupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCodeCore(comparer); } public override string ToString() { return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ")"; } string IValueTupleInternal.ToStringEnd() { return Item1?.ToString() + ", " + Item2?.ToString() + ")"; } } [Serializable] [StructLayout(LayoutKind.Auto)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct ValueTuple : IEquatable<(T1, T2, T3)>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<(T1, T2, T3)>, IValueTupleInternal, ITuple { public T1 Item1; public T2 Item2; public T3 Item3; int ITuple.Length => 3; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, _ => throw new IndexOutOfRangeException(), }; public ValueTuple(T1 item1, T2 item2, T3 item3) { Item1 = item1; Item2 = item2; Item3 = item3; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is (T1, T2, T3) other) { return Equals(other); } return false; } public bool Equals((T1, T2, T3) other) { if (EqualityComparer.Default.Equals(Item1, other.Item1) && EqualityComparer.Default.Equals(Item2, other.Item2)) { return EqualityComparer.Default.Equals(Item3, other.Item3); } return false; } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other is (T1, T2, T3) tuple && comparer.Equals(Item1, tuple.Item1) && comparer.Equals(Item2, tuple.Item2)) { return comparer.Equals(Item3, tuple.Item3); } return false; } int IComparable.CompareTo(object other) { if (other != null) { if (other is (T1, T2, T3) other2) { return CompareTo(other2); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public int CompareTo((T1, T2, T3) other) { int num = Comparer.Default.Compare(Item1, other.Item1); if (num != 0) { return num; } num = Comparer.Default.Compare(Item2, other.Item2); if (num != 0) { return num; } return Comparer.Default.Compare(Item3, other.Item3); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other != null) { if (other is (T1, T2, T3) tuple) { int num = comparer.Compare(Item1, tuple.Item1); if (num != 0) { return num; } num = comparer.Compare(Item2, tuple.Item2); if (num != 0) { return num; } return comparer.Compare(Item3, tuple.Item3); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public override int GetHashCode() { return HashCode.Combine(Item1?.GetHashCode() ?? 0, Item2?.GetHashCode() ?? 0, Item3?.GetHashCode() ?? 0); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCodeCore(comparer); } private int GetHashCodeCore(IEqualityComparer comparer) { return HashCode.Combine(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3)); } int IValueTupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCodeCore(comparer); } public override string ToString() { return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ")"; } string IValueTupleInternal.ToStringEnd() { return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ")"; } } [Serializable] [StructLayout(LayoutKind.Auto)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct ValueTuple : IEquatable<(T1, T2, T3, T4)>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<(T1, T2, T3, T4)>, IValueTupleInternal, ITuple { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; int ITuple.Length => 4; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, _ => throw new IndexOutOfRangeException(), }; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is (T1, T2, T3, T4) other) { return Equals(other); } return false; } public bool Equals((T1, T2, T3, T4) other) { if (EqualityComparer.Default.Equals(Item1, other.Item1) && EqualityComparer.Default.Equals(Item2, other.Item2) && EqualityComparer.Default.Equals(Item3, other.Item3)) { return EqualityComparer.Default.Equals(Item4, other.Item4); } return false; } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other is (T1, T2, T3, T4) tuple && comparer.Equals(Item1, tuple.Item1) && comparer.Equals(Item2, tuple.Item2) && comparer.Equals(Item3, tuple.Item3)) { return comparer.Equals(Item4, tuple.Item4); } return false; } int IComparable.CompareTo(object other) { if (other != null) { if (other is (T1, T2, T3, T4) other2) { return CompareTo(other2); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public int CompareTo((T1, T2, T3, T4) other) { int num = Comparer.Default.Compare(Item1, other.Item1); if (num != 0) { return num; } num = Comparer.Default.Compare(Item2, other.Item2); if (num != 0) { return num; } num = Comparer.Default.Compare(Item3, other.Item3); if (num != 0) { return num; } return Comparer.Default.Compare(Item4, other.Item4); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other != null) { if (other is (T1, T2, T3, T4) tuple) { int num = comparer.Compare(Item1, tuple.Item1); if (num != 0) { return num; } num = comparer.Compare(Item2, tuple.Item2); if (num != 0) { return num; } num = comparer.Compare(Item3, tuple.Item3); if (num != 0) { return num; } return comparer.Compare(Item4, tuple.Item4); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public override int GetHashCode() { return HashCode.Combine(Item1?.GetHashCode() ?? 0, Item2?.GetHashCode() ?? 0, Item3?.GetHashCode() ?? 0, Item4?.GetHashCode() ?? 0); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCodeCore(comparer); } private int GetHashCodeCore(IEqualityComparer comparer) { return HashCode.Combine(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4)); } int IValueTupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCodeCore(comparer); } public override string ToString() { return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ")"; } string IValueTupleInternal.ToStringEnd() { return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ")"; } } [Serializable] [StructLayout(LayoutKind.Auto)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct ValueTuple : IEquatable<(T1, T2, T3, T4, T5)>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<(T1, T2, T3, T4, T5)>, IValueTupleInternal, ITuple { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; int ITuple.Length => 5; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, _ => throw new IndexOutOfRangeException(), }; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is (T1, T2, T3, T4, T5) other) { return Equals(other); } return false; } public bool Equals((T1, T2, T3, T4, T5) other) { if (EqualityComparer.Default.Equals(Item1, other.Item1) && EqualityComparer.Default.Equals(Item2, other.Item2) && EqualityComparer.Default.Equals(Item3, other.Item3) && EqualityComparer.Default.Equals(Item4, other.Item4)) { return EqualityComparer.Default.Equals(Item5, other.Item5); } return false; } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other is (T1, T2, T3, T4, T5) tuple && comparer.Equals(Item1, tuple.Item1) && comparer.Equals(Item2, tuple.Item2) && comparer.Equals(Item3, tuple.Item3)) { return comparer.Equals(Item5, tuple.Item5); } return false; } int IComparable.CompareTo(object other) { if (other != null) { if (other is (T1, T2, T3, T4, T5) other2) { return CompareTo(other2); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public int CompareTo((T1, T2, T3, T4, T5) other) { int num = Comparer.Default.Compare(Item1, other.Item1); if (num != 0) { return num; } num = Comparer.Default.Compare(Item2, other.Item2); if (num != 0) { return num; } num = Comparer.Default.Compare(Item3, other.Item3); if (num != 0) { return num; } num = Comparer.Default.Compare(Item4, other.Item4); if (num != 0) { return num; } return Comparer.Default.Compare(Item5, other.Item5); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other != null) { if (other is (T1, T2, T3, T4, T5) tuple) { int num = comparer.Compare(Item1, tuple.Item1); if (num != 0) { return num; } num = comparer.Compare(Item2, tuple.Item2); if (num != 0) { return num; } num = comparer.Compare(Item3, tuple.Item3); if (num != 0) { return num; } num = comparer.Compare(Item4, tuple.Item4); if (num != 0) { return num; } return comparer.Compare(Item5, tuple.Item5); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public override int GetHashCode() { return HashCode.Combine(Item1?.GetHashCode() ?? 0, Item2?.GetHashCode() ?? 0, Item3?.GetHashCode() ?? 0, Item4?.GetHashCode() ?? 0, Item5?.GetHashCode() ?? 0); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCodeCore(comparer); } private int GetHashCodeCore(IEqualityComparer comparer) { return HashCode.Combine(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5)); } int IValueTupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCodeCore(comparer); } public override string ToString() { return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ")"; } string IValueTupleInternal.ToStringEnd() { return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ")"; } } [Serializable] [StructLayout(LayoutKind.Auto)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct ValueTuple : IEquatable<(T1, T2, T3, T4, T5, T6)>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<(T1, T2, T3, T4, T5, T6)>, IValueTupleInternal, ITuple { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; int ITuple.Length => 6; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, 5 => Item6, _ => throw new IndexOutOfRangeException(), }; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is (T1, T2, T3, T4, T5, T6) other) { return Equals(other); } return false; } public bool Equals((T1, T2, T3, T4, T5, T6) other) { if (EqualityComparer.Default.Equals(Item1, other.Item1) && EqualityComparer.Default.Equals(Item2, other.Item2) && EqualityComparer.Default.Equals(Item3, other.Item3) && EqualityComparer.Default.Equals(Item4, other.Item4) && EqualityComparer.Default.Equals(Item5, other.Item5)) { return EqualityComparer.Default.Equals(Item6, other.Item6); } return false; } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other is (T1, T2, T3, T4, T5, T6) tuple && comparer.Equals(Item1, tuple.Item1) && comparer.Equals(Item2, tuple.Item2) && comparer.Equals(Item3, tuple.Item3) && comparer.Equals(Item5, tuple.Item5)) { return comparer.Equals(Item6, tuple.Item6); } return false; } int IComparable.CompareTo(object other) { if (other != null) { if (other is (T1, T2, T3, T4, T5, T6) other2) { return CompareTo(other2); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public int CompareTo((T1, T2, T3, T4, T5, T6) other) { int num = Comparer.Default.Compare(Item1, other.Item1); if (num != 0) { return num; } num = Comparer.Default.Compare(Item2, other.Item2); if (num != 0) { return num; } num = Comparer.Default.Compare(Item3, other.Item3); if (num != 0) { return num; } num = Comparer.Default.Compare(Item4, other.Item4); if (num != 0) { return num; } num = Comparer.Default.Compare(Item5, other.Item5); if (num != 0) { return num; } return Comparer.Default.Compare(Item6, other.Item6); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other != null) { if (other is (T1, T2, T3, T4, T5, T6) tuple) { int num = comparer.Compare(Item1, tuple.Item1); if (num != 0) { return num; } num = comparer.Compare(Item2, tuple.Item2); if (num != 0) { return num; } num = comparer.Compare(Item3, tuple.Item3); if (num != 0) { return num; } num = comparer.Compare(Item4, tuple.Item4); if (num != 0) { return num; } num = comparer.Compare(Item5, tuple.Item5); if (num != 0) { return num; } return comparer.Compare(Item6, tuple.Item6); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public override int GetHashCode() { return HashCode.Combine(Item1?.GetHashCode() ?? 0, Item2?.GetHashCode() ?? 0, Item3?.GetHashCode() ?? 0, Item4?.GetHashCode() ?? 0, Item5?.GetHashCode() ?? 0, Item6?.GetHashCode() ?? 0); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCodeCore(comparer); } private int GetHashCodeCore(IEqualityComparer comparer) { return HashCode.Combine(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6)); } int IValueTupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCodeCore(comparer); } public override string ToString() { return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ")"; } string IValueTupleInternal.ToStringEnd() { return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ")"; } } [Serializable] [StructLayout(LayoutKind.Auto)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct ValueTuple : IEquatable<(T1, T2, T3, T4, T5, T6, T7)>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable<(T1, T2, T3, T4, T5, T6, T7)>, IValueTupleInternal, ITuple { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; int ITuple.Length => 7; object? ITuple.this[int index] => index switch { 0 => Item1, 1 => Item2, 2 => Item3, 3 => Item4, 4 => Item5, 5 => Item6, 6 => Item7, _ => throw new IndexOutOfRangeException(), }; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is (T1, T2, T3, T4, T5, T6, T7) other) { return Equals(other); } return false; } public bool Equals((T1, T2, T3, T4, T5, T6, T7) other) { if (EqualityComparer.Default.Equals(Item1, other.Item1) && EqualityComparer.Default.Equals(Item2, other.Item2) && EqualityComparer.Default.Equals(Item3, other.Item3) && EqualityComparer.Default.Equals(Item4, other.Item4) && EqualityComparer.Default.Equals(Item5, other.Item5) && EqualityComparer.Default.Equals(Item6, other.Item6)) { return EqualityComparer.Default.Equals(Item7, other.Item7); } return false; } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other is (T1, T2, T3, T4, T5, T6, T7) tuple && comparer.Equals(Item1, tuple.Item1) && comparer.Equals(Item2, tuple.Item2) && comparer.Equals(Item3, tuple.Item3) && comparer.Equals(Item5, tuple.Item5) && comparer.Equals(Item6, tuple.Item6)) { return comparer.Equals(Item7, tuple.Item7); } return false; } int IComparable.CompareTo(object other) { if (other != null) { if (other is (T1, T2, T3, T4, T5, T6, T7) other2) { return CompareTo(other2); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public int CompareTo((T1, T2, T3, T4, T5, T6, T7) other) { int num = Comparer.Default.Compare(Item1, other.Item1); if (num != 0) { return num; } num = Comparer.Default.Compare(Item2, other.Item2); if (num != 0) { return num; } num = Comparer.Default.Compare(Item3, other.Item3); if (num != 0) { return num; } num = Comparer.Default.Compare(Item4, other.Item4); if (num != 0) { return num; } num = Comparer.Default.Compare(Item5, other.Item5); if (num != 0) { return num; } num = Comparer.Default.Compare(Item6, other.Item6); if (num != 0) { return num; } return Comparer.Default.Compare(Item7, other.Item7); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other != null) { if (other is (T1, T2, T3, T4, T5, T6, T7) tuple) { int num = comparer.Compare(Item1, tuple.Item1); if (num != 0) { return num; } num = comparer.Compare(Item2, tuple.Item2); if (num != 0) { return num; } num = comparer.Compare(Item3, tuple.Item3); if (num != 0) { return num; } num = comparer.Compare(Item4, tuple.Item4); if (num != 0) { return num; } num = comparer.Compare(Item5, tuple.Item5); if (num != 0) { return num; } num = comparer.Compare(Item6, tuple.Item6); if (num != 0) { return num; } return comparer.Compare(Item7, tuple.Item7); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public override int GetHashCode() { return HashCode.Combine(Item1?.GetHashCode() ?? 0, Item2?.GetHashCode() ?? 0, Item3?.GetHashCode() ?? 0, Item4?.GetHashCode() ?? 0, Item5?.GetHashCode() ?? 0, Item6?.GetHashCode() ?? 0, Item7?.GetHashCode() ?? 0); } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCodeCore(comparer); } private int GetHashCodeCore(IEqualityComparer comparer) { return HashCode.Combine(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7)); } int IValueTupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCodeCore(comparer); } public override string ToString() { return "(" + Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ")"; } string IValueTupleInternal.ToStringEnd() { return Item1?.ToString() + ", " + Item2?.ToString() + ", " + Item3?.ToString() + ", " + Item4?.ToString() + ", " + Item5?.ToString() + ", " + Item6?.ToString() + ", " + Item7?.ToString() + ")"; } } [Serializable] [StructLayout(LayoutKind.Auto)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public struct ValueTuple : IEquatable>, IStructuralEquatable, IStructuralComparable, IComparable, IComparable>, IValueTupleInternal, ITuple where TRest : struct { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; int ITuple.Length { get { if (!(Rest is IValueTupleInternal)) { return 8; } return 7 + ((IValueTupleInternal)(object)Rest).Length; } } object? ITuple.this[int index] { get { switch (index) { case 0: return Item1; case 1: return Item2; case 2: return Item3; case 3: return Item4; case 4: return Item5; case 5: return Item6; case 6: return Item7; default: if (Rest is IValueTupleInternal) { return ((IValueTupleInternal)(object)Rest)[index - 7]; } if (index == 7) { return Rest; } throw new IndexOutOfRangeException(); } } } public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { if (!(rest is IValueTupleInternal)) { throw new ArgumentException(SR.ArgumentException_ValueTupleLastArgumentNotAValueTuple); } Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; Rest = rest; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ValueTuple other) { return Equals(other); } return false; } public bool Equals(ValueTuple other) { if (EqualityComparer.Default.Equals(Item1, other.Item1) && EqualityComparer.Default.Equals(Item2, other.Item2) && EqualityComparer.Default.Equals(Item3, other.Item3) && EqualityComparer.Default.Equals(Item4, other.Item4) && EqualityComparer.Default.Equals(Item5, other.Item5) && EqualityComparer.Default.Equals(Item6, other.Item6) && EqualityComparer.Default.Equals(Item7, other.Item7)) { return EqualityComparer.Default.Equals(Rest, other.Rest); } return false; } bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) { if (other is ValueTuple valueTuple && comparer.Equals(Item1, valueTuple.Item1) && comparer.Equals(Item2, valueTuple.Item2) && comparer.Equals(Item3, valueTuple.Item3) && comparer.Equals(Item5, valueTuple.Item5) && comparer.Equals(Item6, valueTuple.Item6) && comparer.Equals(Item7, valueTuple.Item7)) { return comparer.Equals(Rest, valueTuple.Rest); } return false; } int IComparable.CompareTo(object other) { if (other != null) { if (other is ValueTuple other2) { return CompareTo(other2); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public int CompareTo(ValueTuple other) { int num = Comparer.Default.Compare(Item1, other.Item1); if (num != 0) { return num; } num = Comparer.Default.Compare(Item2, other.Item2); if (num != 0) { return num; } num = Comparer.Default.Compare(Item3, other.Item3); if (num != 0) { return num; } num = Comparer.Default.Compare(Item4, other.Item4); if (num != 0) { return num; } num = Comparer.Default.Compare(Item5, other.Item5); if (num != 0) { return num; } num = Comparer.Default.Compare(Item6, other.Item6); if (num != 0) { return num; } num = Comparer.Default.Compare(Item7, other.Item7); if (num != 0) { return num; } return Comparer.Default.Compare(Rest, other.Rest); } int IStructuralComparable.CompareTo(object other, IComparer comparer) { if (other != null) { if (other is ValueTuple valueTuple) { int num = comparer.Compare(Item1, valueTuple.Item1); if (num != 0) { return num; } num = comparer.Compare(Item2, valueTuple.Item2); if (num != 0) { return num; } num = comparer.Compare(Item3, valueTuple.Item3); if (num != 0) { return num; } num = comparer.Compare(Item4, valueTuple.Item4); if (num != 0) { return num; } num = comparer.Compare(Item5, valueTuple.Item5); if (num != 0) { return num; } num = comparer.Compare(Item6, valueTuple.Item6); if (num != 0) { return num; } num = comparer.Compare(Item7, valueTuple.Item7); if (num != 0) { return num; } return comparer.Compare(Rest, valueTuple.Rest); } ThrowHelper.ThrowArgumentException_TupleIncorrectType(this); } return 1; } public override int GetHashCode() { T1 val; int value; if (!(Rest is IValueTupleInternal)) { ref T1 reference = ref Item1; val = default(T1); if (val == null) { val = reference; reference = ref val; if (val == null) { value = 0; goto IL_004a; } } value = reference.GetHashCode(); goto IL_004a; } int length = ((IValueTupleInternal)(object)Rest).Length; int hashCode = Rest.GetHashCode(); if (length >= 8) { return hashCode; } T7 val2; int value24; T6 val7; int value12; T5 val5; int value10; T4 val3; int value5; T3 val6; int value26; T2 val4; int value27; int value2; ref T7 reference3; int value3; ref T4 reference4; int value4; int value6; int value7; int value8; ref T2 reference5; int value9; ref T5 reference7; int value11; int value13; ref T3 reference8; int value14; ref T6 reference9; int value15; ref T6 reference10; int value16; ref T5 reference11; int value17; ref T4 reference12; int value18; ref T6 reference13; int value19; ref T6 reference14; ref T7 reference15; ref T5 reference16; int value20; ref T7 reference18; int value21; ref T7 reference19; int value22; ref T6 reference20; int value23; ref T7 reference22; ref T7 reference23; int value25; int value28; int value29; ref T4 reference27; ref T3 reference28; ref T5 reference29; switch (8 - length) { case 1: { ref T7 reference21 = ref Item7; val2 = default(T7); if (val2 == null) { val2 = reference21; reference21 = ref val2; if (val2 == null) { value24 = 0; goto IL_0237; } } value24 = reference21.GetHashCode(); goto IL_0237; } case 2: { ref T6 reference17 = ref Item6; val7 = default(T6); if (val7 == null) { val7 = reference17; reference17 = ref val7; if (val7 == null) { value12 = 0; goto IL_0276; } } value12 = reference17.GetHashCode(); goto IL_0276; } case 3: { ref T5 reference6 = ref Item5; val5 = default(T5); if (val5 == null) { val5 = reference6; reference6 = ref val5; if (val5 == null) { value10 = 0; goto IL_02ed; } } value10 = reference6.GetHashCode(); goto IL_02ed; } case 4: { ref T4 reference25 = ref Item4; val3 = default(T4); if (val3 == null) { val3 = reference25; reference25 = ref val3; if (val3 == null) { value5 = 0; goto IL_039c; } } value5 = reference25.GetHashCode(); goto IL_039c; } case 5: { ref T3 reference24 = ref Item3; val6 = default(T3); if (val6 == null) { val6 = reference24; reference24 = ref val6; if (val6 == null) { value26 = 0; goto IL_0483; } } value26 = reference24.GetHashCode(); goto IL_0483; } case 6: { ref T2 reference26 = ref Item2; val4 = default(T2); if (val4 == null) { val4 = reference26; reference26 = ref val4; if (val4 == null) { value27 = 0; goto IL_05a2; } } value27 = reference26.GetHashCode(); goto IL_05a2; } case 7: case 8: { ref T1 reference2 = ref Item1; val = default(T1); if (val == null) { val = reference2; reference2 = ref val; if (val == null) { value2 = 0; goto IL_06f6; } } value2 = reference2.GetHashCode(); goto IL_06f6; } default: { return -1; } IL_0325: reference3 = ref Item7; val2 = default(T7); if (val2 == null) { val2 = reference3; reference3 = ref val2; if (val2 == null) { value3 = 0; goto IL_035d; } } value3 = reference3.GetHashCode(); goto IL_035d; IL_05da: reference4 = ref Item4; val3 = default(T4); if (val3 == null) { val3 = reference4; reference4 = ref val3; if (val3 == null) { value4 = 0; goto IL_0612; } } value4 = reference4.GetHashCode(); goto IL_0612; IL_0444: return HashCode.Combine(value5, value6, value7, value8, hashCode); IL_06f6: reference5 = ref Item2; val4 = default(T2); if (val4 == null) { val4 = reference5; reference5 = ref val4; if (val4 == null) { value9 = 0; goto IL_072e; } } value9 = reference5.GetHashCode(); goto IL_072e; IL_04bb: reference7 = ref Item5; val5 = default(T5); if (val5 == null) { val5 = reference7; reference7 = ref val5; if (val5 == null) { value11 = 0; goto IL_04f3; } } value11 = reference7.GetHashCode(); goto IL_04f3; IL_02ae: return HashCode.Combine(value12, value13, hashCode); IL_072e: reference8 = ref Item3; val6 = default(T3); if (val6 == null) { val6 = reference8; reference8 = ref val6; if (val6 == null) { value14 = 0; goto IL_0766; } } value14 = reference8.GetHashCode(); goto IL_0766; IL_04f3: reference9 = ref Item6; val7 = default(T6); if (val7 == null) { val7 = reference9; reference9 = ref val7; if (val7 == null) { value15 = 0; goto IL_052b; } } value15 = reference9.GetHashCode(); goto IL_052b; IL_02ed: reference10 = ref Item6; val7 = default(T6); if (val7 == null) { val7 = reference10; reference10 = ref val7; if (val7 == null) { value16 = 0; goto IL_0325; } } value16 = reference10.GetHashCode(); goto IL_0325; IL_0612: reference11 = ref Item5; val5 = default(T5); if (val5 == null) { val5 = reference11; reference11 = ref val5; if (val5 == null) { value17 = 0; goto IL_064a; } } value17 = reference11.GetHashCode(); goto IL_064a; IL_0766: reference12 = ref Item4; val3 = default(T4); if (val3 == null) { val3 = reference12; reference12 = ref val3; if (val3 == null) { value18 = 0; goto IL_079e; } } value18 = reference12.GetHashCode(); goto IL_079e; IL_064a: reference13 = ref Item6; val7 = default(T6); if (val7 == null) { val7 = reference13; reference13 = ref val7; if (val7 == null) { value19 = 0; goto IL_0682; } } value19 = reference13.GetHashCode(); goto IL_0682; IL_03d4: reference14 = ref Item6; val7 = default(T6); if (val7 == null) { val7 = reference14; reference14 = ref val7; if (val7 == null) { value7 = 0; goto IL_040c; } } value7 = reference14.GetHashCode(); goto IL_040c; IL_0276: reference15 = ref Item7; val2 = default(T7); if (val2 == null) { val2 = reference15; reference15 = ref val2; if (val2 == null) { value13 = 0; goto IL_02ae; } } value13 = reference15.GetHashCode(); goto IL_02ae; IL_079e: reference16 = ref Item5; val5 = default(T5); if (val5 == null) { val5 = reference16; reference16 = ref val5; if (val5 == null) { value20 = 0; goto IL_07d6; } } value20 = reference16.GetHashCode(); goto IL_07d6; IL_0682: reference18 = ref Item7; val2 = default(T7); if (val2 == null) { val2 = reference18; reference18 = ref val2; if (val2 == null) { value21 = 0; goto IL_06ba; } } value21 = reference18.GetHashCode(); goto IL_06ba; IL_052b: reference19 = ref Item7; val2 = default(T7); if (val2 == null) { val2 = reference19; reference19 = ref val2; if (val2 == null) { value22 = 0; goto IL_0563; } } value22 = reference19.GetHashCode(); goto IL_0563; IL_07d6: reference20 = ref Item6; val7 = default(T6); if (val7 == null) { val7 = reference20; reference20 = ref val7; if (val7 == null) { value23 = 0; goto IL_080e; } } value23 = reference20.GetHashCode(); goto IL_080e; IL_040c: reference22 = ref Item7; val2 = default(T7); if (val2 == null) { val2 = reference22; reference22 = ref val2; if (val2 == null) { value8 = 0; goto IL_0444; } } value8 = reference22.GetHashCode(); goto IL_0444; IL_035d: return HashCode.Combine(value10, value16, value3, hashCode); IL_080e: reference23 = ref Item7; val2 = default(T7); if (val2 == null) { val2 = reference23; reference23 = ref val2; if (val2 == null) { value25 = 0; goto IL_0846; } } value25 = reference23.GetHashCode(); goto IL_0846; IL_06ba: return HashCode.Combine(value27, value28, value4, value17, value19, value21, hashCode); IL_0846: return HashCode.Combine(value2, value9, value14, value18, value20, value23, value25, hashCode); IL_0563: return HashCode.Combine(value26, value29, value11, value15, value22, hashCode); IL_0483: reference27 = ref Item4; val3 = default(T4); if (val3 == null) { val3 = reference27; reference27 = ref val3; if (val3 == null) { value29 = 0; goto IL_04bb; } } value29 = reference27.GetHashCode(); goto IL_04bb; IL_0237: return HashCode.Combine(value24, hashCode); IL_05a2: reference28 = ref Item3; val6 = default(T3); if (val6 == null) { val6 = reference28; reference28 = ref val6; if (val6 == null) { value28 = 0; goto IL_05da; } } value28 = reference28.GetHashCode(); goto IL_05da; IL_039c: reference29 = ref Item5; val5 = default(T5); if (val5 == null) { val5 = reference29; reference29 = ref val5; if (val5 == null) { value6 = 0; goto IL_03d4; } } value6 = reference29.GetHashCode(); goto IL_03d4; } IL_00ba: ref T4 reference30 = ref Item4; val3 = default(T4); int value30; if (val3 == null) { val3 = reference30; reference30 = ref val3; if (val3 == null) { value30 = 0; goto IL_00f2; } } value30 = reference30.GetHashCode(); goto IL_00f2; IL_0082: ref T3 reference31 = ref Item3; val6 = default(T3); int value31; if (val6 == null) { val6 = reference31; reference31 = ref val6; if (val6 == null) { value31 = 0; goto IL_00ba; } } value31 = reference31.GetHashCode(); goto IL_00ba; IL_0162: ref T7 reference32 = ref Item7; val2 = default(T7); int value32; if (val2 == null) { val2 = reference32; reference32 = ref val2; if (val2 == null) { value32 = 0; goto IL_019a; } } value32 = reference32.GetHashCode(); goto IL_019a; IL_00f2: ref T5 reference33 = ref Item5; val5 = default(T5); int value33; if (val5 == null) { val5 = reference33; reference33 = ref val5; if (val5 == null) { value33 = 0; goto IL_012a; } } value33 = reference33.GetHashCode(); goto IL_012a; IL_004a: ref T2 reference34 = ref Item2; val4 = default(T2); int value34; if (val4 == null) { val4 = reference34; reference34 = ref val4; if (val4 == null) { value34 = 0; goto IL_0082; } } value34 = reference34.GetHashCode(); goto IL_0082; IL_019a: int value35; return HashCode.Combine(value, value34, value31, value30, value33, value35, value32); IL_012a: ref T6 reference35 = ref Item6; val7 = default(T6); if (val7 == null) { val7 = reference35; reference35 = ref val7; if (val7 == null) { value35 = 0; goto IL_0162; } } value35 = reference35.GetHashCode(); goto IL_0162; } int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) { return GetHashCodeCore(comparer); } private int GetHashCodeCore(IEqualityComparer comparer) { if (!((object)Rest is IValueTupleInternal valueTupleInternal)) { return HashCode.Combine(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7)); } int length = valueTupleInternal.Length; int hashCode = valueTupleInternal.GetHashCode(comparer); if (length >= 8) { return hashCode; } switch (8 - length) { case 1: return HashCode.Combine(comparer.GetHashCode(Item7), hashCode); case 2: return HashCode.Combine(comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), hashCode); case 3: return HashCode.Combine(comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), hashCode); case 4: return HashCode.Combine(comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), hashCode); case 5: return HashCode.Combine(comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), hashCode); case 6: return HashCode.Combine(comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), hashCode); case 7: case 8: return HashCode.Combine(comparer.GetHashCode(Item1), comparer.GetHashCode(Item2), comparer.GetHashCode(Item3), comparer.GetHashCode(Item4), comparer.GetHashCode(Item5), comparer.GetHashCode(Item6), comparer.GetHashCode(Item7), hashCode); default: return -1; } } int IValueTupleInternal.GetHashCode(IEqualityComparer comparer) { return GetHashCodeCore(comparer); } public override string ToString() { string[] obj; T1 val; object obj2; if (Rest is IValueTupleInternal) { obj = new string[16] { "(", null, null, null, null, null, null, null, null, null, null, null, null, null, null, null }; ref T1 reference = ref Item1; val = default(T1); if (val == null) { val = reference; reference = ref val; if (val == null) { obj2 = null; goto IL_005b; } } obj2 = reference.ToString(); goto IL_005b; } string[] obj3 = new string[17] { "(", null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null }; ref T1 reference2 = ref Item1; val = default(T1); object obj4; if (val == null) { val = reference2; reference2 = ref val; if (val == null) { obj4 = null; goto IL_0258; } } obj4 = reference2.ToString(); goto IL_0258; IL_02d8: object obj5; obj3[5] = (string)obj5; obj3[6] = ", "; ref T4 reference3 = ref Item4; T4 val2 = default(T4); object obj6; if (val2 == null) { val2 = reference3; reference3 = ref val2; if (val2 == null) { obj6 = null; goto IL_0318; } } obj6 = reference3.ToString(); goto IL_0318; IL_03e6: object obj7; obj3[13] = (string)obj7; obj3[14] = ", "; obj3[15] = Rest.ToString(); obj3[16] = ")"; return string.Concat(obj3); IL_03a1: object obj8; obj3[11] = (string)obj8; obj3[12] = ", "; ref T7 reference4 = ref Item7; T7 val3 = default(T7); if (val3 == null) { val3 = reference4; reference4 = ref val3; if (val3 == null) { obj7 = null; goto IL_03e6; } } obj7 = reference4.ToString(); goto IL_03e6; IL_011b: object obj9; obj[7] = (string)obj9; obj[8] = ", "; ref T5 reference5 = ref Item5; T5 val4 = default(T5); object obj10; if (val4 == null) { val4 = reference5; reference5 = ref val4; if (val4 == null) { obj10 = null; goto IL_015f; } } obj10 = reference5.ToString(); goto IL_015f; IL_005b: obj[1] = (string)obj2; obj[2] = ", "; ref T2 reference6 = ref Item2; T2 val5 = default(T2); object obj11; if (val5 == null) { val5 = reference6; reference6 = ref val5; if (val5 == null) { obj11 = null; goto IL_009b; } } obj11 = reference6.ToString(); goto IL_009b; IL_015f: obj[9] = (string)obj10; obj[10] = ", "; ref T6 reference7 = ref Item6; T6 val6 = default(T6); object obj12; if (val6 == null) { val6 = reference7; reference7 = ref val6; if (val6 == null) { obj12 = null; goto IL_01a4; } } obj12 = reference7.ToString(); goto IL_01a4; IL_0298: object obj13; obj3[3] = (string)obj13; obj3[4] = ", "; ref T3 reference8 = ref Item3; T3 val7 = default(T3); if (val7 == null) { val7 = reference8; reference8 = ref val7; if (val7 == null) { obj5 = null; goto IL_02d8; } } obj5 = reference8.ToString(); goto IL_02d8; IL_01e9: object obj14; obj[13] = (string)obj14; obj[14] = ", "; obj[15] = ((IValueTupleInternal)(object)Rest).ToStringEnd(); return string.Concat(obj); IL_009b: obj[3] = (string)obj11; obj[4] = ", "; ref T3 reference9 = ref Item3; val7 = default(T3); object obj15; if (val7 == null) { val7 = reference9; reference9 = ref val7; if (val7 == null) { obj15 = null; goto IL_00db; } } obj15 = reference9.ToString(); goto IL_00db; IL_0318: obj3[7] = (string)obj6; obj3[8] = ", "; ref T5 reference10 = ref Item5; val4 = default(T5); object obj16; if (val4 == null) { val4 = reference10; reference10 = ref val4; if (val4 == null) { obj16 = null; goto IL_035c; } } obj16 = reference10.ToString(); goto IL_035c; IL_01a4: obj[11] = (string)obj12; obj[12] = ", "; ref T7 reference11 = ref Item7; val3 = default(T7); if (val3 == null) { val3 = reference11; reference11 = ref val3; if (val3 == null) { obj14 = null; goto IL_01e9; } } obj14 = reference11.ToString(); goto IL_01e9; IL_0258: obj3[1] = (string)obj4; obj3[2] = ", "; ref T2 reference12 = ref Item2; val5 = default(T2); if (val5 == null) { val5 = reference12; reference12 = ref val5; if (val5 == null) { obj13 = null; goto IL_0298; } } obj13 = reference12.ToString(); goto IL_0298; IL_00db: obj[5] = (string)obj15; obj[6] = ", "; ref T4 reference13 = ref Item4; val2 = default(T4); if (val2 == null) { val2 = reference13; reference13 = ref val2; if (val2 == null) { obj9 = null; goto IL_011b; } } obj9 = reference13.ToString(); goto IL_011b; IL_035c: obj3[9] = (string)obj16; obj3[10] = ", "; ref T6 reference14 = ref Item6; val6 = default(T6); if (val6 == null) { val6 = reference14; reference14 = ref val6; if (val6 == null) { obj8 = null; goto IL_03a1; } } obj8 = reference14.ToString(); goto IL_03a1; } string IValueTupleInternal.ToStringEnd() { string[] array; T1 val; object obj; if (Rest is IValueTupleInternal) { array = new string[15]; ref T1 reference = ref Item1; val = default(T1); if (val == null) { val = reference; reference = ref val; if (val == null) { obj = null; goto IL_0053; } } obj = reference.ToString(); goto IL_0053; } string[] array2 = new string[16]; ref T1 reference2 = ref Item1; val = default(T1); object obj2; if (val == null) { val = reference2; reference2 = ref val; if (val == null) { obj2 = null; goto IL_0247; } } obj2 = reference2.ToString(); goto IL_0247; IL_02c7: object obj3; array2[4] = (string)obj3; array2[5] = ", "; ref T4 reference3 = ref Item4; T4 val2 = default(T4); object obj4; if (val2 == null) { val2 = reference3; reference3 = ref val2; if (val2 == null) { obj4 = null; goto IL_0307; } } obj4 = reference3.ToString(); goto IL_0307; IL_03d4: object obj5; array2[12] = (string)obj5; array2[13] = ", "; array2[14] = Rest.ToString(); array2[15] = ")"; return string.Concat(array2); IL_038f: object obj6; array2[10] = (string)obj6; array2[11] = ", "; ref T7 reference4 = ref Item7; T7 val3 = default(T7); if (val3 == null) { val3 = reference4; reference4 = ref val3; if (val3 == null) { obj5 = null; goto IL_03d4; } } obj5 = reference4.ToString(); goto IL_03d4; IL_0113: object obj7; array[6] = (string)obj7; array[7] = ", "; ref T5 reference5 = ref Item5; T5 val4 = default(T5); object obj8; if (val4 == null) { val4 = reference5; reference5 = ref val4; if (val4 == null) { obj8 = null; goto IL_0156; } } obj8 = reference5.ToString(); goto IL_0156; IL_0053: array[0] = (string)obj; array[1] = ", "; ref T2 reference6 = ref Item2; T2 val5 = default(T2); object obj9; if (val5 == null) { val5 = reference6; reference6 = ref val5; if (val5 == null) { obj9 = null; goto IL_0093; } } obj9 = reference6.ToString(); goto IL_0093; IL_0156: array[8] = (string)obj8; array[9] = ", "; ref T6 reference7 = ref Item6; T6 val6 = default(T6); object obj10; if (val6 == null) { val6 = reference7; reference7 = ref val6; if (val6 == null) { obj10 = null; goto IL_019b; } } obj10 = reference7.ToString(); goto IL_019b; IL_0287: object obj11; array2[2] = (string)obj11; array2[3] = ", "; ref T3 reference8 = ref Item3; T3 val7 = default(T3); if (val7 == null) { val7 = reference8; reference8 = ref val7; if (val7 == null) { obj3 = null; goto IL_02c7; } } obj3 = reference8.ToString(); goto IL_02c7; IL_01e0: object obj12; array[12] = (string)obj12; array[13] = ", "; array[14] = ((IValueTupleInternal)(object)Rest).ToStringEnd(); return string.Concat(array); IL_0093: array[2] = (string)obj9; array[3] = ", "; ref T3 reference9 = ref Item3; val7 = default(T3); object obj13; if (val7 == null) { val7 = reference9; reference9 = ref val7; if (val7 == null) { obj13 = null; goto IL_00d3; } } obj13 = reference9.ToString(); goto IL_00d3; IL_0307: array2[6] = (string)obj4; array2[7] = ", "; ref T5 reference10 = ref Item5; val4 = default(T5); object obj14; if (val4 == null) { val4 = reference10; reference10 = ref val4; if (val4 == null) { obj14 = null; goto IL_034a; } } obj14 = reference10.ToString(); goto IL_034a; IL_019b: array[10] = (string)obj10; array[11] = ", "; ref T7 reference11 = ref Item7; val3 = default(T7); if (val3 == null) { val3 = reference11; reference11 = ref val3; if (val3 == null) { obj12 = null; goto IL_01e0; } } obj12 = reference11.ToString(); goto IL_01e0; IL_0247: array2[0] = (string)obj2; array2[1] = ", "; ref T2 reference12 = ref Item2; val5 = default(T2); if (val5 == null) { val5 = reference12; reference12 = ref val5; if (val5 == null) { obj11 = null; goto IL_0287; } } obj11 = reference12.ToString(); goto IL_0287; IL_00d3: array[4] = (string)obj13; array[5] = ", "; ref T4 reference13 = ref Item4; val2 = default(T4); if (val2 == null) { val2 = reference13; reference13 = ref val2; if (val2 == null) { obj7 = null; goto IL_0113; } } obj7 = reference13.ToString(); goto IL_0113; IL_034a: array2[8] = (string)obj14; array2[9] = ", "; ref T6 reference14 = ref Item6; val6 = default(T6); if (val6 == null) { val6 = reference14; reference14 = ref val6; if (val6 == null) { obj6 = null; goto IL_038f; } } obj6 = reference14.ToString(); goto IL_038f; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class Version : ICloneable, IComparable, IComparable, IEquatable, ISpanFormattable, IFormattable { private readonly int _Major; private readonly int _Minor; private readonly int _Build; private readonly int _Revision; public int Major => _Major; public int Minor => _Minor; public int Build => _Build; public int Revision => _Revision; public short MajorRevision => (short)(_Revision >> 16); public short MinorRevision => (short)(_Revision & 0xFFFF); private int DefaultFormatFieldCount { get { if (_Build != -1) { if (_Revision != -1) { return 4; } return 3; } return 2; } } public Version(int major, int minor, int build, int revision) { if (major < 0) { throw new ArgumentOutOfRangeException("major", SR.ArgumentOutOfRange_Version); } if (minor < 0) { throw new ArgumentOutOfRangeException("minor", SR.ArgumentOutOfRange_Version); } if (build < 0) { throw new ArgumentOutOfRangeException("build", SR.ArgumentOutOfRange_Version); } if (revision < 0) { throw new ArgumentOutOfRangeException("revision", SR.ArgumentOutOfRange_Version); } _Major = major; _Minor = minor; _Build = build; _Revision = revision; } public Version(int major, int minor, int build) { if (major < 0) { throw new ArgumentOutOfRangeException("major", SR.ArgumentOutOfRange_Version); } if (minor < 0) { throw new ArgumentOutOfRangeException("minor", SR.ArgumentOutOfRange_Version); } if (build < 0) { throw new ArgumentOutOfRangeException("build", SR.ArgumentOutOfRange_Version); } _Major = major; _Minor = minor; _Build = build; _Revision = -1; } public Version(int major, int minor) { if (major < 0) { throw new ArgumentOutOfRangeException("major", SR.ArgumentOutOfRange_Version); } if (minor < 0) { throw new ArgumentOutOfRangeException("minor", SR.ArgumentOutOfRange_Version); } _Major = major; _Minor = minor; _Build = -1; _Revision = -1; } public Version(string version) { Version version2 = Parse(version); _Major = version2.Major; _Minor = version2.Minor; _Build = version2.Build; _Revision = version2.Revision; } public Version() { _Build = -1; _Revision = -1; } private Version(Version version) { _Major = version._Major; _Minor = version._Minor; _Build = version._Build; _Revision = version._Revision; } public object Clone() { return new Version(this); } public int CompareTo(object? version) { if (version == null) { return 1; } if (version is Version value) { return CompareTo(value); } throw new ArgumentException(SR.Arg_MustBeVersion); } public int CompareTo(Version? value) { if ((object)value != this) { if ((object)value != null) { if (_Major == value._Major) { if (_Minor == value._Minor) { if (_Build == value._Build) { if (_Revision == value._Revision) { return 0; } if (_Revision <= value._Revision) { return -1; } return 1; } if (_Build <= value._Build) { return -1; } return 1; } if (_Minor <= value._Minor) { return -1; } return 1; } if (_Major <= value._Major) { return -1; } return 1; } return 1; } return 0; } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj as Version); } public bool Equals([NotNullWhen(true)] Version? obj) { if ((object)obj != this) { if ((object)obj != null && _Major == obj._Major && _Minor == obj._Minor && _Build == obj._Build) { return _Revision == obj._Revision; } return false; } return true; } public override int GetHashCode() { int num = 0; num |= (_Major & 0xF) << 28; num |= (_Minor & 0xFF) << 20; num |= (_Build & 0xFF) << 12; return num | (_Revision & 0xFFF); } public override string ToString() { return ToString(DefaultFormatFieldCount); } public string ToString(int fieldCount) { Span destination = stackalloc char[47]; int charsWritten; bool flag = TryFormat(destination, fieldCount, out charsWritten); return destination.Slice(0, charsWritten).ToString(); } string IFormattable.ToString(string format, IFormatProvider formatProvider) { return ToString(); } public bool TryFormat(Span destination, out int charsWritten) { return TryFormat(destination, DefaultFormatFieldCount, out charsWritten); } public bool TryFormat(Span destination, int fieldCount, out int charsWritten) { switch (fieldCount) { default: ThrowArgumentException("4"); break; case 3: case 4: if (_Build != -1) { if (fieldCount == 4 && _Revision == -1) { ThrowArgumentException("3"); } } else { ThrowArgumentException("2"); } break; case 0: case 1: case 2: break; } int num = 0; for (int i = 0; i < fieldCount; i++) { if (i != 0) { if (destination.IsEmpty) { charsWritten = 0; return false; } destination[0] = '.'; destination = destination.Slice(1); num++; } if (!(i switch { 0 => (uint)_Major, 1 => (uint)_Minor, 2 => (uint)_Build, _ => (uint)_Revision, }).TryFormat(destination, out var charsWritten2)) { charsWritten = 0; return false; } num += charsWritten2; destination = destination.Slice(charsWritten2); } charsWritten = num; return true; static void ThrowArgumentException(string failureUpperBound) { throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", failureUpperBound), "fieldCount"); } } bool ISpanFormattable.TryFormat(Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider provider) { return TryFormat(destination, DefaultFormatFieldCount, out charsWritten); } public static Version Parse(string input) { if (input == null) { throw new ArgumentNullException("input"); } return ParseVersion(input.AsSpan(), throwOnFailure: true); } public static Version Parse(ReadOnlySpan input) { return ParseVersion(input, throwOnFailure: true); } public static bool TryParse([NotNullWhen(true)] string? input, [NotNullWhen(true)] out Version? result) { if (input == null) { result = null; return false; } return (result = ParseVersion(input.AsSpan(), throwOnFailure: false)) != null; } public static bool TryParse(ReadOnlySpan input, [NotNullWhen(true)] out Version? result) { return (result = ParseVersion(input, throwOnFailure: false)) != null; } private static Version ParseVersion(ReadOnlySpan input, bool throwOnFailure) { int num = input.IndexOf('.'); if (num < 0) { if (throwOnFailure) { throw new ArgumentException(SR.Arg_VersionString, "input"); } return null; } int num2 = -1; int num3 = input.Slice(num + 1).IndexOf('.'); if (num3 != -1) { num3 += num + 1; num2 = input.Slice(num3 + 1).IndexOf('.'); if (num2 != -1) { num2 += num3 + 1; if (input.Slice(num2 + 1).Contains('.')) { if (throwOnFailure) { throw new ArgumentException(SR.Arg_VersionString, "input"); } return null; } } } if (!TryParseComponent(input.Slice(0, num), "input", throwOnFailure, out var parsedComponent)) { return null; } int parsedComponent2; if (num3 != -1) { if (!TryParseComponent(input.Slice(num + 1, num3 - num - 1), "input", throwOnFailure, out parsedComponent2)) { return null; } int parsedComponent3; if (num2 != -1) { if (!TryParseComponent(input.Slice(num3 + 1, num2 - num3 - 1), "build", throwOnFailure, out parsedComponent3) || !TryParseComponent(input.Slice(num2 + 1), "revision", throwOnFailure, out var parsedComponent4)) { return null; } return new Version(parsedComponent, parsedComponent2, parsedComponent3, parsedComponent4); } if (!TryParseComponent(input.Slice(num3 + 1), "build", throwOnFailure, out parsedComponent3)) { return null; } return new Version(parsedComponent, parsedComponent2, parsedComponent3); } if (!TryParseComponent(input.Slice(num + 1), "input", throwOnFailure, out parsedComponent2)) { return null; } return new Version(parsedComponent, parsedComponent2); } private static bool TryParseComponent(ReadOnlySpan component, string componentName, bool throwOnFailure, out int parsedComponent) { if (throwOnFailure) { if ((parsedComponent = int.Parse(component, NumberStyles.Integer, CultureInfo.InvariantCulture)) < 0) { throw new ArgumentOutOfRangeException(componentName, SR.ArgumentOutOfRange_Version); } return true; } if (int.TryParse(component, NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedComponent)) { return parsedComponent >= 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Version? v1, Version? v2) { if ((object)v2 == null) { if ((object)v1 != null) { return false; } return true; } if ((object)v2 != v1) { return v2.Equals(v1); } return true; } public static bool operator !=(Version? v1, Version? v2) { return !(v1 == v2); } public static bool operator <(Version? v1, Version? v2) { if ((object)v1 == null) { return (object)v2 != null; } return v1.CompareTo(v2) < 0; } public static bool operator <=(Version? v1, Version? v2) { if ((object)v1 == null) { return true; } return v1.CompareTo(v2) <= 0; } public static bool operator >(Version? v1, Version? v2) { return v2 < v1; } public static bool operator >=(Version? v1, Version? v2) { return v2 <= v1; } } [StructLayout(LayoutKind.Sequential, Size = 1)] public struct Void { } internal static class NotImplemented { internal static Exception ByDesign => new NotImplementedException(); } internal struct Sha1ForNonSecretPurposes { private long _length; private uint[] _w; private int _pos; public void Start() { if (_w == null) { _w = new uint[85]; } _length = 0L; _pos = 0; _w[80] = 1732584193u; _w[81] = 4023233417u; _w[82] = 2562383102u; _w[83] = 271733878u; _w[84] = 3285377520u; } public void Append(byte input) { int num = _pos >> 2; _w[num] = (_w[num] << 8) | input; if (64 == ++_pos) { Drain(); } } public void Append(ReadOnlySpan input) { ReadOnlySpan readOnlySpan = input; for (int i = 0; i < readOnlySpan.Length; i++) { byte input2 = readOnlySpan[i]; Append(input2); } } public void Finish(Span output) { long num = _length + 8 * _pos; Append(128); while (_pos != 56) { Append(0); } Append((byte)(num >> 56)); Append((byte)(num >> 48)); Append((byte)(num >> 40)); Append((byte)(num >> 32)); Append((byte)(num >> 24)); Append((byte)(num >> 16)); Append((byte)(num >> 8)); Append((byte)num); int num2 = ((output.Length < 20) ? output.Length : 20); for (int i = 0; i != num2; i++) { uint num3 = _w[80 + i / 4]; output[i] = (byte)(num3 >> 24); _w[80 + i / 4] = num3 << 8; } } private void Drain() { for (int i = 16; i != 80; i++) { _w[i] = BitOperations.RotateLeft(_w[i - 3] ^ _w[i - 8] ^ _w[i - 14] ^ _w[i - 16], 1); } uint num = _w[80]; uint num2 = _w[81]; uint num3 = _w[82]; uint num4 = _w[83]; uint num5 = _w[84]; for (int j = 0; j != 20; j++) { uint num6 = (num2 & num3) | (~num2 & num4); uint num7 = BitOperations.RotateLeft(num, 5) + num6 + num5 + 1518500249 + _w[j]; num5 = num4; num4 = num3; num3 = BitOperations.RotateLeft(num2, 30); num2 = num; num = num7; } for (int k = 20; k != 40; k++) { uint num8 = num2 ^ num3 ^ num4; uint num9 = BitOperations.RotateLeft(num, 5) + num8 + num5 + 1859775393 + _w[k]; num5 = num4; num4 = num3; num3 = BitOperations.RotateLeft(num2, 30); num2 = num; num = num9; } for (int l = 40; l != 60; l++) { uint num10 = (num2 & num3) | (num2 & num4) | (num3 & num4); uint num11 = (uint)((int)(BitOperations.RotateLeft(num, 5) + num10 + num5) + -1894007588) + _w[l]; num5 = num4; num4 = num3; num3 = BitOperations.RotateLeft(num2, 30); num2 = num; num = num11; } for (int m = 60; m != 80; m++) { uint num12 = num2 ^ num3 ^ num4; uint num13 = (uint)((int)(BitOperations.RotateLeft(num, 5) + num12 + num5) + -899497514) + _w[m]; num5 = num4; num4 = num3; num3 = BitOperations.RotateLeft(num2, 30); num2 = num; num = num13; } _w[80] += num; _w[81] += num2; _w[82] += num3; _w[83] += num4; _w[84] += num5; _length += 512L; _pos = 0; } } internal static class HexConverter { public enum Casing : uint { Upper = 0u, Lower = 8224u } public static ReadOnlySpan 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 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 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); } private static void EncodeToUtf16_Ssse3(ReadOnlySpan bytes, Span chars, Casing casing) { nint num = 0; Vector128 mask = Vector128.Create(byte.MaxValue, byte.MaxValue, 0, byte.MaxValue, byte.MaxValue, byte.MaxValue, 1, byte.MaxValue, byte.MaxValue, byte.MaxValue, 2, byte.MaxValue, byte.MaxValue, byte.MaxValue, 3, byte.MaxValue); Vector128 value = ((casing == Casing.Upper) ? Vector128.Create((byte)48, (byte)49, (byte)50, (byte)51, (byte)52, (byte)53, (byte)54, (byte)55, (byte)56, (byte)57, (byte)65, (byte)66, (byte)67, (byte)68, (byte)69, (byte)70) : Vector128.Create((byte)48, (byte)49, (byte)50, (byte)51, (byte)52, (byte)53, (byte)54, (byte)55, (byte)56, (byte)57, (byte)97, (byte)98, (byte)99, (byte)100, (byte)101, (byte)102)); do { uint value2 = Unsafe.ReadUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetReference(bytes), num)); Vector128 vector = Ssse3.Shuffle(Vector128.CreateScalarUnsafe(value2).AsByte(), mask); Vector128 right = Sse2.ShiftRightLogical(Sse2.ShiftRightLogical128BitLane(vector, 2).AsInt32(), 4).AsByte(); Vector128 mask2 = Sse2.And(Sse2.Or(vector, right), Vector128.Create((byte)15)); Vector128 left = Ssse3.Shuffle(value, mask2); left = Sse2.And(left, Vector128.Create((ushort)255).AsByte()); Unsafe.WriteUnaligned(ref Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetReference(chars), num * 2)), left); num += 4; } while (num < bytes.Length - 3); for (; num < bytes.Length; num++) { ToCharsBuffer(Unsafe.Add(ref MemoryMarshal.GetReference(bytes), num), chars, (int)num * 2, casing); } } public static void EncodeToUtf16(ReadOnlySpan bytes, Span chars, Casing casing = Casing.Upper) { if (Ssse3.IsSupported && bytes.Length >= 4) { EncodeToUtf16_Ssse3(bytes, chars, casing); return; } for (int i = 0; i < bytes.Length; i++) { ToCharsBuffer(bytes[i], chars, i * 2, casing); } } public unsafe static string ToString(ReadOnlySpan bytes, Casing casing = Casing.Upper) { fixed (byte* ptr = bytes) { return string.Create(bytes.Length * 2, ((IntPtr)ptr, bytes.Length, casing), delegate(Span chars, (IntPtr Ptr, int Length, Casing casing) args) { ReadOnlySpan bytes2 = new ReadOnlySpan((void*)args.Ptr, args.Length); EncodeToUtf16(bytes2, chars, args.casing); }); } } [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 chars, Span bytes) { int charsProcessed; return TryDecodeFromUtf16(chars, bytes, out charsProcessed); } public static bool TryDecodeFromUtf16(ReadOnlySpan chars, Span 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 bool IsHexChar(int c) { if (IntPtr.Size == 8) { } return FromChar(c) != 255; } } internal static class FixedBufferExtensions { internal unsafe static string GetStringFromFixedBuffer(this ReadOnlySpan span) { fixed (char* value = &MemoryMarshal.GetReference(span)) { return new string(value, 0, span.GetFixedBufferStringLength()); } } internal static int GetFixedBufferStringLength(this ReadOnlySpan span) { int num = span.IndexOf('\0'); if (num >= 0) { return num; } return span.Length; } internal static bool FixedBufferEqualsString(this ReadOnlySpan span, string value) { if (value == null || value.Length > span.Length) { return false; } int i; for (i = 0; i < value.Length; i++) { if (value[i] == '\0' || value[i] != span[i]) { return false; } } if (i != span.Length) { return span[i] == '\0'; } return true; } } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IAdditionOperators where TSelf : IAdditionOperators { static abstract TResult operator +(TSelf left, TOther right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IAdditiveIdentity where TSelf : IAdditiveIdentity { static abstract TResult AdditiveIdentity { get; } } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IBitwiseOperators where TSelf : IBitwiseOperators { static abstract TResult operator &(TSelf left, TOther right); static abstract TResult operator |(TSelf left, TOther right); static abstract TResult operator ^(TSelf left, TOther right); static abstract TResult operator ~(TSelf value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IComparisonOperators : IComparable, IComparable, IEqualityOperators, IEquatable where TSelf : IComparisonOperators { static abstract bool operator <(TSelf left, TOther right); static abstract bool operator <=(TSelf left, TOther right); static abstract bool operator >(TSelf left, TOther right); static abstract bool operator >=(TSelf left, TOther right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IDecrementOperators where TSelf : IDecrementOperators { static abstract TSelf operator --(TSelf value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IDivisionOperators where TSelf : IDivisionOperators { static abstract TResult operator /(TSelf left, TOther right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IEqualityOperators : IEquatable where TSelf : IEqualityOperators { static abstract bool operator ==(TSelf left, TOther right); static abstract bool operator !=(TSelf left, TOther right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IFloatingPoint : ISignedNumber, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IComparable, IComparable, IEqualityOperators, IEquatable, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanFormattable, IFormattable, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators where TSelf : IFloatingPoint { static abstract TSelf E { get; } static abstract TSelf Epsilon { get; } static abstract TSelf NaN { get; } static abstract TSelf NegativeInfinity { get; } static abstract TSelf NegativeZero { get; } static abstract TSelf Pi { get; } static abstract TSelf PositiveInfinity { get; } static abstract TSelf Tau { get; } static abstract TSelf Acos(TSelf x); static abstract TSelf Acosh(TSelf x); static abstract TSelf Asin(TSelf x); static abstract TSelf Asinh(TSelf x); static abstract TSelf Atan(TSelf x); static abstract TSelf Atan2(TSelf y, TSelf x); static abstract TSelf Atanh(TSelf x); static abstract TSelf BitDecrement(TSelf x); static abstract TSelf BitIncrement(TSelf x); static abstract TSelf Cbrt(TSelf x); static abstract TSelf Ceiling(TSelf x); static abstract TSelf CopySign(TSelf x, TSelf y); static abstract TSelf Cos(TSelf x); static abstract TSelf Cosh(TSelf x); static abstract TSelf Exp(TSelf x); static abstract TSelf Floor(TSelf x); static abstract TSelf FusedMultiplyAdd(TSelf left, TSelf right, TSelf addend); static abstract TSelf IEEERemainder(TSelf left, TSelf right); static abstract TInteger ILogB(TSelf x); static abstract bool IsFinite(TSelf value); static abstract bool IsInfinity(TSelf value); static abstract bool IsNaN(TSelf value); static abstract bool IsNegative(TSelf value); static abstract bool IsNegativeInfinity(TSelf value); static abstract bool IsNormal(TSelf value); static abstract bool IsPositiveInfinity(TSelf value); static abstract bool IsSubnormal(TSelf value); static abstract TSelf Log(TSelf x); static abstract TSelf Log(TSelf x, TSelf newBase); static abstract TSelf Log2(TSelf x); static abstract TSelf Log10(TSelf x); static abstract TSelf MaxMagnitude(TSelf x, TSelf y); static abstract TSelf MinMagnitude(TSelf x, TSelf y); static abstract TSelf Pow(TSelf x, TSelf y); static abstract TSelf Round(TSelf x); static abstract TSelf Round(TSelf x, TInteger digits); static abstract TSelf Round(TSelf x, MidpointRounding mode); static abstract TSelf Round(TSelf x, TInteger digits, MidpointRounding mode); static abstract TSelf ScaleB(TSelf x, TInteger n); static abstract TSelf Sin(TSelf x); static abstract TSelf Sinh(TSelf x); static abstract TSelf Sqrt(TSelf x); static abstract TSelf Tan(TSelf x); static abstract TSelf Tanh(TSelf x); static abstract TSelf Truncate(TSelf x); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IBinaryFloatingPoint : IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IComparable, IComparable, IEqualityOperators, IEquatable, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanFormattable, IFormattable, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IFloatingPoint, ISignedNumber where TSelf : IBinaryFloatingPoint { } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IIncrementOperators where TSelf : IIncrementOperators { static abstract TSelf operator ++(TSelf value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IBinaryInteger : IBinaryNumber, IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IComparable, IComparable, IEqualityOperators, IEquatable, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanFormattable, IFormattable, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators, IShiftOperators where TSelf : IBinaryInteger { static abstract TSelf LeadingZeroCount(TSelf value); static abstract TSelf PopCount(TSelf value); static abstract TSelf RotateLeft(TSelf value, int rotateAmount); static abstract TSelf RotateRight(TSelf value, int rotateAmount); static abstract TSelf TrailingZeroCount(TSelf value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IMinMaxValue where TSelf : IMinMaxValue { static abstract TSelf MinValue { get; } static abstract TSelf MaxValue { get; } } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IModulusOperators where TSelf : IModulusOperators { static abstract TResult operator %(TSelf left, TOther right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IMultiplicativeIdentity where TSelf : IMultiplicativeIdentity { static abstract TResult MultiplicativeIdentity { get; } } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IMultiplyOperators where TSelf : IMultiplyOperators { static abstract TResult operator *(TSelf left, TOther right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface INumber : IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IComparable, IComparable, IEqualityOperators, IEquatable, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanFormattable, IFormattable, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators where TSelf : INumber { static abstract TSelf One { get; } static abstract TSelf Zero { get; } static abstract TSelf Abs(TSelf value); static abstract TSelf Clamp(TSelf value, TSelf min, TSelf max); static abstract TSelf Create(TOther value); static abstract TSelf CreateSaturating(TOther value); static abstract TSelf CreateTruncating(TOther value); static abstract (TSelf Quotient, TSelf Remainder) DivRem(TSelf left, TSelf right); static abstract TSelf Max(TSelf x, TSelf y); static abstract TSelf Min(TSelf x, TSelf y); static abstract TSelf Parse(string s, NumberStyles style, IFormatProvider? provider); static abstract TSelf Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider); static abstract TSelf Sign(TSelf value); static abstract bool TryCreate(TOther value, out TSelf result); static abstract bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out TSelf result); static abstract bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out TSelf result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IBinaryNumber : IBitwiseOperators, INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IComparable, IComparable, IEqualityOperators, IEquatable, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanFormattable, IFormattable, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators where TSelf : IBinaryNumber { static abstract bool IsPow2(TSelf value); static abstract TSelf Log2(TSelf value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface ISignedNumber : INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IComparable, IComparable, IEqualityOperators, IEquatable, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanFormattable, IFormattable, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators where TSelf : ISignedNumber { static abstract TSelf NegativeOne { get; } } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IUnsignedNumber : INumber, IAdditionOperators, IAdditiveIdentity, IComparisonOperators, IComparable, IComparable, IEqualityOperators, IEquatable, IDecrementOperators, IDivisionOperators, IIncrementOperators, IModulusOperators, IMultiplicativeIdentity, IMultiplyOperators, ISpanFormattable, IFormattable, ISpanParseable, IParseable, ISubtractionOperators, IUnaryNegationOperators, IUnaryPlusOperators where TSelf : IUnsignedNumber { } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IParseable where TSelf : IParseable { static abstract TSelf Parse(string s, IFormatProvider? provider); static abstract bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, out TSelf result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IShiftOperators where TSelf : IShiftOperators { static abstract TResult operator <<(TSelf value, int shiftAmount); static abstract TResult operator >>(TSelf value, int shiftAmount); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface ISpanParseable : IParseable where TSelf : ISpanParseable { static abstract TSelf Parse(ReadOnlySpan s, IFormatProvider? provider); static abstract bool TryParse(ReadOnlySpan s, IFormatProvider? provider, out TSelf result); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface ISubtractionOperators where TSelf : ISubtractionOperators { static abstract TResult operator -(TSelf left, TOther right); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IUnaryNegationOperators where TSelf : IUnaryNegationOperators { static abstract TResult operator -(TSelf value); } [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public interface IUnaryPlusOperators where TSelf : IUnaryPlusOperators { static abstract TResult operator +(TSelf value); } } namespace System.Private.CoreLib { internal static class Strings { } } namespace System.Numerics { public static class BitOperations { private static ReadOnlySpan TrailingZeroCountDeBruijn => new byte[32] { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; private static ReadOnlySpan 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 bool IsPow2(int value) { if ((value & (value - 1)) == 0) { return value > 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool IsPow2(uint value) { if ((value & (value - 1)) == 0) { return value != 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsPow2(long value) { if ((value & (value - 1)) == 0L) { return value > 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool IsPow2(ulong value) { if ((value & (value - 1)) == 0L) { return value != 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsPow2(nint value) { if ((value & (value - 1)) == 0) { return value > 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsPow2(nuint value) { if ((value & (value - 1)) == 0) { return value != 0; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint RoundUpToPowerOf2(uint value) { if (!Lzcnt.IsSupported) { _ = ArmBase.IsSupported; if (!X86Base.IsSupported) { value--; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return value + 1; } } int num = 32 - LeadingZeroCount(value - 1); return (uint)((1 ^ (num >> 5)) << num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong RoundUpToPowerOf2(ulong value) { if (Lzcnt.X64.IsSupported || ArmBase.Arm64.IsSupported) { int num = 64 - LeadingZeroCount(value - 1); return (1uL ^ (ulong)(num >> 6)) << num; } value--; value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; value |= value >> 32; return value + 1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int LeadingZeroCount(uint value) { if (Lzcnt.IsSupported) { return (int)Lzcnt.LeadingZeroCount(value); } if (ArmBase.IsSupported) { } if (value == 0) { return 32; } if (X86Base.IsSupported) { return (int)(0x1F ^ X86Base.BitScanReverse(value)); } return 0x1F ^ Log2SoftwareFallback(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int LeadingZeroCount(ulong value) { if (Lzcnt.X64.IsSupported) { return (int)Lzcnt.X64.LeadingZeroCount(value); } if (ArmBase.Arm64.IsSupported) { } if (X86Base.X64.IsSupported) { if (value != 0L) { return 0x3F ^ (int)X86Base.X64.BitScanReverse(value); } return 64; } uint num = (uint)(value >> 32); if (num == 0) { return 32 + LeadingZeroCount((uint)value); } return LeadingZeroCount(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int Log2(uint value) { value |= 1u; if (Lzcnt.IsSupported) { return (int)(0x1F ^ Lzcnt.LeadingZeroCount(value)); } if (ArmBase.IsSupported) { } if (X86Base.IsSupported) { return (int)X86Base.BitScanReverse(value); } return Log2SoftwareFallback(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int Log2(ulong value) { value |= 1; if (Lzcnt.X64.IsSupported) { return 0x3F ^ (int)Lzcnt.X64.LeadingZeroCount(value); } if (ArmBase.Arm64.IsSupported) { } if (X86Base.X64.IsSupported) { return (int)X86Base.X64.BitScanReverse(value); } uint num = (uint)(value >> 32); if (num == 0) { return Log2((uint)value); } return 32 + Log2(num); } private static int Log2SoftwareFallback(uint value) { value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(Log2DeBruijn), (IntPtr)(int)(value * 130329821 >> 27)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int Log2Ceiling(uint value) { int num = Log2(value); if (PopCount(value) != 1) { num++; } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int Log2Ceiling(ulong value) { int num = Log2(value); if (PopCount(value) != 1) { num++; } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] [CLSCompliant(false)] public static int PopCount(uint value) { if (Popcnt.IsSupported) { return (int)Popcnt.PopCount(value); } if (AdvSimd.Arm64.IsSupported) { } return SoftwareFallback(value); static int SoftwareFallback(uint value) { value -= (value >> 1) & 0x55555555; value = (value & 0x33333333) + ((value >> 2) & 0x33333333); value = ((value + (value >> 4)) & 0xF0F0F0F) * 16843009 >> 24; return (int)value; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] [CLSCompliant(false)] public static int PopCount(ulong value) { if (Popcnt.X64.IsSupported) { return (int)Popcnt.X64.PopCount(value); } if (AdvSimd.Arm64.IsSupported) { } return PopCount((uint)value) + PopCount((uint)(value >> 32)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int TrailingZeroCount(int value) { return TrailingZeroCount((uint)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int TrailingZeroCount(uint value) { if (Bmi1.IsSupported) { return (int)Bmi1.TrailingZeroCount(value); } if (ArmBase.IsSupported) { } if (value == 0) { return 32; } if (X86Base.IsSupported) { return (int)X86Base.BitScanForward(value); } return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(TrailingZeroCountDeBruijn), (IntPtr)(int)((value & (0 - value)) * 125613361 >> 27)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int TrailingZeroCount(long value) { return TrailingZeroCount((ulong)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static int TrailingZeroCount(ulong value) { if (Bmi1.X64.IsSupported) { return (int)Bmi1.X64.TrailingZeroCount(value); } if (ArmBase.Arm64.IsSupported) { } if (X86Base.X64.IsSupported) { if (value != 0L) { return (int)X86Base.X64.BitScanForward(value); } return 64; } uint num = (uint)value; if (num == 0) { return 32 + TrailingZeroCount((uint)(value >> 32)); } return TrailingZeroCount(num); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint RotateLeft(uint value, int offset) { return (value << offset) | (value >> 32 - offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong RotateLeft(ulong value, int offset) { return (value << offset) | (value >> 64 - offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint RotateRight(uint value, int offset) { return (value >> offset) | (value << 32 - offset); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong RotateRight(ulong value, int offset) { return (value >> offset) | (value << 64 - offset); } } [Intrinsic] public struct Matrix3x2 : IEquatable { private static readonly Matrix3x2 _identity = new Matrix3x2(1f, 0f, 0f, 1f, 0f, 0f); public float M11; public float M12; public float M21; public float M22; public float M31; public float M32; public static Matrix3x2 Identity => _identity; public readonly bool IsIdentity => this == Identity; public Vector2 Translation { readonly get { return new Vector2(M31, M32); } set { M31 = value.X; M32 = value.Y; } } public Matrix3x2(float m11, float m12, float m21, float m22, float m31, float m32) { M11 = m11; M12 = m12; M21 = m21; M22 = m22; M31 = m31; M32 = m32; } public static Matrix3x2 operator +(Matrix3x2 value1, Matrix3x2 value2) { System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix3x2 result); result.M11 = value1.M11 + value2.M11; result.M12 = value1.M12 + value2.M12; result.M21 = value1.M21 + value2.M21; result.M22 = value1.M22 + value2.M22; result.M31 = value1.M31 + value2.M31; result.M32 = value1.M32 + value2.M32; return result; } public static bool operator ==(Matrix3x2 value1, Matrix3x2 value2) { if (value1.M11 == value2.M11 && value1.M22 == value2.M22 && value1.M12 == value2.M12 && value1.M21 == value2.M21 && value1.M31 == value2.M31) { return value1.M32 == value2.M32; } return false; } public static bool operator !=(Matrix3x2 value1, Matrix3x2 value2) { return !(value1 == value2); } public static Matrix3x2 operator *(Matrix3x2 value1, Matrix3x2 value2) { System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix3x2 result); result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21; result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22; result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21; result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22; result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31; result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32; return result; } public static Matrix3x2 operator *(Matrix3x2 value1, float value2) { System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix3x2 result); result.M11 = value1.M11 * value2; result.M12 = value1.M12 * value2; result.M21 = value1.M21 * value2; result.M22 = value1.M22 * value2; result.M31 = value1.M31 * value2; result.M32 = value1.M32 * value2; return result; } public static Matrix3x2 operator -(Matrix3x2 value1, Matrix3x2 value2) { System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix3x2 result); result.M11 = value1.M11 - value2.M11; result.M12 = value1.M12 - value2.M12; result.M21 = value1.M21 - value2.M21; result.M22 = value1.M22 - value2.M22; result.M31 = value1.M31 - value2.M31; result.M32 = value1.M32 - value2.M32; return result; } public static Matrix3x2 operator -(Matrix3x2 value) { System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix3x2 result); result.M11 = 0f - value.M11; result.M12 = 0f - value.M12; result.M21 = 0f - value.M21; result.M22 = 0f - value.M22; result.M31 = 0f - value.M31; result.M32 = 0f - value.M32; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix3x2 Add(Matrix3x2 value1, Matrix3x2 value2) { return value1 + value2; } public static Matrix3x2 CreateRotation(float radians) { radians = MathF.IEEERemainder(radians, (float)Math.PI * 2f); float num; float num2; if (radians > -1.7453294E-05f && radians < 1.7453294E-05f) { num = 1f; num2 = 0f; } else if (radians > 1.570779f && radians < 1.5708138f) { num = 0f; num2 = 1f; } else if (radians < -3.1415753f || radians > 3.1415753f) { num = -1f; num2 = 0f; } else if (radians > -1.5708138f && radians < -1.570779f) { num = 0f; num2 = -1f; } else { num = MathF.Cos(radians); num2 = MathF.Sin(radians); } Matrix3x2 identity = Identity; identity.M11 = num; identity.M12 = num2; identity.M21 = 0f - num2; identity.M22 = num; return identity; } public static Matrix3x2 CreateRotation(float radians, Vector2 centerPoint) { radians = MathF.IEEERemainder(radians, (float)Math.PI * 2f); float num; float num2; if (radians > -1.7453294E-05f && radians < 1.7453294E-05f) { num = 1f; num2 = 0f; } else if (radians > 1.570779f && radians < 1.5708138f) { num = 0f; num2 = 1f; } else if (radians < -3.1415753f || radians > 3.1415753f) { num = -1f; num2 = 0f; } else if (radians > -1.5708138f && radians < -1.570779f) { num = 0f; num2 = -1f; } else { num = MathF.Cos(radians); num2 = MathF.Sin(radians); } float m = centerPoint.X * (1f - num) + centerPoint.Y * num2; float m2 = centerPoint.Y * (1f - num) - centerPoint.X * num2; System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix3x2 result); result.M11 = num; result.M12 = num2; result.M21 = 0f - num2; result.M22 = num; result.M31 = m; result.M32 = m2; return result; } public static Matrix3x2 CreateScale(Vector2 scales) { Matrix3x2 identity = Identity; identity.M11 = scales.X; identity.M22 = scales.Y; return identity; } public static Matrix3x2 CreateScale(float xScale, float yScale) { Matrix3x2 identity = Identity; identity.M11 = xScale; identity.M22 = yScale; return identity; } public static Matrix3x2 CreateScale(float xScale, float yScale, Vector2 centerPoint) { Matrix3x2 identity = Identity; float m = centerPoint.X * (1f - xScale); float m2 = centerPoint.Y * (1f - yScale); identity.M11 = xScale; identity.M22 = yScale; identity.M31 = m; identity.M32 = m2; return identity; } public static Matrix3x2 CreateScale(Vector2 scales, Vector2 centerPoint) { Matrix3x2 identity = Identity; float m = centerPoint.X * (1f - scales.X); float m2 = centerPoint.Y * (1f - scales.Y); identity.M11 = scales.X; identity.M22 = scales.Y; identity.M31 = m; identity.M32 = m2; return identity; } public static Matrix3x2 CreateScale(float scale) { Matrix3x2 identity = Identity; identity.M11 = scale; identity.M22 = scale; return identity; } public static Matrix3x2 CreateScale(float scale, Vector2 centerPoint) { Matrix3x2 identity = Identity; float m = centerPoint.X * (1f - scale); float m2 = centerPoint.Y * (1f - scale); identity.M11 = scale; identity.M22 = scale; identity.M31 = m; identity.M32 = m2; return identity; } public static Matrix3x2 CreateSkew(float radiansX, float radiansY) { Matrix3x2 identity = Identity; float m = MathF.Tan(radiansX); float m2 = MathF.Tan(radiansY); identity.M12 = m2; identity.M21 = m; return identity; } public static Matrix3x2 CreateSkew(float radiansX, float radiansY, Vector2 centerPoint) { Matrix3x2 identity = Identity; float num = MathF.Tan(radiansX); float num2 = MathF.Tan(radiansY); float m = (0f - centerPoint.Y) * num; float m2 = (0f - centerPoint.X) * num2; identity.M12 = num2; identity.M21 = num; identity.M31 = m; identity.M32 = m2; return identity; } public static Matrix3x2 CreateTranslation(Vector2 position) { Matrix3x2 identity = Identity; identity.M31 = position.X; identity.M32 = position.Y; return identity; } public static Matrix3x2 CreateTranslation(float xPosition, float yPosition) { Matrix3x2 identity = Identity; identity.M31 = xPosition; identity.M32 = yPosition; return identity; } public static bool Invert(Matrix3x2 matrix, out Matrix3x2 result) { float num = matrix.M11 * matrix.M22 - matrix.M21 * matrix.M12; if (MathF.Abs(num) < float.Epsilon) { result = new Matrix3x2(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN); return false; } float num2 = 1f / num; result.M11 = matrix.M22 * num2; result.M12 = (0f - matrix.M12) * num2; result.M21 = (0f - matrix.M21) * num2; result.M22 = matrix.M11 * num2; result.M31 = (matrix.M21 * matrix.M32 - matrix.M31 * matrix.M22) * num2; result.M32 = (matrix.M31 * matrix.M12 - matrix.M11 * matrix.M32) * num2; return true; } public static Matrix3x2 Lerp(Matrix3x2 matrix1, Matrix3x2 matrix2, float amount) { System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix3x2 result); result.M11 = matrix1.M11 + (matrix2.M11 - matrix1.M11) * amount; result.M12 = matrix1.M12 + (matrix2.M12 - matrix1.M12) * amount; result.M21 = matrix1.M21 + (matrix2.M21 - matrix1.M21) * amount; result.M22 = matrix1.M22 + (matrix2.M22 - matrix1.M22) * amount; result.M31 = matrix1.M31 + (matrix2.M31 - matrix1.M31) * amount; result.M32 = matrix1.M32 + (matrix2.M32 - matrix1.M32) * amount; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix3x2 Multiply(Matrix3x2 value1, Matrix3x2 value2) { return value1 * value2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix3x2 Multiply(Matrix3x2 value1, float value2) { return value1 * value2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix3x2 Negate(Matrix3x2 value) { return -value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix3x2 Subtract(Matrix3x2 value1, Matrix3x2 value2) { return value1 - value2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override readonly bool Equals([NotNullWhen(true)] object? obj) { if (obj is Matrix3x2 other) { return Equals(other); } return false; } public readonly bool Equals(Matrix3x2 other) { return this == other; } public readonly float GetDeterminant() { return M11 * M22 - M21 * M12; } public override readonly int GetHashCode() { return HashCode.Combine(M11, M12, M21, M22, M31, M32); } public override readonly string ToString() { return $"{{ {{M11:{M11} M12:{M12}}} {{M21:{M21} M22:{M22}}} {{M31:{M31} M32:{M32}}} }}"; } } [Intrinsic] public struct Matrix4x4 : IEquatable { private struct CanonicalBasis { public Vector3 Row0; public Vector3 Row1; public Vector3 Row2; } private struct VectorBasis { public unsafe Vector3* Element0; public unsafe Vector3* Element1; public unsafe Vector3* Element2; } private static readonly Matrix4x4 _identity = new Matrix4x4(1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f); public float M11; public float M12; public float M13; public float M14; public float M21; public float M22; public float M23; public float M24; public float M31; public float M32; public float M33; public float M34; public float M41; public float M42; public float M43; public float M44; public static Matrix4x4 Identity => _identity; public readonly bool IsIdentity { get { if (M11 == 1f && M22 == 1f && M33 == 1f && M44 == 1f && M12 == 0f && M13 == 0f && M14 == 0f && M21 == 0f && M23 == 0f && M24 == 0f && M31 == 0f && M32 == 0f && M34 == 0f && M41 == 0f && M42 == 0f) { return M43 == 0f; } return false; } } public Vector3 Translation { readonly get { return new Vector3(M41, M42, M43); } set { M41 = value.X; M42 = value.Y; M43 = value.Z; } } public Matrix4x4(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44) { M11 = m11; M12 = m12; M13 = m13; M14 = m14; M21 = m21; M22 = m22; M23 = m23; M24 = m24; M31 = m31; M32 = m32; M33 = m33; M34 = m34; M41 = m41; M42 = m42; M43 = m43; M44 = m44; } public Matrix4x4(Matrix3x2 value) { M11 = value.M11; M12 = value.M12; M13 = 0f; M14 = 0f; M21 = value.M21; M22 = value.M22; M23 = 0f; M24 = 0f; M31 = 0f; M32 = 0f; M33 = 1f; M34 = 0f; M41 = value.M31; M42 = value.M32; M43 = 0f; M44 = 1f; } public unsafe static Matrix4x4 operator +(Matrix4x4 value1, Matrix4x4 value2) { if (AdvSimd.IsSupported) { } if (Sse.IsSupported) { Sse.Store(&value1.M11, Sse.Add(Sse.LoadVector128(&value1.M11), Sse.LoadVector128(&value2.M11))); Sse.Store(&value1.M21, Sse.Add(Sse.LoadVector128(&value1.M21), Sse.LoadVector128(&value2.M21))); Sse.Store(&value1.M31, Sse.Add(Sse.LoadVector128(&value1.M31), Sse.LoadVector128(&value2.M31))); Sse.Store(&value1.M41, Sse.Add(Sse.LoadVector128(&value1.M41), Sse.LoadVector128(&value2.M41))); return value1; } System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix4x4 result); result.M11 = value1.M11 + value2.M11; result.M12 = value1.M12 + value2.M12; result.M13 = value1.M13 + value2.M13; result.M14 = value1.M14 + value2.M14; result.M21 = value1.M21 + value2.M21; result.M22 = value1.M22 + value2.M22; result.M23 = value1.M23 + value2.M23; result.M24 = value1.M24 + value2.M24; result.M31 = value1.M31 + value2.M31; result.M32 = value1.M32 + value2.M32; result.M33 = value1.M33 + value2.M33; result.M34 = value1.M34 + value2.M34; result.M41 = value1.M41 + value2.M41; result.M42 = value1.M42 + value2.M42; result.M43 = value1.M43 + value2.M43; result.M44 = value1.M44 + value2.M44; return result; } public unsafe static bool operator ==(Matrix4x4 value1, Matrix4x4 value2) { if (AdvSimd.Arm64.IsSupported) { } if (Sse.IsSupported) { if (VectorMath.Equal(Sse.LoadVector128(&value1.M11), Sse.LoadVector128(&value2.M11)) && VectorMath.Equal(Sse.LoadVector128(&value1.M21), Sse.LoadVector128(&value2.M21)) && VectorMath.Equal(Sse.LoadVector128(&value1.M31), Sse.LoadVector128(&value2.M31))) { return VectorMath.Equal(Sse.LoadVector128(&value1.M41), Sse.LoadVector128(&value2.M41)); } return false; } if (value1.M11 == value2.M11 && value1.M22 == value2.M22 && value1.M33 == value2.M33 && value1.M44 == value2.M44 && value1.M12 == value2.M12 && value1.M13 == value2.M13 && value1.M14 == value2.M14 && value1.M21 == value2.M21 && value1.M23 == value2.M23 && value1.M24 == value2.M24 && value1.M31 == value2.M31 && value1.M32 == value2.M32 && value1.M34 == value2.M34 && value1.M41 == value2.M41 && value1.M42 == value2.M42) { return value1.M43 == value2.M43; } return false; } public unsafe static bool operator !=(Matrix4x4 value1, Matrix4x4 value2) { if (AdvSimd.Arm64.IsSupported) { } if (Sse.IsSupported) { if (!VectorMath.NotEqual(Sse.LoadVector128(&value1.M11), Sse.LoadVector128(&value2.M11)) && !VectorMath.NotEqual(Sse.LoadVector128(&value1.M21), Sse.LoadVector128(&value2.M21)) && !VectorMath.NotEqual(Sse.LoadVector128(&value1.M31), Sse.LoadVector128(&value2.M31))) { return VectorMath.NotEqual(Sse.LoadVector128(&value1.M41), Sse.LoadVector128(&value2.M41)); } return true; } if (value1.M11 == value2.M11 && value1.M12 == value2.M12 && value1.M13 == value2.M13 && value1.M14 == value2.M14 && value1.M21 == value2.M21 && value1.M22 == value2.M22 && value1.M23 == value2.M23 && value1.M24 == value2.M24 && value1.M31 == value2.M31 && value1.M32 == value2.M32 && value1.M33 == value2.M33 && value1.M34 == value2.M34 && value1.M41 == value2.M41 && value1.M42 == value2.M42 && value1.M43 == value2.M43) { return value1.M44 != value2.M44; } return true; } public unsafe static Matrix4x4 operator *(Matrix4x4 value1, Matrix4x4 value2) { if (AdvSimd.Arm64.IsSupported) { } if (Sse.IsSupported) { Vector128 vector = Sse.LoadVector128(&value1.M11); Sse.Store(&value1.M11, Sse.Add(Sse.Add(Sse.Multiply(Sse.Shuffle(vector, vector, 0), Sse.LoadVector128(&value2.M11)), Sse.Multiply(Sse.Shuffle(vector, vector, 85), Sse.LoadVector128(&value2.M21))), Sse.Add(Sse.Multiply(Sse.Shuffle(vector, vector, 170), Sse.LoadVector128(&value2.M31)), Sse.Multiply(Sse.Shuffle(vector, vector, byte.MaxValue), Sse.LoadVector128(&value2.M41))))); vector = Sse.LoadVector128(&value1.M21); Sse.Store(&value1.M21, Sse.Add(Sse.Add(Sse.Multiply(Sse.Shuffle(vector, vector, 0), Sse.LoadVector128(&value2.M11)), Sse.Multiply(Sse.Shuffle(vector, vector, 85), Sse.LoadVector128(&value2.M21))), Sse.Add(Sse.Multiply(Sse.Shuffle(vector, vector, 170), Sse.LoadVector128(&value2.M31)), Sse.Multiply(Sse.Shuffle(vector, vector, byte.MaxValue), Sse.LoadVector128(&value2.M41))))); vector = Sse.LoadVector128(&value1.M31); Sse.Store(&value1.M31, Sse.Add(Sse.Add(Sse.Multiply(Sse.Shuffle(vector, vector, 0), Sse.LoadVector128(&value2.M11)), Sse.Multiply(Sse.Shuffle(vector, vector, 85), Sse.LoadVector128(&value2.M21))), Sse.Add(Sse.Multiply(Sse.Shuffle(vector, vector, 170), Sse.LoadVector128(&value2.M31)), Sse.Multiply(Sse.Shuffle(vector, vector, byte.MaxValue), Sse.LoadVector128(&value2.M41))))); vector = Sse.LoadVector128(&value1.M41); Sse.Store(&value1.M41, Sse.Add(Sse.Add(Sse.Multiply(Sse.Shuffle(vector, vector, 0), Sse.LoadVector128(&value2.M11)), Sse.Multiply(Sse.Shuffle(vector, vector, 85), Sse.LoadVector128(&value2.M21))), Sse.Add(Sse.Multiply(Sse.Shuffle(vector, vector, 170), Sse.LoadVector128(&value2.M31)), Sse.Multiply(Sse.Shuffle(vector, vector, byte.MaxValue), Sse.LoadVector128(&value2.M41))))); return value1; } System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix4x4 result); result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21 + value1.M13 * value2.M31 + value1.M14 * value2.M41; result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22 + value1.M13 * value2.M32 + value1.M14 * value2.M42; result.M13 = value1.M11 * value2.M13 + value1.M12 * value2.M23 + value1.M13 * value2.M33 + value1.M14 * value2.M43; result.M14 = value1.M11 * value2.M14 + value1.M12 * value2.M24 + value1.M13 * value2.M34 + value1.M14 * value2.M44; result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21 + value1.M23 * value2.M31 + value1.M24 * value2.M41; result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22 + value1.M23 * value2.M32 + value1.M24 * value2.M42; result.M23 = value1.M21 * value2.M13 + value1.M22 * value2.M23 + value1.M23 * value2.M33 + value1.M24 * value2.M43; result.M24 = value1.M21 * value2.M14 + value1.M22 * value2.M24 + value1.M23 * value2.M34 + value1.M24 * value2.M44; result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value1.M33 * value2.M31 + value1.M34 * value2.M41; result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value1.M33 * value2.M32 + value1.M34 * value2.M42; result.M33 = value1.M31 * value2.M13 + value1.M32 * value2.M23 + value1.M33 * value2.M33 + value1.M34 * value2.M43; result.M34 = value1.M31 * value2.M14 + value1.M32 * value2.M24 + value1.M33 * value2.M34 + value1.M34 * value2.M44; result.M41 = value1.M41 * value2.M11 + value1.M42 * value2.M21 + value1.M43 * value2.M31 + value1.M44 * value2.M41; result.M42 = value1.M41 * value2.M12 + value1.M42 * value2.M22 + value1.M43 * value2.M32 + value1.M44 * value2.M42; result.M43 = value1.M41 * value2.M13 + value1.M42 * value2.M23 + value1.M43 * value2.M33 + value1.M44 * value2.M43; result.M44 = value1.M41 * value2.M14 + value1.M42 * value2.M24 + value1.M43 * value2.M34 + value1.M44 * value2.M44; return result; } public unsafe static Matrix4x4 operator *(Matrix4x4 value1, float value2) { if (AdvSimd.IsSupported) { } if (Sse.IsSupported) { Vector128 right = Vector128.Create(value2); Sse.Store(&value1.M11, Sse.Multiply(Sse.LoadVector128(&value1.M11), right)); Sse.Store(&value1.M21, Sse.Multiply(Sse.LoadVector128(&value1.M21), right)); Sse.Store(&value1.M31, Sse.Multiply(Sse.LoadVector128(&value1.M31), right)); Sse.Store(&value1.M41, Sse.Multiply(Sse.LoadVector128(&value1.M41), right)); return value1; } System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix4x4 result); result.M11 = value1.M11 * value2; result.M12 = value1.M12 * value2; result.M13 = value1.M13 * value2; result.M14 = value1.M14 * value2; result.M21 = value1.M21 * value2; result.M22 = value1.M22 * value2; result.M23 = value1.M23 * value2; result.M24 = value1.M24 * value2; result.M31 = value1.M31 * value2; result.M32 = value1.M32 * value2; result.M33 = value1.M33 * value2; result.M34 = value1.M34 * value2; result.M41 = value1.M41 * value2; result.M42 = value1.M42 * value2; result.M43 = value1.M43 * value2; result.M44 = value1.M44 * value2; return result; } public unsafe static Matrix4x4 operator -(Matrix4x4 value1, Matrix4x4 value2) { if (AdvSimd.IsSupported) { } if (Sse.IsSupported) { Sse.Store(&value1.M11, Sse.Subtract(Sse.LoadVector128(&value1.M11), Sse.LoadVector128(&value2.M11))); Sse.Store(&value1.M21, Sse.Subtract(Sse.LoadVector128(&value1.M21), Sse.LoadVector128(&value2.M21))); Sse.Store(&value1.M31, Sse.Subtract(Sse.LoadVector128(&value1.M31), Sse.LoadVector128(&value2.M31))); Sse.Store(&value1.M41, Sse.Subtract(Sse.LoadVector128(&value1.M41), Sse.LoadVector128(&value2.M41))); return value1; } System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix4x4 result); result.M11 = value1.M11 - value2.M11; result.M12 = value1.M12 - value2.M12; result.M13 = value1.M13 - value2.M13; result.M14 = value1.M14 - value2.M14; result.M21 = value1.M21 - value2.M21; result.M22 = value1.M22 - value2.M22; result.M23 = value1.M23 - value2.M23; result.M24 = value1.M24 - value2.M24; result.M31 = value1.M31 - value2.M31; result.M32 = value1.M32 - value2.M32; result.M33 = value1.M33 - value2.M33; result.M34 = value1.M34 - value2.M34; result.M41 = value1.M41 - value2.M41; result.M42 = value1.M42 - value2.M42; result.M43 = value1.M43 - value2.M43; result.M44 = value1.M44 - value2.M44; return result; } public unsafe static Matrix4x4 operator -(Matrix4x4 value) { if (AdvSimd.IsSupported) { } if (Sse.IsSupported) { Vector128 zero = Vector128.Zero; Sse.Store(&value.M11, Sse.Subtract(zero, Sse.LoadVector128(&value.M11))); Sse.Store(&value.M21, Sse.Subtract(zero, Sse.LoadVector128(&value.M21))); Sse.Store(&value.M31, Sse.Subtract(zero, Sse.LoadVector128(&value.M31))); Sse.Store(&value.M41, Sse.Subtract(zero, Sse.LoadVector128(&value.M41))); return value; } System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix4x4 result); result.M11 = 0f - value.M11; result.M12 = 0f - value.M12; result.M13 = 0f - value.M13; result.M14 = 0f - value.M14; result.M21 = 0f - value.M21; result.M22 = 0f - value.M22; result.M23 = 0f - value.M23; result.M24 = 0f - value.M24; result.M31 = 0f - value.M31; result.M32 = 0f - value.M32; result.M33 = 0f - value.M33; result.M34 = 0f - value.M34; result.M41 = 0f - value.M41; result.M42 = 0f - value.M42; result.M43 = 0f - value.M43; result.M44 = 0f - value.M44; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix4x4 Add(Matrix4x4 value1, Matrix4x4 value2) { return value1 + value2; } public static Matrix4x4 CreateBillboard(Vector3 objectPosition, Vector3 cameraPosition, Vector3 cameraUpVector, Vector3 cameraForwardVector) { Vector3 left = objectPosition - cameraPosition; float num = left.LengthSquared(); left = ((!(num < 0.0001f)) ? Vector3.Multiply(left, 1f / MathF.Sqrt(num)) : (-cameraForwardVector)); Vector3 vector = Vector3.Normalize(Vector3.Cross(cameraUpVector, left)); Vector3 vector2 = Vector3.Cross(left, vector); System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix4x4 result); result.M11 = vector.X; result.M12 = vector.Y; result.M13 = vector.Z; result.M14 = 0f; result.M21 = vector2.X; result.M22 = vector2.Y; result.M23 = vector2.Z; result.M24 = 0f; result.M31 = left.X; result.M32 = left.Y; result.M33 = left.Z; result.M34 = 0f; result.M41 = objectPosition.X; result.M42 = objectPosition.Y; result.M43 = objectPosition.Z; result.M44 = 1f; return result; } public static Matrix4x4 CreateConstrainedBillboard(Vector3 objectPosition, Vector3 cameraPosition, Vector3 rotateAxis, Vector3 cameraForwardVector, Vector3 objectForwardVector) { Vector3 left = objectPosition - cameraPosition; float num = left.LengthSquared(); left = ((!(num < 0.0001f)) ? Vector3.Multiply(left, 1f / MathF.Sqrt(num)) : (-cameraForwardVector)); Vector3 vector = rotateAxis; float x = Vector3.Dot(rotateAxis, left); Vector3 vector3; Vector3 vector2; if (MathF.Abs(x) > 0.99825466f) { vector2 = objectForwardVector; x = Vector3.Dot(rotateAxis, vector2); if (MathF.Abs(x) > 0.99825466f) { vector2 = ((MathF.Abs(rotateAxis.Z) > 0.99825466f) ? new Vector3(1f, 0f, 0f) : new Vector3(0f, 0f, -1f)); } vector3 = Vector3.Normalize(Vector3.Cross(rotateAxis, vector2)); vector2 = Vector3.Normalize(Vector3.Cross(vector3, rotateAxis)); } else { vector3 = Vector3.Normalize(Vector3.Cross(rotateAxis, left)); vector2 = Vector3.Normalize(Vector3.Cross(vector3, vector)); } System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix4x4 result); result.M11 = vector3.X; result.M12 = vector3.Y; result.M13 = vector3.Z; result.M14 = 0f; result.M21 = vector.X; result.M22 = vector.Y; result.M23 = vector.Z; result.M24 = 0f; result.M31 = vector2.X; result.M32 = vector2.Y; result.M33 = vector2.Z; result.M34 = 0f; result.M41 = objectPosition.X; result.M42 = objectPosition.Y; result.M43 = objectPosition.Z; result.M44 = 1f; return result; } public static Matrix4x4 CreateFromAxisAngle(Vector3 axis, float angle) { float x = axis.X; float y = axis.Y; float z = axis.Z; float num = MathF.Sin(angle); float num2 = MathF.Cos(angle); float num3 = x * x; float num4 = y * y; float num5 = z * z; float num6 = x * y; float num7 = x * z; float num8 = y * z; Matrix4x4 identity = Identity; identity.M11 = num3 + num2 * (1f - num3); identity.M12 = num6 - num2 * num6 + num * z; identity.M13 = num7 - num2 * num7 - num * y; identity.M21 = num6 - num2 * num6 - num * z; identity.M22 = num4 + num2 * (1f - num4); identity.M23 = num8 - num2 * num8 + num * x; identity.M31 = num7 - num2 * num7 + num * y; identity.M32 = num8 - num2 * num8 - num * x; identity.M33 = num5 + num2 * (1f - num5); return identity; } public static Matrix4x4 CreateFromQuaternion(Quaternion quaternion) { Matrix4x4 identity = Identity; float num = quaternion.X * quaternion.X; float num2 = quaternion.Y * quaternion.Y; float num3 = quaternion.Z * quaternion.Z; float num4 = quaternion.X * quaternion.Y; float num5 = quaternion.Z * quaternion.W; float num6 = quaternion.Z * quaternion.X; float num7 = quaternion.Y * quaternion.W; float num8 = quaternion.Y * quaternion.Z; float num9 = quaternion.X * quaternion.W; identity.M11 = 1f - 2f * (num2 + num3); identity.M12 = 2f * (num4 + num5); identity.M13 = 2f * (num6 - num7); identity.M21 = 2f * (num4 - num5); identity.M22 = 1f - 2f * (num3 + num); identity.M23 = 2f * (num8 + num9); identity.M31 = 2f * (num6 + num7); identity.M32 = 2f * (num8 - num9); identity.M33 = 1f - 2f * (num2 + num); return identity; } public static Matrix4x4 CreateFromYawPitchRoll(float yaw, float pitch, float roll) { Quaternion quaternion = Quaternion.CreateFromYawPitchRoll(yaw, pitch, roll); return CreateFromQuaternion(quaternion); } public static Matrix4x4 CreateLookAt(Vector3 cameraPosition, Vector3 cameraTarget, Vector3 cameraUpVector) { Vector3 vector = Vector3.Normalize(cameraPosition - cameraTarget); Vector3 vector2 = Vector3.Normalize(Vector3.Cross(cameraUpVector, vector)); Vector3 vector3 = Vector3.Cross(vector, vector2); Matrix4x4 identity = Identity; identity.M11 = vector2.X; identity.M12 = vector3.X; identity.M13 = vector.X; identity.M21 = vector2.Y; identity.M22 = vector3.Y; identity.M23 = vector.Y; identity.M31 = vector2.Z; identity.M32 = vector3.Z; identity.M33 = vector.Z; identity.M41 = 0f - Vector3.Dot(vector2, cameraPosition); identity.M42 = 0f - Vector3.Dot(vector3, cameraPosition); identity.M43 = 0f - Vector3.Dot(vector, cameraPosition); return identity; } public static Matrix4x4 CreateOrthographic(float width, float height, float zNearPlane, float zFarPlane) { Matrix4x4 identity = Identity; identity.M11 = 2f / width; identity.M22 = 2f / height; identity.M33 = 1f / (zNearPlane - zFarPlane); identity.M43 = zNearPlane / (zNearPlane - zFarPlane); return identity; } public static Matrix4x4 CreateOrthographicOffCenter(float left, float right, float bottom, float top, float zNearPlane, float zFarPlane) { Matrix4x4 identity = Identity; identity.M11 = 2f / (right - left); identity.M22 = 2f / (top - bottom); identity.M33 = 1f / (zNearPlane - zFarPlane); identity.M41 = (left + right) / (left - right); identity.M42 = (top + bottom) / (bottom - top); identity.M43 = zNearPlane / (zNearPlane - zFarPlane); return identity; } public static Matrix4x4 CreatePerspective(float width, float height, float nearPlaneDistance, float farPlaneDistance) { if (nearPlaneDistance <= 0f) { throw new ArgumentOutOfRangeException("nearPlaneDistance"); } if (farPlaneDistance <= 0f) { throw new ArgumentOutOfRangeException("farPlaneDistance"); } if (nearPlaneDistance >= farPlaneDistance) { throw new ArgumentOutOfRangeException("nearPlaneDistance"); } System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix4x4 result); result.M11 = 2f * nearPlaneDistance / width; result.M12 = (result.M13 = (result.M14 = 0f)); result.M22 = 2f * nearPlaneDistance / height; result.M21 = (result.M23 = (result.M24 = 0f)); float num = (result.M33 = (float.IsPositiveInfinity(farPlaneDistance) ? (-1f) : (farPlaneDistance / (nearPlaneDistance - farPlaneDistance)))); result.M31 = (result.M32 = 0f); result.M34 = -1f; result.M41 = (result.M42 = (result.M44 = 0f)); result.M43 = nearPlaneDistance * num; return result; } public static Matrix4x4 CreatePerspectiveFieldOfView(float fieldOfView, float aspectRatio, float nearPlaneDistance, float farPlaneDistance) { if (fieldOfView <= 0f || fieldOfView >= (float)Math.PI) { throw new ArgumentOutOfRangeException("fieldOfView"); } if (nearPlaneDistance <= 0f) { throw new ArgumentOutOfRangeException("nearPlaneDistance"); } if (farPlaneDistance <= 0f) { throw new ArgumentOutOfRangeException("farPlaneDistance"); } if (nearPlaneDistance >= farPlaneDistance) { throw new ArgumentOutOfRangeException("nearPlaneDistance"); } float num = 1f / MathF.Tan(fieldOfView * 0.5f); float m = num / aspectRatio; System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix4x4 result); result.M11 = m; result.M12 = (result.M13 = (result.M14 = 0f)); result.M22 = num; result.M21 = (result.M23 = (result.M24 = 0f)); result.M31 = (result.M32 = 0f); float num2 = (result.M33 = (float.IsPositiveInfinity(farPlaneDistance) ? (-1f) : (farPlaneDistance / (nearPlaneDistance - farPlaneDistance)))); result.M34 = -1f; result.M41 = (result.M42 = (result.M44 = 0f)); result.M43 = nearPlaneDistance * num2; return result; } public static Matrix4x4 CreatePerspectiveOffCenter(float left, float right, float bottom, float top, float nearPlaneDistance, float farPlaneDistance) { if (nearPlaneDistance <= 0f) { throw new ArgumentOutOfRangeException("nearPlaneDistance"); } if (farPlaneDistance <= 0f) { throw new ArgumentOutOfRangeException("farPlaneDistance"); } if (nearPlaneDistance >= farPlaneDistance) { throw new ArgumentOutOfRangeException("nearPlaneDistance"); } System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix4x4 result); result.M11 = 2f * nearPlaneDistance / (right - left); result.M12 = (result.M13 = (result.M14 = 0f)); result.M22 = 2f * nearPlaneDistance / (top - bottom); result.M21 = (result.M23 = (result.M24 = 0f)); result.M31 = (left + right) / (right - left); result.M32 = (top + bottom) / (top - bottom); float num = (result.M33 = (float.IsPositiveInfinity(farPlaneDistance) ? (-1f) : (farPlaneDistance / (nearPlaneDistance - farPlaneDistance)))); result.M34 = -1f; result.M43 = nearPlaneDistance * num; result.M41 = (result.M42 = (result.M44 = 0f)); return result; } public static Matrix4x4 CreateReflection(Plane value) { value = Plane.Normalize(value); float x = value.Normal.X; float y = value.Normal.Y; float z = value.Normal.Z; float num = -2f * x; float num2 = -2f * y; float num3 = -2f * z; Matrix4x4 identity = Identity; identity.M11 = num * x + 1f; identity.M12 = num2 * x; identity.M13 = num3 * x; identity.M21 = num * y; identity.M22 = num2 * y + 1f; identity.M23 = num3 * y; identity.M31 = num * z; identity.M32 = num2 * z; identity.M33 = num3 * z + 1f; identity.M41 = num * value.D; identity.M42 = num2 * value.D; identity.M43 = num3 * value.D; return identity; } public static Matrix4x4 CreateRotationX(float radians) { Matrix4x4 identity = Identity; float num = MathF.Cos(radians); float num2 = MathF.Sin(radians); identity.M22 = num; identity.M23 = num2; identity.M32 = 0f - num2; identity.M33 = num; return identity; } public static Matrix4x4 CreateRotationX(float radians, Vector3 centerPoint) { Matrix4x4 identity = Identity; float num = MathF.Cos(radians); float num2 = MathF.Sin(radians); float m = centerPoint.Y * (1f - num) + centerPoint.Z * num2; float m2 = centerPoint.Z * (1f - num) - centerPoint.Y * num2; identity.M22 = num; identity.M23 = num2; identity.M32 = 0f - num2; identity.M33 = num; identity.M42 = m; identity.M43 = m2; return identity; } public static Matrix4x4 CreateRotationY(float radians) { Matrix4x4 identity = Identity; float num = MathF.Cos(radians); float num2 = MathF.Sin(radians); identity.M11 = num; identity.M13 = 0f - num2; identity.M31 = num2; identity.M33 = num; return identity; } public static Matrix4x4 CreateRotationY(float radians, Vector3 centerPoint) { Matrix4x4 identity = Identity; float num = MathF.Cos(radians); float num2 = MathF.Sin(radians); float m = centerPoint.X * (1f - num) - centerPoint.Z * num2; float m2 = centerPoint.Z * (1f - num) + centerPoint.X * num2; identity.M11 = num; identity.M13 = 0f - num2; identity.M31 = num2; identity.M33 = num; identity.M41 = m; identity.M43 = m2; return identity; } public static Matrix4x4 CreateRotationZ(float radians) { Matrix4x4 identity = Identity; float num = MathF.Cos(radians); float num2 = MathF.Sin(radians); identity.M11 = num; identity.M12 = num2; identity.M21 = 0f - num2; identity.M22 = num; return identity; } public static Matrix4x4 CreateRotationZ(float radians, Vector3 centerPoint) { Matrix4x4 identity = Identity; float num = MathF.Cos(radians); float num2 = MathF.Sin(radians); float m = centerPoint.X * (1f - num) + centerPoint.Y * num2; float m2 = centerPoint.Y * (1f - num) - centerPoint.X * num2; identity.M11 = num; identity.M12 = num2; identity.M21 = 0f - num2; identity.M22 = num; identity.M41 = m; identity.M42 = m2; return identity; } public static Matrix4x4 CreateScale(float xScale, float yScale, float zScale) { Matrix4x4 identity = Identity; identity.M11 = xScale; identity.M22 = yScale; identity.M33 = zScale; return identity; } public static Matrix4x4 CreateScale(float xScale, float yScale, float zScale, Vector3 centerPoint) { Matrix4x4 identity = Identity; float m = centerPoint.X * (1f - xScale); float m2 = centerPoint.Y * (1f - yScale); float m3 = centerPoint.Z * (1f - zScale); identity.M11 = xScale; identity.M22 = yScale; identity.M33 = zScale; identity.M41 = m; identity.M42 = m2; identity.M43 = m3; return identity; } public static Matrix4x4 CreateScale(Vector3 scales) { Matrix4x4 identity = Identity; identity.M11 = scales.X; identity.M22 = scales.Y; identity.M33 = scales.Z; return identity; } public static Matrix4x4 CreateScale(Vector3 scales, Vector3 centerPoint) { Matrix4x4 identity = Identity; float m = centerPoint.X * (1f - scales.X); float m2 = centerPoint.Y * (1f - scales.Y); float m3 = centerPoint.Z * (1f - scales.Z); identity.M11 = scales.X; identity.M22 = scales.Y; identity.M33 = scales.Z; identity.M41 = m; identity.M42 = m2; identity.M43 = m3; return identity; } public static Matrix4x4 CreateScale(float scale) { Matrix4x4 identity = Identity; identity.M11 = scale; identity.M22 = scale; identity.M33 = scale; return identity; } public static Matrix4x4 CreateScale(float scale, Vector3 centerPoint) { Matrix4x4 identity = Identity; float m = centerPoint.X * (1f - scale); float m2 = centerPoint.Y * (1f - scale); float m3 = centerPoint.Z * (1f - scale); identity.M11 = scale; identity.M22 = scale; identity.M33 = scale; identity.M41 = m; identity.M42 = m2; identity.M43 = m3; return identity; } public static Matrix4x4 CreateShadow(Vector3 lightDirection, Plane plane) { Plane plane2 = Plane.Normalize(plane); float num = plane2.Normal.X * lightDirection.X + plane2.Normal.Y * lightDirection.Y + plane2.Normal.Z * lightDirection.Z; float num2 = 0f - plane2.Normal.X; float num3 = 0f - plane2.Normal.Y; float num4 = 0f - plane2.Normal.Z; float num5 = 0f - plane2.D; Matrix4x4 identity = Identity; identity.M11 = num2 * lightDirection.X + num; identity.M21 = num3 * lightDirection.X; identity.M31 = num4 * lightDirection.X; identity.M41 = num5 * lightDirection.X; identity.M12 = num2 * lightDirection.Y; identity.M22 = num3 * lightDirection.Y + num; identity.M32 = num4 * lightDirection.Y; identity.M42 = num5 * lightDirection.Y; identity.M13 = num2 * lightDirection.Z; identity.M23 = num3 * lightDirection.Z; identity.M33 = num4 * lightDirection.Z + num; identity.M43 = num5 * lightDirection.Z; identity.M44 = num; return identity; } public static Matrix4x4 CreateTranslation(Vector3 position) { Matrix4x4 identity = Identity; identity.M41 = position.X; identity.M42 = position.Y; identity.M43 = position.Z; return identity; } public static Matrix4x4 CreateTranslation(float xPosition, float yPosition, float zPosition) { Matrix4x4 identity = Identity; identity.M41 = xPosition; identity.M42 = yPosition; identity.M43 = zPosition; return identity; } public static Matrix4x4 CreateWorld(Vector3 position, Vector3 forward, Vector3 up) { Vector3 vector = Vector3.Normalize(-forward); Vector3 vector2 = Vector3.Normalize(Vector3.Cross(up, vector)); Vector3 vector3 = Vector3.Cross(vector, vector2); Matrix4x4 identity = Identity; identity.M11 = vector2.X; identity.M12 = vector2.Y; identity.M13 = vector2.Z; identity.M21 = vector3.X; identity.M22 = vector3.Y; identity.M23 = vector3.Z; identity.M31 = vector.X; identity.M32 = vector.Y; identity.M33 = vector.Z; identity.M41 = position.X; identity.M42 = position.Y; identity.M43 = position.Z; return identity; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Invert(Matrix4x4 matrix, out Matrix4x4 result) { if (Sse.IsSupported) { return SseImpl(matrix, out result); } return SoftwareFallback(matrix, out result); static bool SoftwareFallback(Matrix4x4 matrix, out Matrix4x4 result) { float m = matrix.M11; float m2 = matrix.M12; float m3 = matrix.M13; float m4 = matrix.M14; float m5 = matrix.M21; float m6 = matrix.M22; float m7 = matrix.M23; float m8 = matrix.M24; float m9 = matrix.M31; float m10 = matrix.M32; float m11 = matrix.M33; float m12 = matrix.M34; float m13 = matrix.M41; float m14 = matrix.M42; float m15 = matrix.M43; float m16 = matrix.M44; float num = m11 * m16 - m12 * m15; float num2 = m10 * m16 - m12 * m14; float num3 = m10 * m15 - m11 * m14; float num4 = m9 * m16 - m12 * m13; float num5 = m9 * m15 - m11 * m13; float num6 = m9 * m14 - m10 * m13; float num7 = m6 * num - m7 * num2 + m8 * num3; float num8 = 0f - (m5 * num - m7 * num4 + m8 * num5); float num9 = m5 * num2 - m6 * num4 + m8 * num6; float num10 = 0f - (m5 * num3 - m6 * num5 + m7 * num6); float num11 = m * num7 + m2 * num8 + m3 * num9 + m4 * num10; if (MathF.Abs(num11) < float.Epsilon) { result = new Matrix4x4(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN); return false; } float num12 = 1f / num11; result.M11 = num7 * num12; result.M21 = num8 * num12; result.M31 = num9 * num12; result.M41 = num10 * num12; result.M12 = (0f - (m2 * num - m3 * num2 + m4 * num3)) * num12; result.M22 = (m * num - m3 * num4 + m4 * num5) * num12; result.M32 = (0f - (m * num2 - m2 * num4 + m4 * num6)) * num12; result.M42 = (m * num3 - m2 * num5 + m3 * num6) * num12; float num13 = m7 * m16 - m8 * m15; float num14 = m6 * m16 - m8 * m14; float num15 = m6 * m15 - m7 * m14; float num16 = m5 * m16 - m8 * m13; float num17 = m5 * m15 - m7 * m13; float num18 = m5 * m14 - m6 * m13; result.M13 = (m2 * num13 - m3 * num14 + m4 * num15) * num12; result.M23 = (0f - (m * num13 - m3 * num16 + m4 * num17)) * num12; result.M33 = (m * num14 - m2 * num16 + m4 * num18) * num12; result.M43 = (0f - (m * num15 - m2 * num17 + m3 * num18)) * num12; float num19 = m7 * m12 - m8 * m11; float num20 = m6 * m12 - m8 * m10; float num21 = m6 * m11 - m7 * m10; float num22 = m5 * m12 - m8 * m9; float num23 = m5 * m11 - m7 * m9; float num24 = m5 * m10 - m6 * m9; result.M14 = (0f - (m2 * num19 - m3 * num20 + m4 * num21)) * num12; result.M24 = (m * num19 - m3 * num22 + m4 * num23) * num12; result.M34 = (0f - (m * num20 - m2 * num22 + m4 * num24)) * num12; result.M44 = (m * num21 - m2 * num23 + m3 * num24) * num12; return true; } unsafe static bool SseImpl(Matrix4x4 matrix, out Matrix4x4 result) { if (!Sse.IsSupported) { throw new PlatformNotSupportedException(); } Vector128 left = Sse.LoadVector128(&matrix.M11); Vector128 right = Sse.LoadVector128(&matrix.M21); Vector128 left2 = Sse.LoadVector128(&matrix.M31); Vector128 right2 = Sse.LoadVector128(&matrix.M41); Vector128 left3 = Sse.Shuffle(left, right, 68); Vector128 left4 = Sse.Shuffle(left, right, 238); Vector128 right3 = Sse.Shuffle(left2, right2, 68); Vector128 right4 = Sse.Shuffle(left2, right2, 238); left = Sse.Shuffle(left3, right3, 136); right = Sse.Shuffle(left3, right3, 221); left2 = Sse.Shuffle(left4, right4, 136); right2 = Sse.Shuffle(left4, right4, 221); Vector128 left5 = Permute(left2, 80); Vector128 right5 = Permute(right2, 238); Vector128 left6 = Permute(left, 80); Vector128 right6 = Permute(right, 238); Vector128 left7 = Sse.Shuffle(left2, left, 136); Vector128 right7 = Sse.Shuffle(right2, right, 221); Vector128 left8 = Sse.Multiply(left5, right5); Vector128 left9 = Sse.Multiply(left6, right6); Vector128 left10 = Sse.Multiply(left7, right7); left5 = Permute(left2, 238); right5 = Permute(right2, 80); left6 = Permute(left, 238); right6 = Permute(right, 80); left7 = Sse.Shuffle(left2, left, 221); right7 = Sse.Shuffle(right2, right, 136); left8 = Sse.Subtract(left8, Sse.Multiply(left5, right5)); left9 = Sse.Subtract(left9, Sse.Multiply(left6, right6)); left10 = Sse.Subtract(left10, Sse.Multiply(left7, right7)); right6 = Sse.Shuffle(left8, left10, 93); left5 = Permute(right, 73); right5 = Sse.Shuffle(right6, left8, 50); left6 = Permute(left, 18); right6 = Sse.Shuffle(right6, left8, 153); Vector128 left11 = Sse.Shuffle(left9, left10, 253); left7 = Permute(right2, 73); right7 = Sse.Shuffle(left11, left9, 50); Vector128 left12 = Permute(left2, 18); left11 = Sse.Shuffle(left11, left9, 153); Vector128 left13 = Sse.Multiply(left5, right5); Vector128 left14 = Sse.Multiply(left6, right6); Vector128 left15 = Sse.Multiply(left7, right7); Vector128 left16 = Sse.Multiply(left12, left11); right6 = Sse.Shuffle(left8, left10, 4); left5 = Permute(right, 158); right5 = Sse.Shuffle(left8, right6, 147); left6 = Permute(left, 123); right6 = Sse.Shuffle(left8, right6, 38); left11 = Sse.Shuffle(left9, left10, 164); left7 = Permute(right2, 158); right7 = Sse.Shuffle(left9, left11, 147); left12 = Permute(left2, 123); left11 = Sse.Shuffle(left9, left11, 38); left13 = Sse.Subtract(left13, Sse.Multiply(left5, right5)); left14 = Sse.Subtract(left14, Sse.Multiply(left6, right6)); left15 = Sse.Subtract(left15, Sse.Multiply(left7, right7)); left16 = Sse.Subtract(left16, Sse.Multiply(left12, left11)); left5 = Permute(right, 51); right5 = Sse.Shuffle(left8, left10, 74); right5 = Permute(right5, 44); left6 = Permute(left, 141); right6 = Sse.Shuffle(left8, left10, 76); right6 = Permute(right6, 147); left7 = Permute(right2, 51); right7 = Sse.Shuffle(left9, left10, 234); right7 = Permute(right7, 44); left12 = Permute(left2, 141); left11 = Sse.Shuffle(left9, left10, 236); left11 = Permute(left11, 147); left5 = Sse.Multiply(left5, right5); left6 = Sse.Multiply(left6, right6); left7 = Sse.Multiply(left7, right7); left12 = Sse.Multiply(left12, left11); Vector128 right8 = Sse.Subtract(left13, left5); left13 = Sse.Add(left13, left5); Vector128 right9 = Sse.Add(left14, left6); left14 = Sse.Subtract(left14, left6); Vector128 right10 = Sse.Subtract(left15, left7); left15 = Sse.Add(left15, left7); Vector128 right11 = Sse.Add(left16, left12); left16 = Sse.Subtract(left16, left12); left13 = Sse.Shuffle(left13, right8, 216); left14 = Sse.Shuffle(left14, right9, 216); left15 = Sse.Shuffle(left15, right10, 216); left16 = Sse.Shuffle(left16, right11, 216); left13 = Permute(left13, 216); left14 = Permute(left14, 216); left15 = Permute(left15, 216); left16 = Permute(left16, 216); right3 = left; float num25 = Vector4.Dot(left13.AsVector4(), right3.AsVector4()); if (MathF.Abs(num25) < float.Epsilon) { result = new Matrix4x4(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN); return false; } Vector128 left17 = Vector128.Create(1f); Vector128 right12 = Vector128.Create(num25); right12 = Sse.Divide(left17, right12); left = Sse.Multiply(left13, right12); right = Sse.Multiply(left14, right12); left2 = Sse.Multiply(left15, right12); right2 = Sse.Multiply(left16, right12); Unsafe.SkipInit(out result); ref Vector128 reference = ref Unsafe.As>(ref result); reference = left; Unsafe.Add(ref reference, 1) = right; Unsafe.Add(ref reference, 2) = left2; Unsafe.Add(ref reference, 3) = right2; return true; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix4x4 Multiply(Matrix4x4 value1, Matrix4x4 value2) { return value1 * value2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix4x4 Multiply(Matrix4x4 value1, float value2) { return value1 * value2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix4x4 Negate(Matrix4x4 value) { return -value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Matrix4x4 Subtract(Matrix4x4 value1, Matrix4x4 value2) { return value1 - value2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static Vector128 Permute(Vector128 value, byte control) { if (Avx.IsSupported) { return Avx.Permute(value, control); } if (Sse.IsSupported) { return Sse.Shuffle(value, value, control); } throw new PlatformNotSupportedException(); } public unsafe static bool Decompose(Matrix4x4 matrix, out Vector3 scale, out Quaternion rotation, out Vector3 translation) { bool result = true; fixed (Vector3* ptr = &scale) { float* ptr2 = (float*)ptr; System.Runtime.CompilerServices.Unsafe.SkipInit(out VectorBasis vectorBasis); Vector3** ptr3 = (Vector3**)(&vectorBasis); Matrix4x4 identity = Identity; CanonicalBasis canonicalBasis = default(CanonicalBasis); Vector3* ptr4 = &canonicalBasis.Row0; canonicalBasis.Row0 = new Vector3(1f, 0f, 0f); canonicalBasis.Row1 = new Vector3(0f, 1f, 0f); canonicalBasis.Row2 = new Vector3(0f, 0f, 1f); translation = new Vector3(matrix.M41, matrix.M42, matrix.M43); *ptr3 = (Vector3*)(&identity.M11); ptr3[1] = (Vector3*)(&identity.M21); ptr3[2] = (Vector3*)(&identity.M31); *(*ptr3) = new Vector3(matrix.M11, matrix.M12, matrix.M13); *ptr3[1] = new Vector3(matrix.M21, matrix.M22, matrix.M23); *ptr3[2] = new Vector3(matrix.M31, matrix.M32, matrix.M33); scale.X = (*ptr3)->Length(); scale.Y = ptr3[1]->Length(); scale.Z = ptr3[2]->Length(); float num = *ptr2; float num2 = ptr2[1]; float num3 = ptr2[2]; uint num4; uint num5; uint num6; if (num < num2) { if (num2 < num3) { num4 = 2u; num5 = 1u; num6 = 0u; } else { num4 = 1u; if (num < num3) { num5 = 2u; num6 = 0u; } else { num5 = 0u; num6 = 2u; } } } else if (num < num3) { num4 = 2u; num5 = 0u; num6 = 1u; } else { num4 = 0u; if (num2 < num3) { num5 = 2u; num6 = 1u; } else { num5 = 1u; num6 = 2u; } } if (ptr2[num4] < 0.0001f) { *ptr3[num4] = ptr4[num4]; } *ptr3[num4] = Vector3.Normalize(*ptr3[num4]); if (ptr2[num5] < 0.0001f) { float num7 = MathF.Abs(ptr3[num4]->X); float num8 = MathF.Abs(ptr3[num4]->Y); float num9 = MathF.Abs(ptr3[num4]->Z); uint num10 = ((num7 < num8) ? ((!(num8 < num9)) ? ((!(num7 < num9)) ? 2u : 0u) : 0u) : ((num7 < num9) ? 1u : ((num8 < num9) ? 1u : 2u))); *ptr3[num5] = Vector3.Cross(*ptr3[num4], ptr4[num10]); } *ptr3[num5] = Vector3.Normalize(*ptr3[num5]); if (ptr2[num6] < 0.0001f) { *ptr3[num6] = Vector3.Cross(*ptr3[num4], *ptr3[num5]); } *ptr3[num6] = Vector3.Normalize(*ptr3[num6]); float num11 = identity.GetDeterminant(); if (num11 < 0f) { ptr2[num4] = 0f - ptr2[num4]; *ptr3[num4] = -(*ptr3[num4]); num11 = 0f - num11; } num11 -= 1f; num11 *= num11; if (0.0001f < num11) { rotation = Quaternion.Identity; result = false; } else { rotation = Quaternion.CreateFromRotationMatrix(identity); } } return result; } public unsafe static Matrix4x4 Lerp(Matrix4x4 matrix1, Matrix4x4 matrix2, float amount) { if (AdvSimd.IsSupported) { } if (Sse.IsSupported) { Vector128 t = Vector128.Create(amount); Sse.Store(&matrix1.M11, VectorMath.Lerp(Sse.LoadVector128(&matrix1.M11), Sse.LoadVector128(&matrix2.M11), t)); Sse.Store(&matrix1.M21, VectorMath.Lerp(Sse.LoadVector128(&matrix1.M21), Sse.LoadVector128(&matrix2.M21), t)); Sse.Store(&matrix1.M31, VectorMath.Lerp(Sse.LoadVector128(&matrix1.M31), Sse.LoadVector128(&matrix2.M31), t)); Sse.Store(&matrix1.M41, VectorMath.Lerp(Sse.LoadVector128(&matrix1.M41), Sse.LoadVector128(&matrix2.M41), t)); return matrix1; } System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix4x4 result); result.M11 = matrix1.M11 + (matrix2.M11 - matrix1.M11) * amount; result.M12 = matrix1.M12 + (matrix2.M12 - matrix1.M12) * amount; result.M13 = matrix1.M13 + (matrix2.M13 - matrix1.M13) * amount; result.M14 = matrix1.M14 + (matrix2.M14 - matrix1.M14) * amount; result.M21 = matrix1.M21 + (matrix2.M21 - matrix1.M21) * amount; result.M22 = matrix1.M22 + (matrix2.M22 - matrix1.M22) * amount; result.M23 = matrix1.M23 + (matrix2.M23 - matrix1.M23) * amount; result.M24 = matrix1.M24 + (matrix2.M24 - matrix1.M24) * amount; result.M31 = matrix1.M31 + (matrix2.M31 - matrix1.M31) * amount; result.M32 = matrix1.M32 + (matrix2.M32 - matrix1.M32) * amount; result.M33 = matrix1.M33 + (matrix2.M33 - matrix1.M33) * amount; result.M34 = matrix1.M34 + (matrix2.M34 - matrix1.M34) * amount; result.M41 = matrix1.M41 + (matrix2.M41 - matrix1.M41) * amount; result.M42 = matrix1.M42 + (matrix2.M42 - matrix1.M42) * amount; result.M43 = matrix1.M43 + (matrix2.M43 - matrix1.M43) * amount; result.M44 = matrix1.M44 + (matrix2.M44 - matrix1.M44) * amount; return result; } public static Matrix4x4 Transform(Matrix4x4 value, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num; float num5 = rotation.W * num2; float num6 = rotation.W * num3; float num7 = rotation.X * num; float num8 = rotation.X * num2; float num9 = rotation.X * num3; float num10 = rotation.Y * num2; float num11 = rotation.Y * num3; float num12 = rotation.Z * num3; float num13 = 1f - num10 - num12; float num14 = num8 - num6; float num15 = num9 + num5; float num16 = num8 + num6; float num17 = 1f - num7 - num12; float num18 = num11 - num4; float num19 = num9 - num5; float num20 = num11 + num4; float num21 = 1f - num7 - num10; System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix4x4 result); result.M11 = value.M11 * num13 + value.M12 * num14 + value.M13 * num15; result.M12 = value.M11 * num16 + value.M12 * num17 + value.M13 * num18; result.M13 = value.M11 * num19 + value.M12 * num20 + value.M13 * num21; result.M14 = value.M14; result.M21 = value.M21 * num13 + value.M22 * num14 + value.M23 * num15; result.M22 = value.M21 * num16 + value.M22 * num17 + value.M23 * num18; result.M23 = value.M21 * num19 + value.M22 * num20 + value.M23 * num21; result.M24 = value.M24; result.M31 = value.M31 * num13 + value.M32 * num14 + value.M33 * num15; result.M32 = value.M31 * num16 + value.M32 * num17 + value.M33 * num18; result.M33 = value.M31 * num19 + value.M32 * num20 + value.M33 * num21; result.M34 = value.M34; result.M41 = value.M41 * num13 + value.M42 * num14 + value.M43 * num15; result.M42 = value.M41 * num16 + value.M42 * num17 + value.M43 * num18; result.M43 = value.M41 * num19 + value.M42 * num20 + value.M43 * num21; result.M44 = value.M44; return result; } public unsafe static Matrix4x4 Transpose(Matrix4x4 matrix) { if (AdvSimd.Arm64.IsSupported) { } if (Sse.IsSupported) { Vector128 left = Sse.LoadVector128(&matrix.M11); Vector128 right = Sse.LoadVector128(&matrix.M21); Vector128 left2 = Sse.LoadVector128(&matrix.M31); Vector128 right2 = Sse.LoadVector128(&matrix.M41); Vector128 vector = Sse.UnpackLow(left, right); Vector128 vector2 = Sse.UnpackLow(left2, right2); Vector128 vector3 = Sse.UnpackHigh(left, right); Vector128 vector4 = Sse.UnpackHigh(left2, right2); Sse.Store(&matrix.M11, Sse.MoveLowToHigh(vector, vector2)); Sse.Store(&matrix.M21, Sse.MoveHighToLow(vector2, vector)); Sse.Store(&matrix.M31, Sse.MoveLowToHigh(vector3, vector4)); Sse.Store(&matrix.M41, Sse.MoveHighToLow(vector4, vector3)); return matrix; } System.Runtime.CompilerServices.Unsafe.SkipInit(out Matrix4x4 result); result.M11 = matrix.M11; result.M12 = matrix.M21; result.M13 = matrix.M31; result.M14 = matrix.M41; result.M21 = matrix.M12; result.M22 = matrix.M22; result.M23 = matrix.M32; result.M24 = matrix.M42; result.M31 = matrix.M13; result.M32 = matrix.M23; result.M33 = matrix.M33; result.M34 = matrix.M43; result.M41 = matrix.M14; result.M42 = matrix.M24; result.M43 = matrix.M34; result.M44 = matrix.M44; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override readonly bool Equals([NotNullWhen(true)] object? obj) { if (obj is Matrix4x4 other) { return Equals(other); } return false; } public readonly bool Equals(Matrix4x4 other) { return this == other; } public readonly float GetDeterminant() { float m = M11; float m2 = M12; float m3 = M13; float m4 = M14; float m5 = M21; float m6 = M22; float m7 = M23; float m8 = M24; float m9 = M31; float m10 = M32; float m11 = M33; float m12 = M34; float m13 = M41; float m14 = M42; float m15 = M43; float m16 = M44; float num = m11 * m16 - m12 * m15; float num2 = m10 * m16 - m12 * m14; float num3 = m10 * m15 - m11 * m14; float num4 = m9 * m16 - m12 * m13; float num5 = m9 * m15 - m11 * m13; float num6 = m9 * m14 - m10 * m13; return m * (m6 * num - m7 * num2 + m8 * num3) - m2 * (m5 * num - m7 * num4 + m8 * num5) + m3 * (m5 * num2 - m6 * num4 + m8 * num6) - m4 * (m5 * num3 - m6 * num5 + m7 * num6); } public override readonly int GetHashCode() { HashCode hashCode = default(HashCode); hashCode.Add(M11); hashCode.Add(M12); hashCode.Add(M13); hashCode.Add(M14); hashCode.Add(M21); hashCode.Add(M22); hashCode.Add(M23); hashCode.Add(M24); hashCode.Add(M31); hashCode.Add(M32); hashCode.Add(M33); hashCode.Add(M34); hashCode.Add(M41); hashCode.Add(M42); hashCode.Add(M43); hashCode.Add(M44); return hashCode.ToHashCode(); } public override readonly string ToString() { return $"{{ {{M11:{M11} M12:{M12} M13:{M13} M14:{M14}}} {{M21:{M21} M22:{M22} M23:{M23} M24:{M24}}} {{M31:{M31} M32:{M32} M33:{M33} M34:{M34}}} {{M41:{M41} M42:{M42} M43:{M43} M44:{M44}}} }}"; } } [Intrinsic] public struct Plane : IEquatable { public Vector3 Normal; public float D; public Plane(float x, float y, float z, float d) { Normal = new Vector3(x, y, z); D = d; } public Plane(Vector3 normal, float d) { Normal = normal; D = d; } public Plane(Vector4 value) { Normal = new Vector3(value.X, value.Y, value.Z); D = value.W; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane CreateFromVertices(Vector3 point1, Vector3 point2, Vector3 point3) { if (Vector.IsHardwareAccelerated) { Vector3 vector = point2 - point1; Vector3 vector2 = point3 - point1; Vector3 value = Vector3.Cross(vector, vector2); Vector3 vector3 = Vector3.Normalize(value); float d = 0f - Vector3.Dot(vector3, point1); return new Plane(vector3, d); } float num = point2.X - point1.X; float num2 = point2.Y - point1.Y; float num3 = point2.Z - point1.Z; float num4 = point3.X - point1.X; float num5 = point3.Y - point1.Y; float num6 = point3.Z - point1.Z; float num7 = num2 * num6 - num3 * num5; float num8 = num3 * num4 - num * num6; float num9 = num * num5 - num2 * num4; float x = num7 * num7 + num8 * num8 + num9 * num9; float num10 = 1f / MathF.Sqrt(x); Vector3 normal = new Vector3(num7 * num10, num8 * num10, num9 * num10); return new Plane(normal, 0f - (normal.X * point1.X + normal.Y * point1.Y + normal.Z * point1.Z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Dot(Plane plane, Vector4 value) { return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z + plane.D * value.W; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DotCoordinate(Plane plane, Vector3 value) { if (Vector.IsHardwareAccelerated) { return Vector3.Dot(plane.Normal, value) + plane.D; } return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z + plane.D; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DotNormal(Plane plane, Vector3 value) { if (Vector.IsHardwareAccelerated) { return Vector3.Dot(plane.Normal, value); } return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Normalize(Plane value) { if (Vector.IsHardwareAccelerated) { float num = value.Normal.LengthSquared(); if (MathF.Abs(num - 1f) < 1.1920929E-07f) { return value; } float num2 = MathF.Sqrt(num); return new Plane(value.Normal / num2, value.D / num2); } float num3 = value.Normal.X * value.Normal.X + value.Normal.Y * value.Normal.Y + value.Normal.Z * value.Normal.Z; if (MathF.Abs(num3 - 1f) < 1.1920929E-07f) { return value; } float num4 = 1f / MathF.Sqrt(num3); return new Plane(value.Normal.X * num4, value.Normal.Y * num4, value.Normal.Z * num4, value.D * num4); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Transform(Plane plane, Matrix4x4 matrix) { Matrix4x4.Invert(matrix, out var result); float x = plane.Normal.X; float y = plane.Normal.Y; float z = plane.Normal.Z; float d = plane.D; return new Plane(x * result.M11 + y * result.M12 + z * result.M13 + d * result.M14, x * result.M21 + y * result.M22 + z * result.M23 + d * result.M24, x * result.M31 + y * result.M32 + z * result.M33 + d * result.M34, x * result.M41 + y * result.M42 + z * result.M43 + d * result.M44); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Plane Transform(Plane plane, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num; float num5 = rotation.W * num2; float num6 = rotation.W * num3; float num7 = rotation.X * num; float num8 = rotation.X * num2; float num9 = rotation.X * num3; float num10 = rotation.Y * num2; float num11 = rotation.Y * num3; float num12 = rotation.Z * num3; float num13 = 1f - num10 - num12; float num14 = num8 - num6; float num15 = num9 + num5; float num16 = num8 + num6; float num17 = 1f - num7 - num12; float num18 = num11 - num4; float num19 = num9 - num5; float num20 = num11 + num4; float num21 = 1f - num7 - num10; float x = plane.Normal.X; float y = plane.Normal.Y; float z = plane.Normal.Z; return new Plane(x * num13 + y * num14 + z * num15, x * num16 + y * num17 + z * num18, x * num19 + y * num20 + z * num21, plane.D); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Plane value1, Plane value2) { if (value1.Normal.X == value2.Normal.X && value1.Normal.Y == value2.Normal.Y && value1.Normal.Z == value2.Normal.Z) { return value1.D == value2.D; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Plane value1, Plane value2) { return !(value1 == value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override readonly bool Equals([NotNullWhen(true)] object? obj) { if (obj is Plane other) { return Equals(other); } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly bool Equals(Plane other) { if (Vector.IsHardwareAccelerated) { if (Normal.Equals(other.Normal)) { return D == other.D; } return false; } if (Normal.X == other.Normal.X && Normal.Y == other.Normal.Y && Normal.Z == other.Normal.Z) { return D == other.D; } return false; } public override readonly int GetHashCode() { return Normal.GetHashCode() + D.GetHashCode(); } public override readonly string ToString() { return $"{{Normal:{Normal} D:{D}}}"; } } [Intrinsic] public struct Quaternion : IEquatable { public float X; public float Y; public float Z; public float W; public static Quaternion Identity => new Quaternion(0f, 0f, 0f, 1f); public readonly bool IsIdentity => this == Identity; public Quaternion(float x, float y, float z, float w) { X = x; Y = y; Z = z; W = w; } public Quaternion(Vector3 vectorPart, float scalarPart) { X = vectorPart.X; Y = vectorPart.Y; Z = vectorPart.Z; W = scalarPart; } public static Quaternion operator +(Quaternion value1, Quaternion value2) { System.Runtime.CompilerServices.Unsafe.SkipInit(out Quaternion result); result.X = value1.X + value2.X; result.Y = value1.Y + value2.Y; result.Z = value1.Z + value2.Z; result.W = value1.W + value2.W; return result; } public static Quaternion operator /(Quaternion value1, Quaternion value2) { float x = value1.X; float y = value1.Y; float z = value1.Z; float w = value1.W; float num = value2.X * value2.X + value2.Y * value2.Y + value2.Z * value2.Z + value2.W * value2.W; float num2 = 1f / num; float num3 = (0f - value2.X) * num2; float num4 = (0f - value2.Y) * num2; float num5 = (0f - value2.Z) * num2; float num6 = value2.W * num2; float num7 = y * num5 - z * num4; float num8 = z * num3 - x * num5; float num9 = x * num4 - y * num3; float num10 = x * num3 + y * num4 + z * num5; System.Runtime.CompilerServices.Unsafe.SkipInit(out Quaternion result); result.X = x * num6 + num3 * w + num7; result.Y = y * num6 + num4 * w + num8; result.Z = z * num6 + num5 * w + num9; result.W = w * num6 - num10; return result; } public static bool operator ==(Quaternion value1, Quaternion value2) { if (value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z) { return value1.W == value2.W; } return false; } public static bool operator !=(Quaternion value1, Quaternion value2) { return !(value1 == value2); } public static Quaternion operator *(Quaternion value1, Quaternion value2) { float x = value1.X; float y = value1.Y; float z = value1.Z; float w = value1.W; float x2 = value2.X; float y2 = value2.Y; float z2 = value2.Z; float w2 = value2.W; float num = y * z2 - z * y2; float num2 = z * x2 - x * z2; float num3 = x * y2 - y * x2; float num4 = x * x2 + y * y2 + z * z2; System.Runtime.CompilerServices.Unsafe.SkipInit(out Quaternion result); result.X = x * w2 + x2 * w + num; result.Y = y * w2 + y2 * w + num2; result.Z = z * w2 + z2 * w + num3; result.W = w * w2 - num4; return result; } public static Quaternion operator *(Quaternion value1, float value2) { System.Runtime.CompilerServices.Unsafe.SkipInit(out Quaternion result); result.X = value1.X * value2; result.Y = value1.Y * value2; result.Z = value1.Z * value2; result.W = value1.W * value2; return result; } public static Quaternion operator -(Quaternion value1, Quaternion value2) { System.Runtime.CompilerServices.Unsafe.SkipInit(out Quaternion result); result.X = value1.X - value2.X; result.Y = value1.Y - value2.Y; result.Z = value1.Z - value2.Z; result.W = value1.W - value2.W; return result; } public static Quaternion operator -(Quaternion value) { System.Runtime.CompilerServices.Unsafe.SkipInit(out Quaternion result); result.X = 0f - value.X; result.Y = 0f - value.Y; result.Z = 0f - value.Z; result.W = 0f - value.W; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion Add(Quaternion value1, Quaternion value2) { return value1 + value2; } public static Quaternion Concatenate(Quaternion value1, Quaternion value2) { float x = value2.X; float y = value2.Y; float z = value2.Z; float w = value2.W; float x2 = value1.X; float y2 = value1.Y; float z2 = value1.Z; float w2 = value1.W; float num = y * z2 - z * y2; float num2 = z * x2 - x * z2; float num3 = x * y2 - y * x2; float num4 = x * x2 + y * y2 + z * z2; System.Runtime.CompilerServices.Unsafe.SkipInit(out Quaternion result); result.X = x * w2 + x2 * w + num; result.Y = y * w2 + y2 * w + num2; result.Z = z * w2 + z2 * w + num3; result.W = w * w2 - num4; return result; } public static Quaternion Conjugate(Quaternion value) { System.Runtime.CompilerServices.Unsafe.SkipInit(out Quaternion result); result.X = 0f - value.X; result.Y = 0f - value.Y; result.Z = 0f - value.Z; result.W = value.W; return result; } public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle) { float x = angle * 0.5f; float num = MathF.Sin(x); float w = MathF.Cos(x); System.Runtime.CompilerServices.Unsafe.SkipInit(out Quaternion result); result.X = axis.X * num; result.Y = axis.Y * num; result.Z = axis.Z * num; result.W = w; return result; } public static Quaternion CreateFromRotationMatrix(Matrix4x4 matrix) { float num = matrix.M11 + matrix.M22 + matrix.M33; Quaternion result = default(Quaternion); if (num > 0f) { float num2 = MathF.Sqrt(num + 1f); result.W = num2 * 0.5f; num2 = 0.5f / num2; result.X = (matrix.M23 - matrix.M32) * num2; result.Y = (matrix.M31 - matrix.M13) * num2; result.Z = (matrix.M12 - matrix.M21) * num2; } else if (matrix.M11 >= matrix.M22 && matrix.M11 >= matrix.M33) { float num3 = MathF.Sqrt(1f + matrix.M11 - matrix.M22 - matrix.M33); float num4 = 0.5f / num3; result.X = 0.5f * num3; result.Y = (matrix.M12 + matrix.M21) * num4; result.Z = (matrix.M13 + matrix.M31) * num4; result.W = (matrix.M23 - matrix.M32) * num4; } else if (matrix.M22 > matrix.M33) { float num5 = MathF.Sqrt(1f + matrix.M22 - matrix.M11 - matrix.M33); float num6 = 0.5f / num5; result.X = (matrix.M21 + matrix.M12) * num6; result.Y = 0.5f * num5; result.Z = (matrix.M32 + matrix.M23) * num6; result.W = (matrix.M31 - matrix.M13) * num6; } else { float num7 = MathF.Sqrt(1f + matrix.M33 - matrix.M11 - matrix.M22); float num8 = 0.5f / num7; result.X = (matrix.M31 + matrix.M13) * num8; result.Y = (matrix.M32 + matrix.M23) * num8; result.Z = 0.5f * num7; result.W = (matrix.M12 - matrix.M21) * num8; } return result; } public static Quaternion CreateFromYawPitchRoll(float yaw, float pitch, float roll) { float x = roll * 0.5f; float num = MathF.Sin(x); float num2 = MathF.Cos(x); float x2 = pitch * 0.5f; float num3 = MathF.Sin(x2); float num4 = MathF.Cos(x2); float x3 = yaw * 0.5f; float num5 = MathF.Sin(x3); float num6 = MathF.Cos(x3); System.Runtime.CompilerServices.Unsafe.SkipInit(out Quaternion result); result.X = num6 * num3 * num2 + num5 * num4 * num; result.Y = num5 * num4 * num2 - num6 * num3 * num; result.Z = num6 * num4 * num - num5 * num3 * num2; result.W = num6 * num4 * num2 + num5 * num3 * num; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion Divide(Quaternion value1, Quaternion value2) { return value1 / value2; } public static float Dot(Quaternion quaternion1, Quaternion quaternion2) { return quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W; } public static Quaternion Inverse(Quaternion value) { float num = value.X * value.X + value.Y * value.Y + value.Z * value.Z + value.W * value.W; float num2 = 1f / num; System.Runtime.CompilerServices.Unsafe.SkipInit(out Quaternion result); result.X = (0f - value.X) * num2; result.Y = (0f - value.Y) * num2; result.Z = (0f - value.Z) * num2; result.W = value.W * num2; return result; } public static Quaternion Lerp(Quaternion quaternion1, Quaternion quaternion2, float amount) { float num = 1f - amount; Quaternion result = default(Quaternion); float num2 = quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W; if (num2 >= 0f) { result.X = num * quaternion1.X + amount * quaternion2.X; result.Y = num * quaternion1.Y + amount * quaternion2.Y; result.Z = num * quaternion1.Z + amount * quaternion2.Z; result.W = num * quaternion1.W + amount * quaternion2.W; } else { result.X = num * quaternion1.X - amount * quaternion2.X; result.Y = num * quaternion1.Y - amount * quaternion2.Y; result.Z = num * quaternion1.Z - amount * quaternion2.Z; result.W = num * quaternion1.W - amount * quaternion2.W; } float x = result.X * result.X + result.Y * result.Y + result.Z * result.Z + result.W * result.W; float num3 = 1f / MathF.Sqrt(x); result.X *= num3; result.Y *= num3; result.Z *= num3; result.W *= num3; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion Multiply(Quaternion value1, Quaternion value2) { return value1 * value2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion Multiply(Quaternion value1, float value2) { return value1 * value2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion Negate(Quaternion value) { return -value; } public static Quaternion Normalize(Quaternion value) { float x = value.X * value.X + value.Y * value.Y + value.Z * value.Z + value.W * value.W; float num = 1f / MathF.Sqrt(x); System.Runtime.CompilerServices.Unsafe.SkipInit(out Quaternion result); result.X = value.X * num; result.Y = value.Y * num; result.Z = value.Z * num; result.W = value.W * num; return result; } public static Quaternion Slerp(Quaternion quaternion1, Quaternion quaternion2, float amount) { float num = quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W; bool flag = false; if (num < 0f) { flag = true; num = 0f - num; } float num2; float num3; if (num > 0.999999f) { num2 = 1f - amount; num3 = (flag ? (0f - amount) : amount); } else { float num4 = MathF.Acos(num); float num5 = 1f / MathF.Sin(num4); num2 = MathF.Sin((1f - amount) * num4) * num5; num3 = (flag ? ((0f - MathF.Sin(amount * num4)) * num5) : (MathF.Sin(amount * num4) * num5)); } System.Runtime.CompilerServices.Unsafe.SkipInit(out Quaternion result); result.X = num2 * quaternion1.X + num3 * quaternion2.X; result.Y = num2 * quaternion1.Y + num3 * quaternion2.Y; result.Z = num2 * quaternion1.Z + num3 * quaternion2.Z; result.W = num2 * quaternion1.W + num3 * quaternion2.W; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Quaternion Subtract(Quaternion value1, Quaternion value2) { return value1 - value2; } public override readonly bool Equals([NotNullWhen(true)] object? obj) { if (obj is Quaternion other) { return Equals(other); } return false; } public readonly bool Equals(Quaternion other) { return this == other; } public override readonly int GetHashCode() { return X.GetHashCode() + Y.GetHashCode() + Z.GetHashCode() + W.GetHashCode(); } public readonly float Length() { float x = LengthSquared(); return MathF.Sqrt(x); } public readonly float LengthSquared() { return X * X + Y * Y + Z * Z + W * W; } public override readonly string ToString() { return $"{{X:{X} Y:{Y} Z:{Z} W:{W}}}"; } } [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; } [Intrinsic] public static class Vector { public static bool IsHardwareAccelerated { [Intrinsic] get { return false; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector ConditionalSelect(Vector condition, Vector left, Vector right) { return Vector.ConditionalSelect((Vector)condition, left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector ConditionalSelect(Vector condition, Vector left, Vector right) { return Vector.ConditionalSelect((Vector)condition, left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector ConditionalSelect(Vector condition, Vector left, Vector right) where T : struct { return Vector.ConditionalSelect(condition, left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector Equals(Vector left, Vector right) where T : struct { return Vector.Equals(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector Equals(Vector left, Vector right) { return (Vector)Vector.Equals(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector Equals(Vector left, Vector right) { return Vector.Equals(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector Equals(Vector left, Vector right) { return (Vector)Vector.Equals(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector Equals(Vector left, Vector right) { return Vector.Equals(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EqualsAll(Vector left, Vector right) where T : struct { return left == right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EqualsAny(Vector left, Vector right) where T : struct { return !Vector.Equals(left, right).Equals(Vector.Zero); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector LessThan(Vector left, Vector right) where T : struct { return Vector.LessThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector LessThan(Vector left, Vector right) { return (Vector)Vector.LessThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector LessThan(Vector left, Vector right) { return Vector.LessThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector LessThan(Vector left, Vector right) { return (Vector)Vector.LessThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector LessThan(Vector left, Vector right) { return Vector.LessThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool LessThanAll(Vector left, Vector right) where T : struct { return ((Vector)Vector.LessThan(left, right)).Equals(Vector.AllBitsSet); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool LessThanAny(Vector left, Vector right) where T : struct { return !((Vector)Vector.LessThan(left, right)).Equals(Vector.Zero); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector LessThanOrEqual(Vector left, Vector right) where T : struct { return Vector.LessThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector LessThanOrEqual(Vector left, Vector right) { return (Vector)Vector.LessThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector LessThanOrEqual(Vector left, Vector right) { return Vector.LessThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector LessThanOrEqual(Vector left, Vector right) { return Vector.LessThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector LessThanOrEqual(Vector left, Vector right) { return (Vector)Vector.LessThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool LessThanOrEqualAll(Vector left, Vector right) where T : struct { return ((Vector)Vector.LessThanOrEqual(left, right)).Equals(Vector.AllBitsSet); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool LessThanOrEqualAny(Vector left, Vector right) where T : struct { return !((Vector)Vector.LessThanOrEqual(left, right)).Equals(Vector.Zero); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector GreaterThan(Vector left, Vector right) where T : struct { return Vector.GreaterThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector GreaterThan(Vector left, Vector right) { return (Vector)Vector.GreaterThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector GreaterThan(Vector left, Vector right) { return Vector.GreaterThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector GreaterThan(Vector left, Vector right) { return (Vector)Vector.GreaterThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector GreaterThan(Vector left, Vector right) { return Vector.GreaterThan(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanAll(Vector left, Vector right) where T : struct { return ((Vector)Vector.GreaterThan(left, right)).Equals(Vector.AllBitsSet); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanAny(Vector left, Vector right) where T : struct { return !((Vector)Vector.GreaterThan(left, right)).Equals(Vector.Zero); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector GreaterThanOrEqual(Vector left, Vector right) where T : struct { return Vector.GreaterThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector GreaterThanOrEqual(Vector left, Vector right) { return (Vector)Vector.GreaterThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector GreaterThanOrEqual(Vector left, Vector right) { return Vector.GreaterThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector GreaterThanOrEqual(Vector left, Vector right) { return Vector.GreaterThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector GreaterThanOrEqual(Vector left, Vector right) { return (Vector)Vector.GreaterThanOrEqual(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanOrEqualAll(Vector left, Vector right) where T : struct { return ((Vector)Vector.GreaterThanOrEqual(left, right)).Equals(Vector.AllBitsSet); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GreaterThanOrEqualAny(Vector left, Vector right) where T : struct { return !((Vector)Vector.GreaterThanOrEqual(left, right)).Equals(Vector.Zero); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector Abs(Vector value) where T : struct { return Vector.Abs(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector Min(Vector left, Vector right) where T : struct { return Vector.Min(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector Max(Vector left, Vector right) where T : struct { return Vector.Max(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static T Dot(Vector left, Vector right) where T : struct { return Vector.Dot(left, right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector SquareRoot(Vector value) where T : struct { return Vector.SquareRoot(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector Ceiling(Vector value) { return Vector.Ceiling(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector Ceiling(Vector value) { return Vector.Ceiling(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector Floor(Vector value) { return Vector.Floor(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector Floor(Vector value) { return Vector.Floor(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Add(Vector left, Vector right) where T : struct { return left + right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Subtract(Vector left, Vector right) where T : struct { return left - right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Multiply(Vector left, Vector right) where T : struct { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Multiply(Vector left, T right) where T : struct { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Multiply(T left, Vector right) where T : struct { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Divide(Vector left, Vector right) where T : struct { return left / right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Negate(Vector value) where T : struct { return -value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector BitwiseAnd(Vector left, Vector right) where T : struct { return left & right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector BitwiseOr(Vector left, Vector right) where T : struct { return left | right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector OnesComplement(Vector value) where T : struct { return ~value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector Xor(Vector left, Vector right) where T : struct { return left ^ right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector AndNot(Vector left, Vector right) where T : struct { return left & ~right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector AsVectorByte(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector AsVectorSByte(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector AsVectorUInt16(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector AsVectorInt16(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector AsVectorUInt32(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector AsVectorInt32(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector AsVectorUInt64(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector AsVectorInt64(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector AsVectorSingle(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector AsVectorDouble(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector AsVectorNUInt(Vector value) where T : struct { return (Vector)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector AsVectorNInt(Vector value) where T : struct { return (Vector)value; } [CLSCompliant(false)] [Intrinsic] public unsafe static void Widen(Vector source, out Vector low, out Vector high) { int count = Vector.Count; ushort* ptr = stackalloc ushort[count / 2]; for (int i = 0; i < count / 2; i++) { ptr[i] = source[i]; } ushort* ptr2 = stackalloc ushort[count / 2]; for (int j = 0; j < count / 2; j++) { ptr2[j] = source[j + count / 2]; } low = *(Vector*)ptr; high = *(Vector*)ptr2; } [CLSCompliant(false)] [Intrinsic] public unsafe static void Widen(Vector source, out Vector low, out Vector high) { int count = Vector.Count; uint* ptr = stackalloc uint[count / 2]; for (int i = 0; i < count / 2; i++) { ptr[i] = source[i]; } uint* ptr2 = stackalloc uint[count / 2]; for (int j = 0; j < count / 2; j++) { ptr2[j] = source[j + count / 2]; } low = *(Vector*)ptr; high = *(Vector*)ptr2; } [CLSCompliant(false)] [Intrinsic] public unsafe static void Widen(Vector source, out Vector low, out Vector high) { int count = Vector.Count; ulong* ptr = stackalloc ulong[count / 2]; for (int i = 0; i < count / 2; i++) { ptr[i] = source[i]; } ulong* ptr2 = stackalloc ulong[count / 2]; for (int j = 0; j < count / 2; j++) { ptr2[j] = source[j + count / 2]; } low = *(Vector*)ptr; high = *(Vector*)ptr2; } [CLSCompliant(false)] [Intrinsic] public unsafe static void Widen(Vector source, out Vector low, out Vector high) { int count = Vector.Count; short* ptr = stackalloc short[count / 2]; for (int i = 0; i < count / 2; i++) { ptr[i] = source[i]; } short* ptr2 = stackalloc short[count / 2]; for (int j = 0; j < count / 2; j++) { ptr2[j] = source[j + count / 2]; } low = *(Vector*)ptr; high = *(Vector*)ptr2; } [Intrinsic] public unsafe static void Widen(Vector source, out Vector low, out Vector high) { int count = Vector.Count; int* ptr = stackalloc int[count / 2]; for (int i = 0; i < count / 2; i++) { ptr[i] = source[i]; } int* ptr2 = stackalloc int[count / 2]; for (int j = 0; j < count / 2; j++) { ptr2[j] = source[j + count / 2]; } low = *(Vector*)ptr; high = *(Vector*)ptr2; } [Intrinsic] public unsafe static void Widen(Vector source, out Vector low, out Vector high) { int count = Vector.Count; long* ptr = stackalloc long[count / 2]; for (int i = 0; i < count / 2; i++) { ptr[i] = source[i]; } long* ptr2 = stackalloc long[count / 2]; for (int j = 0; j < count / 2; j++) { ptr2[j] = source[j + count / 2]; } low = *(Vector*)ptr; high = *(Vector*)ptr2; } [Intrinsic] public unsafe static void Widen(Vector source, out Vector low, out Vector high) { int count = Vector.Count; double* ptr = stackalloc double[count / 2]; for (int i = 0; i < count / 2; i++) { ptr[i] = source[i]; } double* ptr2 = stackalloc double[count / 2]; for (int j = 0; j < count / 2; j++) { ptr2[j] = source[j + count / 2]; } low = *(Vector*)ptr; high = *(Vector*)ptr2; } [CLSCompliant(false)] [Intrinsic] public unsafe static Vector Narrow(Vector low, Vector high) { int count = Vector.Count; byte* ptr = stackalloc byte[(int)(uint)count]; for (int i = 0; i < count / 2; i++) { ptr[i] = (byte)low[i]; } for (int j = 0; j < count / 2; j++) { ptr[j + count / 2] = (byte)high[j]; } return *(Vector*)ptr; } [CLSCompliant(false)] [Intrinsic] public unsafe static Vector Narrow(Vector low, Vector high) { int count = Vector.Count; ushort* ptr = stackalloc ushort[count]; for (int i = 0; i < count / 2; i++) { ptr[i] = (ushort)low[i]; } for (int j = 0; j < count / 2; j++) { ptr[j + count / 2] = (ushort)high[j]; } return *(Vector*)ptr; } [CLSCompliant(false)] [Intrinsic] public unsafe static Vector Narrow(Vector low, Vector high) { int count = Vector.Count; uint* ptr = stackalloc uint[count]; for (int i = 0; i < count / 2; i++) { ptr[i] = (uint)low[i]; } for (int j = 0; j < count / 2; j++) { ptr[j + count / 2] = (uint)high[j]; } return *(Vector*)ptr; } [CLSCompliant(false)] [Intrinsic] public unsafe static Vector Narrow(Vector low, Vector high) { int count = Vector.Count; sbyte* ptr = stackalloc sbyte[(int)(uint)count]; for (int i = 0; i < count / 2; i++) { ptr[i] = (sbyte)low[i]; } for (int j = 0; j < count / 2; j++) { ptr[j + count / 2] = (sbyte)high[j]; } return *(Vector*)ptr; } [Intrinsic] public unsafe static Vector Narrow(Vector low, Vector high) { int count = Vector.Count; short* ptr = stackalloc short[count]; for (int i = 0; i < count / 2; i++) { ptr[i] = (short)low[i]; } for (int j = 0; j < count / 2; j++) { ptr[j + count / 2] = (short)high[j]; } return *(Vector*)ptr; } [Intrinsic] public unsafe static Vector Narrow(Vector low, Vector high) { int count = Vector.Count; int* ptr = stackalloc int[count]; for (int i = 0; i < count / 2; i++) { ptr[i] = (int)low[i]; } for (int j = 0; j < count / 2; j++) { ptr[j + count / 2] = (int)high[j]; } return *(Vector*)ptr; } [Intrinsic] public unsafe static Vector Narrow(Vector low, Vector high) { int count = Vector.Count; float* ptr = stackalloc float[count]; for (int i = 0; i < count / 2; i++) { ptr[i] = (float)low[i]; } for (int j = 0; j < count / 2; j++) { ptr[j + count / 2] = (float)high[j]; } return *(Vector*)ptr; } [Intrinsic] public unsafe static Vector ConvertToSingle(Vector value) { int count = Vector.Count; float* ptr = stackalloc float[count]; for (int i = 0; i < count; i++) { ptr[i] = value[i]; } return *(Vector*)ptr; } [CLSCompliant(false)] [Intrinsic] public unsafe static Vector ConvertToSingle(Vector value) { int count = Vector.Count; float* ptr = stackalloc float[count]; for (int i = 0; i < count; i++) { ptr[i] = value[i]; } return *(Vector*)ptr; } [Intrinsic] public unsafe static Vector ConvertToDouble(Vector value) { int count = Vector.Count; double* ptr = stackalloc double[count]; for (int i = 0; i < count; i++) { ptr[i] = value[i]; } return *(Vector*)ptr; } [CLSCompliant(false)] [Intrinsic] public unsafe static Vector ConvertToDouble(Vector value) { int count = Vector.Count; double* ptr = stackalloc double[count]; for (int i = 0; i < count; i++) { ptr[i] = value[i]; } return *(Vector*)ptr; } [Intrinsic] public unsafe static Vector ConvertToInt32(Vector value) { int count = Vector.Count; int* ptr = stackalloc int[count]; for (int i = 0; i < count; i++) { ptr[i] = (int)value[i]; } return *(Vector*)ptr; } [CLSCompliant(false)] [Intrinsic] public unsafe static Vector ConvertToUInt32(Vector value) { int count = Vector.Count; uint* ptr = stackalloc uint[count]; for (int i = 0; i < count; i++) { ptr[i] = (uint)value[i]; } return *(Vector*)ptr; } [Intrinsic] public unsafe static Vector ConvertToInt64(Vector value) { int count = Vector.Count; long* ptr = stackalloc long[count]; for (int i = 0; i < count; i++) { ptr[i] = (long)value[i]; } return *(Vector*)ptr; } [CLSCompliant(false)] [Intrinsic] public unsafe static Vector ConvertToUInt64(Vector value) { int count = Vector.Count; ulong* ptr = stackalloc ulong[count]; for (int i = 0; i < count; i++) { ptr[i] = (ulong)value[i]; } return *(Vector*)ptr; } [DoesNotReturn] internal static void ThrowInsufficientNumberOfElementsException(int requiredElementCount) { throw new IndexOutOfRangeException(SR.Format(SR.Arg_InsufficientNumberOfElements, requiredElementCount, "values")); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector As(this Vector vector) where TFrom : struct where TTo : struct { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return Unsafe.As, Vector>(ref vector); } [Intrinsic] public static T Sum(Vector value) where T : struct { return Vector.Sum(value); } } [Intrinsic] public struct Vector : IEquatable>, IFormattable where T : struct { private Register register; public static int Count { [Intrinsic] get { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return Unsafe.SizeOf>() / Unsafe.SizeOf(); } } public static Vector Zero { [Intrinsic] get { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return default(Vector); } } public static Vector One { [Intrinsic] get { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return new Vector(GetOneValue()); } } internal static Vector AllBitsSet { [Intrinsic] get { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return new Vector(GetAllBitsSetValue()); } } public readonly T this[int index] { [Intrinsic] get { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); if ((uint)index >= (uint)Count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return GetElement(index); } } [Intrinsic] public Vector(T value) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); Unsafe.SkipInit>(out this); for (nint num = 0; num < Count; num++) { SetElement(num, value); } } [Intrinsic] public Vector(T[] values) : this(values, 0) { } [Intrinsic] public Vector(T[] values, int index) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); if (values == null) { throw new NullReferenceException(SR.Arg_NullArgumentNullRef); } if (index < 0 || values.Length - index < Count) { Vector.ThrowInsufficientNumberOfElementsException(Count); } this = Unsafe.ReadUnaligned>(ref Unsafe.As(ref values[index])); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector(ReadOnlySpan values) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); if (values.Length < Vector.Count) { Vector.ThrowInsufficientNumberOfElementsException(Vector.Count); } this = Unsafe.ReadUnaligned>(ref MemoryMarshal.GetReference(values)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector(ReadOnlySpan values) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); if (values.Length < Count) { Vector.ThrowInsufficientNumberOfElementsException(Count); } this = Unsafe.ReadUnaligned>(ref Unsafe.As(ref MemoryMarshal.GetReference(values))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Vector(Span values) : this((ReadOnlySpan)values) { } public readonly void CopyTo(Span destination) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); if ((uint)destination.Length < (uint)Vector.Count) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), this); } public readonly void CopyTo(Span destination) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); if ((uint)destination.Length < (uint)Count) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } Unsafe.WriteUnaligned(ref Unsafe.As(ref MemoryMarshal.GetReference(destination)), this); } [Intrinsic] public readonly void CopyTo(T[] destination) { CopyTo(destination, 0); } [Intrinsic] public readonly void CopyTo(T[] destination, int startIndex) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); if (destination == null) { throw new NullReferenceException(SR.Arg_NullArgumentNullRef); } if ((uint)startIndex >= (uint)destination.Length) { throw new ArgumentOutOfRangeException("startIndex", SR.Format(SR.Arg_ArgumentOutOfRangeException, startIndex)); } if (destination.Length - startIndex < Count) { throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, startIndex)); } Unsafe.WriteUnaligned(ref Unsafe.As(ref destination[startIndex]), this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override readonly bool Equals([NotNullWhen(true)] object? obj) { if (obj is Vector other) { return Equals(other); } return false; } [Intrinsic] public readonly bool Equals(Vector other) { return this == other; } public override readonly int GetHashCode() { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); HashCode hashCode = default(HashCode); for (nint num = 0; num < Count; num++) { hashCode.Add(GetElement(num)); } return hashCode.ToHashCode(); } public override readonly string ToString() { return ToString("G", CultureInfo.CurrentCulture); } public readonly string ToString(string? format) { return ToString(format, CultureInfo.CurrentCulture); } public readonly string ToString(string? format, IFormatProvider? formatProvider) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); StringBuilder stringBuilder = new StringBuilder(); string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; stringBuilder.Append('<'); for (int i = 0; i < Count - 1; i++) { stringBuilder.Append(((IFormattable)(object)GetElement(i)).ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); } stringBuilder.Append(((IFormattable)(object)GetElement(Count - 1)).ToString(format, formatProvider)); stringBuilder.Append('>'); return stringBuilder.ToString(); } public readonly bool TryCopyTo(Span destination) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); if ((uint)destination.Length < (uint)Vector.Count) { return false; } Unsafe.WriteUnaligned(ref MemoryMarshal.GetReference(destination), this); return true; } public readonly bool TryCopyTo(Span destination) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); if ((uint)destination.Length < (uint)Count) { return false; } Unsafe.WriteUnaligned(ref Unsafe.As(ref MemoryMarshal.GetReference(destination)), this); return true; } [Intrinsic] public static Vectoroperator +(Vector left, Vector right) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { result.SetElement(num, ScalarAdd(left.GetElement(num), right.GetElement(num))); } return result; } [Intrinsic] public static Vectoroperator -(Vector left, Vector right) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { result.SetElement(num, ScalarSubtract(left.GetElement(num), right.GetElement(num))); } return result; } [Intrinsic] public static Vectoroperator *(Vector left, Vector right) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { result.SetElement(num, ScalarMultiply(left.GetElement(num), right.GetElement(num))); } return result; } [Intrinsic] public static Vectoroperator *(Vector value, T factor) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { result.SetElement(num, ScalarMultiply(value.GetElement(num), factor)); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vectoroperator *(T factor, Vector value) { return value * factor; } [Intrinsic] public static Vectoroperator /(Vector left, Vector right) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { result.SetElement(num, ScalarDivide(left.GetElement(num), right.GetElement(num))); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vectoroperator -(Vector value) { return Zero - value; } [Intrinsic] public static Vectoroperator &(Vector left, Vector right) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); Vector result = default(Vector); result.register.uint64_0 = left.register.uint64_0 & right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 & right.register.uint64_1; return result; } [Intrinsic] public static Vectoroperator |(Vector left, Vector right) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); Vector result = default(Vector); result.register.uint64_0 = left.register.uint64_0 | right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 | right.register.uint64_1; return result; } [Intrinsic] public static Vectoroperator ^(Vector left, Vector right) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); Vector result = default(Vector); result.register.uint64_0 = left.register.uint64_0 ^ right.register.uint64_0; result.register.uint64_1 = left.register.uint64_1 ^ right.register.uint64_1; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vectoroperator ~(Vector value) { return AllBitsSet ^ value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static bool operator ==(Vector left, Vector right) { for (nint num = 0; num < Count; num++) { if (!ScalarEquals(left.GetElement(num), right.GetElement(num))) { return false; } } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static bool operator !=(Vector left, Vector right) { return !(left == right); } [Intrinsic] public static explicit operator Vector(Vector value) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return Unsafe.As, Vector>(ref value); } [CLSCompliant(false)] [Intrinsic] public static explicit operator Vector(Vector value) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return Unsafe.As, Vector>(ref value); } [CLSCompliant(false)] [Intrinsic] public static explicit operator Vector(Vector value) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return Unsafe.As, Vector>(ref value); } [Intrinsic] public static explicit operator Vector(Vector value) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return Unsafe.As, Vector>(ref value); } [CLSCompliant(false)] [Intrinsic] public static explicit operator Vector(Vector value) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return Unsafe.As, Vector>(ref value); } [Intrinsic] public static explicit operator Vector(Vector value) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return Unsafe.As, Vector>(ref value); } [CLSCompliant(false)] [Intrinsic] public static explicit operator Vector(Vector value) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return Unsafe.As, Vector>(ref value); } [Intrinsic] public static explicit operator Vector(Vector value) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return Unsafe.As, Vector>(ref value); } [Intrinsic] public static explicit operator Vector(Vector value) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return Unsafe.As, Vector>(ref value); } [Intrinsic] public static explicit operator Vector(Vector value) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return Unsafe.As, Vector>(ref value); } [CLSCompliant(false)] [Intrinsic] public static explicit operator Vector(Vector value) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return Unsafe.As, Vector>(ref value); } [Intrinsic] public static explicit operator Vector(Vector value) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); return Unsafe.As, Vector>(ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] internal static Vector Equals(Vector left, Vector right) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { T value = (ScalarEquals(left.GetElement(num), right.GetElement(num)) ? GetAllBitsSetValue() : default(T)); result.SetElement(num, value); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] internal static Vector LessThan(Vector left, Vector right) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { T value = (ScalarLessThan(left.GetElement(num), right.GetElement(num)) ? GetAllBitsSetValue() : default(T)); result.SetElement(num, value); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] internal static Vector GreaterThan(Vector left, Vector right) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { T value = (ScalarGreaterThan(left.GetElement(num), right.GetElement(num)) ? GetAllBitsSetValue() : default(T)); result.SetElement(num, value); } return result; } [Intrinsic] internal static Vector GreaterThanOrEqual(Vector left, Vector right) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { T value = (ScalarGreaterThanOrEqual(left.GetElement(num), right.GetElement(num)) ? GetAllBitsSetValue() : default(T)); result.SetElement(num, value); } return result; } [Intrinsic] internal static Vector LessThanOrEqual(Vector left, Vector right) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { T value = (ScalarLessThanOrEqual(left.GetElement(num), right.GetElement(num)) ? GetAllBitsSetValue() : default(T)); result.SetElement(num, value); } return result; } [Intrinsic] internal static Vector ConditionalSelect(Vector condition, Vector left, Vector right) { ThrowHelper.ThrowForUnsupportedNumericsVectorBaseType(); Vector result = default(Vector); result.register.uint64_0 = (left.register.uint64_0 & condition.register.uint64_0) | (right.register.uint64_0 & ~condition.register.uint64_0); result.register.uint64_1 = (left.register.uint64_1 & condition.register.uint64_1) | (right.register.uint64_1 & ~condition.register.uint64_1); return result; } [Intrinsic] internal static Vector Abs(Vector value) { if (typeof(T) == typeof(byte)) { return value; } if (typeof(T) == typeof(ushort)) { return value; } if (typeof(T) == typeof(uint)) { return value; } if (typeof(T) == typeof(ulong)) { return value; } if (typeof(T) == typeof(UIntPtr)) { return value; } Vector result = default(Vector); for (nint num = 0; num < Count; num++) { result.SetElement(num, ScalarAbs(value.GetElement(num))); } return result; } [Intrinsic] internal static Vector Min(Vector left, Vector right) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { T value = (ScalarLessThan(left.GetElement(num), right.GetElement(num)) ? left.GetElement(num) : right.GetElement(num)); result.SetElement(num, value); } return result; } [Intrinsic] internal static Vector Max(Vector left, Vector right) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { T value = (ScalarGreaterThan(left.GetElement(num), right.GetElement(num)) ? left.GetElement(num) : right.GetElement(num)); result.SetElement(num, value); } return result; } [Intrinsic] internal static T Dot(Vector left, Vector right) { T val = default(T); for (nint num = 0; num < Count; num++) { val = ScalarAdd(val, ScalarMultiply(left.GetElement(num), right.GetElement(num))); } return val; } [Intrinsic] internal static T Sum(Vector value) { T val = default(T); for (nint num = 0; num < Count; num++) { val = ScalarAdd(val, value.GetElement(num)); } return val; } [Intrinsic] internal static Vector SquareRoot(Vector value) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { result.SetElement(num, ScalarSqrt(value.GetElement(num))); } return result; } [Intrinsic] internal static Vector Ceiling(Vector value) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { result.SetElement(num, ScalarCeiling(value.GetElement(num))); } return result; } [Intrinsic] internal static Vector Floor(Vector value) { Vector result = default(Vector); for (nint num = 0; num < Count; num++) { result.SetElement(num, ScalarFloor(value.GetElement(num))); } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool ScalarEquals(T left, T right) { if (typeof(T) == typeof(byte)) { return (byte)(object)left == (byte)(object)right; } if (typeof(T) == typeof(sbyte)) { return (sbyte)(object)left == (sbyte)(object)right; } if (typeof(T) == typeof(ushort)) { return (ushort)(object)left == (ushort)(object)right; } if (typeof(T) == typeof(short)) { return (short)(object)left == (short)(object)right; } if (typeof(T) == typeof(uint)) { return (uint)(object)left == (uint)(object)right; } if (typeof(T) == typeof(int)) { return (int)(object)left == (int)(object)right; } if (typeof(T) == typeof(ulong)) { return (ulong)(object)left == (ulong)(object)right; } if (typeof(T) == typeof(long)) { return (long)(object)left == (long)(object)right; } if (typeof(T) == typeof(float)) { return (float)(object)left == (float)(object)right; } if (typeof(T) == typeof(double)) { return (double)(object)left == (double)(object)right; } if (typeof(T) == typeof(UIntPtr)) { return (UIntPtr)(object)left == (UIntPtr)(object)right; } if (typeof(T) == typeof(IntPtr)) { return (IntPtr)(object)left == (IntPtr)(object)right; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool ScalarLessThan(T left, T right) { if (typeof(T) == typeof(byte)) { return (byte)(object)left < (byte)(object)right; } if (typeof(T) == typeof(sbyte)) { return (sbyte)(object)left < (sbyte)(object)right; } if (typeof(T) == typeof(ushort)) { return (ushort)(object)left < (ushort)(object)right; } if (typeof(T) == typeof(short)) { return (short)(object)left < (short)(object)right; } if (typeof(T) == typeof(uint)) { return (uint)(object)left < (uint)(object)right; } if (typeof(T) == typeof(int)) { return (int)(object)left < (int)(object)right; } if (typeof(T) == typeof(ulong)) { return (ulong)(object)left < (ulong)(object)right; } if (typeof(T) == typeof(long)) { return (long)(object)left < (long)(object)right; } if (typeof(T) == typeof(float)) { return (float)(object)left < (float)(object)right; } if (typeof(T) == typeof(double)) { return (double)(object)left < (double)(object)right; } if (typeof(T) == typeof(UIntPtr)) { return (nuint)(UIntPtr)(object)left < (nuint)(UIntPtr)(object)right; } if (typeof(T) == typeof(IntPtr)) { return (nint)(IntPtr)(object)left < (nint)(IntPtr)(object)right; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool ScalarLessThanOrEqual(T left, T right) { if (typeof(T) == typeof(byte)) { return (byte)(object)left <= (byte)(object)right; } if (typeof(T) == typeof(sbyte)) { return (sbyte)(object)left <= (sbyte)(object)right; } if (typeof(T) == typeof(ushort)) { return (ushort)(object)left <= (ushort)(object)right; } if (typeof(T) == typeof(short)) { return (short)(object)left <= (short)(object)right; } if (typeof(T) == typeof(uint)) { return (uint)(object)left <= (uint)(object)right; } if (typeof(T) == typeof(int)) { return (int)(object)left <= (int)(object)right; } if (typeof(T) == typeof(ulong)) { return (ulong)(object)left <= (ulong)(object)right; } if (typeof(T) == typeof(long)) { return (long)(object)left <= (long)(object)right; } if (typeof(T) == typeof(float)) { return (float)(object)left <= (float)(object)right; } if (typeof(T) == typeof(double)) { return (double)(object)left <= (double)(object)right; } if (typeof(T) == typeof(UIntPtr)) { return (nuint)(UIntPtr)(object)left <= (nuint)(UIntPtr)(object)right; } if (typeof(T) == typeof(IntPtr)) { return (nint)(IntPtr)(object)left <= (nint)(IntPtr)(object)right; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool ScalarGreaterThan(T left, T right) { if (typeof(T) == typeof(byte)) { return (byte)(object)left > (byte)(object)right; } if (typeof(T) == typeof(sbyte)) { return (sbyte)(object)left > (sbyte)(object)right; } if (typeof(T) == typeof(ushort)) { return (ushort)(object)left > (ushort)(object)right; } if (typeof(T) == typeof(short)) { return (short)(object)left > (short)(object)right; } if (typeof(T) == typeof(uint)) { return (uint)(object)left > (uint)(object)right; } if (typeof(T) == typeof(int)) { return (int)(object)left > (int)(object)right; } if (typeof(T) == typeof(ulong)) { return (ulong)(object)left > (ulong)(object)right; } if (typeof(T) == typeof(long)) { return (long)(object)left > (long)(object)right; } if (typeof(T) == typeof(float)) { return (float)(object)left > (float)(object)right; } if (typeof(T) == typeof(double)) { return (double)(object)left > (double)(object)right; } if (typeof(T) == typeof(UIntPtr)) { return (nuint)(UIntPtr)(object)left > (nuint)(UIntPtr)(object)right; } if (typeof(T) == typeof(IntPtr)) { return (nint)(IntPtr)(object)left > (nint)(IntPtr)(object)right; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool ScalarGreaterThanOrEqual(T left, T right) { if (typeof(T) == typeof(byte)) { return (byte)(object)left >= (byte)(object)right; } if (typeof(T) == typeof(sbyte)) { return (sbyte)(object)left >= (sbyte)(object)right; } if (typeof(T) == typeof(ushort)) { return (ushort)(object)left >= (ushort)(object)right; } if (typeof(T) == typeof(short)) { return (short)(object)left >= (short)(object)right; } if (typeof(T) == typeof(uint)) { return (uint)(object)left >= (uint)(object)right; } if (typeof(T) == typeof(int)) { return (int)(object)left >= (int)(object)right; } if (typeof(T) == typeof(ulong)) { return (ulong)(object)left >= (ulong)(object)right; } if (typeof(T) == typeof(long)) { return (long)(object)left >= (long)(object)right; } if (typeof(T) == typeof(float)) { return (float)(object)left >= (float)(object)right; } if (typeof(T) == typeof(double)) { return (double)(object)left >= (double)(object)right; } if (typeof(T) == typeof(UIntPtr)) { return (nuint)(UIntPtr)(object)left >= (nuint)(UIntPtr)(object)right; } if (typeof(T) == typeof(IntPtr)) { return (nint)(IntPtr)(object)left >= (nint)(IntPtr)(object)right; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T ScalarAdd(T left, T right) { if (typeof(T) == typeof(byte)) { return (T)(object)(byte)((byte)(object)left + (byte)(object)right); } if (typeof(T) == typeof(sbyte)) { return (T)(object)(sbyte)((sbyte)(object)left + (sbyte)(object)right); } if (typeof(T) == typeof(ushort)) { return (T)(object)(ushort)((ushort)(object)left + (ushort)(object)right); } if (typeof(T) == typeof(short)) { return (T)(object)(short)((short)(object)left + (short)(object)right); } if (typeof(T) == typeof(uint)) { return (T)(object)((uint)(object)left + (uint)(object)right); } if (typeof(T) == typeof(int)) { return (T)(object)((int)(object)left + (int)(object)right); } if (typeof(T) == typeof(ulong)) { return (T)(object)((ulong)(object)left + (ulong)(object)right); } if (typeof(T) == typeof(long)) { return (T)(object)((long)(object)left + (long)(object)right); } if (typeof(T) == typeof(float)) { return (T)(object)((float)(object)left + (float)(object)right); } if (typeof(T) == typeof(double)) { return (T)(object)((double)(object)left + (double)(object)right); } if (typeof(T) == typeof(UIntPtr)) { return (T)(object)(nuint)((nint)(nuint)(UIntPtr)(object)left + (nint)(nuint)(UIntPtr)(object)right); } if (typeof(T) == typeof(IntPtr)) { return (T)(object)((nint)(IntPtr)(object)left + (nint)(IntPtr)(object)right); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T ScalarSubtract(T left, T right) { if (typeof(T) == typeof(byte)) { return (T)(object)(byte)((byte)(object)left - (byte)(object)right); } if (typeof(T) == typeof(sbyte)) { return (T)(object)(sbyte)((sbyte)(object)left - (sbyte)(object)right); } if (typeof(T) == typeof(ushort)) { return (T)(object)(ushort)((ushort)(object)left - (ushort)(object)right); } if (typeof(T) == typeof(short)) { return (T)(object)(short)((short)(object)left - (short)(object)right); } if (typeof(T) == typeof(uint)) { return (T)(object)((uint)(object)left - (uint)(object)right); } if (typeof(T) == typeof(int)) { return (T)(object)((int)(object)left - (int)(object)right); } if (typeof(T) == typeof(ulong)) { return (T)(object)((ulong)(object)left - (ulong)(object)right); } if (typeof(T) == typeof(long)) { return (T)(object)((long)(object)left - (long)(object)right); } if (typeof(T) == typeof(float)) { return (T)(object)((float)(object)left - (float)(object)right); } if (typeof(T) == typeof(double)) { return (T)(object)((double)(object)left - (double)(object)right); } if (typeof(T) == typeof(UIntPtr)) { return (T)(object)(nuint)((nint)(nuint)(UIntPtr)(object)left - (nint)(nuint)(UIntPtr)(object)right); } if (typeof(T) == typeof(IntPtr)) { return (T)(object)((nint)(IntPtr)(object)left - (nint)(IntPtr)(object)right); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T ScalarMultiply(T left, T right) { if (typeof(T) == typeof(byte)) { return (T)(object)(byte)((byte)(object)left * (byte)(object)right); } if (typeof(T) == typeof(sbyte)) { return (T)(object)(sbyte)((sbyte)(object)left * (sbyte)(object)right); } if (typeof(T) == typeof(ushort)) { return (T)(object)(ushort)((ushort)(object)left * (ushort)(object)right); } if (typeof(T) == typeof(short)) { return (T)(object)(short)((short)(object)left * (short)(object)right); } if (typeof(T) == typeof(uint)) { return (T)(object)((uint)(object)left * (uint)(object)right); } if (typeof(T) == typeof(int)) { return (T)(object)((int)(object)left * (int)(object)right); } if (typeof(T) == typeof(ulong)) { return (T)(object)((ulong)(object)left * (ulong)(object)right); } if (typeof(T) == typeof(long)) { return (T)(object)((long)(object)left * (long)(object)right); } if (typeof(T) == typeof(float)) { return (T)(object)((float)(object)left * (float)(object)right); } if (typeof(T) == typeof(double)) { return (T)(object)((double)(object)left * (double)(object)right); } if (typeof(T) == typeof(UIntPtr)) { return (T)(object)(nuint)((nint)(nuint)(UIntPtr)(object)left * (nint)(nuint)(UIntPtr)(object)right); } if (typeof(T) == typeof(IntPtr)) { return (T)(object)((nint)(IntPtr)(object)left * (nint)(IntPtr)(object)right); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T ScalarDivide(T left, T right) { if (typeof(T) == typeof(byte)) { return (T)(object)(byte)((byte)(object)left / (byte)(object)right); } if (typeof(T) == typeof(sbyte)) { return (T)(object)(sbyte)((sbyte)(object)left / (sbyte)(object)right); } if (typeof(T) == typeof(ushort)) { return (T)(object)(ushort)((ushort)(object)left / (ushort)(object)right); } if (typeof(T) == typeof(short)) { return (T)(object)(short)((short)(object)left / (short)(object)right); } if (typeof(T) == typeof(uint)) { return (T)(object)((uint)(object)left / (uint)(object)right); } if (typeof(T) == typeof(int)) { return (T)(object)((int)(object)left / (int)(object)right); } if (typeof(T) == typeof(ulong)) { return (T)(object)((ulong)(object)left / (ulong)(object)right); } if (typeof(T) == typeof(long)) { return (T)(object)((long)(object)left / (long)(object)right); } if (typeof(T) == typeof(float)) { return (T)(object)((float)(object)left / (float)(object)right); } if (typeof(T) == typeof(double)) { return (T)(object)((double)(object)left / (double)(object)right); } if (typeof(T) == typeof(UIntPtr)) { return (T)(object)((nuint)(UIntPtr)(object)left / (nuint)(UIntPtr)(object)right); } if (typeof(T) == typeof(IntPtr)) { return (T)(object)((nint)(IntPtr)(object)left / (nint)(IntPtr)(object)right); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T GetOneValue() { if (typeof(T) == typeof(byte)) { return (T)(object)(byte)1; } if (typeof(T) == typeof(sbyte)) { return (T)(object)(sbyte)1; } if (typeof(T) == typeof(ushort)) { return (T)(object)(ushort)1; } if (typeof(T) == typeof(short)) { return (T)(object)(short)1; } if (typeof(T) == typeof(uint)) { return (T)(object)1u; } if (typeof(T) == typeof(int)) { return (T)(object)1; } if (typeof(T) == typeof(ulong)) { return (T)(object)1uL; } if (typeof(T) == typeof(long)) { return (T)(object)1L; } if (typeof(T) == typeof(float)) { return (T)(object)1f; } if (typeof(T) == typeof(double)) { return (T)(object)1.0; } if (typeof(T) == typeof(UIntPtr)) { return (T)(object)(nuint)1u; } if (typeof(T) == typeof(IntPtr)) { return (T)(object)(nint)1; } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T GetAllBitsSetValue() { if (typeof(T) == typeof(byte)) { return (T)(object)byte.MaxValue; } if (typeof(T) == typeof(sbyte)) { return (T)(object)(sbyte)(-1); } if (typeof(T) == typeof(ushort)) { return (T)(object)ushort.MaxValue; } if (typeof(T) == typeof(short)) { return (T)(object)(short)(-1); } if (typeof(T) == typeof(uint)) { return (T)(object)uint.MaxValue; } if (typeof(T) == typeof(int)) { return (T)(object)(-1); } if (typeof(T) == typeof(ulong)) { return (T)(object)ulong.MaxValue; } if (typeof(T) == typeof(long)) { return (T)(object)(-1L); } if (typeof(T) == typeof(float)) { return (T)(object)BitConverter.Int32BitsToSingle(-1); } if (typeof(T) == typeof(double)) { return (T)(object)BitConverter.Int64BitsToDouble(-1L); } if (typeof(T) == typeof(UIntPtr)) { return (T)(object)UIntPtr.MaxValue; } if (typeof(T) == typeof(IntPtr)) { return (T)(object)(nint)(-1); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T ScalarAbs(T value) { if (typeof(T) == typeof(sbyte)) { return (T)(object)Math.Abs((sbyte)(object)value); } if (typeof(T) == typeof(short)) { return (T)(object)Math.Abs((short)(object)value); } if (typeof(T) == typeof(int)) { return (T)(object)Math.Abs((int)(object)value); } if (typeof(T) == typeof(long)) { return (T)(object)Math.Abs((long)(object)value); } if (typeof(T) == typeof(float)) { return (T)(object)Math.Abs((float)(object)value); } if (typeof(T) == typeof(double)) { return (T)(object)Math.Abs((double)(object)value); } if (typeof(T) == typeof(IntPtr)) { return (T)(object)Math.Abs((IntPtr)(object)value); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T ScalarSqrt(T value) { if (typeof(T) == typeof(byte)) { return (T)(object)(byte)Math.Sqrt((int)(byte)(object)value); } if (typeof(T) == typeof(sbyte)) { return (T)(object)(sbyte)Math.Sqrt((sbyte)(object)value); } if (typeof(T) == typeof(ushort)) { return (T)(object)(ushort)Math.Sqrt((int)(ushort)(object)value); } if (typeof(T) == typeof(short)) { return (T)(object)(short)Math.Sqrt((short)(object)value); } if (typeof(T) == typeof(uint)) { return (T)(object)(uint)Math.Sqrt((uint)(object)value); } if (typeof(T) == typeof(int)) { return (T)(object)(int)Math.Sqrt((int)(object)value); } if (typeof(T) == typeof(ulong)) { return (T)(object)(ulong)Math.Sqrt((ulong)(object)value); } if (typeof(T) == typeof(long)) { return (T)(object)(long)Math.Sqrt((long)(object)value); } if (typeof(T) == typeof(float)) { return (T)(object)(float)Math.Sqrt((float)(object)value); } if (typeof(T) == typeof(double)) { return (T)(object)Math.Sqrt((double)(object)value); } if (typeof(T) == typeof(UIntPtr)) { return (T)(object)(UIntPtr)Math.Sqrt((nint)(nuint)(UIntPtr)(object)value); } if (typeof(T) == typeof(IntPtr)) { return (T)(object)(IntPtr)Math.Sqrt((nint)(IntPtr)(object)value); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T ScalarCeiling(T value) { if (typeof(T) == typeof(float)) { return (T)(object)MathF.Ceiling((float)(object)value); } if (typeof(T) == typeof(double)) { return (T)(object)Math.Ceiling((double)(object)value); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T ScalarFloor(T value) { if (typeof(T) == typeof(float)) { return (T)(object)MathF.Floor((float)(object)value); } if (typeof(T) == typeof(double)) { return (T)(object)Math.Floor((double)(object)value); } throw new NotSupportedException(SR.Arg_TypeNotSupported); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private readonly T GetElement(nint index) { return Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SetElement(nint index, T value) { Unsafe.Add(ref Unsafe.As, T>(ref Unsafe.AsRef(in this)), index) = value; } } [Intrinsic] public struct Vector2 : IEquatable, IFormattable { public float X; public float Y; public static Vector2 Zero { [Intrinsic] get { return default(Vector2); } } public static Vector2 One { [Intrinsic] get { return new Vector2(1f); } } public static Vector2 UnitX => new Vector2(1f, 0f); public static Vector2 UnitY => new Vector2(0f, 1f); [Intrinsic] public Vector2(float value) : this(value, value) { } [Intrinsic] public Vector2(float x, float y) { X = x; Y = y; } public Vector2(ReadOnlySpan values) { if (values.Length < 2) { Vector.ThrowInsufficientNumberOfElementsException(2); } this = Unsafe.ReadUnaligned(ref Unsafe.As(ref MemoryMarshal.GetReference(values))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector2 operator +(Vector2 left, Vector2 right) { return new Vector2(left.X + right.X, left.Y + right.Y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector2 operator /(Vector2 left, Vector2 right) { return new Vector2(left.X / right.X, left.Y / right.Y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator /(Vector2 value1, float value2) { return value1 / new Vector2(value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static bool operator ==(Vector2 left, Vector2 right) { if (left.X == right.X) { return left.Y == right.Y; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static bool operator !=(Vector2 left, Vector2 right) { return !(left == right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector2 operator *(Vector2 left, Vector2 right) { return new Vector2(left.X * right.X, left.Y * right.Y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator *(Vector2 left, float right) { return left * new Vector2(right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator *(float left, Vector2 right) { return right * left; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector2 operator -(Vector2 left, Vector2 right) { return new Vector2(left.X - right.X, left.Y - right.Y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 operator -(Vector2 value) { return Zero - value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector2 Abs(Vector2 value) { return new Vector2(MathF.Abs(value.X), MathF.Abs(value.Y)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Add(Vector2 left, Vector2 right) { return left + right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max) { return Min(Max(value1, min), max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector2 value1, Vector2 value2) { float x = DistanceSquared(value1, value2); return MathF.Sqrt(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DistanceSquared(Vector2 value1, Vector2 value2) { Vector2 vector = value1 - value2; return Dot(vector, vector); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Divide(Vector2 left, Vector2 right) { return left / right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Divide(Vector2 left, float divisor) { return left / divisor; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static float Dot(Vector2 value1, Vector2 value2) { return value1.X * value2.X + value1.Y * value2.Y; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount) { return value1 * (1f - amount) + value2 * amount; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector2 Max(Vector2 value1, Vector2 value2) { return new Vector2((value1.X > value2.X) ? value1.X : value2.X, (value1.Y > value2.Y) ? value1.Y : value2.Y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector2 Min(Vector2 value1, Vector2 value2) { return new Vector2((value1.X < value2.X) ? value1.X : value2.X, (value1.Y < value2.Y) ? value1.Y : value2.Y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(Vector2 left, Vector2 right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(Vector2 left, float right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(float left, Vector2 right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Negate(Vector2 value) { return -value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Normalize(Vector2 value) { return value / value.Length(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Reflect(Vector2 vector, Vector2 normal) { float num = Dot(vector, normal); return vector - 2f * num * normal; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector2 SquareRoot(Vector2 value) { return new Vector2(MathF.Sqrt(value.X), MathF.Sqrt(value.Y)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Subtract(Vector2 left, Vector2 right) { return left - right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 position, Matrix3x2 matrix) { return new Vector2(position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M31, position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M32); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 position, Matrix4x4 matrix) { return new Vector2(position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 value, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num3; float num5 = rotation.X * num; float num6 = rotation.X * num2; float num7 = rotation.Y * num2; float num8 = rotation.Z * num3; return new Vector2(value.X * (1f - num7 - num8) + value.Y * (num6 - num4), value.X * (num6 + num4) + value.Y * (1f - num5 - num8)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 TransformNormal(Vector2 normal, Matrix3x2 matrix) { return new Vector2(normal.X * matrix.M11 + normal.Y * matrix.M21, normal.X * matrix.M12 + normal.Y * matrix.M22); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 TransformNormal(Vector2 normal, Matrix4x4 matrix) { return new Vector2(normal.X * matrix.M11 + normal.Y * matrix.M21, normal.X * matrix.M12 + normal.Y * matrix.M22); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public readonly void CopyTo(float[] array) { CopyTo(array, 0); } [Intrinsic] public readonly void CopyTo(float[] array, int index) { if (array == null) { throw new NullReferenceException(SR.Arg_NullArgumentNullRef); } if (index < 0 || index >= array.Length) { throw new ArgumentOutOfRangeException("index", SR.Format(SR.Arg_ArgumentOutOfRangeException, index)); } if (array.Length - index < 2) { throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index)); } array[index] = X; array[index + 1] = Y; } public readonly void CopyTo(Span destination) { if (destination.Length < 2) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } Unsafe.WriteUnaligned(ref Unsafe.As(ref MemoryMarshal.GetReference(destination)), this); } public readonly bool TryCopyTo(Span destination) { if (destination.Length < 2) { return false; } Unsafe.WriteUnaligned(ref Unsafe.As(ref MemoryMarshal.GetReference(destination)), this); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override readonly bool Equals([NotNullWhen(true)] object? obj) { if (obj is Vector2 other) { return Equals(other); } return false; } [Intrinsic] public readonly bool Equals(Vector2 other) { return this == other; } public override readonly int GetHashCode() { return HashCode.Combine(X, Y); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly float Length() { float x = LengthSquared(); return MathF.Sqrt(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly float LengthSquared() { return Dot(this, this); } public override readonly string ToString() { return ToString("G", CultureInfo.CurrentCulture); } public readonly string ToString(string? format) { return ToString(format, CultureInfo.CurrentCulture); } public readonly string ToString(string? format, IFormatProvider? formatProvider) { StringBuilder stringBuilder = new StringBuilder(); string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; stringBuilder.Append('<'); stringBuilder.Append(X.ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); stringBuilder.Append(Y.ToString(format, formatProvider)); stringBuilder.Append('>'); return stringBuilder.ToString(); } } [Intrinsic] public struct Vector3 : IEquatable, IFormattable { public float X; public float Y; public float Z; public static Vector3 Zero { [Intrinsic] get { return default(Vector3); } } public static Vector3 One { [Intrinsic] get { return new Vector3(1f); } } public static Vector3 UnitX => new Vector3(1f, 0f, 0f); public static Vector3 UnitY => new Vector3(0f, 1f, 0f); public static Vector3 UnitZ => new Vector3(0f, 0f, 1f); [Intrinsic] public Vector3(float value) : this(value, value, value) { } [Intrinsic] public Vector3(Vector2 value, float z) : this(value.X, value.Y, z) { } [Intrinsic] public Vector3(float x, float y, float z) { X = x; Y = y; Z = z; } public Vector3(ReadOnlySpan values) { if (values.Length < 3) { Vector.ThrowInsufficientNumberOfElementsException(3); } this = Unsafe.ReadUnaligned(ref Unsafe.As(ref MemoryMarshal.GetReference(values))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector3 operator +(Vector3 left, Vector3 right) { return new Vector3(left.X + right.X, left.Y + right.Y, left.Z + right.Z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector3 operator /(Vector3 left, Vector3 right) { return new Vector3(left.X / right.X, left.Y / right.Y, left.Z / right.Z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator /(Vector3 value1, float value2) { return value1 / new Vector3(value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static bool operator ==(Vector3 left, Vector3 right) { if (left.X == right.X && left.Y == right.Y) { return left.Z == right.Z; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static bool operator !=(Vector3 left, Vector3 right) { return !(left == right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector3 operator *(Vector3 left, Vector3 right) { return new Vector3(left.X * right.X, left.Y * right.Y, left.Z * right.Z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator *(Vector3 left, float right) { return left * new Vector3(right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator *(float left, Vector3 right) { return right * left; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector3 operator -(Vector3 left, Vector3 right) { return new Vector3(left.X - right.X, left.Y - right.Y, left.Z - right.Z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 operator -(Vector3 value) { return Zero - value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector3 Abs(Vector3 value) { return new Vector3(MathF.Abs(value.X), MathF.Abs(value.Y), MathF.Abs(value.Z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Add(Vector3 left, Vector3 right) { return left + right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max) { return Min(Max(value1, min), max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Cross(Vector3 vector1, Vector3 vector2) { return new Vector3(vector1.Y * vector2.Z - vector1.Z * vector2.Y, vector1.Z * vector2.X - vector1.X * vector2.Z, vector1.X * vector2.Y - vector1.Y * vector2.X); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector3 value1, Vector3 value2) { float x = DistanceSquared(value1, value2); return MathF.Sqrt(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DistanceSquared(Vector3 value1, Vector3 value2) { Vector3 vector = value1 - value2; return Dot(vector, vector); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Divide(Vector3 left, Vector3 right) { return left / right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Divide(Vector3 left, float divisor) { return left / divisor; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static float Dot(Vector3 vector1, Vector3 vector2) { return vector1.X * vector2.X + vector1.Y * vector2.Y + vector1.Z * vector2.Z; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount) { return value1 * (1f - amount) + value2 * amount; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector3 Max(Vector3 value1, Vector3 value2) { return new Vector3((value1.X > value2.X) ? value1.X : value2.X, (value1.Y > value2.Y) ? value1.Y : value2.Y, (value1.Z > value2.Z) ? value1.Z : value2.Z); } [Intrinsic] public static Vector3 Min(Vector3 value1, Vector3 value2) { return new Vector3((value1.X < value2.X) ? value1.X : value2.X, (value1.Y < value2.Y) ? value1.Y : value2.Y, (value1.Z < value2.Z) ? value1.Z : value2.Z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(Vector3 left, Vector3 right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(Vector3 left, float right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Multiply(float left, Vector3 right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Negate(Vector3 value) { return -value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Normalize(Vector3 value) { return value / value.Length(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Reflect(Vector3 vector, Vector3 normal) { float num = Dot(vector, normal); return vector - 2f * num * normal; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector3 SquareRoot(Vector3 value) { return new Vector3(MathF.Sqrt(value.X), MathF.Sqrt(value.Y), MathF.Sqrt(value.Z)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Subtract(Vector3 left, Vector3 right) { return left - right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Transform(Vector3 position, Matrix4x4 matrix) { return new Vector3(position.X * matrix.M11 + position.Y * matrix.M21 + position.Z * matrix.M31 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + position.Z * matrix.M32 + matrix.M42, position.X * matrix.M13 + position.Y * matrix.M23 + position.Z * matrix.M33 + matrix.M43); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 Transform(Vector3 value, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num; float num5 = rotation.W * num2; float num6 = rotation.W * num3; float num7 = rotation.X * num; float num8 = rotation.X * num2; float num9 = rotation.X * num3; float num10 = rotation.Y * num2; float num11 = rotation.Y * num3; float num12 = rotation.Z * num3; return new Vector3(value.X * (1f - num10 - num12) + value.Y * (num8 - num6) + value.Z * (num9 + num5), value.X * (num8 + num6) + value.Y * (1f - num7 - num12) + value.Z * (num11 - num4), value.X * (num9 - num5) + value.Y * (num11 + num4) + value.Z * (1f - num7 - num10)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector3 TransformNormal(Vector3 normal, Matrix4x4 matrix) { return new Vector3(normal.X * matrix.M11 + normal.Y * matrix.M21 + normal.Z * matrix.M31, normal.X * matrix.M12 + normal.Y * matrix.M22 + normal.Z * matrix.M32, normal.X * matrix.M13 + normal.Y * matrix.M23 + normal.Z * matrix.M33); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public readonly void CopyTo(float[] array) { CopyTo(array, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public readonly void CopyTo(float[] array, int index) { if (array == null) { throw new NullReferenceException(SR.Arg_NullArgumentNullRef); } if (index < 0 || index >= array.Length) { throw new ArgumentOutOfRangeException("index", SR.Format(SR.Arg_ArgumentOutOfRangeException, index)); } if (array.Length - index < 3) { throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index)); } array[index] = X; array[index + 1] = Y; array[index + 2] = Z; } public readonly void CopyTo(Span destination) { if (destination.Length < 3) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } Unsafe.WriteUnaligned(ref Unsafe.As(ref MemoryMarshal.GetReference(destination)), this); } public readonly bool TryCopyTo(Span destination) { if (destination.Length < 3) { return false; } Unsafe.WriteUnaligned(ref Unsafe.As(ref MemoryMarshal.GetReference(destination)), this); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override readonly bool Equals([NotNullWhen(true)] object? obj) { if (obj is Vector3 other) { return Equals(other); } return false; } [Intrinsic] public readonly bool Equals(Vector3 other) { return this == other; } public override readonly int GetHashCode() { return HashCode.Combine(X, Y, Z); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly float Length() { float x = LengthSquared(); return MathF.Sqrt(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly float LengthSquared() { return Dot(this, this); } public override readonly string ToString() { return ToString("G", CultureInfo.CurrentCulture); } public readonly string ToString(string? format) { return ToString(format, CultureInfo.CurrentCulture); } public readonly string ToString(string? format, IFormatProvider? formatProvider) { StringBuilder stringBuilder = new StringBuilder(); string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; stringBuilder.Append('<'); stringBuilder.Append(X.ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); stringBuilder.Append(Y.ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); stringBuilder.Append(Z.ToString(format, formatProvider)); stringBuilder.Append('>'); return stringBuilder.ToString(); } } [Intrinsic] public struct Vector4 : IEquatable, IFormattable { public float X; public float Y; public float Z; public float W; public static Vector4 Zero { [Intrinsic] get { return default(Vector4); } } public static Vector4 One { [Intrinsic] get { return new Vector4(1f); } } public static Vector4 UnitX => new Vector4(1f, 0f, 0f, 0f); public static Vector4 UnitY => new Vector4(0f, 1f, 0f, 0f); public static Vector4 UnitZ => new Vector4(0f, 0f, 1f, 0f); public static Vector4 UnitW => new Vector4(0f, 0f, 0f, 1f); [Intrinsic] public Vector4(float value) : this(value, value, value, value) { } [Intrinsic] public Vector4(Vector2 value, float z, float w) : this(value.X, value.Y, z, w) { } [Intrinsic] public Vector4(Vector3 value, float w) : this(value.X, value.Y, value.Z, w) { } [Intrinsic] public Vector4(float x, float y, float z, float w) { X = x; Y = y; Z = z; W = w; } public Vector4(ReadOnlySpan values) { if (values.Length < 4) { Vector.ThrowInsufficientNumberOfElementsException(4); } this = Unsafe.ReadUnaligned(ref Unsafe.As(ref MemoryMarshal.GetReference(values))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector4 operator +(Vector4 left, Vector4 right) { return new Vector4(left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector4 operator /(Vector4 left, Vector4 right) { return new Vector4(left.X / right.X, left.Y / right.Y, left.Z / right.Z, left.W / right.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator /(Vector4 value1, float value2) { return value1 / new Vector4(value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static bool operator ==(Vector4 left, Vector4 right) { if (left.X == right.X && left.Y == right.Y && left.Z == right.Z) { return left.W == right.W; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static bool operator !=(Vector4 left, Vector4 right) { return !(left == right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector4 operator *(Vector4 left, Vector4 right) { return new Vector4(left.X * right.X, left.Y * right.Y, left.Z * right.Z, left.W * right.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator *(Vector4 left, float right) { return left * new Vector4(right); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator *(float left, Vector4 right) { return right * left; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector4 operator -(Vector4 left, Vector4 right) { return new Vector4(left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 operator -(Vector4 value) { return Zero - value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector4 Abs(Vector4 value) { return new Vector4(MathF.Abs(value.X), MathF.Abs(value.Y), MathF.Abs(value.Z), MathF.Abs(value.W)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Add(Vector4 left, Vector4 right) { return left + right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Clamp(Vector4 value1, Vector4 min, Vector4 max) { return Min(Max(value1, min), max); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector4 value1, Vector4 value2) { float x = DistanceSquared(value1, value2); return MathF.Sqrt(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DistanceSquared(Vector4 value1, Vector4 value2) { Vector4 vector = value1 - value2; return Dot(vector, vector); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Divide(Vector4 left, Vector4 right) { return left / right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Divide(Vector4 left, float divisor) { return left / divisor; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static float Dot(Vector4 vector1, Vector4 vector2) { return vector1.X * vector2.X + vector1.Y * vector2.Y + vector1.Z * vector2.Z + vector1.W * vector2.W; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Lerp(Vector4 value1, Vector4 value2, float amount) { return value1 * (1f - amount) + value2 * amount; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector4 Max(Vector4 value1, Vector4 value2) { return new Vector4((value1.X > value2.X) ? value1.X : value2.X, (value1.Y > value2.Y) ? value1.Y : value2.Y, (value1.Z > value2.Z) ? value1.Z : value2.Z, (value1.W > value2.W) ? value1.W : value2.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector4 Min(Vector4 value1, Vector4 value2) { return new Vector4((value1.X < value2.X) ? value1.X : value2.X, (value1.Y < value2.Y) ? value1.Y : value2.Y, (value1.Z < value2.Z) ? value1.Z : value2.Z, (value1.W < value2.W) ? value1.W : value2.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Multiply(Vector4 left, Vector4 right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Multiply(Vector4 left, float right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Multiply(float left, Vector4 right) { return left * right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Negate(Vector4 value) { return -value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Normalize(Vector4 vector) { return vector / vector.Length(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector4 SquareRoot(Vector4 value) { return new Vector4(MathF.Sqrt(value.X), MathF.Sqrt(value.Y), MathF.Sqrt(value.Z), MathF.Sqrt(value.W)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Subtract(Vector4 left, Vector4 right) { return left - right; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector2 position, Matrix4x4 matrix) { return new Vector4(position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42, position.X * matrix.M13 + position.Y * matrix.M23 + matrix.M43, position.X * matrix.M14 + position.Y * matrix.M24 + matrix.M44); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector2 value, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num; float num5 = rotation.W * num2; float num6 = rotation.W * num3; float num7 = rotation.X * num; float num8 = rotation.X * num2; float num9 = rotation.X * num3; float num10 = rotation.Y * num2; float num11 = rotation.Y * num3; float num12 = rotation.Z * num3; return new Vector4(value.X * (1f - num10 - num12) + value.Y * (num8 - num6), value.X * (num8 + num6) + value.Y * (1f - num7 - num12), value.X * (num9 - num5) + value.Y * (num11 + num4), 1f); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector3 position, Matrix4x4 matrix) { return new Vector4(position.X * matrix.M11 + position.Y * matrix.M21 + position.Z * matrix.M31 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + position.Z * matrix.M32 + matrix.M42, position.X * matrix.M13 + position.Y * matrix.M23 + position.Z * matrix.M33 + matrix.M43, position.X * matrix.M14 + position.Y * matrix.M24 + position.Z * matrix.M34 + matrix.M44); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector3 value, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num; float num5 = rotation.W * num2; float num6 = rotation.W * num3; float num7 = rotation.X * num; float num8 = rotation.X * num2; float num9 = rotation.X * num3; float num10 = rotation.Y * num2; float num11 = rotation.Y * num3; float num12 = rotation.Z * num3; return new Vector4(value.X * (1f - num10 - num12) + value.Y * (num8 - num6) + value.Z * (num9 + num5), value.X * (num8 + num6) + value.Y * (1f - num7 - num12) + value.Z * (num11 - num4), value.X * (num9 - num5) + value.Y * (num11 + num4) + value.Z * (1f - num7 - num10), 1f); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector4 vector, Matrix4x4 matrix) { return new Vector4(vector.X * matrix.M11 + vector.Y * matrix.M21 + vector.Z * matrix.M31 + vector.W * matrix.M41, vector.X * matrix.M12 + vector.Y * matrix.M22 + vector.Z * matrix.M32 + vector.W * matrix.M42, vector.X * matrix.M13 + vector.Y * matrix.M23 + vector.Z * matrix.M33 + vector.W * matrix.M43, vector.X * matrix.M14 + vector.Y * matrix.M24 + vector.Z * matrix.M34 + vector.W * matrix.M44); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector4 Transform(Vector4 value, Quaternion rotation) { float num = rotation.X + rotation.X; float num2 = rotation.Y + rotation.Y; float num3 = rotation.Z + rotation.Z; float num4 = rotation.W * num; float num5 = rotation.W * num2; float num6 = rotation.W * num3; float num7 = rotation.X * num; float num8 = rotation.X * num2; float num9 = rotation.X * num3; float num10 = rotation.Y * num2; float num11 = rotation.Y * num3; float num12 = rotation.Z * num3; return new Vector4(value.X * (1f - num10 - num12) + value.Y * (num8 - num6) + value.Z * (num9 + num5), value.X * (num8 + num6) + value.Y * (1f - num7 - num12) + value.Z * (num11 - num4), value.X * (num9 - num5) + value.Y * (num11 + num4) + value.Z * (1f - num7 - num10), value.W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public readonly void CopyTo(float[] array) { CopyTo(array, 0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public readonly void CopyTo(float[] array, int index) { if (array == null) { throw new NullReferenceException(SR.Arg_NullArgumentNullRef); } if (index < 0 || index >= array.Length) { throw new ArgumentOutOfRangeException("index", SR.Format(SR.Arg_ArgumentOutOfRangeException, index)); } if (array.Length - index < 4) { throw new ArgumentException(SR.Format(SR.Arg_ElementsInSourceIsGreaterThanDestination, index)); } array[index] = X; array[index + 1] = Y; array[index + 2] = Z; array[index + 3] = W; } public readonly void CopyTo(Span destination) { if (destination.Length < 4) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } Unsafe.WriteUnaligned(ref Unsafe.As(ref MemoryMarshal.GetReference(destination)), this); } public readonly bool TryCopyTo(Span destination) { if (destination.Length < 4) { return false; } Unsafe.WriteUnaligned(ref Unsafe.As(ref MemoryMarshal.GetReference(destination)), this); return true; } [Intrinsic] public readonly bool Equals(Vector4 other) { return this == other; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override readonly bool Equals([NotNullWhen(true)] object? obj) { if (obj is Vector4 other) { return Equals(other); } return false; } public override readonly int GetHashCode() { return HashCode.Combine(X, Y, Z, W); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly float Length() { float x = LengthSquared(); return MathF.Sqrt(x); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly float LengthSquared() { return Dot(this, this); } public override readonly string ToString() { return ToString("G", CultureInfo.CurrentCulture); } public readonly string ToString(string? format) { return ToString(format, CultureInfo.CurrentCulture); } public readonly string ToString(string? format, IFormatProvider? formatProvider) { StringBuilder stringBuilder = new StringBuilder(); string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; stringBuilder.Append('<'); stringBuilder.Append(X.ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); stringBuilder.Append(Y.ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); stringBuilder.Append(Z.ToString(format, formatProvider)); stringBuilder.Append(numberGroupSeparator); stringBuilder.Append(' '); stringBuilder.Append(W.ToString(format, formatProvider)); stringBuilder.Append('>'); return stringBuilder.ToString(); } } internal static class VectorMath { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 ConditionalSelectBitwise(Vector128 selector, Vector128 ifTrue, Vector128 ifFalse) { if (AdvSimd.IsSupported) { } if (Sse.IsSupported) { return Sse.Or(Sse.And(ifTrue, selector), Sse.AndNot(selector, ifFalse)); } throw new PlatformNotSupportedException(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 ConditionalSelectBitwise(Vector128 selector, Vector128 ifTrue, Vector128 ifFalse) { if (AdvSimd.IsSupported) { } if (Sse2.IsSupported) { return Sse2.Or(Sse2.And(ifTrue, selector), Sse2.AndNot(selector, ifFalse)); } throw new PlatformNotSupportedException(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool Equal(Vector128 vector1, Vector128 vector2) { if (AdvSimd.Arm64.IsSupported) { } if (Sse.IsSupported) { return Sse.MoveMask(Sse.CompareNotEqual(vector1, vector2)) == 0; } throw new PlatformNotSupportedException(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 Lerp(Vector128 a, Vector128 b, Vector128 t) { if (AdvSimd.IsSupported) { } if (Fma.IsSupported) { return Fma.MultiplyAdd(Sse.Subtract(b, a), t, a); } if (Sse.IsSupported) { return Sse.Add(Sse.Multiply(a, Sse.Subtract(Vector128.Create(1f), t)), Sse.Multiply(b, t)); } throw new PlatformNotSupportedException(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool NotEqual(Vector128 vector1, Vector128 vector2) { if (AdvSimd.IsSupported) { } if (Sse.IsSupported) { return Sse.MoveMask(Sse.CompareNotEqual(vector1, vector2)) != 0; } throw new PlatformNotSupportedException(); } } } namespace System.Net { public static class WebUtility { private struct UrlDecoder { private readonly int _bufferSize; private int _numChars; private char[] _charBuffer; private int _numBytes; private byte[] _byteBuffer; private readonly Encoding _encoding; private void FlushBytes() { if (_charBuffer == null) { _charBuffer = new char[_bufferSize]; } _numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars); _numBytes = 0; } internal UrlDecoder(int bufferSize, Encoding encoding) { _bufferSize = bufferSize; _encoding = encoding; _charBuffer = null; _numChars = 0; _numBytes = 0; _byteBuffer = null; } internal void AddChar(char ch) { if (_numBytes > 0) { FlushBytes(); } if (_charBuffer == null) { _charBuffer = new char[_bufferSize]; } _charBuffer[_numChars++] = ch; } internal void AddByte(byte b) { if (_byteBuffer == null) { _byteBuffer = new byte[_bufferSize]; } _byteBuffer[_numBytes++] = b; } internal string GetString() { if (_numBytes > 0) { FlushBytes(); } return new string(_charBuffer, 0, _numChars); } } private static class HtmlEntities { private static readonly Dictionary s_lookupTable = InitializeLookupTable(); private static Dictionary InitializeLookupTable() { ReadOnlySpan source = new byte[2530] { 116, 111, 117, 113, 0, 0, 0, 0, 34, 0, 112, 109, 97, 0, 0, 0, 0, 0, 38, 0, 115, 111, 112, 97, 0, 0, 0, 0, 39, 0, 116, 108, 0, 0, 0, 0, 0, 0, 60, 0, 116, 103, 0, 0, 0, 0, 0, 0, 62, 0, 112, 115, 98, 110, 0, 0, 0, 0, 160, 0, 108, 99, 120, 101, 105, 0, 0, 0, 161, 0, 116, 110, 101, 99, 0, 0, 0, 0, 162, 0, 100, 110, 117, 111, 112, 0, 0, 0, 163, 0, 110, 101, 114, 114, 117, 99, 0, 0, 164, 0, 110, 101, 121, 0, 0, 0, 0, 0, 165, 0, 114, 97, 98, 118, 114, 98, 0, 0, 166, 0, 116, 99, 101, 115, 0, 0, 0, 0, 167, 0, 108, 109, 117, 0, 0, 0, 0, 0, 168, 0, 121, 112, 111, 99, 0, 0, 0, 0, 169, 0, 102, 100, 114, 111, 0, 0, 0, 0, 170, 0, 111, 117, 113, 97, 108, 0, 0, 0, 171, 0, 116, 111, 110, 0, 0, 0, 0, 0, 172, 0, 121, 104, 115, 0, 0, 0, 0, 0, 173, 0, 103, 101, 114, 0, 0, 0, 0, 0, 174, 0, 114, 99, 97, 109, 0, 0, 0, 0, 175, 0, 103, 101, 100, 0, 0, 0, 0, 0, 176, 0, 110, 109, 115, 117, 108, 112, 0, 0, 177, 0, 50, 112, 117, 115, 0, 0, 0, 0, 178, 0, 51, 112, 117, 115, 0, 0, 0, 0, 179, 0, 101, 116, 117, 99, 97, 0, 0, 0, 180, 0, 111, 114, 99, 105, 109, 0, 0, 0, 181, 0, 97, 114, 97, 112, 0, 0, 0, 0, 182, 0, 116, 111, 100, 100, 105, 109, 0, 0, 183, 0, 108, 105, 100, 101, 99, 0, 0, 0, 184, 0, 49, 112, 117, 115, 0, 0, 0, 0, 185, 0, 109, 100, 114, 111, 0, 0, 0, 0, 186, 0, 111, 117, 113, 97, 114, 0, 0, 0, 187, 0, 52, 49, 99, 97, 114, 102, 0, 0, 188, 0, 50, 49, 99, 97, 114, 102, 0, 0, 189, 0, 52, 51, 99, 97, 114, 102, 0, 0, 190, 0, 116, 115, 101, 117, 113, 105, 0, 0, 191, 0, 101, 118, 97, 114, 103, 65, 0, 0, 192, 0, 101, 116, 117, 99, 97, 65, 0, 0, 193, 0, 99, 114, 105, 99, 65, 0, 0, 0, 194, 0, 101, 100, 108, 105, 116, 65, 0, 0, 195, 0, 108, 109, 117, 65, 0, 0, 0, 0, 196, 0, 103, 110, 105, 114, 65, 0, 0, 0, 197, 0, 103, 105, 108, 69, 65, 0, 0, 0, 198, 0, 108, 105, 100, 101, 99, 67, 0, 0, 199, 0, 101, 118, 97, 114, 103, 69, 0, 0, 200, 0, 101, 116, 117, 99, 97, 69, 0, 0, 201, 0, 99, 114, 105, 99, 69, 0, 0, 0, 202, 0, 108, 109, 117, 69, 0, 0, 0, 0, 203, 0, 101, 118, 97, 114, 103, 73, 0, 0, 204, 0, 101, 116, 117, 99, 97, 73, 0, 0, 205, 0, 99, 114, 105, 99, 73, 0, 0, 0, 206, 0, 108, 109, 117, 73, 0, 0, 0, 0, 207, 0, 72, 84, 69, 0, 0, 0, 0, 0, 208, 0, 101, 100, 108, 105, 116, 78, 0, 0, 209, 0, 101, 118, 97, 114, 103, 79, 0, 0, 210, 0, 101, 116, 117, 99, 97, 79, 0, 0, 211, 0, 99, 114, 105, 99, 79, 0, 0, 0, 212, 0, 101, 100, 108, 105, 116, 79, 0, 0, 213, 0, 108, 109, 117, 79, 0, 0, 0, 0, 214, 0, 115, 101, 109, 105, 116, 0, 0, 0, 215, 0, 104, 115, 97, 108, 115, 79, 0, 0, 216, 0, 101, 118, 97, 114, 103, 85, 0, 0, 217, 0, 101, 116, 117, 99, 97, 85, 0, 0, 218, 0, 99, 114, 105, 99, 85, 0, 0, 0, 219, 0, 108, 109, 117, 85, 0, 0, 0, 0, 220, 0, 101, 116, 117, 99, 97, 89, 0, 0, 221, 0, 78, 82, 79, 72, 84, 0, 0, 0, 222, 0, 103, 105, 108, 122, 115, 0, 0, 0, 223, 0, 101, 118, 97, 114, 103, 97, 0, 0, 224, 0, 101, 116, 117, 99, 97, 97, 0, 0, 225, 0, 99, 114, 105, 99, 97, 0, 0, 0, 226, 0, 101, 100, 108, 105, 116, 97, 0, 0, 227, 0, 108, 109, 117, 97, 0, 0, 0, 0, 228, 0, 103, 110, 105, 114, 97, 0, 0, 0, 229, 0, 103, 105, 108, 101, 97, 0, 0, 0, 230, 0, 108, 105, 100, 101, 99, 99, 0, 0, 231, 0, 101, 118, 97, 114, 103, 101, 0, 0, 232, 0, 101, 116, 117, 99, 97, 101, 0, 0, 233, 0, 99, 114, 105, 99, 101, 0, 0, 0, 234, 0, 108, 109, 117, 101, 0, 0, 0, 0, 235, 0, 101, 118, 97, 114, 103, 105, 0, 0, 236, 0, 101, 116, 117, 99, 97, 105, 0, 0, 237, 0, 99, 114, 105, 99, 105, 0, 0, 0, 238, 0, 108, 109, 117, 105, 0, 0, 0, 0, 239, 0, 104, 116, 101, 0, 0, 0, 0, 0, 240, 0, 101, 100, 108, 105, 116, 110, 0, 0, 241, 0, 101, 118, 97, 114, 103, 111, 0, 0, 242, 0, 101, 116, 117, 99, 97, 111, 0, 0, 243, 0, 99, 114, 105, 99, 111, 0, 0, 0, 244, 0, 101, 100, 108, 105, 116, 111, 0, 0, 245, 0, 108, 109, 117, 111, 0, 0, 0, 0, 246, 0, 101, 100, 105, 118, 105, 100, 0, 0, 247, 0, 104, 115, 97, 108, 115, 111, 0, 0, 248, 0, 101, 118, 97, 114, 103, 117, 0, 0, 249, 0, 101, 116, 117, 99, 97, 117, 0, 0, 250, 0, 99, 114, 105, 99, 117, 0, 0, 0, 251, 0, 108, 109, 117, 117, 0, 0, 0, 0, 252, 0, 101, 116, 117, 99, 97, 121, 0, 0, 253, 0, 110, 114, 111, 104, 116, 0, 0, 0, 254, 0, 108, 109, 117, 121, 0, 0, 0, 0, 255, 0, 103, 105, 108, 69, 79, 0, 0, 0, 82, 1, 103, 105, 108, 101, 111, 0, 0, 0, 83, 1, 110, 111, 114, 97, 99, 83, 0, 0, 96, 1, 110, 111, 114, 97, 99, 115, 0, 0, 97, 1, 108, 109, 117, 89, 0, 0, 0, 0, 120, 1, 102, 111, 110, 102, 0, 0, 0, 0, 146, 1, 99, 114, 105, 99, 0, 0, 0, 0, 198, 2, 101, 100, 108, 105, 116, 0, 0, 0, 220, 2, 97, 104, 112, 108, 65, 0, 0, 0, 145, 3, 97, 116, 101, 66, 0, 0, 0, 0, 146, 3, 97, 109, 109, 97, 71, 0, 0, 0, 147, 3, 97, 116, 108, 101, 68, 0, 0, 0, 148, 3, 110, 111, 108, 105, 115, 112, 69, 0, 149, 3, 97, 116, 101, 90, 0, 0, 0, 0, 150, 3, 97, 116, 69, 0, 0, 0, 0, 0, 151, 3, 97, 116, 101, 104, 84, 0, 0, 0, 152, 3, 97, 116, 111, 73, 0, 0, 0, 0, 153, 3, 97, 112, 112, 97, 75, 0, 0, 0, 154, 3, 97, 100, 98, 109, 97, 76, 0, 0, 155, 3, 117, 77, 0, 0, 0, 0, 0, 0, 156, 3, 117, 78, 0, 0, 0, 0, 0, 0, 157, 3, 105, 88, 0, 0, 0, 0, 0, 0, 158, 3, 110, 111, 114, 99, 105, 109, 79, 0, 159, 3, 105, 80, 0, 0, 0, 0, 0, 0, 160, 3, 111, 104, 82, 0, 0, 0, 0, 0, 161, 3, 97, 109, 103, 105, 83, 0, 0, 0, 163, 3, 117, 97, 84, 0, 0, 0, 0, 0, 164, 3, 110, 111, 108, 105, 115, 112, 85, 0, 165, 3, 105, 104, 80, 0, 0, 0, 0, 0, 166, 3, 105, 104, 67, 0, 0, 0, 0, 0, 167, 3, 105, 115, 80, 0, 0, 0, 0, 0, 168, 3, 97, 103, 101, 109, 79, 0, 0, 0, 169, 3, 97, 104, 112, 108, 97, 0, 0, 0, 177, 3, 97, 116, 101, 98, 0, 0, 0, 0, 178, 3, 97, 109, 109, 97, 103, 0, 0, 0, 179, 3, 97, 116, 108, 101, 100, 0, 0, 0, 180, 3, 110, 111, 108, 105, 115, 112, 101, 0, 181, 3, 97, 116, 101, 122, 0, 0, 0, 0, 182, 3, 97, 116, 101, 0, 0, 0, 0, 0, 183, 3, 97, 116, 101, 104, 116, 0, 0, 0, 184, 3, 97, 116, 111, 105, 0, 0, 0, 0, 185, 3, 97, 112, 112, 97, 107, 0, 0, 0, 186, 3, 97, 100, 98, 109, 97, 108, 0, 0, 187, 3, 117, 109, 0, 0, 0, 0, 0, 0, 188, 3, 117, 110, 0, 0, 0, 0, 0, 0, 189, 3, 105, 120, 0, 0, 0, 0, 0, 0, 190, 3, 110, 111, 114, 99, 105, 109, 111, 0, 191, 3, 105, 112, 0, 0, 0, 0, 0, 0, 192, 3, 111, 104, 114, 0, 0, 0, 0, 0, 193, 3, 102, 97, 109, 103, 105, 115, 0, 0, 194, 3, 97, 109, 103, 105, 115, 0, 0, 0, 195, 3, 117, 97, 116, 0, 0, 0, 0, 0, 196, 3, 110, 111, 108, 105, 115, 112, 117, 0, 197, 3, 105, 104, 112, 0, 0, 0, 0, 0, 198, 3, 105, 104, 99, 0, 0, 0, 0, 0, 199, 3, 105, 115, 112, 0, 0, 0, 0, 0, 200, 3, 97, 103, 101, 109, 111, 0, 0, 0, 201, 3, 109, 121, 115, 97, 116, 101, 104, 116, 209, 3, 104, 105, 115, 112, 117, 0, 0, 0, 210, 3, 118, 105, 112, 0, 0, 0, 0, 0, 214, 3, 112, 115, 110, 101, 0, 0, 0, 0, 2, 32, 112, 115, 109, 101, 0, 0, 0, 0, 3, 32, 112, 115, 110, 105, 104, 116, 0, 0, 9, 32, 106, 110, 119, 122, 0, 0, 0, 0, 12, 32, 106, 119, 122, 0, 0, 0, 0, 0, 13, 32, 109, 114, 108, 0, 0, 0, 0, 0, 14, 32, 109, 108, 114, 0, 0, 0, 0, 0, 15, 32, 104, 115, 97, 100, 110, 0, 0, 0, 19, 32, 104, 115, 97, 100, 109, 0, 0, 0, 20, 32, 111, 117, 113, 115, 108, 0, 0, 0, 24, 32, 111, 117, 113, 115, 114, 0, 0, 0, 25, 32, 111, 117, 113, 98, 115, 0, 0, 0, 26, 32, 111, 117, 113, 100, 108, 0, 0, 0, 28, 32, 111, 117, 113, 100, 114, 0, 0, 0, 29, 32, 111, 117, 113, 100, 98, 0, 0, 0, 30, 32, 114, 101, 103, 103, 97, 100, 0, 0, 32, 32, 114, 101, 103, 103, 97, 68, 0, 0, 33, 32, 108, 108, 117, 98, 0, 0, 0, 0, 34, 32, 112, 105, 108, 108, 101, 104, 0, 0, 38, 32, 108, 105, 109, 114, 101, 112, 0, 0, 48, 32, 101, 109, 105, 114, 112, 0, 0, 0, 50, 32, 101, 109, 105, 114, 80, 0, 0, 0, 51, 32, 111, 117, 113, 97, 115, 108, 0, 0, 57, 32, 111, 117, 113, 97, 115, 114, 0, 0, 58, 32, 101, 110, 105, 108, 111, 0, 0, 0, 62, 32, 108, 115, 97, 114, 102, 0, 0, 0, 68, 32, 111, 114, 117, 101, 0, 0, 0, 0, 172, 32, 101, 103, 97, 109, 105, 0, 0, 0, 17, 33, 112, 114, 101, 105, 101, 119, 0, 0, 24, 33, 108, 97, 101, 114, 0, 0, 0, 0, 28, 33, 101, 100, 97, 114, 116, 0, 0, 0, 34, 33, 109, 121, 115, 102, 101, 108, 97, 0, 53, 33, 114, 114, 97, 108, 0, 0, 0, 0, 144, 33, 114, 114, 97, 117, 0, 0, 0, 0, 145, 33, 114, 114, 97, 114, 0, 0, 0, 0, 146, 33, 114, 114, 97, 100, 0, 0, 0, 0, 147, 33, 114, 114, 97, 104, 0, 0, 0, 0, 148, 33, 114, 114, 97, 114, 99, 0, 0, 0, 181, 33, 114, 114, 65, 108, 0, 0, 0, 0, 208, 33, 114, 114, 65, 117, 0, 0, 0, 0, 209, 33, 114, 114, 65, 114, 0, 0, 0, 0, 210, 33, 114, 114, 65, 100, 0, 0, 0, 0, 211, 33, 114, 114, 65, 104, 0, 0, 0, 0, 212, 33, 108, 108, 97, 114, 111, 102, 0, 0, 0, 34, 116, 114, 97, 112, 0, 0, 0, 0, 2, 34, 116, 115, 105, 120, 101, 0, 0, 0, 3, 34, 121, 116, 112, 109, 101, 0, 0, 0, 5, 34, 97, 108, 98, 97, 110, 0, 0, 0, 7, 34, 110, 105, 115, 105, 0, 0, 0, 0, 8, 34, 110, 105, 116, 111, 110, 0, 0, 0, 9, 34, 105, 110, 0, 0, 0, 0, 0, 0, 11, 34, 100, 111, 114, 112, 0, 0, 0, 0, 15, 34, 109, 117, 115, 0, 0, 0, 0, 0, 17, 34, 115, 117, 110, 105, 109, 0, 0, 0, 18, 34, 116, 115, 97, 119, 111, 108, 0, 0, 23, 34, 99, 105, 100, 97, 114, 0, 0, 0, 26, 34, 112, 111, 114, 112, 0, 0, 0, 0, 29, 34, 110, 105, 102, 110, 105, 0, 0, 0, 30, 34, 103, 110, 97, 0, 0, 0, 0, 0, 32, 34, 100, 110, 97, 0, 0, 0, 0, 0, 39, 34, 114, 111, 0, 0, 0, 0, 0, 0, 40, 34, 112, 97, 99, 0, 0, 0, 0, 0, 41, 34, 112, 117, 99, 0, 0, 0, 0, 0, 42, 34, 116, 110, 105, 0, 0, 0, 0, 0, 43, 34, 52, 101, 114, 101, 104, 116, 0, 0, 52, 34, 109, 105, 115, 0, 0, 0, 0, 0, 60, 34, 103, 110, 111, 99, 0, 0, 0, 0, 69, 34, 112, 109, 121, 115, 97, 0, 0, 0, 72, 34, 101, 110, 0, 0, 0, 0, 0, 0, 96, 34, 118, 105, 117, 113, 101, 0, 0, 0, 97, 34, 101, 108, 0, 0, 0, 0, 0, 0, 100, 34, 101, 103, 0, 0, 0, 0, 0, 0, 101, 34, 98, 117, 115, 0, 0, 0, 0, 0, 130, 34, 112, 117, 115, 0, 0, 0, 0, 0, 131, 34, 98, 117, 115, 110, 0, 0, 0, 0, 132, 34, 101, 98, 117, 115, 0, 0, 0, 0, 134, 34, 101, 112, 117, 115, 0, 0, 0, 0, 135, 34, 115, 117, 108, 112, 111, 0, 0, 0, 149, 34, 115, 101, 109, 105, 116, 111, 0, 0, 151, 34, 112, 114, 101, 112, 0, 0, 0, 0, 165, 34, 116, 111, 100, 115, 0, 0, 0, 0, 197, 34, 108, 105, 101, 99, 108, 0, 0, 0, 8, 35, 108, 105, 101, 99, 114, 0, 0, 0, 9, 35, 114, 111, 111, 108, 102, 108, 0, 0, 10, 35, 114, 111, 111, 108, 102, 114, 0, 0, 11, 35, 103, 110, 97, 108, 0, 0, 0, 0, 41, 35, 103, 110, 97, 114, 0, 0, 0, 0, 42, 35, 122, 111, 108, 0, 0, 0, 0, 0, 202, 37, 115, 101, 100, 97, 112, 115, 0, 0, 96, 38, 115, 98, 117, 108, 99, 0, 0, 0, 99, 38, 115, 116, 114, 97, 101, 104, 0, 0, 101, 38, 115, 109, 97, 105, 100, 0, 0, 0, 102, 38 }; Dictionary dictionary = new Dictionary(source.Length / 10); while (!source.IsEmpty) { ulong key = BinaryPrimitives.ReadUInt64LittleEndian(source); char value = (char)BinaryPrimitives.ReadUInt16LittleEndian(source.Slice(8)); dictionary[key] = value; source = source.Slice(10); } return dictionary; } public static char Lookup(ReadOnlySpan entity) { if (entity.Length <= 8) { s_lookupTable.TryGetValue(ToUInt64Key(entity), out var value); return value; } return '\0'; } private static ulong ToUInt64Key(ReadOnlySpan entity) { ulong num = 0uL; for (int i = 0; i < entity.Length; i++) { if (entity[i] > 'ÿ') { return 0uL; } num = (num << 8) | entity[i]; } return num; } } [return: NotNullIfNotNull("value")] public static string? HtmlEncode(string? value) { if (string.IsNullOrEmpty(value)) { return value; } ReadOnlySpan input = value.AsSpan(); int num = IndexOfHtmlEncodingChars(input); if (num == -1) { return value; } ValueStringBuilder valueStringBuilder; if (value.Length < 80) { Span initialBuffer = stackalloc char[256]; valueStringBuilder = new ValueStringBuilder(initialBuffer); } else { valueStringBuilder = new ValueStringBuilder(value.Length + 200); } ValueStringBuilder output = valueStringBuilder; output.Append(input.Slice(0, num)); HtmlEncode(input.Slice(num), ref output); return output.ToString(); } public static void HtmlEncode(string? value, TextWriter output) { if (output == null) { throw new ArgumentNullException("output"); } if (string.IsNullOrEmpty(value)) { output.Write(value); return; } ReadOnlySpan input = value.AsSpan(); int num = IndexOfHtmlEncodingChars(input); if (num == -1) { output.Write(value); return; } ValueStringBuilder valueStringBuilder; if (value.Length < 80) { Span initialBuffer = stackalloc char[256]; valueStringBuilder = new ValueStringBuilder(initialBuffer); } else { valueStringBuilder = new ValueStringBuilder(value.Length + 200); } ValueStringBuilder output2 = valueStringBuilder; output2.Append(input.Slice(0, num)); HtmlEncode(input.Slice(num), ref output2); output.Write(output2.AsSpan()); output2.Dispose(); } private static void HtmlEncode(ReadOnlySpan input, ref ValueStringBuilder output) { for (int i = 0; i < input.Length; i++) { char c = input[i]; if (c <= '>') { switch (c) { case '<': output.Append("<"); break; case '>': output.Append(">"); break; case '"': output.Append("""); break; case '\'': output.Append("'"); break; case '&': output.Append("&"); break; default: output.Append(c); break; } continue; } int num = -1; if (c >= '\u00a0' && c < 'Ā') { num = c; } else if (char.IsSurrogate(c)) { int nextUnicodeScalarValueFromUtf16Surrogate = GetNextUnicodeScalarValueFromUtf16Surrogate(input, ref i); if (nextUnicodeScalarValueFromUtf16Surrogate >= 65536) { num = nextUnicodeScalarValueFromUtf16Surrogate; } else { c = (char)nextUnicodeScalarValueFromUtf16Surrogate; } } if (num >= 0) { output.Append("&#"); Span destination = output.AppendSpan(10); num.TryFormat(destination, out var charsWritten); output.Length -= 10 - charsWritten; output.Append(';'); } else { output.Append(c); } } } [return: NotNullIfNotNull("value")] public static string? HtmlDecode(string? value) { if (string.IsNullOrEmpty(value)) { return value; } ReadOnlySpan input = value.AsSpan(); int num = IndexOfHtmlDecodingChars(input); if (num == -1) { return value; } ValueStringBuilder valueStringBuilder; if (value.Length <= 256) { Span initialBuffer = stackalloc char[256]; valueStringBuilder = new ValueStringBuilder(initialBuffer); } else { valueStringBuilder = new ValueStringBuilder(value.Length); } ValueStringBuilder output = valueStringBuilder; output.Append(input.Slice(0, num)); HtmlDecode(input.Slice(num), ref output); return output.ToString(); } public static void HtmlDecode(string? value, TextWriter output) { if (output == null) { throw new ArgumentNullException("output"); } if (string.IsNullOrEmpty(value)) { output.Write(value); return; } ReadOnlySpan input = value.AsSpan(); int num = IndexOfHtmlDecodingChars(input); if (num == -1) { output.Write(value); return; } ValueStringBuilder valueStringBuilder; if (value.Length <= 256) { Span initialBuffer = stackalloc char[256]; valueStringBuilder = new ValueStringBuilder(initialBuffer); } else { valueStringBuilder = new ValueStringBuilder(value.Length); } ValueStringBuilder output2 = valueStringBuilder; output2.Append(input.Slice(0, num)); HtmlDecode(input.Slice(num), ref output2); output.Write(output2.AsSpan()); output2.Dispose(); } private static void HtmlDecode(ReadOnlySpan input, ref ValueStringBuilder output) { for (int i = 0; i < input.Length; i++) { char c = input[i]; if (c == '&') { ReadOnlySpan span = input.Slice(i + 1); int num = span.IndexOfAny(';', '&'); if (num >= 0 && span[num] == ';') { int num2 = i + 1 + num; if (num > 1 && span[0] == '#') { uint result; bool flag = ((span[1] == 'x' || span[1] == 'X') ? uint.TryParse(span.Slice(2, num - 2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out result) : uint.TryParse(span.Slice(1, num - 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out result)); if (flag) { flag = result < 55296 || (57343 < result && result <= 1114111); } if (flag) { if (result <= 65535) { output.Append((char)result); } else { ConvertSmpToUtf16(result, out var leadingSurrogate, out var trailingSurrogate); output.Append(leadingSurrogate); output.Append(trailingSurrogate); } i = num2; continue; } } else { ReadOnlySpan readOnlySpan = span.Slice(0, num); i = num2; char c2 = HtmlEntities.Lookup(readOnlySpan); if (c2 == '\0') { output.Append('&'); output.Append(readOnlySpan); output.Append(';'); continue; } c = c2; } } } output.Append(c); } } private static int IndexOfHtmlEncodingChars(ReadOnlySpan input) { for (int i = 0; i < input.Length; i++) { char c = input[i]; if (c <= '>') { switch (c) { case '"': case '&': case '\'': case '<': case '>': return i; } continue; } if (c >= '\u00a0' && c < 'Ā') { return i; } if (char.IsSurrogate(c)) { return i; } } return -1; } private static void GetEncodedBytes(byte[] originalBytes, int offset, int count, byte[] expandedBytes) { int num = 0; int num2 = offset + count; for (int i = offset; i < num2; i++) { byte b = originalBytes[i]; char c = (char)b; if (IsUrlSafeChar(c)) { expandedBytes[num++] = b; continue; } if (c == ' ') { expandedBytes[num++] = 43; continue; } expandedBytes[num++] = 37; expandedBytes[num++] = (byte)HexConverter.ToCharUpper(b >> 4); expandedBytes[num++] = (byte)HexConverter.ToCharUpper(b); } } [return: NotNullIfNotNull("value")] public static string? UrlEncode(string? value) { if (string.IsNullOrEmpty(value)) { return value; } int num = 0; int num2 = 0; foreach (char c in value) { if (IsUrlSafeChar(c)) { num++; } else if (c == ' ') { num2++; } } int num3 = num + num2; if (num3 == value.Length) { if (num2 != 0) { return value.Replace(' ', '+'); } return value; } int byteCount = Encoding.UTF8.GetByteCount(value); int num4 = byteCount - num3; int num5 = num4 * 2; byte[] array = new byte[byteCount + num5]; Encoding.UTF8.GetBytes(value, 0, value.Length, array, num5); GetEncodedBytes(array, num5, byteCount, array); return Encoding.UTF8.GetString(array); } [return: NotNullIfNotNull("value")] public static byte[]? UrlEncodeToBytes(byte[]? value, int offset, int count) { if (!ValidateUrlEncodingParameters(value, offset, count)) { return null; } bool flag = false; int num = 0; for (int i = 0; i < count; i++) { char c = (char)value[offset + i]; if (c == ' ') { flag = true; } else if (!IsUrlSafeChar(c)) { num++; } } if (!flag && num == 0) { byte[] array = new byte[count]; Buffer.BlockCopy(value, offset, array, 0, count); return array; } byte[] array2 = new byte[count + num * 2]; GetEncodedBytes(value, offset, count, array2); return array2; } [return: NotNullIfNotNull("value")] private static string UrlDecodeInternal(string value, Encoding encoding) { if (string.IsNullOrEmpty(value)) { return value; } int length = value.Length; UrlDecoder urlDecoder = new UrlDecoder(length, encoding); bool flag = false; bool flag2 = false; for (int i = 0; i < length; i++) { char c = value[i]; switch (c) { case '+': flag2 = true; c = ' '; break; case '%': if (i < length - 2) { int num = HexConverter.FromChar(value[i + 1]); int num2 = HexConverter.FromChar(value[i + 2]); if ((num | num2) != 255) { byte b = (byte)((num << 4) | num2); i += 2; urlDecoder.AddByte(b); flag = true; continue; } } break; } if ((c & 0xFF80) == 0) { urlDecoder.AddByte((byte)c); } else { urlDecoder.AddChar(c); } } if (!flag) { if (flag2) { return value.Replace('+', ' '); } return value; } return urlDecoder.GetString(); } [return: NotNullIfNotNull("bytes")] private static byte[] UrlDecodeInternal(byte[] bytes, int offset, int count) { if (!ValidateUrlEncodingParameters(bytes, offset, count)) { return null; } int num = 0; byte[] array = new byte[count]; for (int i = 0; i < count; i++) { int num2 = offset + i; byte b = bytes[num2]; switch (b) { case 43: b = 32; break; case 37: if (i < count - 2) { int num3 = HexConverter.FromChar(bytes[num2 + 1]); int num4 = HexConverter.FromChar(bytes[num2 + 2]); if ((num3 | num4) != 255) { b = (byte)((num3 << 4) | num4); i += 2; } } break; } array[num++] = b; } if (num < array.Length) { Array.Resize(ref array, num); } return array; } [return: NotNullIfNotNull("encodedValue")] public static string? UrlDecode(string? encodedValue) { return UrlDecodeInternal(encodedValue, Encoding.UTF8); } [return: NotNullIfNotNull("encodedValue")] public static byte[]? UrlDecodeToBytes(byte[]? encodedValue, int offset, int count) { return UrlDecodeInternal(encodedValue, offset, count); } private static void ConvertSmpToUtf16(uint smpChar, out char leadingSurrogate, out char trailingSurrogate) { int num = (int)(smpChar - 65536); leadingSurrogate = (char)(num / 1024 + 55296); trailingSurrogate = (char)(num % 1024 + 56320); } private static int GetNextUnicodeScalarValueFromUtf16Surrogate(ReadOnlySpan input, ref int index) { if (input.Length - index <= 1) { return 65533; } char c = input[index]; char c2 = input[index + 1]; if (!char.IsSurrogatePair(c, c2)) { return 65533; } index++; return (c - 55296) * 1024 + (c2 - 56320) + 65536; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsUrlSafeChar(char ch) { if ((uint)(ch - 97) > 25u && (uint)(ch - 65) > 25u && ((uint)(ch - 32) > 25u || ((1 << ch - 32) & 0x3FF6702) == 0)) { return ch == '_'; } return true; } private static bool ValidateUrlEncodingParameters(byte[] bytes, int offset, int count) { if (bytes == null && count == 0) { return false; } if (bytes == null) { throw new ArgumentNullException("bytes"); } if (offset < 0 || offset > bytes.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || offset + count > bytes.Length) { throw new ArgumentOutOfRangeException("count"); } return true; } private static int IndexOfHtmlDecodingChars(ReadOnlySpan input) { for (int i = 0; i < input.Length; i++) { char c = input[i]; if (c == '&' || char.IsSurrogate(c)) { return i; } } return -1; } } } namespace System.Globalization { public abstract class Calendar : ICloneable { private int _currentEraValue = -1; private bool _isReadOnly; public const int CurrentEra = 0; internal int _twoDigitYearMax = -1; public virtual DateTime MinSupportedDateTime => DateTime.MinValue; public virtual DateTime MaxSupportedDateTime => DateTime.MaxValue; public virtual CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.Unknown; internal virtual CalendarId ID => CalendarId.UNINITIALIZED_VALUE; internal virtual CalendarId BaseCalendarID => ID; public bool IsReadOnly => _isReadOnly; internal virtual int CurrentEraValue { get { if (_currentEraValue == -1) { _currentEraValue = CalendarData.GetCalendarCurrentEra(this); } return _currentEraValue; } } public abstract int[] Eras { get; } protected virtual int DaysInYearBeforeMinSupportedYear => 365; public virtual int TwoDigitYearMax { get { return _twoDigitYearMax; } set { VerifyWritable(); _twoDigitYearMax = value; } } public virtual object Clone() { object obj = MemberwiseClone(); ((Calendar)obj).SetReadOnlyState(readOnly: false); return obj; } public static Calendar ReadOnly(Calendar calendar) { if (calendar == null) { throw new ArgumentNullException("calendar"); } if (calendar.IsReadOnly) { return calendar; } Calendar calendar2 = (Calendar)calendar.MemberwiseClone(); calendar2.SetReadOnlyState(readOnly: true); return calendar2; } internal void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } internal void SetReadOnlyState(bool readOnly) { _isReadOnly = readOnly; } internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue) { if (ticks < minValue.Ticks || ticks > maxValue.Ticks) { throw new ArgumentException(SR.Format(SR.Argument_ResultCalendarRange, minValue, maxValue)); } } internal DateTime Add(DateTime time, double value, int scale) { double num = value * (double)scale + ((value >= 0.0) ? 0.5 : (-0.5)); if (!(num > -315537897600000.0) || !(num < 315537897600000.0)) { throw new ArgumentOutOfRangeException("value", value, SR.ArgumentOutOfRange_AddValue); } long num2 = (long)num; long ticks = time.Ticks + num2 * 10000; CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return new DateTime(ticks); } public virtual DateTime AddMilliseconds(DateTime time, double milliseconds) { return Add(time, milliseconds, 1); } public virtual DateTime AddDays(DateTime time, int days) { return Add(time, days, 86400000); } public virtual DateTime AddHours(DateTime time, int hours) { return Add(time, hours, 3600000); } public virtual DateTime AddMinutes(DateTime time, int minutes) { return Add(time, minutes, 60000); } public abstract DateTime AddMonths(DateTime time, int months); public virtual DateTime AddSeconds(DateTime time, int seconds) { return Add(time, seconds, 1000); } public virtual DateTime AddWeeks(DateTime time, int weeks) { return AddDays(time, weeks * 7); } public abstract DateTime AddYears(DateTime time, int years); public abstract int GetDayOfMonth(DateTime time); public abstract DayOfWeek GetDayOfWeek(DateTime time); public abstract int GetDayOfYear(DateTime time); public virtual int GetDaysInMonth(int year, int month) { return GetDaysInMonth(year, month, 0); } public abstract int GetDaysInMonth(int year, int month, int era); public virtual int GetDaysInYear(int year) { return GetDaysInYear(year, 0); } public abstract int GetDaysInYear(int year, int era); public abstract int GetEra(DateTime time); public virtual int GetHour(DateTime time) { return (int)(time.Ticks / 36000000000L % 24); } public virtual double GetMilliseconds(DateTime time) { return time.Ticks / 10000 % 1000; } public virtual int GetMinute(DateTime time) { return (int)(time.Ticks / 600000000 % 60); } public abstract int GetMonth(DateTime time); public virtual int GetMonthsInYear(int year) { return GetMonthsInYear(year, 0); } public abstract int GetMonthsInYear(int year, int era); public virtual int GetSecond(DateTime time) { return (int)(time.Ticks / 10000000 % 60); } internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek) { int num = GetDayOfYear(time) - 1; int num2 = (int)(GetDayOfWeek(time) - num % 7); int num3 = (num2 - firstDayOfWeek + 14) % 7; return (num + num3) / 7 + 1; } private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays) { int num = GetDayOfYear(time) - 1; int num2 = (int)(GetDayOfWeek(time) - num % 7); int num3 = (firstDayOfWeek - num2 + 14) % 7; if (num3 != 0 && num3 >= fullDays) { num3 -= 7; } int num4 = num - num3; if (num4 >= 0) { return num4 / 7 + 1; } if (time <= MinSupportedDateTime.AddDays(num)) { return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays); } return GetWeekOfYearFullDays(time.AddDays(-(num + 1)), firstDayOfWeek, fullDays); } private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek) { int num = GetDayOfYear(MinSupportedDateTime) - 1; int num2 = (int)(GetDayOfWeek(MinSupportedDateTime) - num % 7); int num3 = (firstDayOfWeek + 7 - num2) % 7; if (num3 == 0 || num3 >= minimumDaysInFirstWeek) { return 1; } int num4 = DaysInYearBeforeMinSupportedYear - 1; int num5 = num2 - 1 - num4 % 7; int num6 = (firstDayOfWeek - num5 + 14) % 7; int num7 = num4 - num6; if (num6 >= minimumDaysInFirstWeek) { num7 += 7; } return num7 / 7 + 1; } public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { if (firstDayOfWeek < DayOfWeek.Sunday || firstDayOfWeek > DayOfWeek.Saturday) { throw new ArgumentOutOfRangeException("firstDayOfWeek", firstDayOfWeek, SR.Format(SR.ArgumentOutOfRange_Range, DayOfWeek.Sunday, DayOfWeek.Saturday)); } return rule switch { CalendarWeekRule.FirstDay => GetFirstDayWeekOfYear(time, (int)firstDayOfWeek), CalendarWeekRule.FirstFullWeek => GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7), CalendarWeekRule.FirstFourDayWeek => GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4), _ => throw new ArgumentOutOfRangeException("rule", rule, SR.Format(SR.ArgumentOutOfRange_Range, CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek)), }; } public abstract int GetYear(DateTime time); public virtual bool IsLeapDay(int year, int month, int day) { return IsLeapDay(year, month, day, 0); } public abstract bool IsLeapDay(int year, int month, int day, int era); public virtual bool IsLeapMonth(int year, int month) { return IsLeapMonth(year, month, 0); } public abstract bool IsLeapMonth(int year, int month, int era); public virtual int GetLeapMonth(int year) { return GetLeapMonth(year, 0); } public virtual int GetLeapMonth(int year, int era) { if (!IsLeapYear(year, era)) { return 0; } int monthsInYear = GetMonthsInYear(year, era); for (int i = 1; i <= monthsInYear; i++) { if (IsLeapMonth(year, i, era)) { return i; } } return 0; } public virtual bool IsLeapYear(int year) { return IsLeapYear(year, 0); } public abstract bool IsLeapYear(int year, int era); public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { return ToDateTime(year, month, day, hour, minute, second, millisecond, 0); } public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era); internal virtual bool TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { result = DateTime.MinValue; try { result = ToDateTime(year, month, day, hour, minute, second, millisecond, era); return true; } catch (ArgumentException) { return false; } } internal virtual bool IsValidYear(int year, int era) { if (year >= GetYear(MinSupportedDateTime)) { return year <= GetYear(MaxSupportedDateTime); } return false; } internal virtual bool IsValidMonth(int year, int month, int era) { if (IsValidYear(year, era) && month >= 1) { return month <= GetMonthsInYear(year, era); } return false; } internal virtual bool IsValidDay(int year, int month, int day, int era) { if (IsValidMonth(year, month, era) && day >= 1) { return day <= GetDaysInMonth(year, month, era); } return false; } public virtual int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", year, SR.ArgumentOutOfRange_NeedNonNegNum); } if (year < 100) { return (TwoDigitYearMax / 100 - ((year > TwoDigitYearMax % 100) ? 1 : 0)) * 100 + year; } return year; } internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { if (hour < 0 || hour >= 24 || minute < 0 || minute >= 60 || second < 0 || second >= 60) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } if (millisecond < 0 || millisecond >= 1000) { throw new ArgumentOutOfRangeException("millisecond", millisecond, SR.Format(SR.ArgumentOutOfRange_Range, 0, 999)); } return InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + (long)millisecond * 10000L; } internal static int GetSystemTwoDigitYearSetting(CalendarId CalID, int defaultYearValue) { int num = (GlobalizationMode.UseNls ? CalendarData.NlsGetTwoDigitYearMax(CalID) : CalendarData.IcuGetTwoDigitYearMax(CalID)); if (num < 0) { return defaultYearValue; } return num; } } public enum CalendarAlgorithmType { Unknown, SolarCalendar, LunarCalendar, LunisolarCalendar } internal sealed class CalendarData { private struct IcuEnumCalendarsData { public List Results; public bool DisallowDuplicates; } private struct EnumData { public string userOverride; public List strings; } public struct NlsEnumCalendarsData { public int userOverride; public List calendars; } internal string sNativeName; internal string[] saShortDates; internal string[] saYearMonths; internal string[] saLongDates; internal string sMonthDay; internal string[] saEraNames; internal string[] saAbbrevEraNames; internal string[] saAbbrevEnglishEraNames; internal string[] saDayNames; internal string[] saAbbrevDayNames; internal string[] saSuperShortDayNames; internal string[] saMonthNames; internal string[] saAbbrevMonthNames; internal string[] saMonthGenitiveNames; internal string[] saAbbrevMonthGenitiveNames; internal string[] saLeapYearMonthNames; internal int iTwoDigitYearMax = 2029; private int iCurrentEra; internal bool bUseUserOverrides; internal static readonly CalendarData Invariant = CreateInvariant(); private CalendarData() { } private static CalendarData CreateInvariant() { CalendarData calendarData = new CalendarData(); calendarData.sNativeName = "Gregorian Calendar"; calendarData.iTwoDigitYearMax = 2029; calendarData.iCurrentEra = 1; calendarData.saShortDates = new string[2] { "MM/dd/yyyy", "yyyy-MM-dd" }; calendarData.saLongDates = new string[1] { "dddd, dd MMMM yyyy" }; calendarData.saYearMonths = new string[1] { "yyyy MMMM" }; calendarData.sMonthDay = "MMMM dd"; calendarData.saEraNames = new string[1] { "A.D." }; calendarData.saAbbrevEraNames = new string[1] { "AD" }; calendarData.saAbbrevEnglishEraNames = new string[1] { "AD" }; calendarData.saDayNames = new string[7] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; calendarData.saAbbrevDayNames = new string[7] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; calendarData.saSuperShortDayNames = new string[7] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; calendarData.saMonthNames = new string[13] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", string.Empty }; calendarData.saAbbrevMonthNames = new string[13] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", string.Empty }; calendarData.saMonthGenitiveNames = calendarData.saMonthNames; calendarData.saAbbrevMonthGenitiveNames = calendarData.saAbbrevMonthNames; calendarData.saLeapYearMonthNames = calendarData.saMonthNames; calendarData.bUseUserOverrides = false; return calendarData; } internal CalendarData(string localeName, CalendarId calendarId, bool bUseUserOverrides) { this.bUseUserOverrides = bUseUserOverrides; if (!LoadCalendarDataFromSystemCore(localeName, calendarId)) { if (sNativeName == null) { sNativeName = string.Empty; } if (saShortDates == null) { saShortDates = Invariant.saShortDates; } if (saYearMonths == null) { saYearMonths = Invariant.saYearMonths; } if (saLongDates == null) { saLongDates = Invariant.saLongDates; } if (sMonthDay == null) { sMonthDay = Invariant.sMonthDay; } if (saEraNames == null) { saEraNames = Invariant.saEraNames; } if (saAbbrevEraNames == null) { saAbbrevEraNames = Invariant.saAbbrevEraNames; } if (saAbbrevEnglishEraNames == null) { saAbbrevEnglishEraNames = Invariant.saAbbrevEnglishEraNames; } if (saDayNames == null) { saDayNames = Invariant.saDayNames; } if (saAbbrevDayNames == null) { saAbbrevDayNames = Invariant.saAbbrevDayNames; } if (saSuperShortDayNames == null) { saSuperShortDayNames = Invariant.saSuperShortDayNames; } if (saMonthNames == null) { saMonthNames = Invariant.saMonthNames; } if (saAbbrevMonthNames == null) { saAbbrevMonthNames = Invariant.saAbbrevMonthNames; } } if (calendarId == CalendarId.TAIWAN) { if (SystemSupportsTaiwaneseCalendar()) { sNativeName = "中華民國曆"; } else { sNativeName = string.Empty; } } if (saMonthGenitiveNames == null || saMonthGenitiveNames.Length == 0 || string.IsNullOrEmpty(saMonthGenitiveNames[0])) { saMonthGenitiveNames = saMonthNames; } if (saAbbrevMonthGenitiveNames == null || saAbbrevMonthGenitiveNames.Length == 0 || string.IsNullOrEmpty(saAbbrevMonthGenitiveNames[0])) { saAbbrevMonthGenitiveNames = saAbbrevMonthNames; } if (saLeapYearMonthNames == null || saLeapYearMonthNames.Length == 0 || string.IsNullOrEmpty(saLeapYearMonthNames[0])) { saLeapYearMonthNames = saMonthNames; } InitializeEraNames(localeName, calendarId); InitializeAbbreviatedEraNames(localeName, calendarId); if (calendarId == CalendarId.JAPAN) { saAbbrevEnglishEraNames = JapaneseCalendar.EnglishEraNames(); } else { saAbbrevEnglishEraNames = new string[1] { "" }; } iCurrentEra = saEraNames.Length; } private void InitializeEraNames(string localeName, CalendarId calendarId) { switch (calendarId) { case CalendarId.GREGORIAN: if (saEraNames == null || saEraNames.Length == 0 || string.IsNullOrEmpty(saEraNames[0])) { saEraNames = new string[1] { "A.D." }; } break; case CalendarId.GREGORIAN_US: case CalendarId.JULIAN: saEraNames = new string[1] { "A.D." }; break; case CalendarId.HEBREW: saEraNames = new string[1] { "C.E." }; break; case CalendarId.HIJRI: case CalendarId.UMALQURA: if (localeName == "dv-MV") { saEraNames = new string[1] { "ހ\u07a8ޖ\u07b0ރ\u07a9" }; } else { saEraNames = new string[1] { "بعد الهجرة" }; } break; case CalendarId.GREGORIAN_ARABIC: case CalendarId.GREGORIAN_XLIT_ENGLISH: case CalendarId.GREGORIAN_XLIT_FRENCH: saEraNames = new string[1] { "م" }; break; case CalendarId.GREGORIAN_ME_FRENCH: saEraNames = new string[1] { "ap. J.-C." }; break; case CalendarId.TAIWAN: if (SystemSupportsTaiwaneseCalendar()) { saEraNames = new string[1] { "中華民國" }; } else { saEraNames = new string[1] { string.Empty }; } break; case CalendarId.KOREA: saEraNames = new string[1] { "단기" }; break; case CalendarId.THAI: saEraNames = new string[1] { "พ.ศ." }; break; case CalendarId.JAPAN: case CalendarId.JAPANESELUNISOLAR: saEraNames = JapaneseCalendar.EraNames(); break; case CalendarId.PERSIAN: if (saEraNames == null || saEraNames.Length == 0 || string.IsNullOrEmpty(saEraNames[0])) { saEraNames = new string[1] { "ه.ش" }; } break; default: saEraNames = Invariant.saEraNames; break; } } private void InitializeAbbreviatedEraNames(string localeName, CalendarId calendarId) { switch (calendarId) { case CalendarId.GREGORIAN: if (saAbbrevEraNames == null || saAbbrevEraNames.Length == 0 || string.IsNullOrEmpty(saAbbrevEraNames[0])) { saAbbrevEraNames = new string[1] { "AD" }; } break; case CalendarId.GREGORIAN_US: case CalendarId.JULIAN: saAbbrevEraNames = new string[1] { "AD" }; break; case CalendarId.JAPAN: case CalendarId.JAPANESELUNISOLAR: saAbbrevEraNames = JapaneseCalendar.AbbrevEraNames(); break; case CalendarId.HIJRI: case CalendarId.UMALQURA: if (localeName == "dv-MV") { saAbbrevEraNames = new string[1] { "ހ." }; } else { saAbbrevEraNames = new string[1] { "هـ" }; } break; case CalendarId.TAIWAN: saAbbrevEraNames = new string[1]; if (saEraNames[0].Length == 4) { saAbbrevEraNames[0] = saEraNames[0].Substring(2, 2); } else { saAbbrevEraNames[0] = saEraNames[0]; } break; case CalendarId.PERSIAN: if (saAbbrevEraNames == null || saAbbrevEraNames.Length == 0 || string.IsNullOrEmpty(saAbbrevEraNames[0])) { saAbbrevEraNames = saEraNames; } break; default: saAbbrevEraNames = saEraNames; break; } } internal static int GetCalendarCurrentEra(Calendar calendar) { if (GlobalizationMode.Invariant) { return Invariant.iCurrentEra; } CalendarId baseCalendarID = calendar.BaseCalendarID; string name = CalendarIdToCultureName(baseCalendarID); return CultureInfo.GetCultureInfo(name)._cultureData.GetCalendar(baseCalendarID).iCurrentEra; } private static string CalendarIdToCultureName(CalendarId calendarId) { switch (calendarId) { case CalendarId.GREGORIAN_US: return "fa-IR"; case CalendarId.JAPAN: return "ja-JP"; case CalendarId.TAIWAN: return "zh-TW"; case CalendarId.KOREA: return "ko-KR"; case CalendarId.HIJRI: case CalendarId.GREGORIAN_ARABIC: case CalendarId.UMALQURA: return "ar-SA"; case CalendarId.THAI: return "th-TH"; case CalendarId.HEBREW: return "he-IL"; case CalendarId.GREGORIAN_ME_FRENCH: return "ar-DZ"; case CalendarId.GREGORIAN_XLIT_ENGLISH: case CalendarId.GREGORIAN_XLIT_FRENCH: return "ar-IQ"; default: return "en-US"; } } private static bool SystemSupportsTaiwaneseCalendar() { if (!GlobalizationMode.UseNls) { return IcuSystemSupportsTaiwaneseCalendar(); } return NlsSystemSupportsTaiwaneseCalendar(); } private bool IcuLoadCalendarDataFromSystem(string localeName, CalendarId calendarId) { bool flag = true; flag &= GetCalendarInfo(localeName, calendarId, CalendarDataType.NativeName, out sNativeName); flag &= GetCalendarInfo(localeName, calendarId, CalendarDataType.MonthDay, out sMonthDay); if (sMonthDay != null) { sMonthDay = NormalizeDatePattern(sMonthDay); } flag &= EnumDatePatterns(localeName, calendarId, CalendarDataType.ShortDates, out saShortDates); flag &= EnumDatePatterns(localeName, calendarId, CalendarDataType.LongDates, out saLongDates); flag &= EnumDatePatterns(localeName, calendarId, CalendarDataType.YearMonths, out saYearMonths); flag &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.DayNames, out saDayNames); flag &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.AbbrevDayNames, out saAbbrevDayNames); flag &= EnumCalendarInfo(localeName, calendarId, CalendarDataType.SuperShortDayNames, out saSuperShortDayNames); string leapHebrewMonthName = null; flag &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthNames, out saMonthNames, ref leapHebrewMonthName); if (leapHebrewMonthName != null) { saLeapYearMonthNames = (string[])saMonthNames.Clone(); saLeapYearMonthNames[6] = leapHebrewMonthName; saMonthNames[5] = saMonthNames[6]; saMonthNames[6] = leapHebrewMonthName; } flag &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthNames, out saAbbrevMonthNames, ref leapHebrewMonthName); flag &= EnumMonthNames(localeName, calendarId, CalendarDataType.MonthGenitiveNames, out saMonthGenitiveNames, ref leapHebrewMonthName); flag &= EnumMonthNames(localeName, calendarId, CalendarDataType.AbbrevMonthGenitiveNames, out saAbbrevMonthGenitiveNames, ref leapHebrewMonthName); flag &= EnumEraNames(localeName, calendarId, CalendarDataType.EraNames, out saEraNames); return flag & EnumEraNames(localeName, calendarId, CalendarDataType.AbbrevEraNames, out saAbbrevEraNames); } internal static int IcuGetTwoDigitYearMax(CalendarId calendarId) { return -1; } internal static int IcuGetCalendars(string localeName, CalendarId[] calendars) { int num = Interop.Globalization.GetCalendars(localeName, calendars, calendars.Length); if (num == 0 && calendars.Length != 0) { calendars[0] = CalendarId.GREGORIAN; num = 1; } return num; } private static bool IcuSystemSupportsTaiwaneseCalendar() { return true; } private unsafe static bool GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string calendarString) { return Interop.CallStringMethod(delegate(Span buffer, string locale, CalendarId id, CalendarDataType type) { fixed (char* result = buffer) { return Interop.Globalization.GetCalendarInfo(locale, id, type, result, buffer.Length); } }, localeName, calendarId, dataType, out calendarString); } private static bool EnumDatePatterns(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] datePatterns) { datePatterns = null; IcuEnumCalendarsData callbackContext = default(IcuEnumCalendarsData); callbackContext.Results = new List(); callbackContext.DisallowDuplicates = true; bool flag = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (flag) { List results = callbackContext.Results; for (int i = 0; i < results.Count; i++) { results[i] = NormalizeDatePattern(results[i]); } if (dataType == CalendarDataType.ShortDates) { FixDefaultShortDatePattern(results); } datePatterns = results.ToArray(); } return flag; } private static void FixDefaultShortDatePattern(List shortDatePatterns) { if (shortDatePatterns.Count == 0) { return; } string text = shortDatePatterns[0]; if (text.Length > 100) { return; } Span span = stackalloc char[text.Length + 2]; int i; for (i = 0; i < text.Length; i++) { if (text[i] == '\'') { do { span[i] = text[i]; i++; } while (i < text.Length && text[i] != '\''); if (i >= text.Length) { return; } } else if (text[i] == 'y') { span[i] = 'y'; break; } span[i] = text[i]; } if (i >= text.Length - 1 || text[i + 1] != 'y' || (i + 2 < text.Length && text[i + 2] == 'y')) { return; } span[i + 1] = 'y'; span[i + 2] = 'y'; span[i + 3] = 'y'; for (i += 2; i < text.Length; i++) { span[i + 2] = text[i]; } shortDatePatterns[0] = span.ToString(); for (int j = 1; j < shortDatePatterns.Count; j++) { if (shortDatePatterns[j] == shortDatePatterns[0]) { shortDatePatterns[j] = text; return; } } shortDatePatterns.Add(text); } private static string NormalizeDatePattern(string input) { StringBuilder stringBuilder = StringBuilderCache.Acquire(input.Length); int index = 0; while (index < input.Length) { switch (input[index]) { case '\'': stringBuilder.Append(input[index++]); while (index < input.Length) { char c = input[index++]; stringBuilder.Append(c); if (c == '\'') { break; } } break; case 'E': case 'c': case 'e': NormalizeDayOfWeek(input, stringBuilder, ref index); break; case 'L': case 'M': { int num = CountOccurrences(input, input[index], ref index); if (num > 4) { num = 3; } stringBuilder.Append('M', num); break; } case 'G': { int num = CountOccurrences(input, 'G', ref index); stringBuilder.Append('g'); break; } case 'y': { int num = CountOccurrences(input, 'y', ref index); if (num == 1) { num = 4; } stringBuilder.Append('y', num); break; } default: stringBuilder.Append(input[index++]); break; } } return StringBuilderCache.GetStringAndRelease(stringBuilder); } private static void NormalizeDayOfWeek(string input, StringBuilder destination, ref int index) { char value = input[index]; int val = CountOccurrences(input, value, ref index); val = Math.Max(val, 3); if (val > 4) { val = 3; } destination.Append('d', val); } private static int CountOccurrences(string input, char value, ref int index) { int num = index; while (index < input.Length && input[index] == value) { index++; } return index - num; } private static bool EnumMonthNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] monthNames, ref string leapHebrewMonthName) { monthNames = null; IcuEnumCalendarsData callbackContext = default(IcuEnumCalendarsData); callbackContext.Results = new List(); bool flag = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (flag) { if (callbackContext.Results.Count == 12) { callbackContext.Results.Add(string.Empty); } if (callbackContext.Results.Count > 13) { if (calendarId == CalendarId.HEBREW) { leapHebrewMonthName = callbackContext.Results[13]; } callbackContext.Results.RemoveRange(13, callbackContext.Results.Count - 13); } monthNames = callbackContext.Results.ToArray(); } return flag; } private static bool EnumEraNames(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] eraNames) { bool result = EnumCalendarInfo(localeName, calendarId, dataType, out eraNames); if (calendarId != CalendarId.JAPAN && calendarId != CalendarId.JAPANESELUNISOLAR) { string[] obj = eraNames; if (obj != null && obj.Length != 0) { string[] array = new string[1] { eraNames[eraNames.Length - 1] }; eraNames = array; } } return result; } internal static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string[] calendarData) { calendarData = null; IcuEnumCalendarsData callbackContext = default(IcuEnumCalendarsData); callbackContext.Results = new List(); bool flag = EnumCalendarInfo(localeName, calendarId, dataType, ref callbackContext); if (flag) { calendarData = callbackContext.Results.ToArray(); } return flag; } private unsafe static bool EnumCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, ref IcuEnumCalendarsData callbackContext) { return Interop.Globalization.EnumCalendarInfo((delegate* unmanaged)(delegate*)(&EnumCalendarInfoCallback), localeName, calendarId, dataType, (IntPtr)Unsafe.AsPointer(ref callbackContext)); } [UnmanagedCallersOnly] private unsafe static void EnumCalendarInfoCallback(char* calendarStringPtr, IntPtr context) { try { ReadOnlySpan strA = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(calendarStringPtr); ref IcuEnumCalendarsData reference = ref Unsafe.As(ref *(byte*)(void*)context); if (reference.DisallowDuplicates) { foreach (string result in reference.Results) { if (string.CompareOrdinal(strA, result) == 0) { return; } } } reference.Results.Add(strA.ToString()); } catch (Exception) { } } internal static int NlsGetTwoDigitYearMax(CalendarId calendarId) { if (!GlobalizationMode.Invariant) { if (!CallGetCalendarInfoEx((string)null, calendarId, 48u, out int data)) { return -1; } return data; } return Invariant.iTwoDigitYearMax; } private static bool NlsSystemSupportsTaiwaneseCalendar() { string data; return CallGetCalendarInfoEx("zh-TW", CalendarId.TAIWAN, 2u, out data); } private static bool CallGetCalendarInfoEx(string localeName, CalendarId calendar, uint calType, out int data) { return Interop.Kernel32.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType | 0x20000000u, IntPtr.Zero, 0, out data) != 0; } private unsafe static bool CallGetCalendarInfoEx(string localeName, CalendarId calendar, uint calType, out string data) { char* ptr = stackalloc char[80]; int num = Interop.Kernel32.GetCalendarInfoEx(localeName, (uint)calendar, IntPtr.Zero, calType, (IntPtr)ptr, 80, IntPtr.Zero); if (num > 0) { if (ptr[num - 1] == '\0') { num--; } data = new string(ptr, 0, num); return true; } data = ""; return false; } [UnmanagedCallersOnly] private unsafe static Interop.BOOL EnumCalendarInfoCallback(char* lpCalendarInfoString, uint calendar, IntPtr pReserved, void* lParam) { ref EnumData reference = ref Unsafe.As(ref *(byte*)lParam); try { string text = new string(lpCalendarInfoString); if (reference.userOverride != text) { reference.strings.Add(text); } return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } [UnmanagedCallersOnly] private unsafe static Interop.BOOL EnumCalendarsCallback(char* lpCalendarInfoString, uint calendar, IntPtr reserved, void* lParam) { ref NlsEnumCalendarsData reference = ref Unsafe.As(ref *(byte*)lParam); try { if (reference.userOverride != calendar) { reference.calendars.Add((int)calendar); } return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } private bool LoadCalendarDataFromSystemCore(string localeName, CalendarId calendarId) { if (GlobalizationMode.UseNls) { return NlsLoadCalendarDataFromSystem(localeName, calendarId); } bool flag = IcuLoadCalendarDataFromSystem(localeName, calendarId); if (flag && bUseUserOverrides) { NormalizeCalendarId(ref calendarId, ref localeName); flag &= CallGetCalendarInfoEx(localeName, calendarId, 48u, out iTwoDigitYearMax); CalendarId calendarId2 = (CalendarId)CultureData.GetLocaleInfoExInt(localeName, 4105u); if (calendarId2 == calendarId) { string value = CultureData.ReescapeWin32String(CultureData.GetLocaleInfoEx(localeName, 31u)); string value2 = CultureData.ReescapeWin32String(CultureData.GetLocaleInfoEx(localeName, 32u)); InsertOrSwapOverride(value, ref saShortDates); InsertOrSwapOverride(value2, ref saLongDates); } } return flag; } private void InsertOrSwapOverride(string value, ref string[] destination) { if (value == null) { return; } for (int i = 0; i < destination.Length; i++) { if (destination[i] == value) { if (i > 0) { string text = destination[0]; destination[0] = value; destination[i] = text; } return; } } string[] array = new string[destination.Length + 1]; array[0] = value; Array.Copy(destination, 0, array, 1, destination.Length); destination = array; } private bool NlsLoadCalendarDataFromSystem(string localeName, CalendarId calendarId) { bool flag = true; uint num = ((!bUseUserOverrides) ? 2147483648u : 0u); NormalizeCalendarId(ref calendarId, ref localeName); flag &= CallGetCalendarInfoEx(localeName, calendarId, 0x30u | num, out iTwoDigitYearMax); flag &= CallGetCalendarInfoEx(localeName, calendarId, 2u, out sNativeName); flag &= CallGetCalendarInfoEx(localeName, calendarId, 56u, out sMonthDay); flag &= CallEnumCalendarInfo(localeName, calendarId, 5u, 0x1Fu | num, out saShortDates); flag &= CallEnumCalendarInfo(localeName, calendarId, 6u, 0x20u | num, out saLongDates); flag &= CallEnumCalendarInfo(localeName, calendarId, 47u, 4102u, out saYearMonths); flag &= GetCalendarDayInfo(localeName, calendarId, 13u, out saDayNames); flag &= GetCalendarDayInfo(localeName, calendarId, 20u, out saAbbrevDayNames); flag &= GetCalendarMonthInfo(localeName, calendarId, 21u, out saMonthNames); flag &= GetCalendarMonthInfo(localeName, calendarId, 34u, out saAbbrevMonthNames); GetCalendarDayInfo(localeName, calendarId, 55u, out saSuperShortDayNames); if (calendarId == CalendarId.GREGORIAN) { GetCalendarMonthInfo(localeName, calendarId, 268435477u, out saMonthGenitiveNames); GetCalendarMonthInfo(localeName, calendarId, 268435490u, out saAbbrevMonthGenitiveNames); } CallEnumCalendarInfo(localeName, calendarId, 4u, 0u, out saEraNames); CallEnumCalendarInfo(localeName, calendarId, 57u, 0u, out saAbbrevEraNames); saShortDates = CultureData.ReescapeWin32Strings(saShortDates); saLongDates = CultureData.ReescapeWin32Strings(saLongDates); saYearMonths = CultureData.ReescapeWin32Strings(saYearMonths); sMonthDay = CultureData.ReescapeWin32String(sMonthDay); return flag; } private static void NormalizeCalendarId(ref CalendarId calendarId, ref string localeName) { switch (calendarId) { case CalendarId.JAPANESELUNISOLAR: calendarId = CalendarId.JAPAN; break; case CalendarId.JULIAN: case CalendarId.CHINESELUNISOLAR: case CalendarId.SAKA: case CalendarId.LUNAR_ETO_CHN: case CalendarId.LUNAR_ETO_KOR: case CalendarId.LUNAR_ETO_ROKUYOU: case CalendarId.KOREANLUNISOLAR: case CalendarId.TAIWANLUNISOLAR: calendarId = CalendarId.GREGORIAN_US; break; } CheckSpecialCalendar(ref calendarId, ref localeName); } private static void CheckSpecialCalendar(ref CalendarId calendar, ref string localeName) { switch (calendar) { case CalendarId.GREGORIAN_US: { if (!CallGetCalendarInfoEx(localeName, calendar, 2u, out string data)) { localeName = "fa-IR"; if (!CallGetCalendarInfoEx(localeName, calendar, 2u, out data)) { localeName = "en-US"; calendar = CalendarId.GREGORIAN; } } break; } case CalendarId.TAIWAN: if (!NlsSystemSupportsTaiwaneseCalendar()) { calendar = CalendarId.GREGORIAN; } break; } } private unsafe static bool CallEnumCalendarInfo(string localeName, CalendarId calendar, uint calType, uint lcType, out string[] data) { EnumData value = default(EnumData); value.userOverride = null; value.strings = new List(); if (lcType != 0 && (lcType & 0x80000000u) == 0) { CalendarId calendarId = (CalendarId)CultureData.GetLocaleInfoExInt(localeName, 4105u); if (calendarId == calendar) { string localeInfoEx = CultureData.GetLocaleInfoEx(localeName, lcType); if (localeInfoEx != null) { value.userOverride = localeInfoEx; value.strings.Add(localeInfoEx); } } } Interop.Kernel32.EnumCalendarInfoExEx((delegate* unmanaged)(delegate*)(&EnumCalendarInfoCallback), localeName, (uint)calendar, null, calType, Unsafe.AsPointer(ref value)); if (value.strings.Count == 0) { data = null; return false; } string[] array = value.strings.ToArray(); if (calType == 57 || calType == 4) { Array.Reverse(array, 0, array.Length); } data = array; return true; } private static bool GetCalendarDayInfo(string localeName, CalendarId calendar, uint calType, out string[] outputStrings) { bool flag = true; string[] array = new string[7]; int num = 0; while (num < 7) { flag &= CallGetCalendarInfoEx(localeName, calendar, calType, out array[num]); if (num == 0) { calType -= 7; } num++; calType++; } outputStrings = array; return flag; } private static bool GetCalendarMonthInfo(string localeName, CalendarId calendar, uint calType, out string[] outputStrings) { string[] array = new string[13]; int num = 0; while (num < 13) { if (!CallGetCalendarInfoEx(localeName, calendar, calType, out array[num])) { array[num] = ""; } num++; calType++; } outputStrings = array; return true; } internal static int GetCalendarsCore(string localeName, bool useUserOverride, CalendarId[] calendars) { if (GlobalizationMode.UseNls) { return NlsGetCalendars(localeName, useUserOverride, calendars); } int num = IcuGetCalendars(localeName, calendars); if (useUserOverride) { int localeInfoExInt = CultureData.GetLocaleInfoExInt(localeName, 4105u); if (localeInfoExInt != 0 && (uint)(ushort)localeInfoExInt != (uint)calendars[0]) { CalendarId calendarId = (CalendarId)localeInfoExInt; for (int i = 1; i < calendars.Length; i++) { if (calendars[i] == calendarId) { CalendarId calendarId2 = calendars[0]; calendars[0] = calendarId; calendars[i] = calendarId2; return num; } } num = ((num < calendars.Length) ? (num + 1) : num); Span span = stackalloc CalendarId[num]; span[0] = calendarId; calendars.AsSpan(0, num - 1).CopyTo(span.Slice(1)); span.CopyTo(calendars); } } return num; } private unsafe static int NlsGetCalendars(string localeName, bool useUserOverride, CalendarId[] calendars) { NlsEnumCalendarsData value = default(NlsEnumCalendarsData); value.userOverride = 0; value.calendars = new List(); if (useUserOverride) { int localeInfoExInt = CultureData.GetLocaleInfoExInt(localeName, 4105u); if (localeInfoExInt != 0) { value.userOverride = localeInfoExInt; value.calendars.Add(localeInfoExInt); } } Interop.Kernel32.EnumCalendarInfoExEx((delegate* unmanaged)(delegate*)(&EnumCalendarsCallback), localeName, uint.MaxValue, null, 1u, Unsafe.AsPointer(ref value)); for (int i = 0; i < Math.Min(calendars.Length, value.calendars.Count); i++) { calendars[i] = (CalendarId)value.calendars[i]; } return value.calendars.Count; } } internal enum CalendarDataType { Uninitialized, NativeName, MonthDay, ShortDates, LongDates, YearMonths, DayNames, AbbrevDayNames, MonthNames, AbbrevMonthNames, SuperShortDayNames, MonthGenitiveNames, AbbrevMonthGenitiveNames, EraNames, AbbrevEraNames } public enum CalendarWeekRule { FirstDay, FirstFullWeek, FirstFourDayWeek } internal static class CalendricalCalculationsHelper { private enum CorrectionAlgorithm { Default, Year1988to2019, Year1900to1987, Year1800to1899, Year1700to1799, Year1620to1699 } private struct EphemerisCorrectionAlgorithmMap { internal int _lowestYear; internal CorrectionAlgorithm _algorithm; public EphemerisCorrectionAlgorithmMap(int year, CorrectionAlgorithm algorithm) { _lowestYear = year; _algorithm = algorithm; } } private static readonly long s_startOf1810 = GetNumberOfDays(new DateTime(1810, 1, 1)); private static readonly long s_startOf1900Century = GetNumberOfDays(new DateTime(1900, 1, 1)); private static readonly double[] s_coefficients1900to1987 = new double[8] { -2E-05, 0.000297, 0.025184, -0.181133, 0.55304, -0.861938, 0.677066, -0.212591 }; private static readonly double[] s_coefficients1800to1899 = new double[11] { -9E-06, 0.003844, 0.083563, 0.865736, 4.867575, 15.845535, 31.332267, 38.291999, 28.316289, 11.636204, 2.043794 }; private static readonly double[] s_coefficients1700to1799 = new double[4] { 8.118780842, -0.005092142, 0.003336121, -2.66484E-05 }; private static readonly double[] s_coefficients1620to1699 = new double[3] { 196.58333, -4.0675, 0.0219167 }; private static readonly double[] s_lambdaCoefficients = new double[3] { 280.46645, 36000.76983, 0.0003032 }; private static readonly double[] s_anomalyCoefficients = new double[4] { 357.5291, 35999.0503, -0.0001559, -4.8E-07 }; private static readonly double[] s_eccentricityCoefficients = new double[3] { 0.016708617, -4.2037E-05, -1.236E-07 }; private static readonly double[] s_coefficients = new double[4] { Angle(23, 26, 21.448), Angle(0, 0, -46.815), Angle(0, 0, -0.00059), Angle(0, 0, 0.001813) }; private static readonly double[] s_coefficientsA = new double[3] { 124.9, -1934.134, 0.002063 }; private static readonly double[] s_coefficientsB = new double[3] { 201.11, 72001.5377, 0.00057 }; private static readonly EphemerisCorrectionAlgorithmMap[] s_ephemerisCorrectionTable = new EphemerisCorrectionAlgorithmMap[7] { new EphemerisCorrectionAlgorithmMap(2020, CorrectionAlgorithm.Default), new EphemerisCorrectionAlgorithmMap(1988, CorrectionAlgorithm.Year1988to2019), new EphemerisCorrectionAlgorithmMap(1900, CorrectionAlgorithm.Year1900to1987), new EphemerisCorrectionAlgorithmMap(1800, CorrectionAlgorithm.Year1800to1899), new EphemerisCorrectionAlgorithmMap(1700, CorrectionAlgorithm.Year1700to1799), new EphemerisCorrectionAlgorithmMap(1620, CorrectionAlgorithm.Year1620to1699), new EphemerisCorrectionAlgorithmMap(int.MinValue, CorrectionAlgorithm.Default) }; private static double RadiansFromDegrees(double degree) { return degree * Math.PI / 180.0; } private static double SinOfDegree(double degree) { return Math.Sin(RadiansFromDegrees(degree)); } private static double CosOfDegree(double degree) { return Math.Cos(RadiansFromDegrees(degree)); } private static double TanOfDegree(double degree) { return Math.Tan(RadiansFromDegrees(degree)); } public static double Angle(int degrees, int minutes, double seconds) { return (seconds / 60.0 + (double)minutes) / 60.0 + (double)degrees; } private static double Obliquity(double julianCenturies) { return PolynomialSum(s_coefficients, julianCenturies); } internal static long GetNumberOfDays(DateTime date) { return date.Ticks / 864000000000L; } private static int GetGregorianYear(double numberOfDays) { return new DateTime(Math.Min((long)(Math.Floor(numberOfDays) * 864000000000.0), DateTime.MaxValue.Ticks)).Year; } private static double Reminder(double divisor, double dividend) { double num = Math.Floor(divisor / dividend); return divisor - dividend * num; } private static double NormalizeLongitude(double longitude) { longitude = Reminder(longitude, 360.0); if (longitude < 0.0) { longitude += 360.0; } return longitude; } public static double AsDayFraction(double longitude) { return longitude / 360.0; } private static double PolynomialSum(double[] coefficients, double indeterminate) { double num = coefficients[0]; double num2 = 1.0; for (int i = 1; i < coefficients.Length; i++) { num2 *= indeterminate; num += coefficients[i] * num2; } return num; } private static double CenturiesFrom1900(int gregorianYear) { long numberOfDays = GetNumberOfDays(new DateTime(gregorianYear, 7, 1)); return (double)(numberOfDays - s_startOf1900Century) / 36525.0; } private static double DefaultEphemerisCorrection(int gregorianYear) { long numberOfDays = GetNumberOfDays(new DateTime(gregorianYear, 1, 1)); double num = numberOfDays - s_startOf1810; double x = 0.5 + num; return (Math.Pow(x, 2.0) / 41048480.0 - 15.0) / 86400.0; } private static double EphemerisCorrection1988to2019(int gregorianYear) { return (double)(gregorianYear - 1933) / 86400.0; } private static double EphemerisCorrection1900to1987(int gregorianYear) { double indeterminate = CenturiesFrom1900(gregorianYear); return PolynomialSum(s_coefficients1900to1987, indeterminate); } private static double EphemerisCorrection1800to1899(int gregorianYear) { double indeterminate = CenturiesFrom1900(gregorianYear); return PolynomialSum(s_coefficients1800to1899, indeterminate); } private static double EphemerisCorrection1700to1799(int gregorianYear) { double indeterminate = gregorianYear - 1700; return PolynomialSum(s_coefficients1700to1799, indeterminate) / 86400.0; } private static double EphemerisCorrection1620to1699(int gregorianYear) { double indeterminate = gregorianYear - 1600; return PolynomialSum(s_coefficients1620to1699, indeterminate) / 86400.0; } private static double EphemerisCorrection(double time) { int gregorianYear = GetGregorianYear(time); EphemerisCorrectionAlgorithmMap[] array = s_ephemerisCorrectionTable; for (int i = 0; i < array.Length; i++) { EphemerisCorrectionAlgorithmMap ephemerisCorrectionAlgorithmMap = array[i]; if (ephemerisCorrectionAlgorithmMap._lowestYear <= gregorianYear) { switch (ephemerisCorrectionAlgorithmMap._algorithm) { case CorrectionAlgorithm.Default: return DefaultEphemerisCorrection(gregorianYear); case CorrectionAlgorithm.Year1988to2019: return EphemerisCorrection1988to2019(gregorianYear); case CorrectionAlgorithm.Year1900to1987: return EphemerisCorrection1900to1987(gregorianYear); case CorrectionAlgorithm.Year1800to1899: return EphemerisCorrection1800to1899(gregorianYear); case CorrectionAlgorithm.Year1700to1799: return EphemerisCorrection1700to1799(gregorianYear); case CorrectionAlgorithm.Year1620to1699: return EphemerisCorrection1620to1699(gregorianYear); } break; } } return DefaultEphemerisCorrection(gregorianYear); } public static double JulianCenturies(double moment) { double num = moment + EphemerisCorrection(moment); return (num - 730120.5) / 36525.0; } private static bool IsNegative(double value) { return Math.Sign(value) == -1; } private static double CopySign(double value, double sign) { if (IsNegative(value) != IsNegative(sign)) { return 0.0 - value; } return value; } private static double EquationOfTime(double time) { double num = JulianCenturies(time); double num2 = PolynomialSum(s_lambdaCoefficients, num); double num3 = PolynomialSum(s_anomalyCoefficients, num); double num4 = PolynomialSum(s_eccentricityCoefficients, num); double num5 = Obliquity(num); double num6 = TanOfDegree(num5 / 2.0); double num7 = num6 * num6; double num8 = num7 * SinOfDegree(2.0 * num2) - 2.0 * num4 * SinOfDegree(num3) + 4.0 * num4 * num7 * SinOfDegree(num3) * CosOfDegree(2.0 * num2) - 0.5 * Math.Pow(num7, 2.0) * SinOfDegree(4.0 * num2) - 1.25 * Math.Pow(num4, 2.0) * SinOfDegree(2.0 * num3); double num9 = num8 / (Math.PI * 2.0); return CopySign(Math.Min(Math.Abs(num9), 0.5), num9); } private static double AsLocalTime(double apparentMidday, double longitude) { double time = apparentMidday - AsDayFraction(longitude); return apparentMidday - EquationOfTime(time); } public static double Midday(double date, double longitude) { return AsLocalTime(date + 0.5, longitude) - AsDayFraction(longitude); } private static double InitLongitude(double longitude) { return NormalizeLongitude(longitude + 180.0) - 180.0; } public static double MiddayAtPersianObservationSite(double date) { return Midday(date, InitLongitude(52.5)); } private static double PeriodicTerm(double julianCenturies, int x, double y, double z) { return (double)x * SinOfDegree(y + z * julianCenturies); } private static double SumLongSequenceOfPeriodicTerms(double julianCenturies) { double num = 0.0; num += PeriodicTerm(julianCenturies, 403406, 270.54861, 0.9287892); num += PeriodicTerm(julianCenturies, 195207, 340.19128, 35999.1376958); num += PeriodicTerm(julianCenturies, 119433, 63.91854, 35999.4089666); num += PeriodicTerm(julianCenturies, 112392, 331.2622, 35998.7287385); num += PeriodicTerm(julianCenturies, 3891, 317.843, 71998.20261); num += PeriodicTerm(julianCenturies, 2819, 86.631, 71998.4403); num += PeriodicTerm(julianCenturies, 1721, 240.052, 36000.35726); num += PeriodicTerm(julianCenturies, 660, 310.26, 71997.4812); num += PeriodicTerm(julianCenturies, 350, 247.23, 32964.4678); num += PeriodicTerm(julianCenturies, 334, 260.87, -19.441); num += PeriodicTerm(julianCenturies, 314, 297.82, 445267.1117); num += PeriodicTerm(julianCenturies, 268, 343.14, 45036.884); num += PeriodicTerm(julianCenturies, 242, 166.79, 3.1008); num += PeriodicTerm(julianCenturies, 234, 81.53, 22518.4434); num += PeriodicTerm(julianCenturies, 158, 3.5, -19.9739); num += PeriodicTerm(julianCenturies, 132, 132.75, 65928.9345); num += PeriodicTerm(julianCenturies, 129, 182.95, 9038.0293); num += PeriodicTerm(julianCenturies, 114, 162.03, 3034.7684); num += PeriodicTerm(julianCenturies, 99, 29.8, 33718.148); num += PeriodicTerm(julianCenturies, 93, 266.4, 3034.448); num += PeriodicTerm(julianCenturies, 86, 249.2, -2280.773); num += PeriodicTerm(julianCenturies, 78, 157.6, 29929.992); num += PeriodicTerm(julianCenturies, 72, 257.8, 31556.493); num += PeriodicTerm(julianCenturies, 68, 185.1, 149.588); num += PeriodicTerm(julianCenturies, 64, 69.9, 9037.75); num += PeriodicTerm(julianCenturies, 46, 8.0, 107997.405); num += PeriodicTerm(julianCenturies, 38, 197.1, -4444.176); num += PeriodicTerm(julianCenturies, 37, 250.4, 151.771); num += PeriodicTerm(julianCenturies, 32, 65.3, 67555.316); num += PeriodicTerm(julianCenturies, 29, 162.7, 31556.08); num += PeriodicTerm(julianCenturies, 28, 341.5, -4561.54); num += PeriodicTerm(julianCenturies, 27, 291.6, 107996.706); num += PeriodicTerm(julianCenturies, 27, 98.5, 1221.655); num += PeriodicTerm(julianCenturies, 25, 146.7, 62894.167); num += PeriodicTerm(julianCenturies, 24, 110.0, 31437.369); num += PeriodicTerm(julianCenturies, 21, 5.2, 14578.298); num += PeriodicTerm(julianCenturies, 21, 342.6, -31931.757); num += PeriodicTerm(julianCenturies, 20, 230.9, 34777.243); num += PeriodicTerm(julianCenturies, 18, 256.1, 1221.999); num += PeriodicTerm(julianCenturies, 17, 45.3, 62894.511); num += PeriodicTerm(julianCenturies, 14, 242.9, -4442.039); num += PeriodicTerm(julianCenturies, 13, 115.2, 107997.909); num += PeriodicTerm(julianCenturies, 13, 151.8, 119.066); num += PeriodicTerm(julianCenturies, 13, 285.3, 16859.071); num += PeriodicTerm(julianCenturies, 12, 53.3, -4.578); num += PeriodicTerm(julianCenturies, 10, 126.6, 26895.292); num += PeriodicTerm(julianCenturies, 10, 205.7, -39.127); num += PeriodicTerm(julianCenturies, 10, 85.9, 12297.536); return num + PeriodicTerm(julianCenturies, 10, 146.1, 90073.778); } private static double Aberration(double julianCenturies) { return 9.74E-05 * CosOfDegree(177.63 + 35999.01848 * julianCenturies) - 0.005575; } private static double Nutation(double julianCenturies) { double degree = PolynomialSum(s_coefficientsA, julianCenturies); double degree2 = PolynomialSum(s_coefficientsB, julianCenturies); return -0.004778 * SinOfDegree(degree) - 0.0003667 * SinOfDegree(degree2); } public static double Compute(double time) { double num = JulianCenturies(time); double num2 = 282.7771834 + 36000.76953744 * num + 5.729577951308232E-06 * SumLongSequenceOfPeriodicTerms(num); double longitude = num2 + Aberration(num) + Nutation(num); return InitLongitude(longitude); } public static double AsSeason(double longitude) { if (!(longitude < 0.0)) { return longitude; } return longitude + 360.0; } private static double EstimatePrior(double longitude, double time) { double num = time - 1.0145616361111112 * AsSeason(InitLongitude(Compute(time) - longitude)); double num2 = InitLongitude(Compute(num) - longitude); return Math.Min(time, num - 1.0145616361111112 * num2); } internal static long PersianNewYearOnOrBefore(long numberOfDays) { double date = numberOfDays; double d = EstimatePrior(0.0, MiddayAtPersianObservationSite(date)); long num = (long)Math.Floor(d) - 1; long num2 = num + 3; long num3; for (num3 = num; num3 != num2; num3++) { double time = MiddayAtPersianObservationSite(num3); double num4 = Compute(time); if (0.0 <= num4 && num4 <= 2.0) { break; } } return num3 - 1; } } public static class CharUnicodeInfo { private static ReadOnlySpan CategoryCasingLevel1Index => new byte[2176] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 28, 29, 26, 30, 31, 32, 33, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 34, 35, 35, 35, 35, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 26, 57, 58, 59, 59, 59, 59, 59, 26, 26, 60, 59, 59, 59, 59, 59, 59, 59, 26, 61, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 26, 62, 59, 63, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 64, 26, 26, 65, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 66, 67, 59, 59, 59, 59, 68, 59, 59, 59, 59, 59, 59, 59, 59, 59, 69, 70, 71, 72, 73, 74, 59, 59, 75, 76, 59, 59, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 59, 87, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 88, 26, 26, 26, 26, 26, 26, 26, 89, 90, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 91, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 92, 59, 59, 59, 59, 59, 59, 26, 93, 59, 87, 26, 26, 26, 26, 26, 26, 26, 26, 26, 94, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 87, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 87, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 87, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 87, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 87, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 87, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 87, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 87, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 87, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 87, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 87, 95, 96, 96, 96, 96, 96, 96, 96, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 59, 87, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 97, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 97 }; private static ReadOnlySpan CategoryCasingLevel2Index => new byte[6272] { 0, 0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0, 7, 0, 8, 0, 1, 0, 9, 0, 10, 0, 11, 0, 12, 0, 13, 0, 14, 0, 15, 0, 15, 0, 15, 0, 16, 0, 17, 0, 15, 0, 15, 0, 18, 0, 19, 0, 20, 0, 21, 0, 22, 0, 23, 0, 24, 0, 15, 0, 25, 0, 15, 0, 15, 0, 26, 0, 27, 0, 28, 0, 29, 0, 30, 0, 31, 0, 32, 0, 33, 0, 34, 0, 35, 0, 36, 0, 37, 0, 38, 0, 39, 0, 40, 0, 40, 0, 40, 0, 40, 0, 41, 0, 40, 0, 40, 0, 42, 0, 43, 0, 44, 0, 45, 0, 46, 0, 47, 0, 48, 0, 15, 0, 49, 0, 50, 0, 11, 0, 11, 0, 13, 0, 13, 0, 51, 0, 15, 0, 15, 0, 52, 0, 15, 0, 15, 0, 15, 0, 53, 0, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 54, 0, 55, 0, 56, 0, 57, 0, 58, 0, 59, 0, 60, 0, 40, 0, 61, 0, 62, 0, 63, 0, 64, 0, 65, 0, 66, 0, 67, 0, 63, 0, 63, 0, 68, 0, 40, 0, 69, 0, 70, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 71, 0, 72, 0, 73, 0, 74, 0, 75, 0, 63, 0, 40, 0, 76, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 77, 0, 78, 0, 79, 0, 63, 0, 80, 0, 81, 0, 63, 0, 82, 0, 83, 0, 84, 0, 63, 0, 85, 0, 86, 0, 87, 0, 87, 0, 87, 0, 63, 0, 88, 0, 89, 0, 90, 0, 91, 0, 40, 0, 92, 0, 93, 0, 93, 0, 94, 0, 95, 0, 96, 0, 97, 0, 98, 0, 99, 0, 100, 0, 101, 0, 102, 0, 103, 0, 104, 0, 105, 0, 106, 0, 107, 0, 100, 0, 101, 0, 108, 0, 109, 0, 110, 0, 111, 0, 112, 0, 113, 0, 114, 0, 101, 0, 115, 0, 116, 0, 117, 0, 105, 0, 118, 0, 119, 0, 100, 0, 101, 0, 120, 0, 121, 0, 122, 0, 105, 0, 123, 0, 124, 0, 125, 0, 126, 0, 127, 0, 128, 0, 129, 0, 111, 0, 130, 0, 131, 0, 132, 0, 101, 0, 133, 0, 134, 0, 135, 0, 105, 0, 136, 0, 137, 0, 132, 0, 101, 0, 138, 0, 139, 0, 140, 0, 105, 0, 141, 0, 142, 0, 132, 0, 93, 0, 143, 0, 144, 0, 145, 0, 105, 0, 146, 0, 147, 0, 148, 0, 93, 0, 149, 0, 150, 0, 151, 0, 111, 0, 152, 0, 153, 0, 93, 0, 93, 0, 154, 0, 155, 0, 156, 0, 157, 0, 157, 0, 158, 0, 93, 0, 159, 0, 160, 0, 161, 0, 162, 0, 157, 0, 157, 0, 163, 0, 164, 0, 165, 0, 166, 0, 167, 0, 93, 0, 168, 0, 169, 0, 170, 0, 171, 0, 40, 0, 172, 0, 173, 0, 174, 0, 157, 0, 157, 0, 93, 0, 93, 0, 175, 0, 176, 0, 177, 0, 178, 0, 179, 0, 180, 0, 181, 0, 182, 0, 183, 0, 183, 0, 184, 0, 185, 0, 185, 0, 186, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 187, 0, 188, 0, 93, 0, 93, 0, 187, 0, 93, 0, 93, 0, 189, 0, 190, 0, 191, 0, 93, 0, 93, 0, 93, 0, 190, 0, 93, 0, 93, 0, 93, 0, 192, 0, 193, 0, 194, 0, 93, 0, 195, 0, 196, 0, 196, 0, 196, 0, 196, 0, 196, 0, 197, 0, 198, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 199, 0, 93, 0, 200, 0, 201, 0, 93, 0, 93, 0, 93, 0, 93, 0, 202, 0, 203, 0, 204, 0, 205, 0, 93, 0, 206, 0, 93, 0, 207, 0, 204, 0, 208, 0, 93, 0, 93, 0, 93, 0, 209, 0, 210, 0, 211, 0, 212, 0, 213, 0, 214, 0, 212, 0, 93, 0, 93, 0, 215, 0, 93, 0, 93, 0, 216, 0, 217, 0, 93, 0, 218, 0, 93, 0, 93, 0, 93, 0, 93, 0, 219, 0, 93, 0, 220, 0, 221, 0, 222, 0, 223, 0, 93, 0, 224, 0, 225, 0, 93, 0, 93, 0, 226, 0, 93, 0, 227, 0, 228, 0, 229, 0, 229, 0, 93, 0, 230, 0, 93, 0, 93, 0, 93, 0, 231, 0, 232, 0, 233, 0, 212, 0, 212, 0, 234, 0, 235, 0, 236, 0, 157, 0, 157, 0, 157, 0, 237, 0, 93, 0, 93, 0, 238, 0, 239, 0, 177, 0, 240, 0, 241, 0, 242, 0, 93, 0, 243, 0, 244, 0, 93, 0, 93, 0, 245, 0, 246, 0, 93, 0, 93, 0, 247, 0, 248, 0, 249, 0, 244, 0, 93, 0, 250, 0, 251, 0, 252, 0, 252, 0, 253, 0, 254, 0, 255, 0, 0, 1, 1, 1, 34, 0, 34, 0, 2, 1, 3, 1, 3, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7, 1, 3, 1, 3, 1, 40, 0, 40, 0, 40, 0, 8, 1, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 9, 1, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 10, 1, 11, 1, 10, 1, 10, 1, 11, 1, 12, 1, 10, 1, 13, 1, 14, 1, 14, 1, 14, 1, 15, 1, 16, 1, 17, 1, 18, 1, 19, 1, 20, 1, 21, 1, 22, 1, 23, 1, 24, 1, 25, 1, 26, 1, 27, 1, 28, 1, 29, 1, 30, 1, 30, 1, 31, 1, 32, 1, 33, 1, 236, 0, 34, 1, 35, 1, 36, 1, 37, 1, 38, 1, 39, 1, 40, 1, 41, 1, 42, 1, 43, 1, 44, 1, 229, 0, 45, 1, 46, 1, 229, 0, 47, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 49, 1, 229, 0, 50, 1, 51, 1, 52, 1, 52, 1, 52, 1, 53, 1, 229, 0, 54, 1, 48, 1, 55, 1, 229, 0, 56, 1, 57, 1, 229, 0, 229, 0, 229, 0, 58, 1, 157, 0, 59, 1, 157, 0, 39, 1, 39, 1, 39, 1, 60, 1, 52, 1, 61, 1, 62, 1, 63, 1, 64, 1, 39, 1, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 65, 1, 66, 1, 229, 0, 229, 0, 67, 1, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 68, 1, 229, 0, 229, 0, 229, 0, 69, 1, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 70, 1, 71, 1, 39, 1, 72, 1, 229, 0, 229, 0, 73, 1, 48, 1, 74, 1, 48, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 75, 1, 76, 1, 48, 1, 48, 1, 48, 1, 77, 1, 48, 1, 78, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 48, 1, 229, 0, 229, 0, 229, 0, 48, 1, 79, 1, 229, 0, 229, 0, 80, 1, 229, 0, 81, 1, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 55, 0, 55, 0, 82, 1, 58, 0, 58, 0, 83, 1, 84, 1, 85, 1, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 15, 0, 86, 1, 87, 1, 88, 1, 88, 1, 89, 1, 93, 0, 93, 0, 93, 0, 90, 1, 91, 1, 93, 0, 92, 1, 93, 1, 93, 1, 93, 1, 93, 1, 40, 0, 40, 0, 94, 1, 95, 1, 96, 1, 97, 1, 98, 1, 99, 1, 157, 0, 157, 0, 229, 0, 100, 1, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 101, 1, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 102, 1, 157, 0, 103, 1, 104, 1, 105, 1, 106, 1, 107, 1, 153, 0, 93, 0, 93, 0, 93, 0, 93, 0, 108, 1, 198, 0, 93, 0, 93, 0, 93, 0, 93, 0, 109, 1, 110, 1, 93, 0, 93, 0, 153, 0, 93, 0, 93, 0, 93, 0, 93, 0, 220, 0, 111, 1, 93, 0, 93, 0, 229, 0, 229, 0, 101, 1, 93, 0, 52, 1, 112, 1, 113, 1, 52, 1, 114, 1, 115, 1, 52, 1, 116, 1, 113, 1, 52, 1, 52, 1, 117, 1, 118, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 119, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 120, 1, 52, 1, 121, 1, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 229, 0, 229, 0, 229, 0, 229, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 168, 0, 93, 0, 122, 1, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 168, 0, 229, 0, 229, 0, 229, 0, 58, 1, 93, 0, 93, 0, 250, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 123, 1, 93, 0, 124, 1, 157, 0, 15, 0, 15, 0, 125, 1, 126, 1, 15, 0, 127, 1, 93, 0, 93, 0, 93, 0, 93, 0, 128, 1, 129, 1, 39, 0, 130, 1, 131, 1, 132, 1, 15, 0, 15, 0, 15, 0, 133, 1, 134, 1, 135, 1, 136, 1, 137, 1, 138, 1, 157, 0, 157, 0, 139, 1, 140, 1, 93, 0, 141, 1, 142, 1, 93, 0, 93, 0, 93, 0, 143, 1, 144, 1, 93, 0, 93, 0, 145, 1, 146, 1, 212, 0, 40, 0, 147, 1, 244, 0, 93, 0, 148, 1, 93, 0, 149, 1, 150, 1, 93, 0, 168, 0, 92, 0, 93, 0, 93, 0, 151, 1, 152, 1, 153, 1, 154, 1, 155, 1, 93, 0, 93, 0, 156, 1, 157, 1, 158, 1, 159, 1, 93, 0, 160, 1, 93, 0, 93, 0, 93, 0, 161, 1, 162, 1, 163, 1, 164, 1, 165, 1, 166, 1, 167, 1, 93, 1, 34, 0, 34, 0, 168, 1, 169, 1, 170, 1, 170, 1, 170, 1, 170, 1, 170, 1, 93, 0, 93, 0, 171, 1, 212, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 172, 1, 93, 0, 173, 1, 93, 0, 93, 0, 226, 0, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 174, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 224, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 227, 0, 157, 0, 157, 0, 176, 1, 177, 1, 178, 1, 179, 1, 180, 1, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 181, 1, 182, 1, 183, 1, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 184, 1, 87, 0, 63, 0, 63, 0, 63, 0, 63, 0, 185, 1, 63, 0, 63, 0, 89, 0, 31, 1, 31, 1, 186, 1, 40, 0, 187, 1, 40, 0, 188, 1, 189, 1, 190, 1, 191, 1, 88, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 192, 1, 193, 1, 3, 0, 4, 0, 5, 0, 6, 0, 194, 1, 195, 1, 196, 1, 93, 0, 197, 1, 93, 0, 220, 0, 198, 1, 199, 1, 200, 1, 201, 1, 202, 1, 93, 0, 191, 0, 203, 1, 224, 0, 224, 0, 157, 0, 157, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 204, 1, 205, 1, 206, 1, 206, 1, 207, 1, 208, 1, 208, 1, 208, 1, 209, 1, 210, 1, 211, 1, 212, 1, 157, 0, 157, 0, 52, 1, 52, 1, 213, 1, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 168, 0, 93, 0, 93, 0, 93, 0, 117, 0, 214, 1, 215, 1, 93, 0, 93, 0, 216, 1, 93, 0, 217, 1, 93, 0, 93, 0, 218, 1, 93, 0, 219, 1, 93, 0, 93, 0, 220, 1, 221, 1, 157, 0, 157, 0, 222, 1, 222, 1, 223, 1, 224, 1, 224, 1, 93, 0, 93, 0, 93, 0, 93, 0, 224, 0, 212, 0, 222, 1, 222, 1, 225, 1, 224, 1, 226, 1, 93, 0, 93, 0, 227, 1, 93, 0, 93, 0, 93, 0, 228, 1, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 92, 1, 93, 0, 219, 0, 227, 1, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 229, 1, 63, 0, 63, 0, 230, 1, 63, 0, 231, 1, 63, 0, 232, 1, 63, 0, 233, 1, 234, 1, 87, 0, 87, 0, 87, 0, 63, 0, 235, 1, 63, 0, 236, 1, 63, 0, 237, 1, 87, 0, 87, 0, 87, 0, 87, 0, 63, 0, 63, 0, 63, 0, 238, 1, 239, 1, 240, 1, 239, 1, 239, 1, 241, 1, 242, 1, 63, 0, 243, 1, 244, 1, 245, 1, 63, 0, 246, 1, 63, 0, 247, 1, 87, 0, 87, 0, 248, 1, 63, 0, 249, 1, 250, 1, 63, 0, 63, 0, 63, 0, 251, 1, 63, 0, 252, 1, 63, 0, 253, 1, 63, 0, 254, 1, 255, 1, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 63, 0, 63, 0, 63, 0, 63, 0, 0, 2, 87, 0, 87, 0, 87, 0, 1, 2, 1, 2, 1, 2, 2, 2, 3, 2, 3, 2, 3, 2, 4, 2, 63, 0, 63, 0, 5, 2, 6, 2, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 39, 1, 7, 2, 63, 0, 63, 0, 8, 2, 9, 2, 87, 0, 87, 0, 87, 0, 87, 0, 63, 0, 247, 1, 10, 2, 63, 0, 77, 0, 11, 2, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 63, 0, 12, 2, 87, 0, 63, 0, 13, 2, 14, 2, 93, 0, 93, 0, 15, 2, 16, 2, 17, 2, 18, 2, 19, 2, 242, 0, 93, 0, 93, 0, 20, 2, 21, 2, 93, 0, 216, 0, 212, 0, 22, 2, 93, 0, 23, 2, 24, 2, 25, 2, 93, 0, 93, 0, 26, 2, 242, 0, 93, 0, 93, 0, 27, 2, 28, 2, 29, 2, 30, 2, 31, 2, 93, 0, 114, 0, 32, 2, 33, 2, 157, 0, 157, 0, 157, 0, 157, 0, 34, 2, 35, 2, 36, 2, 93, 0, 93, 0, 37, 2, 38, 2, 212, 0, 39, 2, 100, 0, 101, 0, 40, 2, 41, 2, 42, 2, 43, 2, 44, 2, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 93, 0, 93, 0, 45, 2, 46, 2, 47, 2, 48, 2, 157, 0, 93, 0, 93, 0, 93, 0, 49, 2, 50, 2, 212, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 93, 0, 51, 2, 52, 2, 53, 2, 54, 2, 157, 0, 157, 0, 93, 0, 93, 0, 93, 0, 55, 2, 56, 2, 212, 0, 57, 2, 157, 0, 93, 0, 93, 0, 58, 2, 59, 2, 212, 0, 157, 0, 157, 0, 157, 0, 93, 0, 192, 0, 60, 2, 61, 2, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 93, 0, 32, 2, 62, 2, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 11, 0, 11, 0, 13, 0, 13, 0, 165, 0, 63, 2, 64, 2, 65, 2, 93, 0, 66, 2, 67, 2, 212, 0, 157, 0, 157, 0, 157, 0, 157, 0, 68, 2, 93, 0, 93, 0, 69, 2, 70, 2, 157, 0, 71, 2, 93, 0, 93, 0, 72, 2, 73, 2, 74, 2, 93, 0, 93, 0, 75, 2, 76, 2, 77, 2, 157, 0, 93, 0, 93, 0, 93, 0, 216, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 101, 0, 93, 0, 51, 2, 78, 2, 79, 2, 165, 0, 194, 0, 80, 2, 93, 0, 81, 2, 82, 2, 83, 2, 157, 0, 157, 0, 157, 0, 157, 0, 84, 2, 93, 0, 93, 0, 85, 2, 86, 2, 212, 0, 87, 2, 93, 0, 88, 2, 89, 2, 212, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 90, 2, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 117, 0, 206, 1, 91, 2, 92, 2, 93, 2, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 227, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 94, 2, 94, 2, 94, 2, 94, 2, 94, 2, 94, 2, 95, 2, 96, 2, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 172, 1, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 93, 0, 220, 0, 97, 2, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 93, 0, 93, 0, 93, 0, 92, 1, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 93, 0, 93, 0, 216, 0, 93, 0, 220, 0, 153, 1, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 224, 0, 98, 2, 93, 0, 93, 0, 93, 0, 99, 2, 100, 2, 101, 2, 102, 2, 103, 2, 93, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 11, 0, 11, 0, 13, 0, 13, 0, 206, 1, 104, 2, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 93, 0, 93, 0, 93, 0, 105, 2, 106, 2, 107, 2, 107, 2, 108, 2, 109, 2, 157, 0, 157, 0, 157, 0, 157, 0, 110, 2, 111, 2, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 227, 1, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 219, 0, 157, 0, 157, 0, 216, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 220, 0, 157, 0, 157, 0, 157, 0, 112, 2, 113, 2, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 226, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 204, 1, 168, 0, 216, 0, 114, 2, 115, 2, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 116, 2, 52, 1, 52, 1, 117, 2, 52, 1, 52, 1, 52, 1, 118, 2, 119, 2, 120, 2, 52, 1, 121, 2, 52, 1, 52, 1, 52, 1, 122, 2, 157, 0, 229, 0, 229, 0, 229, 0, 229, 0, 123, 2, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 206, 1, 124, 2, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 58, 1, 206, 1, 125, 2, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 126, 2, 127, 2, 34, 0, 128, 2, 129, 2, 130, 2, 131, 2, 126, 2, 132, 2, 133, 2, 134, 2, 135, 2, 136, 2, 126, 2, 127, 2, 34, 0, 137, 2, 138, 2, 34, 0, 139, 2, 140, 2, 141, 2, 142, 2, 126, 2, 143, 2, 34, 0, 126, 2, 127, 2, 34, 0, 128, 2, 129, 2, 34, 0, 131, 2, 126, 2, 132, 2, 142, 2, 126, 2, 143, 2, 34, 0, 126, 2, 127, 2, 34, 0, 144, 2, 126, 2, 145, 2, 146, 2, 147, 2, 148, 2, 34, 0, 149, 2, 126, 2, 150, 2, 151, 2, 152, 2, 153, 2, 34, 0, 154, 2, 126, 2, 155, 2, 34, 0, 156, 2, 157, 2, 157, 2, 157, 2, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 52, 1, 40, 0, 40, 0, 40, 0, 158, 2, 40, 0, 40, 0, 159, 2, 160, 2, 161, 2, 162, 2, 163, 2, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 164, 2, 165, 2, 166, 2, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 93, 0, 168, 0, 167, 2, 168, 2, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 93, 0, 169, 2, 170, 2, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 63, 0, 171, 2, 172, 2, 87, 0, 87, 0, 173, 2, 173, 2, 174, 2, 175, 2, 176, 2, 177, 2, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 178, 2, 239, 1, 239, 1, 179, 2, 180, 2, 87, 0, 87, 0, 87, 0, 87, 0, 178, 2, 239, 1, 181, 2, 182, 2, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 183, 2, 63, 0, 184, 2, 185, 2, 186, 2, 187, 2, 188, 2, 189, 2, 190, 2, 191, 2, 192, 2, 191, 2, 87, 0, 87, 0, 87, 0, 193, 2, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 87, 0, 229, 0, 229, 0, 103, 1, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 101, 1, 194, 2, 195, 2, 195, 2, 195, 2, 229, 0, 102, 1, 196, 2, 52, 1, 121, 1, 52, 1, 52, 1, 52, 1, 197, 2, 52, 1, 52, 1, 52, 1, 198, 2, 157, 0, 157, 0, 157, 0, 199, 2, 52, 1, 200, 2, 52, 1, 52, 1, 201, 2, 122, 2, 202, 2, 102, 1, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 203, 2, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 204, 2, 211, 1, 211, 1, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 101, 1, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 205, 2, 103, 1, 157, 0, 103, 1, 229, 0, 229, 0, 229, 0, 204, 2, 195, 0, 229, 0, 229, 0, 204, 2, 229, 0, 206, 2, 207, 2, 157, 0, 157, 0, 157, 0, 157, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 208, 2, 229, 0, 229, 0, 229, 0, 229, 0, 209, 2, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 101, 1, 206, 2, 210, 2, 58, 1, 229, 0, 205, 2, 58, 1, 211, 2, 58, 1, 157, 0, 157, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 229, 0, 212, 2, 229, 0, 229, 0, 59, 1, 157, 0, 157, 0, 213, 2, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 214, 2, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 224, 0, 157, 0, 157, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 225, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 224, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 48, 2, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 117, 0, 157, 0, 93, 0, 224, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 93, 0, 204, 1, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 157, 0, 215, 2, 31, 1, 216, 2, 216, 2, 216, 2, 216, 2, 216, 2, 216, 2, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 40, 0, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 31, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 175, 1, 217, 2 }; private static ReadOnlySpan CategoryCasingLevel3Index => new byte[11680] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 3, 4, 3, 3, 3, 5, 6, 3, 7, 3, 8, 3, 3, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 3, 7, 7, 7, 3, 3, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 5, 3, 6, 11, 12, 11, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 5, 7, 6, 7, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 4, 4, 4, 4, 14, 3, 11, 14, 15, 16, 7, 17, 14, 11, 14, 7, 18, 18, 11, 19, 3, 3, 11, 18, 15, 20, 18, 18, 18, 3, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 7, 10, 10, 10, 10, 10, 10, 10, 21, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 7, 13, 13, 13, 13, 13, 13, 13, 22, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 25, 21, 23, 24, 23, 24, 23, 24, 21, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 21, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 26, 23, 24, 23, 24, 23, 24, 21, 27, 28, 23, 24, 23, 24, 29, 23, 24, 30, 30, 23, 24, 21, 31, 32, 33, 23, 24, 30, 34, 35, 36, 37, 23, 24, 38, 21, 36, 39, 40, 41, 23, 24, 23, 24, 23, 24, 42, 23, 24, 42, 21, 21, 23, 24, 42, 23, 24, 43, 43, 23, 24, 23, 24, 44, 23, 24, 21, 15, 23, 24, 21, 45, 15, 15, 15, 15, 46, 47, 48, 46, 47, 48, 46, 47, 48, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 49, 23, 24, 21, 46, 47, 48, 23, 24, 50, 51, 23, 24, 23, 24, 23, 24, 23, 24, 52, 21, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 21, 21, 21, 21, 21, 21, 53, 23, 24, 54, 55, 56, 56, 23, 24, 57, 58, 59, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 60, 61, 62, 63, 64, 21, 65, 65, 21, 66, 21, 67, 68, 21, 21, 21, 65, 69, 21, 70, 21, 71, 72, 21, 73, 74, 72, 75, 76, 21, 21, 74, 21, 77, 78, 21, 21, 79, 21, 21, 21, 21, 21, 21, 21, 80, 21, 21, 81, 21, 82, 81, 21, 21, 21, 83, 81, 84, 85, 85, 86, 21, 21, 21, 21, 21, 87, 21, 15, 21, 21, 21, 21, 21, 21, 21, 21, 88, 89, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 90, 90, 90, 90, 90, 90, 90, 90, 90, 91, 91, 90, 90, 90, 90, 90, 90, 90, 11, 11, 11, 11, 91, 91, 91, 91, 91, 91, 91, 91, 91, 91, 90, 90, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 90, 90, 90, 90, 90, 11, 11, 11, 11, 11, 11, 11, 91, 11, 90, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 93, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 23, 24, 23, 24, 91, 11, 23, 24, 94, 94, 90, 40, 40, 40, 3, 95, 94, 94, 94, 94, 11, 11, 96, 3, 97, 97, 97, 94, 98, 94, 99, 99, 21, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 94, 10, 10, 10, 10, 10, 10, 10, 10, 10, 100, 101, 101, 101, 21, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 102, 13, 13, 13, 13, 13, 13, 13, 13, 13, 103, 104, 104, 105, 106, 107, 25, 25, 25, 108, 109, 110, 23, 24, 23, 24, 23, 24, 23, 24, 111, 112, 113, 114, 115, 116, 7, 23, 24, 117, 23, 24, 21, 52, 52, 52, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 118, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 119, 23, 24, 120, 92, 92, 92, 92, 92, 121, 121, 23, 24, 23, 24, 23, 24, 122, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 123, 94, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 94, 94, 90, 125, 125, 125, 125, 125, 125, 21, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 21, 21, 125, 8, 94, 94, 14, 14, 4, 127, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 128, 92, 129, 92, 92, 129, 92, 92, 129, 92, 127, 127, 127, 127, 127, 127, 127, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 127, 127, 127, 130, 130, 130, 130, 129, 129, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 17, 17, 17, 17, 17, 17, 7, 7, 131, 3, 3, 132, 3, 129, 14, 14, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 129, 133, 127, 129, 129, 134, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 92, 92, 92, 92, 92, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 3, 3, 3, 129, 130, 130, 92, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 129, 130, 92, 92, 92, 92, 92, 92, 92, 17, 14, 92, 92, 92, 92, 92, 92, 134, 134, 92, 92, 14, 92, 92, 92, 92, 130, 130, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 130, 130, 130, 135, 135, 130, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 127, 133, 130, 92, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 127, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 130, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 92, 92, 92, 92, 92, 92, 92, 92, 92, 134, 134, 14, 3, 3, 3, 134, 127, 127, 92, 132, 132, 130, 130, 130, 130, 130, 130, 92, 92, 92, 92, 134, 92, 92, 92, 92, 92, 92, 92, 92, 92, 134, 92, 92, 92, 134, 92, 92, 92, 92, 92, 127, 127, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 92, 92, 92, 127, 127, 129, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 130, 130, 130, 130, 130, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 17, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 137, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 137, 92, 15, 137, 137, 137, 92, 92, 92, 92, 92, 92, 92, 92, 137, 137, 137, 137, 92, 137, 137, 15, 92, 92, 92, 92, 92, 92, 92, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 92, 125, 125, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 125, 90, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 137, 137, 94, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 15, 15, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 94, 15, 94, 94, 94, 15, 15, 15, 15, 94, 94, 92, 15, 137, 137, 137, 92, 92, 92, 92, 94, 94, 137, 137, 94, 94, 137, 137, 92, 15, 94, 94, 94, 94, 94, 94, 94, 94, 137, 94, 94, 94, 94, 15, 15, 94, 15, 15, 15, 92, 92, 94, 94, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 15, 15, 4, 4, 139, 139, 139, 139, 139, 139, 120, 4, 15, 125, 92, 94, 94, 92, 92, 137, 94, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 15, 15, 94, 15, 15, 94, 15, 15, 94, 15, 15, 94, 94, 92, 94, 137, 137, 137, 92, 92, 94, 94, 94, 94, 92, 92, 94, 94, 92, 92, 92, 94, 94, 94, 92, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 94, 15, 94, 94, 94, 94, 94, 94, 94, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 92, 92, 15, 15, 15, 92, 125, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 92, 92, 137, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 94, 15, 15, 15, 15, 15, 94, 94, 92, 15, 137, 137, 137, 92, 92, 92, 92, 92, 94, 92, 92, 137, 94, 137, 137, 92, 94, 94, 15, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 125, 4, 94, 94, 94, 94, 94, 94, 94, 15, 92, 92, 92, 92, 92, 92, 94, 92, 137, 137, 94, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 15, 15, 94, 15, 15, 94, 15, 15, 15, 15, 15, 94, 94, 92, 15, 137, 92, 137, 92, 92, 92, 92, 94, 94, 137, 137, 94, 94, 137, 137, 92, 94, 94, 94, 94, 94, 94, 94, 92, 92, 137, 94, 94, 94, 94, 15, 15, 94, 15, 120, 15, 139, 139, 139, 139, 139, 139, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 92, 15, 94, 15, 15, 15, 15, 15, 15, 94, 94, 94, 15, 15, 15, 94, 15, 15, 15, 15, 94, 94, 94, 15, 15, 94, 15, 94, 15, 15, 94, 94, 94, 15, 15, 94, 94, 94, 15, 15, 15, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 137, 137, 92, 137, 137, 94, 94, 94, 137, 137, 137, 94, 137, 137, 137, 92, 94, 94, 15, 94, 94, 94, 94, 94, 94, 137, 94, 94, 94, 94, 94, 94, 94, 94, 139, 139, 139, 14, 14, 14, 14, 14, 14, 4, 14, 94, 94, 94, 94, 94, 92, 137, 137, 137, 92, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 15, 92, 92, 92, 137, 137, 137, 137, 94, 92, 92, 92, 94, 92, 92, 92, 92, 94, 94, 94, 94, 94, 94, 94, 92, 92, 94, 15, 15, 15, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 125, 18, 18, 18, 18, 18, 18, 18, 120, 15, 92, 137, 137, 125, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 15, 15, 15, 15, 94, 15, 15, 15, 15, 15, 94, 94, 92, 15, 137, 140, 137, 137, 137, 137, 137, 94, 140, 137, 137, 94, 137, 137, 92, 92, 94, 94, 94, 94, 94, 94, 94, 137, 137, 94, 94, 94, 94, 94, 94, 94, 15, 94, 94, 15, 15, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 92, 92, 137, 137, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 92, 15, 137, 137, 137, 92, 92, 92, 92, 94, 137, 137, 137, 94, 137, 137, 137, 92, 15, 120, 94, 94, 94, 94, 15, 15, 15, 137, 139, 139, 139, 139, 139, 139, 139, 15, 139, 139, 139, 139, 139, 139, 139, 139, 139, 120, 15, 15, 15, 15, 15, 15, 94, 92, 137, 137, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 94, 94, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 92, 94, 94, 94, 94, 137, 137, 137, 92, 92, 92, 94, 92, 94, 137, 137, 137, 137, 137, 137, 137, 137, 94, 94, 137, 137, 125, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 15, 15, 92, 92, 92, 92, 92, 92, 92, 94, 94, 94, 94, 4, 15, 15, 15, 15, 15, 15, 90, 92, 92, 92, 92, 92, 92, 92, 92, 125, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 125, 125, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 94, 15, 94, 15, 15, 15, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 15, 15, 92, 92, 92, 92, 92, 92, 92, 92, 92, 15, 94, 94, 15, 15, 15, 15, 15, 94, 90, 94, 92, 92, 92, 92, 92, 92, 94, 94, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 94, 94, 15, 15, 15, 15, 15, 120, 120, 120, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 120, 125, 120, 120, 120, 92, 92, 120, 120, 120, 120, 120, 120, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 120, 92, 120, 92, 120, 92, 5, 6, 5, 6, 137, 137, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 137, 92, 92, 92, 92, 92, 125, 92, 92, 15, 15, 15, 15, 15, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 94, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 94, 120, 120, 120, 120, 120, 120, 120, 120, 92, 120, 120, 120, 120, 120, 120, 94, 120, 120, 125, 125, 125, 125, 125, 120, 120, 120, 120, 125, 125, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 137, 137, 92, 92, 92, 92, 137, 92, 92, 92, 92, 92, 92, 137, 92, 92, 137, 137, 92, 92, 15, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 125, 125, 125, 125, 125, 125, 15, 15, 15, 15, 15, 15, 137, 137, 92, 92, 15, 15, 15, 15, 92, 92, 92, 15, 137, 137, 137, 15, 15, 137, 137, 137, 137, 137, 137, 137, 15, 15, 15, 92, 92, 92, 92, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 137, 137, 92, 92, 137, 137, 137, 137, 137, 137, 92, 15, 137, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 137, 137, 137, 92, 120, 120, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 141, 94, 141, 94, 94, 94, 94, 94, 141, 94, 94, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 142, 125, 90, 142, 142, 142, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 15, 15, 94, 94, 15, 15, 15, 15, 15, 15, 15, 94, 15, 94, 15, 15, 15, 15, 94, 94, 15, 94, 15, 15, 15, 15, 94, 94, 15, 15, 15, 15, 15, 15, 15, 94, 15, 94, 15, 15, 15, 15, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 92, 92, 92, 125, 125, 125, 125, 125, 125, 125, 125, 125, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 94, 94, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 94, 94, 94, 94, 94, 94, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 143, 144, 144, 144, 144, 144, 144, 94, 94, 145, 145, 145, 145, 145, 145, 94, 94, 8, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 120, 125, 15, 2, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 5, 6, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 125, 125, 125, 146, 146, 146, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 15, 15, 92, 92, 92, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 92, 92, 92, 125, 125, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 92, 92, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 94, 92, 92, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 92, 92, 137, 92, 92, 92, 92, 92, 92, 92, 137, 137, 137, 137, 137, 137, 137, 137, 92, 137, 137, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 125, 125, 125, 90, 125, 125, 125, 4, 15, 92, 94, 94, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 94, 94, 94, 94, 94, 94, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 94, 94, 94, 94, 94, 94, 3, 3, 3, 3, 3, 3, 8, 3, 3, 3, 3, 92, 92, 92, 17, 94, 15, 15, 15, 90, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 92, 92, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 15, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 92, 92, 92, 137, 137, 137, 137, 92, 92, 137, 137, 137, 94, 94, 94, 94, 137, 137, 92, 137, 137, 137, 137, 137, 137, 92, 92, 92, 94, 94, 94, 94, 14, 94, 94, 94, 3, 3, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 15, 15, 15, 15, 15, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 94, 94, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 139, 94, 94, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 92, 92, 137, 137, 92, 94, 94, 125, 125, 15, 15, 15, 15, 15, 137, 92, 137, 92, 92, 92, 92, 92, 92, 92, 94, 92, 137, 92, 137, 137, 92, 92, 92, 92, 92, 92, 92, 92, 137, 137, 137, 137, 137, 137, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 94, 94, 92, 125, 125, 125, 125, 125, 125, 125, 90, 125, 125, 125, 125, 125, 125, 94, 94, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 121, 92, 92, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 92, 92, 92, 92, 137, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 137, 92, 92, 92, 92, 92, 137, 92, 137, 137, 137, 137, 137, 92, 137, 137, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 125, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 92, 92, 92, 92, 92, 92, 92, 92, 92, 120, 120, 120, 120, 120, 120, 120, 120, 120, 94, 94, 94, 92, 92, 137, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 137, 92, 92, 92, 92, 137, 137, 92, 92, 137, 92, 92, 92, 15, 15, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 137, 92, 92, 137, 137, 137, 92, 137, 92, 92, 92, 137, 137, 94, 94, 94, 94, 94, 94, 94, 94, 125, 125, 125, 125, 15, 15, 15, 15, 137, 137, 137, 137, 137, 137, 137, 137, 92, 92, 92, 92, 92, 92, 92, 92, 137, 137, 92, 92, 94, 94, 94, 125, 125, 125, 125, 125, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 90, 90, 90, 90, 90, 90, 125, 125, 147, 148, 149, 150, 150, 151, 152, 153, 154, 94, 94, 94, 94, 94, 94, 94, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 155, 94, 94, 155, 155, 155, 125, 125, 125, 125, 125, 125, 125, 125, 94, 94, 94, 94, 94, 94, 94, 94, 92, 92, 92, 125, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 137, 92, 92, 92, 92, 92, 92, 92, 15, 15, 15, 15, 92, 15, 15, 15, 15, 15, 15, 92, 15, 15, 137, 92, 92, 15, 94, 94, 94, 94, 94, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 90, 156, 21, 21, 21, 157, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 158, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 90, 90, 90, 90, 90, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 94, 92, 92, 92, 92, 92, 23, 24, 23, 24, 23, 24, 21, 21, 21, 21, 21, 159, 21, 21, 160, 21, 161, 161, 161, 161, 161, 161, 161, 161, 162, 162, 162, 162, 162, 162, 162, 162, 161, 161, 161, 161, 161, 161, 94, 94, 162, 162, 162, 162, 162, 162, 94, 94, 21, 161, 21, 161, 21, 161, 21, 161, 94, 162, 94, 162, 94, 162, 94, 162, 163, 163, 164, 164, 164, 164, 165, 165, 166, 166, 167, 167, 168, 168, 94, 94, 161, 161, 161, 161, 161, 161, 161, 161, 169, 169, 169, 169, 169, 169, 169, 169, 161, 161, 21, 170, 21, 94, 21, 21, 162, 162, 171, 171, 172, 11, 173, 11, 11, 11, 21, 170, 21, 94, 21, 21, 174, 174, 174, 174, 172, 11, 11, 11, 161, 161, 21, 21, 94, 94, 21, 21, 162, 162, 175, 175, 94, 11, 11, 11, 161, 161, 21, 21, 21, 113, 21, 21, 162, 162, 176, 176, 117, 11, 11, 11, 94, 94, 21, 170, 21, 94, 21, 21, 177, 177, 178, 178, 172, 11, 11, 94, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 17, 17, 17, 179, 133, 8, 8, 8, 8, 8, 8, 3, 3, 16, 20, 5, 16, 16, 20, 5, 16, 3, 3, 3, 3, 3, 3, 3, 3, 180, 181, 17, 17, 17, 17, 17, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 16, 20, 3, 3, 3, 3, 12, 12, 3, 3, 3, 7, 5, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 7, 3, 12, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 17, 17, 17, 17, 17, 182, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 18, 90, 94, 94, 18, 18, 18, 18, 18, 18, 7, 7, 7, 5, 6, 90, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 7, 7, 7, 5, 6, 94, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 94, 94, 94, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 121, 121, 121, 121, 92, 121, 121, 121, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 14, 14, 25, 14, 14, 14, 14, 25, 14, 14, 21, 25, 25, 25, 21, 21, 25, 25, 25, 21, 14, 25, 14, 14, 7, 25, 25, 25, 25, 25, 14, 14, 14, 14, 14, 14, 25, 14, 183, 14, 25, 14, 184, 185, 25, 25, 14, 21, 25, 25, 186, 25, 21, 15, 15, 15, 15, 21, 14, 14, 21, 21, 25, 25, 7, 7, 7, 7, 7, 25, 21, 21, 21, 21, 14, 7, 14, 14, 187, 120, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 188, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 146, 146, 146, 23, 24, 146, 146, 146, 146, 18, 14, 14, 94, 94, 94, 94, 7, 7, 7, 7, 7, 14, 14, 14, 14, 14, 7, 7, 14, 14, 14, 14, 7, 14, 14, 7, 14, 14, 7, 14, 14, 14, 14, 14, 14, 14, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 7, 14, 14, 7, 14, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 14, 14, 14, 14, 14, 14, 14, 14, 5, 6, 5, 6, 14, 14, 14, 14, 7, 7, 14, 14, 14, 14, 14, 14, 14, 5, 6, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 14, 7, 14, 14, 14, 14, 14, 14, 14, 14, 120, 14, 14, 14, 14, 14, 7, 7, 7, 7, 7, 7, 7, 7, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 7, 7, 7, 7, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 94, 94, 94, 94, 94, 94, 94, 94, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 94, 94, 94, 94, 94, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 190, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 191, 18, 18, 18, 18, 18, 18, 14, 14, 14, 14, 14, 14, 14, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 7, 7, 7, 7, 7, 7, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 120, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 7, 7, 7, 7, 7, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 7, 7, 7, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 5, 6, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 5, 6, 7, 7, 7, 7, 7, 7, 7, 14, 14, 7, 7, 7, 7, 7, 7, 14, 14, 14, 14, 14, 14, 14, 94, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 94, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 126, 94, 23, 24, 192, 193, 194, 195, 196, 23, 24, 23, 24, 23, 24, 197, 198, 199, 200, 21, 23, 24, 21, 23, 24, 21, 21, 21, 21, 21, 90, 90, 201, 201, 23, 24, 23, 24, 21, 14, 14, 14, 14, 14, 14, 23, 24, 23, 24, 92, 92, 92, 23, 24, 94, 94, 94, 94, 94, 3, 3, 3, 3, 18, 3, 3, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 202, 94, 202, 94, 94, 94, 94, 94, 202, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 94, 94, 94, 90, 125, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 92, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 94, 3, 3, 16, 20, 16, 20, 3, 3, 3, 16, 20, 3, 16, 20, 3, 3, 3, 3, 3, 3, 3, 3, 3, 8, 3, 3, 8, 3, 16, 20, 3, 3, 16, 20, 5, 6, 5, 6, 5, 6, 5, 6, 3, 3, 3, 3, 3, 91, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 8, 8, 3, 3, 3, 3, 8, 3, 5, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 3, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 14, 14, 14, 14, 14, 14, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 94, 94, 94, 94, 2, 3, 3, 3, 14, 90, 15, 146, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 14, 14, 5, 6, 5, 6, 5, 6, 5, 6, 8, 5, 6, 6, 14, 146, 146, 146, 146, 146, 146, 146, 146, 146, 92, 92, 92, 92, 137, 137, 8, 90, 90, 90, 90, 90, 14, 14, 146, 146, 146, 90, 15, 3, 14, 14, 15, 15, 15, 15, 15, 15, 15, 94, 94, 92, 92, 11, 11, 90, 90, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 3, 90, 90, 90, 15, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 120, 120, 139, 139, 139, 139, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 14, 14, 94, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 139, 139, 139, 139, 139, 139, 139, 139, 14, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 14, 14, 14, 120, 120, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 14, 14, 14, 14, 120, 120, 120, 120, 120, 120, 120, 14, 14, 14, 14, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 14, 14, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 14, 15, 15, 15, 15, 15, 90, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 90, 3, 3, 3, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 15, 15, 94, 94, 94, 94, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 15, 92, 121, 121, 121, 3, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 3, 91, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 90, 90, 92, 92, 15, 15, 15, 15, 15, 15, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 92, 92, 125, 125, 125, 125, 125, 125, 94, 94, 94, 94, 94, 94, 94, 94, 11, 11, 11, 11, 11, 11, 11, 91, 91, 91, 91, 91, 91, 91, 91, 91, 11, 11, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 21, 21, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 90, 21, 21, 21, 21, 21, 21, 21, 21, 23, 24, 23, 24, 203, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 91, 204, 204, 23, 24, 205, 21, 15, 23, 24, 23, 24, 206, 21, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 207, 208, 209, 210, 207, 21, 211, 212, 213, 214, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 23, 24, 94, 94, 23, 24, 215, 216, 217, 23, 24, 23, 24, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 23, 24, 15, 90, 90, 21, 15, 15, 15, 15, 15, 15, 15, 92, 15, 15, 15, 92, 15, 15, 15, 15, 92, 15, 15, 15, 15, 15, 15, 15, 137, 137, 92, 92, 137, 14, 14, 14, 14, 92, 94, 94, 94, 139, 139, 139, 139, 139, 139, 120, 120, 4, 14, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 3, 3, 3, 3, 94, 94, 94, 94, 94, 94, 94, 94, 137, 137, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 92, 92, 94, 94, 94, 94, 94, 94, 94, 94, 125, 125, 92, 92, 15, 15, 15, 15, 15, 15, 125, 125, 125, 15, 125, 15, 15, 92, 15, 15, 15, 15, 15, 15, 92, 92, 92, 92, 92, 92, 92, 92, 125, 125, 15, 15, 15, 15, 15, 15, 15, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 137, 137, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 125, 15, 15, 15, 92, 137, 137, 92, 92, 92, 92, 137, 137, 92, 92, 137, 137, 137, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 94, 90, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 94, 94, 94, 94, 125, 125, 15, 15, 15, 15, 15, 92, 90, 15, 15, 15, 15, 15, 15, 15, 15, 15, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 15, 15, 15, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 92, 92, 92, 92, 92, 137, 137, 92, 92, 137, 137, 92, 92, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 92, 15, 15, 15, 15, 15, 15, 15, 15, 92, 137, 94, 94, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 94, 94, 125, 125, 125, 125, 90, 15, 15, 15, 15, 15, 15, 120, 120, 120, 15, 137, 92, 137, 15, 15, 92, 15, 92, 92, 92, 15, 15, 92, 92, 15, 15, 15, 15, 15, 92, 92, 15, 92, 15, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 90, 125, 125, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 137, 92, 92, 137, 137, 125, 125, 15, 90, 90, 137, 92, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 94, 94, 15, 15, 15, 15, 15, 15, 94, 94, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 94, 94, 94, 94, 94, 21, 21, 21, 218, 21, 21, 21, 21, 21, 21, 21, 204, 90, 90, 90, 90, 21, 21, 21, 21, 21, 21, 21, 21, 21, 90, 11, 11, 94, 94, 94, 94, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 219, 15, 15, 15, 137, 137, 92, 137, 137, 92, 137, 137, 125, 137, 92, 94, 94, 15, 15, 15, 15, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 15, 15, 15, 15, 15, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 221, 221, 221, 221, 221, 221, 221, 221, 221, 221, 221, 221, 221, 221, 221, 221, 21, 21, 21, 21, 21, 21, 21, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 21, 21, 21, 21, 21, 94, 94, 94, 94, 94, 130, 92, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 7, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 130, 130, 130, 130, 130, 127, 130, 127, 130, 130, 127, 130, 130, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 222, 222, 222, 222, 222, 222, 222, 222, 222, 222, 222, 222, 222, 222, 222, 222, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 6, 5, 127, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 132, 14, 127, 127, 3, 3, 3, 3, 3, 3, 3, 5, 6, 3, 94, 94, 94, 94, 94, 94, 3, 8, 8, 12, 12, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 3, 3, 5, 6, 3, 3, 3, 3, 12, 12, 12, 3, 3, 3, 94, 3, 3, 3, 3, 8, 5, 6, 5, 6, 5, 6, 3, 3, 3, 7, 8, 7, 7, 7, 94, 3, 4, 3, 3, 94, 94, 94, 94, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 127, 17, 94, 3, 3, 3, 4, 3, 3, 3, 5, 6, 3, 7, 3, 8, 3, 3, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 5, 7, 6, 7, 5, 6, 3, 5, 6, 3, 3, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 90, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 90, 90, 94, 94, 15, 15, 15, 15, 15, 15, 94, 94, 15, 15, 15, 15, 15, 15, 94, 94, 15, 15, 15, 15, 15, 15, 94, 94, 15, 15, 15, 94, 94, 94, 4, 4, 7, 11, 14, 4, 4, 94, 14, 7, 7, 7, 7, 14, 14, 94, 182, 182, 182, 182, 182, 182, 182, 182, 182, 17, 17, 17, 14, 14, 182, 182, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 94, 125, 3, 125, 94, 94, 94, 94, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 94, 94, 94, 120, 120, 120, 120, 120, 120, 120, 120, 120, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 223, 18, 18, 18, 18, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 18, 18, 14, 120, 120, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 94, 94, 94, 14, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 92, 94, 94, 92, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 94, 94, 94, 94, 139, 139, 139, 139, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 146, 15, 15, 15, 15, 15, 15, 15, 15, 146, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 92, 92, 92, 92, 92, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 125, 15, 15, 15, 15, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 125, 146, 146, 146, 146, 146, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 224, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 224, 224, 224, 224, 94, 94, 94, 94, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 225, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 125, 130, 130, 130, 130, 130, 130, 127, 127, 130, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 130, 130, 127, 127, 127, 130, 127, 127, 130, 130, 130, 130, 130, 130, 130, 127, 129, 226, 226, 226, 226, 226, 226, 226, 226, 130, 130, 130, 130, 130, 130, 130, 135, 135, 226, 226, 226, 226, 226, 226, 226, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 127, 127, 127, 127, 127, 127, 127, 226, 226, 226, 226, 226, 226, 226, 226, 226, 130, 130, 130, 127, 130, 130, 127, 127, 127, 127, 127, 226, 226, 226, 226, 226, 130, 130, 130, 130, 130, 130, 226, 226, 226, 226, 226, 226, 127, 127, 127, 3, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 127, 127, 127, 127, 129, 130, 130, 130, 130, 130, 130, 130, 130, 127, 127, 127, 127, 226, 226, 130, 130, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 127, 127, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 130, 92, 92, 92, 127, 92, 92, 127, 127, 127, 127, 127, 92, 92, 92, 92, 130, 130, 130, 130, 127, 130, 130, 130, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 127, 92, 92, 92, 127, 127, 127, 127, 92, 226, 226, 226, 226, 226, 226, 226, 226, 226, 127, 127, 127, 127, 127, 127, 127, 129, 129, 129, 129, 129, 129, 129, 129, 129, 127, 127, 127, 127, 127, 127, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 226, 226, 129, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 226, 226, 226, 130, 130, 130, 130, 130, 130, 130, 130, 135, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 92, 92, 127, 127, 127, 127, 226, 226, 226, 226, 226, 129, 129, 129, 129, 129, 129, 129, 127, 127, 127, 127, 127, 127, 127, 127, 127, 130, 130, 130, 130, 130, 130, 127, 127, 127, 3, 3, 3, 3, 3, 3, 3, 130, 130, 130, 130, 130, 130, 127, 127, 226, 226, 226, 226, 226, 226, 226, 226, 130, 130, 130, 127, 127, 127, 127, 127, 226, 226, 226, 226, 226, 226, 226, 226, 130, 130, 127, 127, 127, 127, 127, 127, 127, 129, 129, 129, 129, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 226, 226, 226, 226, 226, 226, 226, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 127, 127, 127, 127, 127, 127, 227, 227, 227, 227, 227, 227, 227, 227, 227, 227, 227, 227, 227, 227, 227, 227, 227, 227, 227, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 228, 127, 127, 127, 127, 127, 127, 127, 226, 226, 226, 226, 226, 226, 130, 130, 130, 130, 92, 92, 92, 92, 127, 127, 127, 127, 127, 127, 127, 127, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 127, 127, 127, 127, 127, 127, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 92, 92, 128, 127, 127, 130, 130, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 226, 226, 226, 226, 226, 226, 226, 130, 127, 127, 127, 127, 127, 127, 127, 127, 92, 226, 226, 226, 226, 129, 129, 129, 129, 129, 127, 127, 127, 127, 127, 127, 130, 130, 130, 130, 130, 226, 226, 226, 226, 226, 226, 226, 127, 127, 127, 127, 130, 130, 130, 130, 130, 130, 130, 127, 127, 127, 127, 127, 127, 127, 127, 127, 137, 92, 137, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 125, 125, 125, 125, 125, 125, 125, 94, 94, 94, 94, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 92, 137, 137, 137, 92, 92, 92, 92, 137, 137, 92, 92, 125, 125, 179, 125, 125, 125, 125, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 179, 94, 94, 92, 92, 92, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 92, 92, 92, 92, 137, 92, 92, 92, 92, 92, 92, 92, 92, 94, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 125, 125, 125, 125, 15, 137, 137, 15, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 92, 125, 125, 15, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 137, 137, 137, 92, 92, 92, 92, 92, 92, 92, 92, 92, 137, 137, 15, 15, 15, 15, 125, 125, 125, 125, 92, 92, 92, 92, 125, 137, 92, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 15, 125, 15, 125, 125, 125, 94, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 139, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 137, 137, 137, 92, 92, 92, 137, 137, 92, 137, 92, 92, 125, 125, 125, 125, 125, 125, 92, 94, 15, 15, 15, 15, 15, 15, 15, 94, 15, 94, 15, 15, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 125, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 137, 137, 137, 92, 92, 92, 92, 92, 92, 92, 92, 94, 94, 94, 94, 94, 92, 92, 137, 137, 94, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 15, 15, 94, 15, 15, 94, 15, 15, 15, 15, 15, 94, 92, 92, 15, 137, 137, 92, 137, 137, 137, 137, 94, 94, 137, 137, 94, 94, 137, 137, 137, 94, 94, 15, 94, 94, 94, 94, 94, 94, 137, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 137, 137, 94, 94, 92, 92, 92, 92, 92, 92, 92, 94, 94, 94, 92, 92, 92, 92, 92, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 137, 137, 137, 92, 92, 92, 92, 92, 92, 92, 92, 137, 137, 92, 92, 92, 137, 92, 15, 15, 15, 15, 125, 125, 125, 125, 125, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 125, 125, 94, 125, 92, 15, 15, 15, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 137, 137, 137, 92, 92, 92, 92, 92, 92, 137, 92, 137, 137, 137, 137, 92, 92, 137, 92, 92, 15, 15, 125, 15, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 137, 137, 137, 92, 92, 92, 92, 94, 94, 137, 137, 137, 137, 92, 92, 137, 92, 92, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 125, 15, 15, 15, 15, 92, 92, 94, 94, 137, 137, 137, 92, 92, 92, 92, 92, 92, 92, 92, 137, 137, 92, 137, 92, 92, 125, 125, 125, 15, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 137, 92, 137, 137, 92, 92, 92, 92, 92, 92, 137, 92, 15, 94, 94, 94, 94, 94, 94, 94, 137, 137, 92, 92, 92, 92, 137, 92, 92, 92, 92, 92, 94, 94, 94, 94, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 139, 139, 125, 125, 125, 120, 92, 92, 92, 92, 92, 92, 92, 92, 137, 92, 92, 125, 94, 94, 94, 94, 139, 139, 139, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 15, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 137, 137, 137, 137, 137, 137, 94, 137, 137, 94, 94, 92, 92, 137, 92, 15, 137, 15, 137, 92, 125, 125, 125, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 15, 15, 15, 15, 15, 15, 15, 137, 137, 137, 92, 92, 92, 92, 94, 94, 92, 92, 137, 137, 137, 137, 92, 15, 125, 15, 137, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 92, 92, 92, 92, 92, 92, 140, 140, 92, 92, 15, 15, 15, 15, 15, 15, 15, 15, 92, 92, 92, 92, 92, 92, 137, 15, 92, 92, 92, 92, 125, 125, 125, 125, 125, 125, 125, 125, 92, 94, 94, 94, 94, 94, 94, 94, 94, 15, 92, 92, 92, 92, 92, 92, 137, 137, 92, 92, 92, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 137, 92, 92, 125, 125, 125, 15, 125, 125, 125, 125, 125, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 92, 92, 92, 92, 92, 92, 92, 94, 92, 92, 92, 92, 92, 92, 137, 140, 15, 125, 125, 125, 125, 125, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 125, 125, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 94, 137, 92, 92, 92, 92, 92, 92, 92, 137, 92, 92, 137, 92, 92, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 94, 15, 15, 94, 15, 15, 15, 15, 15, 15, 92, 92, 92, 92, 92, 92, 94, 94, 94, 92, 94, 92, 92, 94, 92, 92, 92, 92, 92, 92, 92, 15, 92, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 94, 15, 15, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 137, 137, 137, 137, 137, 94, 92, 92, 94, 137, 137, 92, 137, 92, 15, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 92, 92, 137, 137, 125, 125, 94, 94, 94, 94, 94, 94, 94, 139, 139, 139, 139, 139, 14, 14, 14, 14, 14, 14, 14, 14, 4, 4, 4, 4, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 125, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 146, 94, 125, 125, 125, 125, 125, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 179, 179, 179, 179, 179, 179, 179, 179, 179, 94, 94, 94, 94, 94, 94, 94, 92, 92, 92, 92, 92, 125, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 92, 92, 92, 92, 92, 92, 92, 125, 125, 125, 125, 125, 120, 120, 120, 120, 90, 90, 90, 90, 125, 120, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 94, 139, 139, 139, 139, 139, 139, 139, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 94, 15, 15, 15, 139, 139, 139, 139, 139, 139, 139, 125, 125, 125, 125, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 94, 94, 92, 15, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 137, 94, 94, 94, 94, 94, 94, 94, 92, 92, 92, 92, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 3, 90, 92, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 137, 137, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 94, 94, 94, 94, 94, 94, 94, 94, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 94, 94, 120, 92, 92, 125, 17, 17, 17, 17, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 120, 120, 120, 120, 120, 120, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 120, 120, 120, 120, 120, 120, 120, 94, 94, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 137, 137, 92, 92, 92, 120, 120, 120, 137, 137, 137, 137, 137, 137, 17, 17, 17, 17, 17, 17, 17, 17, 92, 92, 92, 92, 92, 92, 92, 92, 120, 120, 92, 92, 92, 92, 92, 92, 92, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 92, 92, 92, 92, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 94, 94, 94, 94, 94, 94, 94, 14, 14, 92, 92, 92, 14, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 139, 139, 139, 139, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 139, 139, 139, 139, 139, 139, 139, 139, 139, 94, 94, 94, 94, 94, 94, 94, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 21, 21, 21, 21, 21, 21, 21, 94, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 25, 94, 25, 25, 94, 94, 25, 94, 94, 25, 25, 94, 94, 25, 25, 25, 25, 94, 25, 25, 25, 25, 25, 25, 25, 25, 21, 21, 21, 21, 94, 21, 94, 21, 21, 21, 21, 21, 21, 21, 94, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 25, 25, 94, 25, 25, 25, 25, 94, 94, 25, 25, 25, 25, 25, 25, 25, 25, 94, 25, 25, 25, 25, 25, 25, 25, 94, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 25, 25, 94, 25, 25, 25, 25, 94, 25, 25, 25, 25, 25, 94, 25, 94, 94, 94, 25, 25, 25, 25, 25, 25, 25, 94, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 94, 94, 25, 25, 25, 25, 25, 25, 25, 25, 25, 229, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 7, 21, 21, 21, 21, 21, 21, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 229, 21, 21, 21, 21, 21, 21, 21, 21, 21, 7, 21, 21, 21, 21, 21, 21, 25, 25, 25, 25, 25, 25, 25, 25, 25, 229, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 7, 21, 21, 21, 21, 21, 21, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 229, 21, 21, 21, 21, 21, 21, 21, 21, 21, 7, 21, 21, 21, 21, 21, 21, 25, 25, 25, 25, 25, 25, 25, 25, 25, 229, 21, 21, 21, 21, 21, 21, 21, 21, 21, 7, 21, 21, 21, 21, 21, 21, 25, 21, 94, 94, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 92, 92, 92, 92, 92, 92, 92, 120, 120, 120, 120, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 120, 120, 120, 120, 120, 120, 120, 120, 92, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 92, 120, 120, 125, 125, 125, 125, 125, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 92, 92, 92, 92, 92, 94, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 94, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 92, 94, 94, 92, 92, 92, 92, 92, 92, 92, 94, 92, 92, 94, 92, 92, 92, 92, 92, 94, 94, 94, 94, 94, 92, 92, 92, 92, 92, 92, 92, 90, 90, 90, 90, 90, 90, 90, 94, 94, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 94, 94, 94, 94, 15, 120, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 92, 92, 92, 92, 138, 138, 138, 138, 138, 138, 138, 138, 138, 138, 94, 94, 94, 94, 94, 4, 130, 130, 130, 130, 130, 127, 127, 226, 226, 226, 226, 226, 226, 226, 226, 226, 92, 92, 92, 92, 92, 92, 92, 127, 127, 127, 127, 127, 127, 127, 127, 127, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 230, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 231, 92, 92, 92, 92, 92, 92, 92, 134, 127, 127, 127, 127, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 127, 127, 127, 127, 129, 129, 127, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 135, 226, 226, 226, 132, 226, 226, 226, 226, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 135, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 226, 127, 127, 130, 130, 130, 130, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 130, 130, 127, 130, 127, 127, 130, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 130, 130, 130, 130, 127, 130, 127, 130, 127, 127, 127, 127, 127, 127, 130, 127, 127, 127, 127, 130, 127, 130, 127, 130, 127, 130, 130, 130, 127, 130, 130, 127, 130, 127, 127, 130, 127, 130, 127, 130, 127, 130, 127, 130, 127, 130, 130, 127, 130, 127, 127, 130, 130, 130, 130, 127, 130, 130, 130, 130, 130, 130, 130, 127, 130, 130, 130, 130, 127, 130, 130, 130, 130, 127, 130, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 130, 127, 127, 127, 127, 127, 130, 130, 130, 127, 130, 130, 130, 130, 130, 127, 130, 130, 130, 130, 130, 7, 7, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 94, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 14, 14, 14, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 14, 14, 14, 14, 14, 14, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 14, 94, 94, 94, 94, 94, 94, 94, 94, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 94, 94, 94, 94, 120, 120, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 11, 11, 11, 11, 11, 14, 14, 14, 14, 14, 14, 14, 14, 94, 94, 94, 94, 94, 94, 94, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 94, 94, 94, 94, 94, 94, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 94, 94, 14, 14, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 94, 14, 14, 14, 14, 14, 14, 14, 14, 94, 94, 94, 14, 14, 14, 94, 94, 94, 94, 94, 14, 14, 14, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 14, 14, 14, 94, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 94, 182, 182, 182, 17, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 182, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 221, 221, 221, 221, 221, 221, 221, 221, 221, 221, 221, 221, 221, 221, 182, 182 }; private static ReadOnlySpan CategoriesValues => new byte[232] { 14, 142, 139, 24, 26, 20, 21, 25, 19, 8, 32, 27, 18, 33, 28, 36, 22, 15, 10, 33, 23, 33, 33, 32, 33, 32, 32, 33, 32, 32, 32, 32, 32, 32, 32, 33, 32, 32, 33, 32, 33, 32, 32, 32, 32, 33, 32, 34, 33, 33, 32, 32, 32, 32, 32, 32, 33, 32, 32, 32, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 33, 35, 3, 5, 5, 61, 32, 32, 32, 32, 32, 33, 33, 33, 33, 33, 32, 33, 33, 33, 33, 33, 33, 33, 33, 33, 32, 33, 32, 32, 33, 60, 7, 32, 33, 32, 56, 33, 93, 83, 88, 68, 89, 90, 79, 67, 92, 72, 38, 40, 42, 37, 32, 33, 32, 32, 33, 41, 33, 33, 33, 33, 33, 33, 33, 33, 32, 33, 33, 33, 33, 32, 33, 32, 33, 33, 33, 33, 33, 33, 34, 33, 32, 34, 33, 32, 32, 32, 32, 32, 47, 140, 141, 29, 32, 32, 32, 32, 33, 41, 41, 60, 60, 32, 32, 32, 33, 33, 32, 32, 32, 32, 32, 33, 32, 59, 32, 33, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 33, 33, 48, 49, 91, 9, 32, 33, 74, 64, 65, 57, 64, 65 }; private static ReadOnlySpan UppercaseValues => new byte[464] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 224, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 231, 2, 0, 0, 0, 0, 121, 0, 0, 0, 255, 255, 0, 0, 0, 0, 195, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 97, 0, 0, 0, 0, 0, 163, 0, 0, 0, 130, 0, 0, 0, 0, 0, 0, 0, 0, 0, 56, 0, 0, 0, 255, 255, 254, 255, 177, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 63, 42, 0, 0, 0, 0, 0, 0, 31, 42, 28, 42, 30, 42, 46, 255, 50, 255, 51, 255, 54, 255, 53, 255, 79, 165, 75, 165, 49, 255, 40, 165, 68, 165, 47, 255, 45, 255, 247, 41, 65, 165, 253, 41, 43, 255, 42, 255, 231, 41, 38, 255, 67, 165, 42, 165, 187, 255, 39, 255, 185, 255, 37, 255, 21, 165, 18, 165, 0, 0, 0, 0, 0, 0, 84, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 218, 255, 219, 255, 225, 255, 192, 255, 193, 255, 0, 0, 194, 255, 199, 255, 209, 255, 202, 255, 248, 255, 170, 255, 176, 255, 7, 0, 140, 255, 0, 0, 160, 255, 0, 0, 0, 0, 176, 255, 0, 0, 0, 0, 0, 0, 241, 255, 0, 0, 0, 0, 208, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 192, 11, 0, 0, 0, 0, 248, 255, 0, 0, 146, 231, 147, 231, 156, 231, 158, 231, 157, 231, 164, 231, 219, 231, 194, 137, 0, 0, 4, 138, 230, 14, 56, 138, 197, 255, 0, 0, 8, 0, 0, 0, 74, 0, 86, 0, 100, 0, 128, 0, 112, 0, 126, 0, 0, 0, 9, 0, 0, 0, 0, 0, 219, 227, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 228, 255, 0, 0, 240, 255, 0, 0, 230, 255, 0, 0, 0, 0, 0, 0, 213, 213, 216, 213, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 160, 227, 0, 0, 0, 0, 0, 0, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 252, 48, 104, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 216, 255, 0, 0, 0, 0, 192, 255, 0, 0, 0, 0, 222, 255 }; private static ReadOnlySpan LowercaseValues => new byte[464] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 135, 255, 0, 0, 210, 0, 206, 0, 205, 0, 79, 0, 202, 0, 203, 0, 207, 0, 0, 0, 211, 0, 209, 0, 0, 0, 213, 0, 0, 0, 214, 0, 218, 0, 217, 0, 219, 0, 0, 0, 2, 0, 1, 0, 0, 0, 0, 0, 159, 255, 200, 255, 126, 255, 43, 42, 93, 255, 40, 42, 0, 0, 61, 255, 69, 0, 71, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 116, 0, 38, 0, 37, 0, 64, 0, 63, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 196, 255, 0, 0, 249, 255, 80, 0, 0, 0, 0, 0, 0, 0, 15, 0, 0, 0, 48, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 96, 28, 0, 0, 208, 151, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 244, 0, 0, 0, 0, 0, 0, 0, 0, 65, 226, 0, 0, 248, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 248, 255, 0, 0, 182, 255, 247, 255, 0, 0, 170, 255, 156, 255, 144, 255, 128, 255, 130, 255, 0, 0, 0, 0, 0, 0, 0, 0, 163, 226, 65, 223, 186, 223, 28, 0, 0, 0, 16, 0, 0, 0, 26, 0, 0, 0, 9, 214, 26, 241, 25, 214, 0, 0, 0, 0, 228, 213, 3, 214, 225, 213, 226, 213, 193, 213, 0, 0, 252, 117, 0, 0, 216, 90, 0, 0, 188, 90, 177, 90, 181, 90, 191, 90, 238, 90, 214, 90, 235, 90, 160, 3, 208, 255, 189, 90, 200, 117, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 40, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 34, 0, 0, 0 }; private static ReadOnlySpan NumericGraphemeLevel1Index => new byte[2176] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 10, 15, 16, 17, 18, 19, 20, 21, 10, 22, 23, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 27, 28, 29, 30, 31, 32, 33, 27, 28, 29, 30, 31, 32, 33, 34, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 35, 36, 10, 37, 38, 39, 40, 10, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 10, 10, 53, 10, 10, 10, 10, 10, 10, 10, 54, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 55, 10, 56, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 57, 10, 10, 10, 10, 10, 10, 10, 10, 10, 58, 59, 10, 60, 10, 61, 10, 10, 62, 63, 10, 10, 64, 10, 65, 10, 66, 67, 68, 69, 70, 71, 72, 73, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 74, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 75, 76, 76, 76, 76, 76, 76, 76, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 }; private static ReadOnlySpan NumericGraphemeLevel2Index => new byte[4928] { 0, 0, 1, 0, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 4, 0, 1, 0, 1, 0, 5, 0, 6, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 8, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 9, 0, 7, 0, 10, 0, 11, 0, 2, 0, 2, 0, 2, 0, 12, 0, 13, 0, 2, 0, 2, 0, 14, 0, 7, 0, 3, 0, 15, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 16, 0, 17, 0, 3, 0, 18, 0, 19, 0, 2, 0, 7, 0, 20, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 21, 0, 15, 0, 3, 0, 2, 0, 14, 0, 22, 0, 2, 0, 23, 0, 24, 0, 2, 0, 2, 0, 25, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 26, 0, 27, 0, 7, 0, 28, 0, 2, 0, 2, 0, 29, 0, 30, 0, 31, 0, 32, 0, 2, 0, 33, 0, 2, 0, 2, 0, 34, 0, 35, 0, 36, 0, 32, 0, 37, 0, 38, 0, 2, 0, 2, 0, 39, 0, 40, 0, 19, 0, 41, 0, 42, 0, 38, 0, 2, 0, 2, 0, 39, 0, 43, 0, 2, 0, 32, 0, 44, 0, 33, 0, 2, 0, 2, 0, 45, 0, 35, 0, 46, 0, 32, 0, 47, 0, 48, 0, 2, 0, 2, 0, 49, 0, 50, 0, 36, 0, 41, 0, 51, 0, 52, 0, 2, 0, 2, 0, 53, 0, 54, 0, 55, 0, 32, 0, 56, 0, 33, 0, 2, 0, 2, 0, 57, 0, 58, 0, 55, 0, 32, 0, 2, 0, 59, 0, 2, 0, 2, 0, 60, 0, 61, 0, 62, 0, 32, 0, 63, 0, 33, 0, 2, 0, 2, 0, 2, 0, 64, 0, 65, 0, 41, 0, 66, 0, 2, 0, 2, 0, 2, 0, 67, 0, 68, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 69, 0, 70, 0, 3, 0, 2, 0, 2, 0, 2, 0, 71, 0, 72, 0, 73, 0, 2, 0, 2, 0, 2, 0, 74, 0, 75, 0, 76, 0, 7, 0, 77, 0, 78, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 79, 0, 80, 0, 3, 0, 81, 0, 15, 0, 82, 0, 83, 0, 84, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 85, 0, 85, 0, 85, 0, 85, 0, 85, 0, 85, 0, 86, 0, 86, 0, 86, 0, 86, 0, 87, 0, 88, 0, 88, 0, 88, 0, 88, 0, 88, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 79, 0, 89, 0, 90, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 91, 0, 92, 0, 2, 0, 93, 0, 2, 0, 93, 0, 2, 0, 94, 0, 2, 0, 94, 0, 2, 0, 2, 0, 2, 0, 95, 0, 96, 0, 22, 0, 3, 0, 97, 0, 98, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 55, 0, 2, 0, 99, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 100, 0, 101, 0, 41, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 102, 0, 2, 0, 2, 0, 2, 0, 103, 0, 2, 0, 2, 0, 2, 0, 104, 0, 105, 0, 106, 0, 3, 0, 3, 0, 2, 0, 7, 0, 15, 0, 2, 0, 2, 0, 2, 0, 107, 0, 2, 0, 2, 0, 108, 0, 109, 0, 3, 0, 14, 0, 110, 0, 111, 0, 2, 0, 112, 0, 3, 0, 2, 0, 2, 0, 113, 0, 59, 0, 2, 0, 2, 0, 114, 0, 115, 0, 3, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 116, 0, 117, 0, 118, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 7, 0, 7, 0, 7, 0, 119, 0, 120, 0, 2, 0, 121, 0, 122, 0, 123, 0, 2, 0, 1, 0, 124, 0, 125, 0, 2, 0, 2, 0, 2, 0, 2, 0, 7, 0, 7, 0, 15, 0, 2, 0, 2, 0, 126, 0, 123, 0, 2, 0, 127, 0, 128, 0, 128, 0, 129, 0, 130, 0, 131, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 132, 0, 133, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 133, 0, 2, 0, 2, 0, 2, 0, 134, 0, 2, 0, 135, 0, 136, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 137, 0, 138, 0, 139, 0, 140, 0, 2, 0, 2, 0, 126, 0, 2, 0, 141, 0, 142, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 132, 0, 143, 0, 144, 0, 2, 0, 2, 0, 145, 0, 146, 0, 147, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 149, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 150, 0, 151, 0, 152, 0, 153, 0, 154, 0, 155, 0, 156, 0, 157, 0, 158, 0, 159, 0, 160, 0, 161, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 162, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 163, 0, 164, 0, 2, 0, 2, 0, 2, 0, 165, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 166, 0, 167, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 166, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 7, 0, 7, 0, 168, 0, 2, 0, 169, 0, 170, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 171, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 172, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 173, 0, 2, 0, 174, 0, 175, 0, 2, 0, 2, 0, 173, 0, 176, 0, 2, 0, 177, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 166, 0, 178, 0, 2, 0, 53, 0, 2, 0, 2, 0, 2, 0, 2, 0, 179, 0, 180, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 181, 0, 2, 0, 182, 0, 183, 0, 2, 0, 2, 0, 2, 0, 2, 0, 184, 0, 2, 0, 2, 0, 185, 0, 186, 0, 3, 0, 7, 0, 187, 0, 3, 0, 2, 0, 188, 0, 2, 0, 189, 0, 59, 0, 85, 0, 190, 0, 28, 0, 2, 0, 2, 0, 191, 0, 192, 0, 3, 0, 193, 0, 3, 0, 2, 0, 2, 0, 194, 0, 195, 0, 196, 0, 3, 0, 2, 0, 197, 0, 2, 0, 2, 0, 2, 0, 198, 0, 19, 0, 2, 0, 199, 0, 200, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 201, 0, 3, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 206, 0, 204, 0, 202, 0, 203, 0, 204, 0, 205, 0, 204, 0, 207, 0, 86, 0, 208, 0, 88, 0, 88, 0, 209, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 210, 0, 211, 0, 2, 0, 2, 0, 2, 0, 212, 0, 2, 0, 213, 0, 2, 0, 214, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 215, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 7, 0, 2, 0, 7, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 4, 0, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 53, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 216, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 217, 0, 218, 0, 219, 0, 220, 0, 221, 0, 222, 0, 223, 0, 224, 0, 225, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 226, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 227, 0, 228, 0, 2, 0, 2, 0, 229, 0, 2, 0, 230, 0, 2, 0, 2, 0, 231, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 232, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 233, 0, 2, 0, 234, 0, 2, 0, 2, 0, 235, 0, 2, 0, 2, 0, 2, 0, 2, 0, 236, 0, 2, 0, 237, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 238, 0, 239, 0, 240, 0, 241, 0, 242, 0, 243, 0, 2, 0, 2, 0, 244, 0, 245, 0, 2, 0, 2, 0, 246, 0, 2, 0, 247, 0, 2, 0, 2, 0, 2, 0, 2, 0, 248, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 249, 0, 2, 0, 249, 0, 2, 0, 2, 0, 250, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 251, 0, 2, 0, 2, 0, 252, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 253, 0, 254, 0, 2, 0, 2, 0, 255, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 0, 1, 1, 1, 2, 0, 21, 0, 2, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 3, 1, 2, 0, 2, 0, 2, 0, 4, 1, 2, 0, 2, 0, 5, 1, 6, 1, 7, 1, 8, 1, 166, 0, 111, 0, 2, 0, 2, 0, 9, 1, 10, 1, 2, 0, 2, 0, 3, 0, 11, 1, 2, 0, 12, 1, 13, 1, 14, 1, 2, 0, 2, 0, 15, 1, 111, 0, 2, 0, 2, 0, 16, 1, 17, 1, 3, 0, 18, 1, 19, 1, 2, 0, 2, 0, 20, 1, 21, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 166, 0, 22, 1, 3, 0, 59, 0, 2, 0, 2, 0, 60, 0, 23, 1, 36, 0, 24, 1, 25, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 26, 1, 27, 1, 28, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 29, 1, 30, 1, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 166, 0, 31, 1, 15, 0, 32, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 33, 1, 15, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 34, 1, 35, 1, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 79, 0, 36, 1, 37, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 20, 1, 38, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 39, 1, 40, 1, 2, 0, 2, 0, 2, 0, 41, 1, 42, 1, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 43, 1, 44, 1, 2, 0, 45, 1, 2, 0, 2, 0, 46, 1, 36, 0, 47, 1, 2, 0, 2, 0, 48, 1, 49, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 50, 1, 51, 1, 2, 0, 52, 1, 53, 1, 2, 0, 2, 0, 54, 1, 55, 1, 56, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 57, 1, 58, 1, 3, 0, 2, 0, 2, 0, 59, 1, 60, 1, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 61, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 62, 1, 63, 1, 2, 0, 2, 0, 64, 1, 65, 1, 66, 1, 67, 1, 68, 1, 69, 1, 70, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 71, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 25, 1, 2, 0, 2, 0, 2, 0, 6, 1, 2, 0, 72, 1, 73, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 74, 1, 75, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 166, 0, 76, 1, 77, 1, 77, 1, 78, 1, 11, 1, 2, 0, 2, 0, 2, 0, 2, 0, 79, 1, 184, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 80, 1, 81, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 82, 1, 83, 1, 84, 1, 2, 0, 85, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 93, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 74, 1, 86, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 239, 0, 87, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 88, 1, 89, 1, 90, 1, 91, 1, 7, 0, 7, 0, 7, 0, 92, 1, 7, 0, 7, 0, 77, 0, 193, 0, 79, 1, 14, 0, 9, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 93, 1, 94, 1, 95, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 6, 1, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 96, 1, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 217, 0, 6, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 97, 1, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 18, 1, 98, 1, 99, 1, 100, 1, 101, 1, 2, 0, 2, 0, 2, 0, 2, 0, 18, 1, 98, 1, 102, 1, 103, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 104, 1, 2, 0, 134, 0, 2, 0, 2, 0, 2, 0, 105, 1, 106, 1, 107, 1, 108, 1, 109, 1, 148, 0, 148, 0, 148, 0, 110, 1, 111, 1, 112, 1, 113, 1, 134, 0, 114, 1, 135, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 115, 1, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 116, 1, 117, 1, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 2, 0, 2, 0, 2, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 118, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 119, 1, 148, 0, 148, 0, 105, 1, 2, 0, 2, 0, 2, 0, 120, 1, 121, 1, 2, 0, 2, 0, 120, 1, 2, 0, 122, 1, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 105, 1, 148, 0, 148, 0, 123, 1, 146, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 3, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 148, 0, 116, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 124, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 1, 0, 1, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 7, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0 }; private static ReadOnlySpan NumericGraphemeLevel3Index => new byte[6096] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 3, 3, 3, 0, 14, 3, 3, 3, 15, 16, 3, 3, 3, 3, 3, 17, 3, 3, 18, 19, 20, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 21, 3, 21, 21, 3, 21, 21, 3, 21, 3, 3, 3, 3, 3, 3, 3, 3, 22, 22, 22, 22, 22, 22, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 22, 3, 21, 21, 21, 21, 21, 21, 3, 3, 21, 21, 3, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 22, 3, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 21, 21, 21, 3, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 23, 21, 3, 23, 23, 23, 21, 21, 21, 21, 21, 21, 21, 21, 23, 23, 23, 23, 21, 23, 23, 3, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 3, 21, 23, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 21, 23, 23, 21, 21, 21, 21, 3, 3, 23, 23, 3, 3, 23, 23, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 24, 25, 26, 18, 20, 27, 3, 3, 3, 3, 21, 3, 3, 21, 21, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 23, 23, 23, 21, 21, 3, 3, 3, 3, 21, 21, 3, 3, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 21, 21, 3, 3, 3, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 21, 21, 21, 21, 21, 3, 21, 21, 23, 3, 23, 23, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 21, 21, 3, 3, 3, 3, 3, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 18, 19, 20, 24, 25, 26, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 23, 21, 23, 23, 3, 3, 3, 23, 23, 23, 3, 23, 23, 23, 21, 3, 3, 28, 29, 30, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 23, 23, 23, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 23, 23, 23, 23, 3, 21, 21, 21, 3, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 31, 32, 33, 34, 32, 33, 34, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 23, 21, 23, 23, 21, 23, 23, 3, 21, 23, 23, 3, 23, 23, 21, 21, 3, 3, 21, 21, 23, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 3, 21, 23, 23, 21, 21, 21, 21, 3, 23, 23, 23, 3, 23, 23, 23, 21, 22, 3, 3, 3, 3, 3, 3, 3, 3, 21, 35, 36, 37, 38, 39, 40, 41, 3, 28, 29, 30, 18, 19, 20, 24, 25, 26, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 3, 3, 3, 21, 23, 23, 21, 21, 21, 3, 21, 3, 23, 23, 23, 23, 23, 23, 23, 21, 3, 3, 23, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 23, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 3, 3, 21, 3, 23, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 19, 42, 43, 44, 45, 46, 47, 48, 49, 50, 3, 21, 3, 21, 3, 21, 3, 3, 3, 3, 23, 23, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 23, 21, 21, 21, 21, 21, 3, 21, 21, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 23, 21, 21, 21, 21, 21, 21, 3, 21, 21, 23, 23, 21, 21, 3, 3, 3, 3, 3, 3, 3, 23, 23, 21, 21, 3, 3, 3, 3, 21, 21, 3, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 23, 21, 21, 3, 3, 3, 3, 3, 3, 21, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 3, 3, 3, 21, 3, 3, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 52, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 3, 3, 3, 3, 3, 3, 3, 3, 3, 17, 15, 16, 54, 55, 56, 57, 58, 59, 28, 60, 61, 62, 63, 64, 65, 66, 67, 29, 68, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 69, 70, 71, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 23, 21, 21, 21, 21, 21, 21, 21, 23, 23, 23, 23, 23, 23, 23, 23, 21, 23, 23, 21, 21, 21, 21, 21, 21, 21, 31, 32, 33, 34, 72, 73, 74, 75, 76, 77, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 3, 3, 3, 3, 3, 21, 21, 21, 23, 23, 23, 23, 21, 21, 23, 23, 23, 3, 3, 3, 3, 23, 23, 21, 23, 23, 23, 23, 23, 23, 21, 21, 21, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 17, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 23, 23, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 21, 23, 21, 21, 21, 21, 21, 21, 21, 3, 21, 3, 21, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 23, 23, 23, 23, 23, 23, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 3, 21, 21, 21, 21, 21, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 23, 21, 23, 23, 23, 23, 23, 21, 23, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 21, 21, 21, 21, 23, 23, 21, 21, 23, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 21, 23, 21, 21, 23, 23, 23, 21, 23, 21, 3, 3, 3, 3, 23, 23, 23, 23, 23, 23, 23, 23, 21, 21, 21, 21, 21, 21, 21, 21, 23, 23, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 23, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 21, 3, 3, 3, 3, 3, 3, 21, 3, 3, 23, 21, 21, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0, 21, 78, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 3, 3, 3, 3, 3, 3, 79, 3, 3, 3, 54, 55, 56, 57, 58, 59, 3, 3, 3, 3, 3, 3, 79, 17, 15, 16, 54, 55, 56, 57, 58, 59, 3, 3, 3, 3, 3, 3, 3, 3, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 80, 81, 39, 82, 83, 41, 84, 85, 86, 87, 88, 25, 89, 90, 91, 32, 32, 33, 34, 72, 73, 74, 75, 76, 77, 28, 92, 93, 63, 29, 94, 30, 30, 95, 68, 3, 3, 74, 63, 96, 97, 31, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 3, 3, 3, 3, 14, 14, 14, 3, 3, 3, 3, 3, 17, 15, 16, 54, 55, 56, 57, 58, 59, 28, 92, 93, 98, 99, 100, 27, 69, 70, 71, 60, 17, 15, 16, 54, 55, 56, 57, 58, 59, 28, 92, 93, 98, 99, 100, 27, 69, 70, 71, 60, 17, 15, 16, 54, 55, 56, 57, 58, 59, 28, 92, 93, 98, 99, 100, 27, 69, 70, 71, 60, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 79, 92, 93, 98, 99, 100, 27, 69, 70, 71, 60, 17, 15, 16, 54, 55, 56, 57, 58, 59, 28, 79, 3, 3, 3, 3, 3, 3, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 3, 14, 14, 14, 14, 14, 14, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 14, 3, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 3, 14, 3, 14, 3, 3, 3, 3, 3, 3, 14, 3, 3, 3, 14, 3, 3, 3, 3, 3, 3, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 3, 3, 14, 3, 3, 3, 3, 14, 3, 14, 3, 3, 3, 3, 14, 14, 14, 3, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 17, 15, 16, 54, 55, 56, 57, 58, 59, 28, 17, 15, 16, 54, 55, 56, 57, 58, 59, 28, 17, 15, 16, 54, 55, 56, 57, 58, 59, 28, 3, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 3, 3, 3, 3, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 3, 3, 3, 14, 3, 3, 3, 3, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 19, 3, 3, 3, 3, 3, 3, 3, 3, 3, 31, 3, 3, 3, 3, 3, 3, 3, 3, 3, 32, 33, 34, 72, 73, 74, 75, 76, 77, 21, 21, 21, 21, 21, 21, 14, 3, 3, 3, 3, 3, 3, 3, 28, 60, 61, 3, 3, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 3, 3, 3, 3, 3, 3, 3, 32, 33, 34, 72, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 32, 33, 34, 72, 73, 74, 75, 76, 77, 28, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 28, 60, 61, 62, 63, 64, 65, 66, 3, 101, 102, 103, 104, 105, 106, 107, 108, 109, 61, 110, 111, 112, 113, 114, 3, 3, 3, 3, 3, 3, 3, 14, 3, 14, 3, 3, 3, 3, 3, 3, 3, 115, 116, 117, 118, 62, 119, 120, 121, 122, 123, 124, 125, 126, 127, 63, 21, 21, 21, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 32, 33, 34, 72, 73, 74, 75, 76, 77, 31, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 3, 3, 21, 3, 3, 3, 3, 21, 3, 3, 3, 3, 3, 3, 3, 23, 23, 21, 21, 23, 3, 3, 3, 3, 21, 3, 3, 3, 18, 19, 20, 24, 25, 26, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 51, 3, 3, 3, 3, 3, 3, 21, 23, 23, 21, 21, 21, 21, 23, 23, 21, 21, 23, 23, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 23, 23, 21, 21, 23, 23, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 3, 3, 3, 3, 3, 3, 3, 21, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 3, 3, 21, 3, 21, 21, 21, 3, 3, 21, 21, 3, 3, 3, 3, 3, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 21, 21, 23, 23, 3, 3, 3, 3, 3, 23, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 23, 21, 23, 23, 21, 23, 23, 3, 23, 21, 3, 3, 128, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 128, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 128, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 128, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 129, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 52, 52, 52, 52, 52, 52, 52, 3, 3, 3, 3, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 53, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 34, 3, 3, 3, 3, 3, 3, 3, 28, 3, 3, 3, 3, 33, 3, 3, 3, 3, 3, 3, 3, 3, 3, 31, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 74, 3, 74, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 28, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 32, 33, 34, 72, 73, 74, 75, 76, 77, 28, 60, 61, 62, 63, 64, 65, 66, 67, 29, 130, 131, 132, 94, 133, 134, 135, 136, 30, 137, 138, 139, 95, 140, 141, 142, 143, 68, 144, 145, 146, 96, 147, 148, 149, 150, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 18, 19, 32, 73, 63, 94, 95, 96, 73, 28, 63, 29, 94, 30, 95, 73, 28, 63, 29, 94, 30, 68, 96, 28, 32, 32, 32, 33, 33, 33, 33, 73, 28, 28, 28, 28, 28, 61, 63, 63, 63, 63, 29, 131, 94, 94, 94, 94, 94, 30, 95, 73, 63, 19, 19, 83, 20, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 31, 18, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 3, 21, 32, 33, 34, 72, 73, 74, 75, 76, 77, 28, 60, 61, 62, 63, 64, 65, 66, 67, 29, 130, 131, 132, 94, 133, 134, 135, 136, 3, 3, 3, 3, 32, 73, 28, 63, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 67, 3, 3, 3, 3, 3, 3, 3, 3, 136, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 32, 33, 28, 60, 29, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 32, 33, 34, 28, 60, 29, 30, 68, 3, 3, 3, 3, 3, 3, 3, 3, 3, 32, 33, 34, 72, 73, 28, 60, 3, 3, 3, 3, 3, 3, 3, 32, 33, 34, 72, 72, 73, 28, 60, 29, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 32, 73, 28, 60, 29, 3, 3, 3, 3, 3, 3, 32, 28, 60, 29, 33, 34, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 151, 19, 3, 3, 32, 33, 34, 72, 73, 74, 75, 76, 77, 28, 60, 61, 62, 63, 64, 65, 3, 3, 29, 130, 131, 132, 94, 133, 134, 135, 136, 30, 137, 138, 139, 95, 140, 141, 142, 143, 68, 144, 145, 146, 96, 147, 148, 149, 150, 97, 152, 153, 154, 155, 156, 157, 158, 159, 160, 87, 18, 82, 161, 19, 162, 83, 20, 88, 3, 21, 21, 21, 3, 21, 21, 3, 3, 3, 3, 3, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 3, 3, 3, 3, 21, 17, 15, 16, 54, 28, 60, 29, 30, 19, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 32, 63, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 32, 28, 60, 3, 3, 3, 3, 3, 21, 21, 3, 3, 3, 3, 32, 73, 28, 60, 29, 3, 3, 3, 3, 3, 3, 3, 3, 32, 33, 34, 72, 28, 60, 29, 30, 3, 3, 3, 3, 3, 3, 3, 3, 3, 32, 33, 34, 72, 28, 60, 29, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 32, 73, 28, 63, 29, 30, 3, 3, 3, 3, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 17, 15, 16, 54, 55, 56, 57, 58, 59, 28, 60, 61, 62, 63, 64, 65, 66, 67, 29, 130, 131, 132, 94, 133, 134, 135, 136, 19, 18, 82, 83, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 32, 33, 34, 72, 73, 28, 60, 61, 29, 19, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 32, 28, 60, 29, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 32, 33, 34, 72, 28, 60, 29, 3, 3, 3, 3, 23, 21, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 17, 15, 16, 54, 55, 56, 57, 58, 59, 28, 60, 61, 62, 63, 64, 65, 66, 67, 29, 30, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 23, 23, 23, 21, 21, 21, 21, 23, 23, 21, 21, 3, 3, 22, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 22, 3, 3, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 23, 21, 21, 21, 21, 21, 21, 21, 21, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 3, 3, 3, 3, 3, 23, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 23, 23, 21, 21, 21, 21, 21, 21, 21, 21, 21, 23, 23, 3, 22, 22, 3, 3, 3, 3, 3, 21, 21, 21, 21, 3, 23, 21, 3, 32, 33, 34, 72, 73, 74, 75, 76, 77, 28, 60, 61, 62, 63, 64, 65, 66, 67, 29, 30, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 23, 23, 21, 21, 21, 23, 23, 21, 23, 21, 21, 3, 3, 3, 3, 3, 3, 21, 3, 23, 23, 23, 21, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 21, 23, 23, 23, 23, 3, 3, 23, 23, 3, 3, 23, 23, 23, 3, 3, 3, 3, 23, 23, 3, 3, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 23, 23, 21, 21, 21, 21, 21, 21, 21, 21, 23, 23, 21, 21, 21, 23, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 3, 3, 3, 3, 21, 3, 21, 23, 23, 21, 21, 21, 21, 21, 21, 23, 21, 23, 23, 21, 23, 21, 21, 23, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 23, 21, 21, 21, 21, 3, 3, 23, 23, 23, 23, 21, 21, 23, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 3, 3, 23, 23, 23, 21, 21, 21, 21, 21, 21, 21, 21, 23, 23, 21, 23, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 23, 21, 23, 23, 21, 21, 21, 21, 21, 21, 23, 21, 3, 3, 3, 3, 3, 3, 3, 3, 23, 23, 21, 21, 21, 21, 23, 21, 21, 21, 21, 21, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 60, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 23, 21, 21, 3, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 28, 60, 61, 62, 63, 64, 65, 66, 67, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 23, 23, 23, 23, 23, 3, 23, 23, 3, 3, 21, 21, 23, 21, 22, 23, 22, 23, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 23, 23, 21, 21, 21, 21, 3, 3, 21, 21, 23, 23, 23, 23, 21, 3, 3, 3, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 23, 22, 21, 21, 21, 21, 3, 3, 21, 21, 21, 21, 21, 21, 23, 23, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 22, 22, 22, 22, 22, 22, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 23, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 21, 21, 21, 21, 21, 21, 21, 3, 21, 21, 21, 21, 21, 21, 23, 21, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 32, 33, 34, 72, 73, 74, 75, 76, 77, 28, 60, 61, 62, 63, 64, 65, 66, 67, 29, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 23, 21, 21, 21, 21, 21, 21, 21, 23, 21, 21, 23, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 3, 3, 3, 21, 3, 21, 21, 3, 21, 21, 21, 21, 21, 21, 21, 22, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 23, 23, 23, 23, 3, 21, 21, 3, 23, 23, 21, 23, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 23, 23, 3, 3, 3, 3, 3, 3, 3, 3, 3, 163, 35, 164, 165, 36, 166, 37, 167, 38, 24, 24, 39, 25, 40, 26, 41, 18, 19, 19, 20, 163, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 33, 34, 72, 73, 74, 75, 76, 77, 34, 72, 73, 74, 75, 76, 77, 72, 73, 74, 75, 76, 77, 32, 33, 34, 72, 73, 74, 75, 76, 77, 32, 33, 34, 72, 73, 33, 34, 34, 72, 73, 74, 75, 76, 77, 32, 33, 34, 34, 72, 73, 168, 169, 32, 33, 34, 34, 72, 73, 34, 34, 72, 72, 72, 72, 74, 75, 75, 75, 76, 76, 77, 77, 77, 77, 33, 34, 72, 73, 74, 32, 33, 34, 72, 72, 73, 73, 33, 34, 32, 33, 82, 83, 88, 82, 83, 25, 18, 87, 18, 18, 19, 82, 83, 62, 63, 72, 73, 74, 75, 76, 77, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 3, 28, 29, 68, 170, 171, 172, 173, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 31, 32, 33, 34, 72, 73, 74, 75, 76, 77, 28, 92, 93, 98, 99, 100, 27, 69, 70, 71, 32, 33, 34, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 3, 3, 3, 3, 3, 3, 3, 21, 3, 3, 3, 3, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 3, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 23, 21, 21, 21, 3, 3, 3, 23, 21, 21, 21, 21, 21, 0, 0, 0, 0, 0, 0, 0, 0, 21, 21, 21, 21, 21, 21, 21, 21, 3, 3, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 3, 3, 27, 69, 70, 71, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 66, 67, 32, 33, 34, 72, 73, 32, 73, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 3, 3, 21, 21, 21, 21, 21, 21, 21, 3, 21, 21, 3, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 21, 21, 21, 21, 3, 3, 3, 3, 21, 21, 21, 21, 21, 21, 21, 3, 3, 3, 3, 3, 65, 66, 67, 29, 130, 131, 132, 94, 133, 134, 135, 136, 30, 137, 138, 139, 95, 140, 141, 142, 143, 68, 144, 145, 146, 96, 147, 148, 149, 150, 97, 152, 97, 174, 175, 32, 33, 34, 72, 73, 74, 75, 76, 77, 3, 18, 19, 20, 3, 32, 33, 68, 97, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 95, 140, 141, 142, 143, 68, 144, 145, 146, 96, 147, 148, 149, 150, 3, 33, 34, 72, 73, 74, 75, 76, 77, 28, 132, 133, 137, 68, 19, 87, 3, 3, 79, 79, 17, 15, 16, 54, 55, 56, 57, 58, 59, 31, 31, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 3, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 176, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 21, 21, 21, 21, 21, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 3, 3, 3, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 14, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 3, 14, 14, 14, 14, 77, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }; private static ReadOnlySpan DigitValues => new byte[177] { 0, 0, 0, 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 0, 3, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 6, 7, 8, 9, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; private static ReadOnlySpan NumericValues => new byte[1416] { 0, 0, 0, 0, 0, 0, 240, 191, 0, 0, 0, 0, 0, 0, 240, 191, 0, 0, 0, 0, 0, 0, 240, 191, 0, 0, 0, 0, 0, 0, 240, 191, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 63, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 8, 64, 0, 0, 0, 0, 0, 0, 16, 64, 0, 0, 0, 0, 0, 0, 20, 64, 0, 0, 0, 0, 0, 0, 24, 64, 0, 0, 0, 0, 0, 0, 28, 64, 0, 0, 0, 0, 0, 0, 32, 64, 0, 0, 0, 0, 0, 0, 34, 64, 0, 0, 0, 0, 0, 0, 240, 191, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 8, 64, 0, 0, 0, 0, 0, 0, 240, 63, 0, 0, 0, 0, 0, 0, 208, 63, 0, 0, 0, 0, 0, 0, 224, 63, 0, 0, 0, 0, 0, 0, 232, 63, 0, 0, 0, 0, 0, 0, 240, 191, 0, 0, 0, 0, 0, 0, 240, 191, 0, 0, 0, 0, 0, 0, 240, 191, 0, 0, 0, 0, 0, 0, 176, 63, 0, 0, 0, 0, 0, 0, 192, 63, 0, 0, 0, 0, 0, 0, 200, 63, 0, 0, 0, 0, 0, 0, 48, 64, 0, 0, 0, 0, 0, 0, 36, 64, 0, 0, 0, 0, 0, 0, 89, 64, 0, 0, 0, 0, 0, 64, 143, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 240, 63, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 0, 0, 0, 8, 64, 154, 153, 153, 153, 153, 153, 121, 63, 154, 153, 153, 153, 153, 153, 153, 63, 51, 51, 51, 51, 51, 51, 163, 63, 154, 153, 153, 153, 153, 153, 169, 63, 154, 153, 153, 153, 153, 153, 185, 63, 51, 51, 51, 51, 51, 51, 195, 63, 154, 153, 153, 153, 153, 153, 201, 63, 0, 0, 0, 0, 0, 0, 248, 63, 0, 0, 0, 0, 0, 0, 4, 64, 0, 0, 0, 0, 0, 0, 12, 64, 0, 0, 0, 0, 0, 0, 18, 64, 0, 0, 0, 0, 0, 0, 22, 64, 0, 0, 0, 0, 0, 0, 26, 64, 0, 0, 0, 0, 0, 0, 30, 64, 0, 0, 0, 0, 0, 0, 33, 64, 0, 0, 0, 0, 0, 0, 224, 191, 0, 0, 0, 0, 0, 0, 240, 191, 0, 0, 0, 0, 0, 0, 240, 191, 0, 0, 0, 0, 0, 0, 240, 191, 0, 0, 0, 0, 0, 0, 16, 64, 0, 0, 0, 0, 0, 0, 20, 64, 0, 0, 0, 0, 0, 0, 24, 64, 0, 0, 0, 0, 0, 0, 28, 64, 0, 0, 0, 0, 0, 0, 32, 64, 0, 0, 0, 0, 0, 0, 34, 64, 0, 0, 0, 0, 0, 0, 52, 64, 0, 0, 0, 0, 0, 0, 62, 64, 0, 0, 0, 0, 0, 0, 68, 64, 0, 0, 0, 0, 0, 0, 73, 64, 0, 0, 0, 0, 0, 0, 78, 64, 0, 0, 0, 0, 0, 128, 81, 64, 0, 0, 0, 0, 0, 0, 84, 64, 0, 0, 0, 0, 0, 128, 86, 64, 0, 0, 0, 0, 0, 136, 195, 64, 0, 0, 0, 0, 0, 0, 49, 64, 0, 0, 0, 0, 0, 0, 50, 64, 0, 0, 0, 0, 0, 0, 51, 64, 0, 0, 0, 0, 0, 0, 16, 64, 0, 0, 0, 0, 0, 0, 20, 64, 0, 0, 0, 0, 0, 0, 24, 64, 0, 0, 0, 0, 0, 0, 28, 64, 0, 0, 0, 0, 0, 0, 32, 64, 0, 0, 0, 0, 0, 0, 34, 64, 0, 0, 0, 0, 0, 0, 240, 191, 0, 0, 0, 0, 0, 0, 0, 0, 146, 36, 73, 146, 36, 73, 194, 63, 28, 199, 113, 28, 199, 113, 188, 63, 85, 85, 85, 85, 85, 85, 213, 63, 85, 85, 85, 85, 85, 85, 229, 63, 154, 153, 153, 153, 153, 153, 217, 63, 51, 51, 51, 51, 51, 51, 227, 63, 154, 153, 153, 153, 153, 153, 233, 63, 85, 85, 85, 85, 85, 85, 197, 63, 171, 170, 170, 170, 170, 170, 234, 63, 0, 0, 0, 0, 0, 0, 216, 63, 0, 0, 0, 0, 0, 0, 228, 63, 0, 0, 0, 0, 0, 0, 236, 63, 0, 0, 0, 0, 0, 0, 38, 64, 0, 0, 0, 0, 0, 0, 40, 64, 0, 0, 0, 0, 0, 64, 127, 64, 0, 0, 0, 0, 0, 136, 179, 64, 0, 0, 0, 0, 0, 106, 232, 64, 0, 0, 0, 0, 0, 106, 248, 64, 0, 0, 0, 0, 0, 0, 42, 64, 0, 0, 0, 0, 0, 0, 44, 64, 0, 0, 0, 0, 0, 0, 46, 64, 0, 0, 0, 0, 0, 0, 53, 64, 0, 0, 0, 0, 0, 0, 54, 64, 0, 0, 0, 0, 0, 0, 55, 64, 0, 0, 0, 0, 0, 0, 56, 64, 0, 0, 0, 0, 0, 0, 57, 64, 0, 0, 0, 0, 0, 0, 58, 64, 0, 0, 0, 0, 0, 0, 59, 64, 0, 0, 0, 0, 0, 0, 60, 64, 0, 0, 0, 0, 0, 0, 61, 64, 0, 0, 0, 0, 0, 0, 63, 64, 0, 0, 0, 0, 0, 0, 64, 64, 0, 0, 0, 0, 0, 128, 64, 64, 0, 0, 0, 0, 0, 0, 65, 64, 0, 0, 0, 0, 0, 128, 65, 64, 0, 0, 0, 0, 0, 0, 66, 64, 0, 0, 0, 0, 0, 128, 66, 64, 0, 0, 0, 0, 0, 0, 67, 64, 0, 0, 0, 0, 0, 128, 67, 64, 0, 0, 0, 0, 0, 128, 68, 64, 0, 0, 0, 0, 0, 0, 69, 64, 0, 0, 0, 0, 0, 128, 69, 64, 0, 0, 0, 0, 0, 0, 70, 64, 0, 0, 0, 0, 0, 128, 70, 64, 0, 0, 0, 0, 0, 0, 71, 64, 0, 0, 0, 0, 0, 128, 71, 64, 0, 0, 0, 0, 0, 0, 72, 64, 0, 0, 0, 0, 0, 128, 72, 64, 0, 0, 0, 0, 0, 0, 240, 191, 0, 0, 0, 0, 0, 0, 240, 191, 0, 0, 0, 0, 0, 0, 105, 64, 0, 0, 0, 0, 0, 192, 114, 64, 0, 0, 0, 0, 0, 0, 121, 64, 0, 0, 0, 0, 0, 192, 130, 64, 0, 0, 0, 0, 0, 224, 133, 64, 0, 0, 0, 0, 0, 0, 137, 64, 0, 0, 0, 0, 0, 32, 140, 64, 0, 0, 0, 0, 0, 64, 159, 64, 0, 0, 0, 0, 0, 112, 167, 64, 0, 0, 0, 0, 0, 64, 175, 64, 0, 0, 0, 0, 0, 112, 183, 64, 0, 0, 0, 0, 0, 88, 187, 64, 0, 0, 0, 0, 0, 64, 191, 64, 0, 0, 0, 0, 0, 148, 193, 64, 0, 0, 0, 0, 0, 136, 211, 64, 0, 0, 0, 0, 0, 76, 221, 64, 0, 0, 0, 0, 0, 136, 227, 64, 0, 0, 0, 0, 0, 76, 237, 64, 0, 0, 0, 0, 0, 23, 241, 64, 0, 0, 0, 0, 0, 136, 243, 64, 0, 0, 0, 0, 0, 249, 245, 64, 85, 85, 85, 85, 85, 85, 237, 63, 0, 0, 0, 0, 0, 106, 8, 65, 0, 0, 0, 0, 128, 79, 18, 65, 0, 0, 0, 0, 0, 106, 24, 65, 0, 0, 0, 0, 128, 132, 30, 65, 0, 0, 0, 0, 128, 79, 34, 65, 0, 0, 0, 0, 192, 92, 37, 65, 0, 0, 0, 0, 0, 106, 40, 65, 0, 0, 0, 0, 64, 119, 43, 65, 85, 85, 85, 85, 85, 85, 181, 63, 171, 170, 170, 170, 170, 170, 218, 63, 171, 170, 170, 170, 170, 170, 226, 63, 154, 153, 153, 153, 153, 153, 105, 63, 154, 153, 153, 153, 153, 153, 137, 63, 0, 0, 0, 0, 0, 0, 144, 63, 0, 0, 0, 0, 0, 0, 160, 63, 0, 0, 0, 0, 0, 0, 168, 63, 0, 0, 0, 0, 0, 94, 10, 65, 0, 0, 0, 0, 0, 94, 26, 65, 0, 0, 0, 0, 128, 132, 46, 65, 0, 0, 0, 0, 132, 215, 151, 65, 0, 0, 0, 32, 95, 160, 2, 66, 0, 0, 0, 162, 148, 26, 109, 66, 0, 0, 0, 0, 208, 18, 99, 65, 0, 0, 0, 0, 208, 18, 115, 65, 0, 0, 0, 0, 0, 0, 240, 191 }; private static ReadOnlySpan GraphemeSegmentationValues => new byte[177] { 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 4, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6 }; internal static StrongBidiCategory GetBidiCategory(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return GetBidiCategoryNoBoundsChecks((uint)GetCodePointFromString(s, index)); } internal static StrongBidiCategory GetBidiCategory(StringBuilder s, int index) { int num = s[index]; if (index < s.Length - 1) { int num2 = num - 55296; if ((uint)num2 <= 1023u) { int num3 = s[index + 1] - 56320; if ((uint)num3 <= 1023u) { num = (num2 << 10) + num3 + 65536; } } } return GetBidiCategoryNoBoundsChecks((uint)num); } private static StrongBidiCategory GetBidiCategoryNoBoundsChecks(uint codePoint) { nuint categoryCasingTableOffsetNoBoundsChecks = GetCategoryCasingTableOffsetNoBoundsChecks(codePoint); return (StrongBidiCategory)(Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(CategoriesValues), categoryCasingTableOffsetNoBoundsChecks) & 0x60); } public static int GetDecimalDigitValue(char ch) { return GetDecimalDigitValueInternalNoBoundsCheck(ch); } public static int GetDecimalDigitValue(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return GetDecimalDigitValueInternalNoBoundsCheck((uint)GetCodePointFromString(s, index)); } private static int GetDecimalDigitValueInternalNoBoundsCheck(uint codePoint) { nuint numericGraphemeTableOffsetNoBoundsChecks = GetNumericGraphemeTableOffsetNoBoundsChecks(codePoint); uint num = Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(DigitValues), numericGraphemeTableOffsetNoBoundsChecks); return (int)((num >> 4) - 1); } public static int GetDigitValue(char ch) { return GetDigitValueInternalNoBoundsCheck(ch); } public static int GetDigitValue(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return GetDigitValueInternalNoBoundsCheck((uint)GetCodePointFromString(s, index)); } private static int GetDigitValueInternalNoBoundsCheck(uint codePoint) { nuint numericGraphemeTableOffsetNoBoundsChecks = GetNumericGraphemeTableOffsetNoBoundsChecks(codePoint); int num = Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(DigitValues), numericGraphemeTableOffsetNoBoundsChecks); return (num & 0xF) - 1; } internal static GraphemeClusterBreakType GetGraphemeClusterBreakType(Rune rune) { nuint numericGraphemeTableOffsetNoBoundsChecks = GetNumericGraphemeTableOffsetNoBoundsChecks((uint)rune.Value); return (GraphemeClusterBreakType)Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(GraphemeSegmentationValues), numericGraphemeTableOffsetNoBoundsChecks); } internal static bool GetIsWhiteSpace(char ch) { nuint categoryCasingTableOffsetNoBoundsChecks = GetCategoryCasingTableOffsetNoBoundsChecks(ch); return (sbyte)Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(CategoriesValues), categoryCasingTableOffsetNoBoundsChecks) < 0; } public static double GetNumericValue(char ch) { return GetNumericValueNoBoundsCheck(ch); } internal static double GetNumericValue(int codePoint) { if (!UnicodeUtility.IsValidCodePoint((uint)codePoint)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.codePoint); } return GetNumericValueNoBoundsCheck((uint)codePoint); } public static double GetNumericValue(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return GetNumericValueInternal(s, index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static double GetNumericValueInternal(string s, int index) { return GetNumericValueNoBoundsCheck((uint)GetCodePointFromString(s, index)); } private static double GetNumericValueNoBoundsCheck(uint codePoint) { nuint numericGraphemeTableOffsetNoBoundsChecks = GetNumericGraphemeTableOffsetNoBoundsChecks(codePoint); ref byte source = ref Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(NumericValues), numericGraphemeTableOffsetNoBoundsChecks * 8); _ = BitConverter.IsLittleEndian; return Unsafe.ReadUnaligned(ref source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static char ToUpper(char codePoint) { nuint categoryCasingTableOffsetNoBoundsChecks = GetCategoryCasingTableOffsetNoBoundsChecks(codePoint); ref short reference = ref Unsafe.Add(ref Unsafe.As(ref MemoryMarshal.GetReference(UppercaseValues)), (nint)categoryCasingTableOffsetNoBoundsChecks); if (!BitConverter.IsLittleEndian) { } int num = reference; return (char)(num + codePoint); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static uint ToUpper(uint codePoint) { if (!UnicodeUtility.IsValidCodePoint(codePoint)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.codePoint); } nuint categoryCasingTableOffsetNoBoundsChecks = GetCategoryCasingTableOffsetNoBoundsChecks(codePoint); ref short reference = ref Unsafe.Add(ref Unsafe.As(ref MemoryMarshal.GetReference(UppercaseValues)), (nint)categoryCasingTableOffsetNoBoundsChecks); if (!BitConverter.IsLittleEndian) { } int num = reference; return (uint)num + codePoint; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static char ToLower(char codePoint) { nuint categoryCasingTableOffsetNoBoundsChecks = GetCategoryCasingTableOffsetNoBoundsChecks(codePoint); ref short reference = ref Unsafe.Add(ref Unsafe.As(ref MemoryMarshal.GetReference(LowercaseValues)), (nint)categoryCasingTableOffsetNoBoundsChecks); if (!BitConverter.IsLittleEndian) { } int num = reference; return (char)(num + codePoint); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static uint ToLower(uint codePoint) { if (!UnicodeUtility.IsValidCodePoint(codePoint)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.codePoint); } nuint categoryCasingTableOffsetNoBoundsChecks = GetCategoryCasingTableOffsetNoBoundsChecks(codePoint); ref short reference = ref Unsafe.Add(ref Unsafe.As(ref MemoryMarshal.GetReference(LowercaseValues)), (nint)categoryCasingTableOffsetNoBoundsChecks); if (!BitConverter.IsLittleEndian) { } int num = reference; return (uint)num + codePoint; } public static UnicodeCategory GetUnicodeCategory(char ch) { return GetUnicodeCategoryNoBoundsChecks(ch); } public static UnicodeCategory GetUnicodeCategory(int codePoint) { if (!UnicodeUtility.IsValidCodePoint((uint)codePoint)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.codePoint); } return GetUnicodeCategoryNoBoundsChecks((uint)codePoint); } public static UnicodeCategory GetUnicodeCategory(string s, int index) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } if ((uint)index >= (uint)s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return GetUnicodeCategoryInternal(s, index); } internal static UnicodeCategory GetUnicodeCategoryInternal(string value, int index) { return GetUnicodeCategoryNoBoundsChecks((uint)GetCodePointFromString(value, index)); } internal static UnicodeCategory GetUnicodeCategoryInternal(string str, int index, out int charLength) { uint codePointFromString = (uint)GetCodePointFromString(str, index); charLength = ((codePointFromString < 65536) ? 1 : 2); return GetUnicodeCategoryNoBoundsChecks(codePointFromString); } private static UnicodeCategory GetUnicodeCategoryNoBoundsChecks(uint codePoint) { nuint categoryCasingTableOffsetNoBoundsChecks = GetCategoryCasingTableOffsetNoBoundsChecks(codePoint); return (UnicodeCategory)(Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(CategoriesValues), categoryCasingTableOffsetNoBoundsChecks) & 0x1F); } private static int GetCodePointFromString(string s, int index) { int num = 0; if ((uint)index < (uint)s.Length) { num = s[index]; int num2 = num - 55296; if ((uint)num2 <= 1023u) { index++; if ((uint)index < (uint)s.Length) { int num3 = s[index] - 56320; if ((uint)num3 <= 1023u) { num = (num2 << 10) + num3 + 65536; } } } } return num; } private static nuint GetCategoryCasingTableOffsetNoBoundsChecks(uint codePoint) { uint num = Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(CategoryCasingLevel1Index), codePoint >> 9); ref byte source = ref Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(CategoryCasingLevel2Index), (num << 6) + ((codePoint >> 3) & 0x3E)); _ = BitConverter.IsLittleEndian; num = Unsafe.ReadUnaligned(ref source); return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(CategoryCasingLevel3Index), (num << 4) + (codePoint & 0xF)); } private static nuint GetNumericGraphemeTableOffsetNoBoundsChecks(uint codePoint) { uint num = Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(NumericGraphemeLevel1Index), codePoint >> 9); ref byte source = ref Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(NumericGraphemeLevel2Index), (num << 6) + ((codePoint >> 3) & 0x3E)); _ = BitConverter.IsLittleEndian; num = Unsafe.ReadUnaligned(ref source); return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(NumericGraphemeLevel3Index), (num << 4) + (codePoint & 0xF)); } } public class ChineseLunisolarCalendar : EastAsianLunisolarCalendar { public const int ChineseEra = 1; private static readonly DateTime s_minDate = new DateTime(1901, 2, 19); private static readonly DateTime s_maxDate = new DateTime(new DateTime(2101, 1, 28, 23, 59, 59, 999).Ticks + 9999); private static readonly int[,] s_yinfo = new int[200, 4] { { 0, 2, 19, 19168 }, { 0, 2, 8, 42352 }, { 5, 1, 29, 21096 }, { 0, 2, 16, 53856 }, { 0, 2, 4, 55632 }, { 4, 1, 25, 27304 }, { 0, 2, 13, 22176 }, { 0, 2, 2, 39632 }, { 2, 1, 22, 19176 }, { 0, 2, 10, 19168 }, { 6, 1, 30, 42200 }, { 0, 2, 18, 42192 }, { 0, 2, 6, 53840 }, { 5, 1, 26, 54568 }, { 0, 2, 14, 46400 }, { 0, 2, 3, 54944 }, { 2, 1, 23, 38608 }, { 0, 2, 11, 38320 }, { 7, 2, 1, 18872 }, { 0, 2, 20, 18800 }, { 0, 2, 8, 42160 }, { 5, 1, 28, 45656 }, { 0, 2, 16, 27216 }, { 0, 2, 5, 27968 }, { 4, 1, 24, 44456 }, { 0, 2, 13, 11104 }, { 0, 2, 2, 38256 }, { 2, 1, 23, 18808 }, { 0, 2, 10, 18800 }, { 6, 1, 30, 25776 }, { 0, 2, 17, 54432 }, { 0, 2, 6, 59984 }, { 5, 1, 26, 27976 }, { 0, 2, 14, 23248 }, { 0, 2, 4, 11104 }, { 3, 1, 24, 37744 }, { 0, 2, 11, 37600 }, { 7, 1, 31, 51560 }, { 0, 2, 19, 51536 }, { 0, 2, 8, 54432 }, { 6, 1, 27, 55888 }, { 0, 2, 15, 46416 }, { 0, 2, 5, 22176 }, { 4, 1, 25, 43736 }, { 0, 2, 13, 9680 }, { 0, 2, 2, 37584 }, { 2, 1, 22, 51544 }, { 0, 2, 10, 43344 }, { 7, 1, 29, 46248 }, { 0, 2, 17, 27808 }, { 0, 2, 6, 46416 }, { 5, 1, 27, 21928 }, { 0, 2, 14, 19872 }, { 0, 2, 3, 42416 }, { 3, 1, 24, 21176 }, { 0, 2, 12, 21168 }, { 8, 1, 31, 43344 }, { 0, 2, 18, 59728 }, { 0, 2, 8, 27296 }, { 6, 1, 28, 44368 }, { 0, 2, 15, 43856 }, { 0, 2, 5, 19296 }, { 4, 1, 25, 42352 }, { 0, 2, 13, 42352 }, { 0, 2, 2, 21088 }, { 3, 1, 21, 59696 }, { 0, 2, 9, 55632 }, { 7, 1, 30, 23208 }, { 0, 2, 17, 22176 }, { 0, 2, 6, 38608 }, { 5, 1, 27, 19176 }, { 0, 2, 15, 19152 }, { 0, 2, 3, 42192 }, { 4, 1, 23, 53864 }, { 0, 2, 11, 53840 }, { 8, 1, 31, 54568 }, { 0, 2, 18, 46400 }, { 0, 2, 7, 46752 }, { 6, 1, 28, 38608 }, { 0, 2, 16, 38320 }, { 0, 2, 5, 18864 }, { 4, 1, 25, 42168 }, { 0, 2, 13, 42160 }, { 10, 2, 2, 45656 }, { 0, 2, 20, 27216 }, { 0, 2, 9, 27968 }, { 6, 1, 29, 44448 }, { 0, 2, 17, 43872 }, { 0, 2, 6, 38256 }, { 5, 1, 27, 18808 }, { 0, 2, 15, 18800 }, { 0, 2, 4, 25776 }, { 3, 1, 23, 27216 }, { 0, 2, 10, 59984 }, { 8, 1, 31, 27432 }, { 0, 2, 19, 23232 }, { 0, 2, 7, 43872 }, { 5, 1, 28, 37736 }, { 0, 2, 16, 37600 }, { 0, 2, 5, 51552 }, { 4, 1, 24, 54440 }, { 0, 2, 12, 54432 }, { 0, 2, 1, 55888 }, { 2, 1, 22, 23208 }, { 0, 2, 9, 22176 }, { 7, 1, 29, 43736 }, { 0, 2, 18, 9680 }, { 0, 2, 7, 37584 }, { 5, 1, 26, 51544 }, { 0, 2, 14, 43344 }, { 0, 2, 3, 46240 }, { 4, 1, 23, 46416 }, { 0, 2, 10, 44368 }, { 9, 1, 31, 21928 }, { 0, 2, 19, 19360 }, { 0, 2, 8, 42416 }, { 6, 1, 28, 21176 }, { 0, 2, 16, 21168 }, { 0, 2, 5, 43312 }, { 4, 1, 25, 29864 }, { 0, 2, 12, 27296 }, { 0, 2, 1, 44368 }, { 2, 1, 22, 19880 }, { 0, 2, 10, 19296 }, { 6, 1, 29, 42352 }, { 0, 2, 17, 42208 }, { 0, 2, 6, 53856 }, { 5, 1, 26, 59696 }, { 0, 2, 13, 54576 }, { 0, 2, 3, 23200 }, { 3, 1, 23, 27472 }, { 0, 2, 11, 38608 }, { 11, 1, 31, 19176 }, { 0, 2, 19, 19152 }, { 0, 2, 8, 42192 }, { 6, 1, 28, 53848 }, { 0, 2, 15, 53840 }, { 0, 2, 4, 54560 }, { 5, 1, 24, 55968 }, { 0, 2, 12, 46496 }, { 0, 2, 1, 22224 }, { 2, 1, 22, 19160 }, { 0, 2, 10, 18864 }, { 7, 1, 30, 42168 }, { 0, 2, 17, 42160 }, { 0, 2, 6, 43600 }, { 5, 1, 26, 46376 }, { 0, 2, 14, 27936 }, { 0, 2, 2, 44448 }, { 3, 1, 23, 21936 }, { 0, 2, 11, 37744 }, { 8, 2, 1, 18808 }, { 0, 2, 19, 18800 }, { 0, 2, 8, 25776 }, { 6, 1, 28, 27216 }, { 0, 2, 15, 59984 }, { 0, 2, 4, 27296 }, { 4, 1, 24, 43872 }, { 0, 2, 12, 43744 }, { 0, 2, 2, 37600 }, { 3, 1, 21, 51568 }, { 0, 2, 9, 51552 }, { 7, 1, 29, 54440 }, { 0, 2, 17, 54432 }, { 0, 2, 5, 55888 }, { 5, 1, 26, 23208 }, { 0, 2, 14, 22176 }, { 0, 2, 3, 42704 }, { 4, 1, 23, 21224 }, { 0, 2, 11, 21200 }, { 8, 1, 31, 43352 }, { 0, 2, 19, 43344 }, { 0, 2, 7, 46240 }, { 6, 1, 27, 46416 }, { 0, 2, 15, 44368 }, { 0, 2, 5, 21920 }, { 4, 1, 24, 42448 }, { 0, 2, 12, 42416 }, { 0, 2, 2, 21168 }, { 3, 1, 22, 43320 }, { 0, 2, 9, 26928 }, { 7, 1, 29, 29336 }, { 0, 2, 17, 27296 }, { 0, 2, 6, 44368 }, { 5, 1, 26, 19880 }, { 0, 2, 14, 19296 }, { 0, 2, 3, 42352 }, { 4, 1, 24, 21104 }, { 0, 2, 10, 53600 }, { 8, 1, 30, 59696 }, { 0, 2, 18, 54560 }, { 0, 2, 7, 55968 }, { 6, 1, 27, 27472 }, { 0, 2, 15, 22224 }, { 0, 2, 5, 19168 }, { 4, 1, 25, 42216 }, { 0, 2, 12, 41680 }, { 0, 2, 1, 53584 }, { 2, 1, 21, 55592 }, { 0, 2, 9, 54560 } }; public override DateTime MinSupportedDateTime => s_minDate; public override DateTime MaxSupportedDateTime => s_maxDate; protected override int DaysInYearBeforeMinSupportedYear => 384; internal override int MinCalendarYear => 1901; internal override int MaxCalendarYear => 2100; internal override DateTime MinDate => s_minDate; internal override DateTime MaxDate => s_maxDate; internal override EraInfo[]? CalEraInfo => null; internal override CalendarId ID => CalendarId.CHINESELUNISOLAR; internal override CalendarId BaseCalendarID => CalendarId.GREGORIAN; public override int[] Eras => new int[1] { 1 }; internal override int GetYearInfo(int lunarYear, int index) { if (lunarYear < 1901 || lunarYear > 2100) { throw new ArgumentOutOfRangeException("year", lunarYear, SR.Format(SR.ArgumentOutOfRange_Range, 1901, 2100)); } return s_yinfo[lunarYear - 1901, index]; } internal override int GetYear(int year, DateTime time) { return year; } internal override int GetGregorianYear(int year, int era) { if (era != 0 && era != 1) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1901 || year > 2100) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 1901, 2100)); } return year; } public override int GetEra(DateTime time) { CheckTicksRange(time.Ticks); return 1; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class CompareInfo : IDeserializationCallback { private static class SortHandleCache { private static readonly Dictionary s_sortNameToSortHandleCache = new Dictionary(); internal static IntPtr GetCachedSortHandle(string sortName) { lock (s_sortNameToSortHandleCache) { if (!s_sortNameToSortHandleCache.TryGetValue(sortName, out var value)) { switch (Interop.Globalization.GetSortHandle(sortName, out value)) { case Interop.Globalization.ResultCode.OutOfMemory: throw new OutOfMemoryException(); default: throw new ExternalException(SR.Arg_ExternalException); case Interop.Globalization.ResultCode.Success: break; } try { s_sortNameToSortHandleCache.Add(sortName, value); } catch { Interop.Globalization.CloseSortHandle(value); throw; } } return value; } } } internal static readonly CompareInfo Invariant = CultureInfo.InvariantCulture.CompareInfo; [OptionalField(VersionAdded = 2)] private string m_name; [NonSerialized] private IntPtr _sortHandle; [NonSerialized] private string _sortName; [OptionalField(VersionAdded = 3)] private SortVersion m_SortVersion; private int culture; [NonSerialized] private bool _isAsciiEqualityOrdinal; public string Name { get { if (m_name == "zh-CHT" || m_name == "zh-CHS") { return m_name; } return _sortName; } } public SortVersion Version { get { if (m_SortVersion == null) { if (GlobalizationMode.Invariant) { m_SortVersion = new SortVersion(0, 127, new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 127)); } else { m_SortVersion = (GlobalizationMode.UseNls ? NlsGetSortVersion() : IcuGetSortVersion()); } } return m_SortVersion; } } public int LCID => CultureInfo.GetCultureInfo(Name).LCID; private static ReadOnlySpan HighCharTable => new bool[128] { true, true, true, true, true, true, true, true, true, false, true, false, false, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, false, false, false, false, false, false, true, false, false, false, false, false, true, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, true }; internal CompareInfo(CultureInfo culture) { m_name = culture._name; InitSort(culture); } public static CompareInfo GetCompareInfo(int culture, Assembly assembly) { if (assembly == null) { throw new ArgumentNullException("assembly"); } if (assembly != typeof(object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib, "assembly"); } return GetCompareInfo(culture); } public static CompareInfo GetCompareInfo(string name, Assembly assembly) { if (name == null) { throw new ArgumentNullException("name"); } if (assembly == null) { throw new ArgumentNullException("assembly"); } if (assembly != typeof(object).Module.Assembly) { throw new ArgumentException(SR.Argument_OnlyMscorlib, "assembly"); } return GetCompareInfo(name); } public static CompareInfo GetCompareInfo(int culture) { if (CultureData.IsCustomCultureId(culture)) { throw new ArgumentException(SR.Argument_CustomCultureCannotBePassedByNumber, "culture"); } return CultureInfo.GetCultureInfo(culture).CompareInfo; } public static CompareInfo GetCompareInfo(string name) { if (name == null) { throw new ArgumentNullException("name"); } return CultureInfo.GetCultureInfo(name).CompareInfo; } public static bool IsSortable(char ch) { return IsSortable(MemoryMarshal.CreateReadOnlySpan(ref ch, 1)); } public static bool IsSortable(string text) { if (text == null) { throw new ArgumentNullException("text"); } return IsSortable(text.AsSpan()); } public static bool IsSortable(ReadOnlySpan text) { if (text.Length == 0) { return false; } if (GlobalizationMode.Invariant) { return true; } if (!GlobalizationMode.UseNls) { return IcuIsSortable(text); } return NlsIsSortable(text); } public static bool IsSortable(Rune value) { Span destination = stackalloc char[2]; return IsSortable(destination[..value.EncodeToUtf16(destination)]); } [MemberNotNull("_sortName")] private void InitSort(CultureInfo culture) { _sortName = culture.SortName; if (GlobalizationMode.UseNls) { NlsInitSortHandle(); } else { IcuInitSortHandle(); } } [OnDeserializing] private void OnDeserializing(StreamingContext ctx) { m_name = null; } void IDeserializationCallback.OnDeserialization(object sender) { OnDeserialized(); } [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { OnDeserialized(); } private void OnDeserialized() { if (m_name == null) { m_name = CultureInfo.GetCultureInfo(culture)._name; } else { InitSort(CultureInfo.GetCultureInfo(m_name)); } } [OnSerializing] private void OnSerializing(StreamingContext ctx) { culture = CultureInfo.GetCultureInfo(Name).LCID; } public int Compare(string? string1, string? string2) { return Compare(string1, string2, CompareOptions.None); } public int Compare(string? string1, string? string2, CompareOptions options) { int result; if (string1 == null) { result = ((string2 != null) ? (-1) : 0); } else { if (string2 != null) { return Compare(string1.AsSpan(), string2.AsSpan(), options); } result = 1; } CheckCompareOptionsForCompare(options); return result; } internal int CompareOptionIgnoreCase(ReadOnlySpan string1, ReadOnlySpan string2) { if (!GlobalizationMode.Invariant) { return CompareStringCore(string1, string2, CompareOptions.IgnoreCase); } return InvariantModeCasing.CompareStringIgnoreCase(ref MemoryMarshal.GetReference(string1), string1.Length, ref MemoryMarshal.GetReference(string2), string2.Length); } public int Compare(string? string1, int offset1, int length1, string? string2, int offset2, int length2) { return Compare(string1, offset1, length1, string2, offset2, length2, CompareOptions.None); } public int Compare(string? string1, int offset1, string? string2, int offset2, CompareOptions options) { return Compare(string1, offset1, (string1 != null) ? (string1.Length - offset1) : 0, string2, offset2, (string2 != null) ? (string2.Length - offset2) : 0, options); } public int Compare(string? string1, int offset1, string? string2, int offset2) { return Compare(string1, offset1, string2, offset2, CompareOptions.None); } public int Compare(string? string1, int offset1, int length1, string? string2, int offset2, int length2, CompareOptions options) { ReadOnlySpan slice = default(ReadOnlySpan); ReadOnlySpan slice2 = default(ReadOnlySpan); if (string1 == null) { if (offset1 == 0 && length1 == 0) { goto IL_0027; } } else if (string1.TryGetSpan(offset1, length1, out slice)) { goto IL_0027; } goto IL_006e; IL_0027: if (string2 == null) { if (offset2 == 0 && length2 == 0) { goto IL_0044; } } else if (string2.TryGetSpan(offset2, length2, out slice2)) { goto IL_0044; } goto IL_006e; IL_006e: if (length1 < 0 || length2 < 0) { throw new ArgumentOutOfRangeException((length1 < 0) ? "length1" : "length2", SR.ArgumentOutOfRange_NeedPosNum); } if (offset1 < 0 || offset2 < 0) { throw new ArgumentOutOfRangeException((offset1 < 0) ? "offset1" : "offset2", SR.ArgumentOutOfRange_NeedPosNum); } if (offset1 > (string1?.Length ?? 0) - length1) { throw new ArgumentOutOfRangeException("string1", SR.ArgumentOutOfRange_OffsetLength); } throw new ArgumentOutOfRangeException("string2", SR.ArgumentOutOfRange_OffsetLength); IL_0044: int result; if (string1 == null) { result = ((string2 != null) ? (-1) : 0); } else { if (string2 != null) { return Compare(slice, slice2, options); } result = 1; } CheckCompareOptionsForCompare(options); return result; } public int Compare(ReadOnlySpan string1, ReadOnlySpan string2, CompareOptions options = CompareOptions.None) { if (string1 == string2) { CheckCompareOptionsForCompare(options); return 0; } if ((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.StringSort)) == 0) { if (!GlobalizationMode.Invariant) { return CompareStringCore(string1, string2, options); } if ((options & CompareOptions.IgnoreCase) == 0) { return string1.SequenceCompareTo(string2); } return Ordinal.CompareStringIgnoreCase(ref MemoryMarshal.GetReference(string1), string1.Length, ref MemoryMarshal.GetReference(string2), string2.Length); } switch (options) { case CompareOptions.Ordinal: return string1.SequenceCompareTo(string2); case CompareOptions.OrdinalIgnoreCase: return Ordinal.CompareStringIgnoreCase(ref MemoryMarshal.GetReference(string1), string1.Length, ref MemoryMarshal.GetReference(string2), string2.Length); default: ThrowCompareOptionsCheckFailed(options); return -1; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [StackTraceHidden] private static void CheckCompareOptionsForCompare(CompareOptions options) { if (((uint)options & 0xDFFFFFE0u) != 0 && options != CompareOptions.Ordinal && options != CompareOptions.OrdinalIgnoreCase) { ThrowCompareOptionsCheckFailed(options); } } [DoesNotReturn] [StackTraceHidden] private static void ThrowCompareOptionsCheckFailed(CompareOptions options) { throw new ArgumentException(((options & CompareOptions.Ordinal) != 0) ? SR.Argument_CompareOptionOrdinal : SR.Argument_InvalidFlag, "options"); } private int CompareStringCore(ReadOnlySpan string1, ReadOnlySpan string2, CompareOptions options) { if (!GlobalizationMode.UseNls) { return IcuCompareString(string1, string2, options); } return NlsCompareString(string1, string2, options); } public bool IsPrefix(string source, string prefix, CompareOptions options) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } if (prefix == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.prefix); } return IsPrefix(source.AsSpan(), prefix.AsSpan(), options); } public unsafe bool IsPrefix(ReadOnlySpan source, ReadOnlySpan prefix, CompareOptions options = CompareOptions.None) { if (prefix.IsEmpty) { return true; } if ((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth)) == 0) { if (!GlobalizationMode.Invariant) { return StartsWithCore(source, prefix, options, null); } if ((options & CompareOptions.IgnoreCase) == 0) { return source.StartsWith(prefix); } return source.StartsWithOrdinalIgnoreCase(prefix); } switch (options) { case CompareOptions.Ordinal: return source.StartsWith(prefix); case CompareOptions.OrdinalIgnoreCase: return source.StartsWithOrdinalIgnoreCase(prefix); default: ThrowCompareOptionsCheckFailed(options); return false; } } public unsafe bool IsPrefix(ReadOnlySpan source, ReadOnlySpan prefix, CompareOptions options, out int matchLength) { bool flag; if (GlobalizationMode.Invariant || prefix.IsEmpty || ((uint)options & 0xFFFFFFE0u) != 0) { flag = IsPrefix(source, prefix, options); matchLength = (flag ? prefix.Length : 0); } else { int num = 0; flag = StartsWithCore(source, prefix, options, &num); matchLength = num; } return flag; } private unsafe bool StartsWithCore(ReadOnlySpan source, ReadOnlySpan prefix, CompareOptions options, int* matchLengthPtr) { if (!GlobalizationMode.UseNls) { return IcuStartsWith(source, prefix, options, matchLengthPtr); } return NlsStartsWith(source, prefix, options, matchLengthPtr); } public bool IsPrefix(string source, string prefix) { return IsPrefix(source, prefix, CompareOptions.None); } public bool IsSuffix(string source, string suffix, CompareOptions options) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } if (suffix == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.suffix); } return IsSuffix(source.AsSpan(), suffix.AsSpan(), options); } public unsafe bool IsSuffix(ReadOnlySpan source, ReadOnlySpan suffix, CompareOptions options = CompareOptions.None) { if (suffix.IsEmpty) { return true; } if ((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth)) == 0) { if (!GlobalizationMode.Invariant) { return EndsWithCore(source, suffix, options, null); } if ((options & CompareOptions.IgnoreCase) == 0) { return source.EndsWith(suffix); } return source.EndsWithOrdinalIgnoreCase(suffix); } switch (options) { case CompareOptions.Ordinal: return source.EndsWith(suffix); case CompareOptions.OrdinalIgnoreCase: return source.EndsWithOrdinalIgnoreCase(suffix); default: ThrowCompareOptionsCheckFailed(options); return false; } } public unsafe bool IsSuffix(ReadOnlySpan source, ReadOnlySpan suffix, CompareOptions options, out int matchLength) { bool flag; if (GlobalizationMode.Invariant || suffix.IsEmpty || ((uint)options & 0xFFFFFFE0u) != 0) { flag = IsSuffix(source, suffix, options); matchLength = (flag ? suffix.Length : 0); } else { int num = 0; flag = EndsWithCore(source, suffix, options, &num); matchLength = num; } return flag; } public bool IsSuffix(string source, string suffix) { return IsSuffix(source, suffix, CompareOptions.None); } private unsafe bool EndsWithCore(ReadOnlySpan source, ReadOnlySpan suffix, CompareOptions options, int* matchLengthPtr) { if (!GlobalizationMode.UseNls) { return IcuEndsWith(source, suffix, options, matchLengthPtr); } return NlsEndsWith(source, suffix, options, matchLengthPtr); } public int IndexOf(string source, char value) { return IndexOf(source, value, CompareOptions.None); } public int IndexOf(string source, string value) { return IndexOf(source, value, CompareOptions.None); } public int IndexOf(string source, char value, CompareOptions options) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } return IndexOf(source, MemoryMarshal.CreateReadOnlySpan(ref value, 1), options); } public int IndexOf(string source, string value, CompareOptions options) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } return IndexOf(source.AsSpan(), value.AsSpan(), options); } public int IndexOf(string source, char value, int startIndex) { return IndexOf(source, value, startIndex, CompareOptions.None); } public int IndexOf(string source, string value, int startIndex) { return IndexOf(source, value, startIndex, CompareOptions.None); } public int IndexOf(string source, char value, int startIndex, CompareOptions options) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } return IndexOf(source, value, startIndex, source.Length - startIndex, options); } public int IndexOf(string source, string value, int startIndex, CompareOptions options) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } return IndexOf(source, value, startIndex, source.Length - startIndex, options); } public int IndexOf(string source, char value, int startIndex, int count) { return IndexOf(source, value, startIndex, count, CompareOptions.None); } public int IndexOf(string source, string value, int startIndex, int count) { return IndexOf(source, value, startIndex, count, CompareOptions.None); } public int IndexOf(string source, char value, int startIndex, int count, CompareOptions options) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } if (!source.TryGetSpan(startIndex, count, out var slice)) { if ((uint)startIndex > (uint)source.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } else { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } } int num = IndexOf(slice, MemoryMarshal.CreateReadOnlySpan(ref value, 1), options); if (num >= 0) { num += startIndex; } return num; } public int IndexOf(string source, string value, int startIndex, int count, CompareOptions options) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if (!source.TryGetSpan(startIndex, count, out var slice)) { if ((uint)startIndex > (uint)source.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } else { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } } int num = IndexOf(slice, value, options); if (num >= 0) { num += startIndex; } return num; } public unsafe int IndexOf(ReadOnlySpan source, ReadOnlySpan value, CompareOptions options = CompareOptions.None) { if ((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth)) == 0) { if (!GlobalizationMode.Invariant) { if (value.IsEmpty) { return 0; } return IndexOfCore(source, value, options, null, fromBeginning: true); } if ((options & CompareOptions.IgnoreCase) == 0) { return source.IndexOf(value); } return Ordinal.IndexOfOrdinalIgnoreCase(source, value); } switch (options) { case CompareOptions.Ordinal: return source.IndexOf(value); case CompareOptions.OrdinalIgnoreCase: return Ordinal.IndexOfOrdinalIgnoreCase(source, value); default: ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidFlag, ExceptionArgument.options); return -1; } } public unsafe int IndexOf(ReadOnlySpan source, ReadOnlySpan value, CompareOptions options, out int matchLength) { System.Runtime.CompilerServices.Unsafe.SkipInit(out int num); int result = IndexOf(source, value, &num, options, fromBeginning: true); matchLength = num; return result; } public int IndexOf(ReadOnlySpan source, Rune value, CompareOptions options = CompareOptions.None) { Span destination = stackalloc char[2]; return IndexOf(source, destination[..value.EncodeToUtf16(destination)], options); } private unsafe int IndexOf(ReadOnlySpan source, ReadOnlySpan value, int* matchLengthPtr, CompareOptions options, bool fromBeginning) { *matchLengthPtr = 0; int num = 0; if ((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth)) == 0) { if (!GlobalizationMode.Invariant) { if (value.IsEmpty) { if (!fromBeginning) { return source.Length; } return 0; } return IndexOfCore(source, value, options, matchLengthPtr, fromBeginning); } num = (((options & CompareOptions.IgnoreCase) != 0) ? (fromBeginning ? Ordinal.IndexOfOrdinalIgnoreCase(source, value) : Ordinal.LastIndexOfOrdinalIgnoreCase(source, value)) : (fromBeginning ? source.IndexOf(value) : source.LastIndexOf(value))); } else { switch (options) { case CompareOptions.Ordinal: num = (fromBeginning ? source.IndexOf(value) : source.LastIndexOf(value)); break; case CompareOptions.OrdinalIgnoreCase: num = (fromBeginning ? Ordinal.IndexOfOrdinalIgnoreCase(source, value) : Ordinal.LastIndexOfOrdinalIgnoreCase(source, value)); break; default: ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidFlag, ExceptionArgument.options); break; } } if (num >= 0) { *matchLengthPtr = value.Length; } return num; } private unsafe int IndexOfCore(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { if (!GlobalizationMode.UseNls) { return IcuIndexOfCore(source, target, options, matchLengthPtr, fromBeginning); } return NlsIndexOfCore(source, target, options, matchLengthPtr, fromBeginning); } public int LastIndexOf(string source, char value) { return LastIndexOf(source, value, CompareOptions.None); } public int LastIndexOf(string source, string value) { return LastIndexOf(source, value, CompareOptions.None); } public int LastIndexOf(string source, char value, CompareOptions options) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } return LastIndexOf(source, MemoryMarshal.CreateReadOnlySpan(ref value, 1), options); } public int LastIndexOf(string source, string value, CompareOptions options) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } return LastIndexOf(source.AsSpan(), value.AsSpan(), options); } public int LastIndexOf(string source, char value, int startIndex) { return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None); } public int LastIndexOf(string source, string value, int startIndex) { return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None); } public int LastIndexOf(string source, char value, int startIndex, CompareOptions options) { return LastIndexOf(source, value, startIndex, startIndex + 1, options); } public int LastIndexOf(string source, string value, int startIndex, CompareOptions options) { return LastIndexOf(source, value, startIndex, startIndex + 1, options); } public int LastIndexOf(string source, char value, int startIndex, int count) { return LastIndexOf(source, value, startIndex, count, CompareOptions.None); } public int LastIndexOf(string source, string value, int startIndex, int count) { return LastIndexOf(source, value, startIndex, count, CompareOptions.None); } public int LastIndexOf(string source, char value, int startIndex, int count, CompareOptions options) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } while ((uint)startIndex >= (uint)source.Length) { if (startIndex == -1 && source.Length == 0) { count = 0; break; } if (startIndex == source.Length) { startIndex--; if (count > 0) { count--; } continue; } ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); break; } startIndex = startIndex - count + 1; if (!source.TryGetSpan(startIndex, count, out var slice)) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } int num = LastIndexOf(slice, MemoryMarshal.CreateReadOnlySpan(ref value, 1), options); if (num >= 0) { num += startIndex; } return num; } public int LastIndexOf(string source, string value, int startIndex, int count, CompareOptions options) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } while ((uint)startIndex >= (uint)source.Length) { if (startIndex == -1 && source.Length == 0) { count = 0; break; } if (startIndex == source.Length) { startIndex--; if (count > 0) { count--; } continue; } ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); break; } startIndex = startIndex - count + 1; if (!source.TryGetSpan(startIndex, count, out var slice)) { ThrowHelper.ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count(); } int num = LastIndexOf(slice, value, options); if (num >= 0) { num += startIndex; } return num; } public unsafe int LastIndexOf(ReadOnlySpan source, ReadOnlySpan value, CompareOptions options = CompareOptions.None) { if ((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth)) == 0) { if (!GlobalizationMode.Invariant) { if (value.IsEmpty) { return source.Length; } return IndexOfCore(source, value, options, null, fromBeginning: false); } if ((options & CompareOptions.IgnoreCase) == 0) { return source.LastIndexOf(value); } return Ordinal.LastIndexOfOrdinalIgnoreCase(source, value); } return options switch { CompareOptions.Ordinal => source.LastIndexOf(value), CompareOptions.OrdinalIgnoreCase => Ordinal.LastIndexOfOrdinalIgnoreCase(source, value), _ => throw new ArgumentException(SR.Argument_InvalidFlag, "options"), }; } public unsafe int LastIndexOf(ReadOnlySpan source, ReadOnlySpan value, CompareOptions options, out int matchLength) { System.Runtime.CompilerServices.Unsafe.SkipInit(out int num); int result = IndexOf(source, value, &num, options, fromBeginning: false); matchLength = num; return result; } public int LastIndexOf(ReadOnlySpan source, Rune value, CompareOptions options = CompareOptions.None) { Span destination = stackalloc char[2]; return LastIndexOf(source, destination[..value.EncodeToUtf16(destination)], options); } public SortKey GetSortKey(string source, CompareOptions options) { if (GlobalizationMode.Invariant) { return InvariantCreateSortKey(source, options); } return CreateSortKeyCore(source, options); } public SortKey GetSortKey(string source) { if (GlobalizationMode.Invariant) { return InvariantCreateSortKey(source, CompareOptions.None); } return CreateSortKeyCore(source, CompareOptions.None); } private SortKey CreateSortKeyCore(string source, CompareOptions options) { if (!GlobalizationMode.UseNls) { return IcuCreateSortKey(source, options); } return NlsCreateSortKey(source, options); } public int GetSortKey(ReadOnlySpan source, Span destination, CompareOptions options = CompareOptions.None) { if (((uint)options & 0xDFFFFFE0u) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidFlag, ExceptionArgument.options); } if (GlobalizationMode.Invariant) { return InvariantGetSortKey(source, destination, options); } return GetSortKeyCore(source, destination, options); } private int GetSortKeyCore(ReadOnlySpan source, Span destination, CompareOptions options) { if (!GlobalizationMode.UseNls) { return IcuGetSortKey(source, destination, options); } return NlsGetSortKey(source, destination, options); } public int GetSortKeyLength(ReadOnlySpan source, CompareOptions options = CompareOptions.None) { if (((uint)options & 0xDFFFFFE0u) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidFlag, ExceptionArgument.options); } if (GlobalizationMode.Invariant) { return InvariantGetSortKeyLength(source, options); } return GetSortKeyLengthCore(source, options); } private int GetSortKeyLengthCore(ReadOnlySpan source, CompareOptions options) { if (!GlobalizationMode.UseNls) { return IcuGetSortKeyLength(source, options); } return NlsGetSortKeyLength(source, options); } public override bool Equals([NotNullWhen(true)] object? value) { if (value is CompareInfo compareInfo) { return Name == compareInfo.Name; } return false; } public override int GetHashCode() { return Name.GetHashCode(); } public int GetHashCode(string source, CompareOptions options) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } return GetHashCode(source.AsSpan(), options); } public int GetHashCode(ReadOnlySpan source, CompareOptions options) { if ((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.StringSort)) == 0) { if (!GlobalizationMode.Invariant) { return GetHashCodeOfStringCore(source, options); } if ((options & CompareOptions.IgnoreCase) == 0) { return string.GetHashCode(source); } return string.GetHashCodeOrdinalIgnoreCase(source); } switch (options) { case CompareOptions.Ordinal: return string.GetHashCode(source); case CompareOptions.OrdinalIgnoreCase: return string.GetHashCodeOrdinalIgnoreCase(source); default: ThrowCompareOptionsCheckFailed(options); return -1; } } private int GetHashCodeOfStringCore(ReadOnlySpan source, CompareOptions options) { if (!GlobalizationMode.UseNls) { return IcuGetHashCodeOfString(source, options); } return NlsGetHashCodeOfString(source, options); } public override string ToString() { return "CompareInfo - " + Name; } private void IcuInitSortHandle() { if (GlobalizationMode.Invariant) { _isAsciiEqualityOrdinal = true; return; } _isAsciiEqualityOrdinal = _sortName.Length == 0 || (_sortName.Length >= 2 && _sortName[0] == 'e' && _sortName[1] == 'n' && (_sortName.Length == 2 || _sortName[2] == '-')); _sortHandle = SortHandleCache.GetCachedSortHandle(_sortName); } private unsafe int IcuCompareString(ReadOnlySpan string1, ReadOnlySpan string2, CompareOptions options) { fixed (char* lpStr = &MemoryMarshal.GetReference(string1)) { fixed (char* lpStr2 = &MemoryMarshal.GetReference(string2)) { return Interop.Globalization.CompareString(_sortHandle, lpStr, string1.Length, lpStr2, string2.Length, options); } } } private unsafe int IcuIndexOfCore(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options)) { if ((options & CompareOptions.IgnoreCase) != 0) { return IndexOfOrdinalIgnoreCaseHelper(source, target, options, matchLengthPtr, fromBeginning); } return IndexOfOrdinalHelper(source, target, options, matchLengthPtr, fromBeginning); } fixed (char* pSource = &MemoryMarshal.GetReference(source)) { fixed (char* target2 = &MemoryMarshal.GetReference(target)) { if (fromBeginning) { return Interop.Globalization.IndexOf(_sortHandle, target2, target.Length, pSource, source.Length, options, matchLengthPtr); } return Interop.Globalization.LastIndexOf(_sortHandle, target2, target.Length, pSource, source.Length, options, matchLengthPtr); } } } private unsafe int IndexOfOrdinalIgnoreCaseHelper(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { fixed (char* ptr = &MemoryMarshal.GetReference(source)) { fixed (char* ptr3 = &MemoryMarshal.GetReference(target)) { char* ptr2 = ptr; char* ptr4 = ptr3; int num = 0; while (true) { if (num < target.Length) { char c = ptr4[num]; if (c >= '\u0080' || HighCharTable[c]) { break; } num++; continue; } if (target.Length > source.Length) { int num2 = 0; while (true) { if (num2 < source.Length) { char c2 = ptr2[num2]; if (c2 >= '\u0080' || HighCharTable[c2]) { break; } num2++; continue; } return -1; } break; } int num3; int num4; int num5; if (fromBeginning) { num3 = 0; num4 = source.Length - target.Length + 1; num5 = 1; } else { num3 = source.Length - target.Length; num4 = -1; num5 = -1; } int num6 = num3; while (true) { int num8; if (num6 != num4) { int num7 = 0; num8 = num6; while (true) { if (num7 < target.Length) { char c3 = ptr2[num8]; char c4 = ptr4[num7]; if (c3 >= '\u0080' || HighCharTable[c3]) { break; } if (c3 == c4) { goto IL_0184; } if ((uint)(c3 - 97) <= 25u) { c3 = (char)(c3 - 32); } if ((uint)(c4 - 97) <= 25u) { c4 = (char)(c4 - 32); } if (c3 == c4) { goto IL_0184; } goto IL_0163; } if (num8 < source.Length && ptr2[num8] >= '\u0080') { break; } if (matchLengthPtr != null) { *matchLengthPtr = target.Length; } return num6; IL_0184: num7++; num8++; } break; } return -1; IL_0163: if (num8 < source.Length - 1 && (ptr2 + num8)[1] >= '\u0080') { break; } num6 += num5; } break; } if (fromBeginning) { return Interop.Globalization.IndexOf(_sortHandle, ptr4, target.Length, ptr2, source.Length, options, matchLengthPtr); } return Interop.Globalization.LastIndexOf(_sortHandle, ptr4, target.Length, ptr2, source.Length, options, matchLengthPtr); } } } private unsafe int IndexOfOrdinalHelper(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { fixed (char* ptr = &MemoryMarshal.GetReference(source)) { fixed (char* ptr3 = &MemoryMarshal.GetReference(target)) { char* ptr2 = ptr; char* ptr4 = ptr3; int num = 0; while (true) { if (num < target.Length) { char c = ptr4[num]; if (c >= '\u0080' || HighCharTable[c]) { break; } num++; continue; } if (target.Length > source.Length) { int num2 = 0; while (true) { if (num2 < source.Length) { char c2 = ptr2[num2]; if (c2 >= '\u0080' || HighCharTable[c2]) { break; } num2++; continue; } return -1; } break; } int num3; int num4; int num5; if (fromBeginning) { num3 = 0; num4 = source.Length - target.Length + 1; num5 = 1; } else { num3 = source.Length - target.Length; num4 = -1; num5 = -1; } int num6 = num3; while (true) { int num8; if (num6 != num4) { int num7 = 0; num8 = num6; while (true) { if (num7 < target.Length) { char c3 = ptr2[num8]; char c4 = ptr4[num7]; if (c3 >= '\u0080' || HighCharTable[c3]) { break; } if (c3 == c4) { num7++; num8++; continue; } goto IL_0135; } if (num8 < source.Length && ptr2[num8] >= '\u0080') { break; } if (matchLengthPtr != null) { *matchLengthPtr = target.Length; } return num6; } break; } return -1; IL_0135: if (num8 < source.Length - 1 && (ptr2 + num8)[1] >= '\u0080') { break; } num6 += num5; } break; } if (fromBeginning) { return Interop.Globalization.IndexOf(_sortHandle, ptr4, target.Length, ptr2, source.Length, options, matchLengthPtr); } return Interop.Globalization.LastIndexOf(_sortHandle, ptr4, target.Length, ptr2, source.Length, options, matchLengthPtr); } } } private unsafe bool IcuStartsWith(ReadOnlySpan source, ReadOnlySpan prefix, CompareOptions options, int* matchLengthPtr) { if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options)) { if ((options & CompareOptions.IgnoreCase) != 0) { return StartsWithOrdinalIgnoreCaseHelper(source, prefix, options, matchLengthPtr); } return StartsWithOrdinalHelper(source, prefix, options, matchLengthPtr); } fixed (char* source2 = &MemoryMarshal.GetReference(source)) { fixed (char* target = &MemoryMarshal.GetReference(prefix)) { return Interop.Globalization.StartsWith(_sortHandle, target, prefix.Length, source2, source.Length, options, matchLengthPtr); } } } private unsafe bool StartsWithOrdinalIgnoreCaseHelper(ReadOnlySpan source, ReadOnlySpan prefix, CompareOptions options, int* matchLengthPtr) { int num = Math.Min(source.Length, prefix.Length); fixed (char* ptr = &MemoryMarshal.GetReference(source)) { fixed (char* ptr3 = &MemoryMarshal.GetReference(prefix)) { char* ptr2 = ptr; char* ptr4 = ptr3; while (true) { if (num != 0) { int num2 = *ptr2; int num3 = *ptr4; if (num2 >= 128 || num3 >= 128 || HighCharTable[num2] || HighCharTable[num3]) { break; } if (num2 == num3) { ptr2++; ptr4++; num--; continue; } if ((uint)(num2 - 97) <= 25u) { num2 -= 32; } if ((uint)(num3 - 97) <= 25u) { num3 -= 32; } if (num2 == num3) { ptr2++; ptr4++; num--; continue; } if ((ptr2 < ptr + source.Length - 1 && ptr2[1] >= '\u0080') || (ptr4 < ptr3 + prefix.Length - 1 && ptr4[1] >= '\u0080')) { break; } return false; } if (source.Length < prefix.Length) { if (*ptr4 >= '\u0080') { break; } return false; } if (source.Length > prefix.Length && *ptr2 >= '\u0080') { break; } if (matchLengthPtr != null) { *matchLengthPtr = prefix.Length; } return true; } return Interop.Globalization.StartsWith(_sortHandle, ptr3, prefix.Length, ptr, source.Length, options, matchLengthPtr); } } } private unsafe bool StartsWithOrdinalHelper(ReadOnlySpan source, ReadOnlySpan prefix, CompareOptions options, int* matchLengthPtr) { int num = Math.Min(source.Length, prefix.Length); fixed (char* ptr = &MemoryMarshal.GetReference(source)) { fixed (char* ptr3 = &MemoryMarshal.GetReference(prefix)) { char* ptr2 = ptr; char* ptr4 = ptr3; while (true) { if (num != 0) { int num2 = *ptr2; int num3 = *ptr4; if (num2 >= 128 || num3 >= 128 || HighCharTable[num2] || HighCharTable[num3]) { break; } if (num2 == num3) { ptr2++; ptr4++; num--; continue; } if ((ptr2 < ptr + source.Length - 1 && ptr2[1] >= '\u0080') || (ptr4 < ptr3 + prefix.Length - 1 && ptr4[1] >= '\u0080')) { break; } return false; } if (source.Length < prefix.Length) { if (*ptr4 >= '\u0080') { break; } return false; } if (source.Length > prefix.Length && *ptr2 >= '\u0080') { break; } if (matchLengthPtr != null) { *matchLengthPtr = prefix.Length; } return true; } return Interop.Globalization.StartsWith(_sortHandle, ptr3, prefix.Length, ptr, source.Length, options, matchLengthPtr); } } } private unsafe bool IcuEndsWith(ReadOnlySpan source, ReadOnlySpan suffix, CompareOptions options, int* matchLengthPtr) { if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options)) { if ((options & CompareOptions.IgnoreCase) != 0) { return EndsWithOrdinalIgnoreCaseHelper(source, suffix, options, matchLengthPtr); } return EndsWithOrdinalHelper(source, suffix, options, matchLengthPtr); } fixed (char* source2 = &MemoryMarshal.GetReference(source)) { fixed (char* target = &MemoryMarshal.GetReference(suffix)) { return Interop.Globalization.EndsWith(_sortHandle, target, suffix.Length, source2, source.Length, options, matchLengthPtr); } } } private unsafe bool EndsWithOrdinalIgnoreCaseHelper(ReadOnlySpan source, ReadOnlySpan suffix, CompareOptions options, int* matchLengthPtr) { int num = Math.Min(source.Length, suffix.Length); fixed (char* ptr = &MemoryMarshal.GetReference(source)) { fixed (char* ptr3 = &MemoryMarshal.GetReference(suffix)) { char* ptr2 = ptr + source.Length - 1; char* ptr4 = ptr3 + suffix.Length - 1; while (true) { if (num != 0) { int num2 = *ptr2; int num3 = *ptr4; if (num2 >= 128 || num3 >= 128 || HighCharTable[num2] || HighCharTable[num3]) { break; } if (num2 == num3) { ptr2--; ptr4--; num--; continue; } if ((uint)(num2 - 97) <= 25u) { num2 -= 32; } if ((uint)(num3 - 97) <= 25u) { num3 -= 32; } if (num2 == num3) { ptr2--; ptr4--; num--; continue; } if ((ptr2 > ptr && *(ptr2 - 1) >= '\u0080') || (ptr4 > ptr3 && *(ptr4 - 1) >= '\u0080')) { break; } return false; } if (source.Length < suffix.Length) { if (*ptr4 >= '\u0080') { break; } return false; } if (source.Length > suffix.Length && *ptr2 >= '\u0080') { break; } if (matchLengthPtr != null) { *matchLengthPtr = suffix.Length; } return true; } return Interop.Globalization.EndsWith(_sortHandle, ptr3, suffix.Length, ptr, source.Length, options, matchLengthPtr); } } } private unsafe bool EndsWithOrdinalHelper(ReadOnlySpan source, ReadOnlySpan suffix, CompareOptions options, int* matchLengthPtr) { int num = Math.Min(source.Length, suffix.Length); fixed (char* ptr = &MemoryMarshal.GetReference(source)) { fixed (char* ptr3 = &MemoryMarshal.GetReference(suffix)) { char* ptr2 = ptr + source.Length - 1; char* ptr4 = ptr3 + suffix.Length - 1; while (true) { if (num != 0) { int num2 = *ptr2; int num3 = *ptr4; if (num2 >= 128 || num3 >= 128 || HighCharTable[num2] || HighCharTable[num3]) { break; } if (num2 == num3) { ptr2--; ptr4--; num--; continue; } if ((ptr2 > ptr && *(ptr2 - 1) >= '\u0080') || (ptr4 > ptr3 && *(ptr4 - 1) >= '\u0080')) { break; } return false; } if (source.Length < suffix.Length) { if (*ptr4 >= '\u0080') { break; } return false; } if (source.Length > suffix.Length && *ptr2 >= '\u0080') { break; } if (matchLengthPtr != null) { *matchLengthPtr = suffix.Length; } return true; } return Interop.Globalization.EndsWith(_sortHandle, ptr3, suffix.Length, ptr, source.Length, options, matchLengthPtr); } } } private unsafe SortKey IcuCreateSortKey(string source, CompareOptions options) { if (source == null) { throw new ArgumentNullException("source"); } if (((uint)options & 0xDFFFFFE0u) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, "options"); } byte[] array; fixed (char* str = source) { int sortKey = Interop.Globalization.GetSortKey(_sortHandle, str, source.Length, null, 0, options); array = new byte[sortKey]; fixed (byte[] array2 = array) { if (Interop.Globalization.GetSortKey(sortKey: (byte*)((array != null && array2.Length != 0) ? System.Runtime.CompilerServices.Unsafe.AsPointer(ref array2[0]) : null), sortHandle: _sortHandle, str: str, strLength: source.Length, sortKeyLength: sortKey, options: options) != sortKey) { throw new ArgumentException(SR.Arg_ExternalException); } } array2 = null; } return new SortKey(this, source, options, array); } private unsafe int IcuGetSortKey(ReadOnlySpan source, Span destination, CompareOptions options) { int sortKey2; fixed (char* str = &MemoryMarshal.GetReference(source)) { fixed (byte* sortKey = &MemoryMarshal.GetReference(destination)) { sortKey2 = Interop.Globalization.GetSortKey(_sortHandle, str, source.Length, sortKey, destination.Length, options); } } if ((uint)sortKey2 > (uint)destination.Length) { if (sortKey2 <= destination.Length) { throw new ArgumentException(SR.Arg_ExternalException); } ThrowHelper.ThrowArgumentException_DestinationTooShort(); } return sortKey2; } private unsafe int IcuGetSortKeyLength(ReadOnlySpan source, CompareOptions options) { fixed (char* str = &MemoryMarshal.GetReference(source)) { return Interop.Globalization.GetSortKey(_sortHandle, str, source.Length, null, 0, options); } } private static bool IcuIsSortable(ReadOnlySpan text) { do { if (Rune.DecodeFromUtf16(text, out var result, out var charsConsumed) != 0) { return false; } UnicodeCategory unicodeCategory = Rune.GetUnicodeCategory(result); if (unicodeCategory == UnicodeCategory.PrivateUse || unicodeCategory == UnicodeCategory.OtherNotAssigned) { return false; } text = text.Slice(charsConsumed); } while (!text.IsEmpty); return true; } private unsafe int IcuGetHashCodeOfString(ReadOnlySpan source, CompareOptions options) { int num = ((source.Length <= 262144) ? (4 * source.Length) : 0); byte[] array = null; Span span = ((num > 1024) ? ((Span)(array = ArrayPool.Shared.Rent(num))) : stackalloc byte[1024]); Span span2 = span; fixed (char* str = &MemoryMarshal.GetNonNullPinnableReference(source)) { fixed (byte* sortKey = &MemoryMarshal.GetReference(span2)) { num = Interop.Globalization.GetSortKey(_sortHandle, str, source.Length, sortKey, span2.Length, options); } if (num > span2.Length) { if (array != null) { ArrayPool.Shared.Return(array); } span2 = (array = ArrayPool.Shared.Rent(num)); fixed (byte* sortKey2 = &MemoryMarshal.GetReference(span2)) { num = Interop.Globalization.GetSortKey(_sortHandle, str, source.Length, sortKey2, span2.Length, options); } } } if (num == 0 || num > span2.Length) { throw new ArgumentException(SR.Arg_ExternalException); } int result = Marvin.ComputeHash32(span2.Slice(0, num), Marvin.DefaultSeed); if (array != null) { ArrayPool.Shared.Return(array); } return result; } private static bool CanUseAsciiOrdinalForOptions(CompareOptions options) { return (options & CompareOptions.IgnoreSymbols) == 0; } private SortVersion IcuGetSortVersion() { int sortVersion = Interop.Globalization.GetSortVersion(_sortHandle); return new SortVersion(sortVersion, LCID, new Guid(sortVersion, 0, 0, 0, 0, 0, 0, (byte)(LCID >> 24), (byte)((LCID & 0xFF0000) >> 16), (byte)((LCID & 0xFF00) >> 8), (byte)((uint)LCID & 0xFFu))); } private SortKey InvariantCreateSortKey(string source, CompareOptions options) { if (source == null) { throw new ArgumentNullException("source"); } if (((uint)options & 0xDFFFFFE0u) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, "options"); } byte[] array; if (source.Length == 0) { array = Array.Empty(); } else { array = new byte[source.Length * 2]; if ((options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0) { InvariantCreateSortKeyOrdinalIgnoreCase(source, array); } else { InvariantCreateSortKeyOrdinal(source, array); } } return new SortKey(this, source, options, array); } private static void InvariantCreateSortKeyOrdinal(ReadOnlySpan source, Span sortKey) { for (int i = 0; i < source.Length; i++) { BinaryPrimitives.WriteUInt16BigEndian(sortKey, source[i]); sortKey = sortKey.Slice(2); } } private static void InvariantCreateSortKeyOrdinalIgnoreCase(ReadOnlySpan source, Span sortKey) { for (int i = 0; i < source.Length; i++) { char c = source[i]; if (char.IsHighSurrogate(c) && i < source.Length - 1) { char c2 = source[i + 1]; if (char.IsLowSurrogate(c2)) { SurrogateCasing.ToUpper(c, c2, out var hr, out var lr); BinaryPrimitives.WriteUInt16BigEndian(sortKey, hr); BinaryPrimitives.WriteUInt16BigEndian(sortKey, lr); i++; sortKey = sortKey.Slice(4); continue; } } BinaryPrimitives.WriteUInt16BigEndian(sortKey, InvariantModeCasing.ToUpper(c)); sortKey = sortKey.Slice(2); } } private static int InvariantGetSortKey(ReadOnlySpan source, Span destination, CompareOptions options) { if ((uint)destination.Length < (uint)(source.Length * 2)) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } if ((options & CompareOptions.IgnoreCase) == 0) { InvariantCreateSortKeyOrdinal(source, destination); } else { InvariantCreateSortKeyOrdinalIgnoreCase(source, destination); } return source.Length * 2; } private static int InvariantGetSortKeyLength(ReadOnlySpan source, CompareOptions options) { int num = source.Length * 2; if (num < 0) { throw new ArgumentException(SR.ArgumentOutOfRange_GetByteCountOverflow, "source"); } return num; } private void NlsInitSortHandle() { _sortHandle = NlsGetSortHandle(_sortName); } internal unsafe static IntPtr NlsGetSortHandle(string cultureName) { if (GlobalizationMode.Invariant) { return IntPtr.Zero; } System.Runtime.CompilerServices.Unsafe.SkipInit(out IntPtr intPtr); int num = Interop.Kernel32.LCMapStringEx(cultureName, 536870912u, null, 0, &intPtr, IntPtr.Size, null, null, IntPtr.Zero); if (num > 0) { int num2 = 0; char c = 'a'; num = Interop.Kernel32.LCMapStringEx(null, 262144u, &c, 1, &num2, 4, null, null, intPtr); if (num > 1) { return intPtr; } } return IntPtr.Zero; } private unsafe static int FindStringOrdinal(uint dwFindStringOrdinalFlags, ReadOnlySpan source, ReadOnlySpan value, bool bIgnoreCase) { fixed (char* lpStringSource = &MemoryMarshal.GetReference(source)) { fixed (char* lpStringValue = &MemoryMarshal.GetReference(value)) { return Interop.Kernel32.FindStringOrdinal(dwFindStringOrdinalFlags, lpStringSource, source.Length, lpStringValue, value.Length, bIgnoreCase ? Interop.BOOL.TRUE : Interop.BOOL.FALSE); } } } internal static int NlsIndexOfOrdinalCore(ReadOnlySpan source, ReadOnlySpan value, bool ignoreCase, bool fromBeginning) { uint dwFindStringOrdinalFlags = (fromBeginning ? 4194304u : 8388608u); return FindStringOrdinal(dwFindStringOrdinalFlags, source, value, ignoreCase); } private unsafe int NlsGetHashCodeOfString(ReadOnlySpan source, CompareOptions options) { if (!Environment.IsWindows8OrAbove) { source = source.ToString(); } int num = source.Length; if (num == 0) { source = string.Empty; num = -1; } uint dwMapFlags = 0x400u | (uint)GetNativeCompareFlags(options); fixed (char* lpSrcStr = &MemoryMarshal.GetReference(source)) { int num2 = Interop.Kernel32.LCMapStringEx((_sortHandle != IntPtr.Zero) ? null : _sortName, dwMapFlags, lpSrcStr, num, null, 0, null, null, _sortHandle); if (num2 == 0) { throw new ArgumentException(SR.Arg_ExternalException); } byte[] array = null; Span span = ((num2 > 512) ? ((Span)(array = ArrayPool.Shared.Rent(num2))) : stackalloc byte[512]); Span span2 = span; fixed (byte* lpDestStr = &MemoryMarshal.GetReference(span2)) { if (Interop.Kernel32.LCMapStringEx((_sortHandle != IntPtr.Zero) ? null : _sortName, dwMapFlags, lpSrcStr, num, lpDestStr, num2, null, null, _sortHandle) != num2) { throw new ArgumentException(SR.Arg_ExternalException); } } int result = Marvin.ComputeHash32(span2.Slice(0, num2), Marvin.DefaultSeed); if (array != null) { ArrayPool.Shared.Return(array); } return result; } } internal unsafe static int NlsCompareStringOrdinalIgnoreCase(ref char string1, int count1, ref char string2, int count2) { fixed (char* lpString = &string1) { fixed (char* lpString2 = &string2) { int num = Interop.Kernel32.CompareStringOrdinal(lpString, count1, lpString2, count2, bIgnoreCase: true); if (num == 0) { throw new ArgumentException(SR.Arg_ExternalException); } return num - 2; } } } private unsafe int NlsCompareString(ReadOnlySpan string1, ReadOnlySpan string2, CompareOptions options) { string text = ((_sortHandle != IntPtr.Zero) ? null : _sortName); if (string1.IsEmpty) { string1 = string.Empty; } if (string2.IsEmpty) { string2 = string.Empty; } fixed (char* lpLocaleName = text) { fixed (char* lpString = &MemoryMarshal.GetReference(string1)) { fixed (char* lpString2 = &MemoryMarshal.GetReference(string2)) { int num = Interop.Kernel32.CompareStringEx(lpLocaleName, (uint)GetNativeCompareFlags(options), lpString, string1.Length, lpString2, string2.Length, null, null, _sortHandle); if (num == 0) { throw new ArgumentException(SR.Arg_ExternalException); } return num - 2; } } } } private unsafe int FindString(uint dwFindNLSStringFlags, ReadOnlySpan lpStringSource, ReadOnlySpan lpStringValue, int* pcchFound) { string text = ((_sortHandle != IntPtr.Zero) ? null : _sortName); int num = lpStringSource.Length; if (num == 0) { lpStringSource = string.Empty; num = -1; } fixed (char* lpLocaleName = text) { fixed (char* lpStringSource2 = &MemoryMarshal.GetReference(lpStringSource)) { fixed (char* lpStringValue2 = &MemoryMarshal.GetReference(lpStringValue)) { return Interop.Kernel32.FindNLSStringEx(lpLocaleName, dwFindNLSStringFlags, lpStringSource2, num, lpStringValue2, lpStringValue.Length, pcchFound, null, null, _sortHandle); } } } } private unsafe int NlsIndexOfCore(ReadOnlySpan source, ReadOnlySpan target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { uint num = (fromBeginning ? 4194304u : 8388608u); return FindString(num | (uint)GetNativeCompareFlags(options), source, target, matchLengthPtr); } private unsafe bool NlsStartsWith(ReadOnlySpan source, ReadOnlySpan prefix, CompareOptions options, int* matchLengthPtr) { int num = FindString(0x100000u | (uint)GetNativeCompareFlags(options), source, prefix, matchLengthPtr); if (num >= 0) { if (matchLengthPtr != null) { *matchLengthPtr += num; } return true; } return false; } private unsafe bool NlsEndsWith(ReadOnlySpan source, ReadOnlySpan suffix, CompareOptions options, int* matchLengthPtr) { int num = FindString(0x200000u | (uint)GetNativeCompareFlags(options), source, suffix, null); if (num >= 0) { if (matchLengthPtr != null) { *matchLengthPtr = source.Length - num; } return true; } return false; } private unsafe SortKey NlsCreateSortKey(string source, CompareOptions options) { if (source == null) { throw new ArgumentNullException("source"); } if (((uint)options & 0xDFFFFFE0u) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, "options"); } uint dwMapFlags = 0x400u | (uint)GetNativeCompareFlags(options); int num = source.Length; if (num == 0) { num = -1; } byte[] array; fixed (char* lpSrcStr = source) { int num2 = Interop.Kernel32.LCMapStringEx((_sortHandle != IntPtr.Zero) ? null : _sortName, dwMapFlags, lpSrcStr, num, null, 0, null, null, _sortHandle); if (num2 == 0) { throw new ArgumentException(SR.Arg_ExternalException); } array = new byte[num2]; fixed (byte* lpDestStr = array) { if (Interop.Kernel32.LCMapStringEx((_sortHandle != IntPtr.Zero) ? null : _sortName, dwMapFlags, lpSrcStr, num, lpDestStr, array.Length, null, null, _sortHandle) != num2) { throw new ArgumentException(SR.Arg_ExternalException); } } } return new SortKey(this, source, options, array); } private unsafe int NlsGetSortKey(ReadOnlySpan source, Span destination, CompareOptions options) { if (destination.IsEmpty) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } if (!Environment.IsWindows8OrAbove) { source = source.ToString(); } uint dwMapFlags = 0x400u | (uint)GetNativeCompareFlags(options); int num = source.Length; if (num == 0) { source = string.Empty; num = -1; } int num3; fixed (char* lpSrcStr = &MemoryMarshal.GetReference(source)) { fixed (byte* lpDestStr = &MemoryMarshal.GetReference(destination)) { if (!Environment.IsWindows8OrAbove) { int num2 = Interop.Kernel32.LCMapStringEx((_sortHandle != IntPtr.Zero) ? null : _sortName, dwMapFlags, lpSrcStr, num, null, 0, null, null, _sortHandle); if (num2 > destination.Length) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } if (num2 <= 0) { throw new ArgumentException(SR.Arg_ExternalException); } } num3 = Interop.Kernel32.LCMapStringEx((_sortHandle != IntPtr.Zero) ? null : _sortName, dwMapFlags, lpSrcStr, num, lpDestStr, destination.Length, null, null, _sortHandle); } } if (num3 <= 0) { if (Marshal.GetLastPInvokeError() != 122) { throw new ArgumentException(SR.Arg_ExternalException); } ThrowHelper.ThrowArgumentException_DestinationTooShort(); } return num3; } private unsafe int NlsGetSortKeyLength(ReadOnlySpan source, CompareOptions options) { uint dwMapFlags = 0x400u | (uint)GetNativeCompareFlags(options); int num = source.Length; if (num == 0) { source = string.Empty; num = -1; } int num2; fixed (char* lpSrcStr = &MemoryMarshal.GetReference(source)) { num2 = Interop.Kernel32.LCMapStringEx((_sortHandle != IntPtr.Zero) ? null : _sortName, dwMapFlags, lpSrcStr, num, null, 0, null, null, _sortHandle); } if (num2 <= 0) { throw new ArgumentException(SR.Arg_ExternalException); } return num2; } private unsafe static bool NlsIsSortable(ReadOnlySpan text) { fixed (char* lpString = &MemoryMarshal.GetReference(text)) { return Interop.Kernel32.IsNLSDefinedString(1, 0u, IntPtr.Zero, lpString, text.Length); } } private static int GetNativeCompareFlags(CompareOptions options) { int num = 134217728; if ((options & CompareOptions.IgnoreCase) != 0) { num |= 1; } if ((options & CompareOptions.IgnoreKanaType) != 0) { num |= 0x10000; } if ((options & CompareOptions.IgnoreNonSpace) != 0) { num |= 2; } if ((options & CompareOptions.IgnoreSymbols) != 0) { num |= 4; } if ((options & CompareOptions.IgnoreWidth) != 0) { num |= 0x20000; } if ((options & CompareOptions.StringSort) != 0) { num |= 0x1000; } if (options == CompareOptions.Ordinal) { num = 1073741824; } return num; } private unsafe SortVersion NlsGetSortVersion() { Interop.Kernel32.NlsVersionInfoEx nlsVersionInfoEx = default(Interop.Kernel32.NlsVersionInfoEx); nlsVersionInfoEx.dwNLSVersionInfoSize = sizeof(Interop.Kernel32.NlsVersionInfoEx); Interop.Kernel32.GetNLSVersionEx(1, _sortName, &nlsVersionInfoEx); return new SortVersion(nlsVersionInfoEx.dwNLSVersion, (nlsVersionInfoEx.dwEffectiveId == 0) ? LCID : nlsVersionInfoEx.dwEffectiveId, nlsVersionInfoEx.guidCustomVersion); } } [Flags] public enum CompareOptions { None = 0, IgnoreCase = 1, IgnoreNonSpace = 2, IgnoreSymbols = 4, IgnoreKanaType = 8, IgnoreWidth = 0x10, OrdinalIgnoreCase = 0x10000000, StringSort = 0x20000000, Ordinal = 0x40000000 } internal sealed class CultureData { private enum LocaleStringData : uint { LocalizedDisplayName = 2u, EnglishDisplayName = 114u, NativeDisplayName = 115u, LocalizedLanguageName = 111u, EnglishLanguageName = 4097u, NativeLanguageName = 4u, LocalizedCountryName = 6u, EnglishCountryName = 4098u, NativeCountryName = 8u, AbbreviatedWindowsLanguageName = 3u, ListSeparator = 12u, DecimalSeparator = 14u, ThousandSeparator = 15u, Digits = 19u, MonetarySymbol = 20u, CurrencyEnglishName = 4103u, CurrencyNativeName = 4104u, Iso4217MonetarySymbol = 21u, MonetaryDecimalSeparator = 22u, MonetaryThousandSeparator = 23u, AMDesignator = 40u, PMDesignator = 41u, PositiveSign = 80u, NegativeSign = 81u, Iso639LanguageTwoLetterName = 89u, Iso639LanguageThreeLetterName = 103u, Iso639LanguageName = 89u, Iso3166CountryName = 90u, Iso3166CountryName2 = 104u, NaNSymbol = 105u, PositiveInfinitySymbol = 106u, NegativeInfinitySymbol = 107u, ParentName = 109u, ConsoleFallbackName = 110u, PercentSymbol = 118u, PerMilleSymbol = 119u } private enum LocaleGroupingData : uint { Digit = 16u, Monetary = 24u } private enum LocaleNumberData : uint { LanguageId = 1u, GeoId = 91u, DigitSubstitution = 4116u, MeasurementSystem = 13u, FractionalDigitsCount = 17u, NegativeNumberFormat = 4112u, MonetaryFractionalDigitsCount = 25u, PositiveMonetaryNumberFormat = 27u, NegativeMonetaryNumberFormat = 28u, CalendarType = 4105u, FirstDayOfWeek = 4108u, FirstWeekOfYear = 4109u, ReadingLayout = 112u, NegativePercentFormat = 116u, PositivePercentFormat = 117u, OemCodePage = 11u, AnsiCodePage = 4100u, MacCodePage = 4113u, EbcdicCodePage = 4114u } private struct EnumLocaleData { public string regionName; public string cultureName; } private struct EnumData { public List strings; } private string _sRealName; private string _sWindowsName; private string _sName; private string _sParent; private string _sEnglishDisplayName; private string _sNativeDisplayName; private string _sSpecificCulture; private string _sISO639Language; private string _sISO639Language2; private string _sEnglishLanguage; private string _sNativeLanguage; private string _sAbbrevLang; private string _sConsoleFallbackName; private int _iInputLanguageHandle = -1; private string _sRegionName; private string _sLocalizedCountry; private string _sEnglishCountry; private string _sNativeCountry; private string _sISO3166CountryName; private string _sISO3166CountryName2; private int _iGeoId = -1; private string _sPositiveSign; private string _sNegativeSign; private int _iDigits; private int _iNegativeNumber; private int[] _waGrouping; private string _sDecimalSeparator; private string _sThousandSeparator; private string _sNaN; private string _sPositiveInfinity; private string _sNegativeInfinity; private int _iNegativePercent = -1; private int _iPositivePercent = -1; private string _sPercent; private string _sPerMille; private string _sCurrency; private string _sIntlMonetarySymbol; private string _sEnglishCurrency; private string _sNativeCurrency; private int _iCurrencyDigits; private int _iCurrency; private int _iNegativeCurrency; private int[] _waMonetaryGrouping; private string _sMonetaryDecimal; private string _sMonetaryThousand; private int _iMeasure = -1; private string _sListSeparator; private string _sAM1159; private string _sPM2359; private string _sTimeSeparator; private volatile string[] _saLongTimes; private volatile string[] _saShortTimes; private volatile string[] _saDurationFormats; private int _iFirstDayOfWeek = -1; private int _iFirstWeekOfYear = -1; private volatile CalendarId[] _waCalendars; private CalendarData[] _calendars; private int _iReadingLayout = -1; private int _iDefaultAnsiCodePage = -1; private int _iDefaultOemCodePage = -1; private int _iDefaultMacCodePage = -1; private int _iDefaultEbcdicCodePage = -1; private int _iLanguage; private bool _bUseOverrides; private bool _bUseOverridesUserSetting; private bool _bNeutral; private static volatile Dictionary s_cachedRegions; private static volatile Dictionary s_regionNames; private static volatile CultureData s_Invariant; private static volatile Dictionary s_cachedCultures; private static readonly object s_lock = new object(); private static Dictionary RegionNames { get { object obj = s_regionNames; if (obj == null) { obj = new Dictionary(257, StringComparer.OrdinalIgnoreCase) { { "001", "en-001" }, { "029", "en-029" }, { "150", "en-150" }, { "419", "es-419" }, { "AD", "ca-AD" }, { "AE", "ar-AE" }, { "AF", "prs-AF" }, { "AG", "en-AG" }, { "AI", "en-AI" }, { "AL", "sq-AL" }, { "AM", "hy-AM" }, { "AO", "pt-AO" }, { "AQ", "en-A" }, { "AR", "es-AR" }, { "AS", "en-AS" }, { "AT", "de-AT" }, { "AU", "en-AU" }, { "AW", "nl-AW" }, { "AX", "sv-AX" }, { "AZ", "az-Cyrl-AZ" }, { "BA", "bs-Latn-BA" }, { "BB", "en-BB" }, { "BD", "bn-BD" }, { "BE", "nl-BE" }, { "BF", "fr-BF" }, { "BG", "bg-BG" }, { "BH", "ar-BH" }, { "BI", "rn-BI" }, { "BJ", "fr-BJ" }, { "BL", "fr-BL" }, { "BM", "en-BM" }, { "BN", "ms-BN" }, { "BO", "es-BO" }, { "BQ", "nl-BQ" }, { "BR", "pt-BR" }, { "BS", "en-BS" }, { "BT", "dz-BT" }, { "BV", "nb-B" }, { "BW", "en-BW" }, { "BY", "be-BY" }, { "BZ", "en-BZ" }, { "CA", "en-CA" }, { "CC", "en-CC" }, { "CD", "fr-CD" }, { "CF", "sg-CF" }, { "CG", "fr-CG" }, { "CH", "it-CH" }, { "CI", "fr-CI" }, { "CK", "en-CK" }, { "CL", "es-CL" }, { "CM", "fr-C" }, { "CN", "zh-CN" }, { "CO", "es-CO" }, { "CR", "es-CR" }, { "CS", "sr-Cyrl-CS" }, { "CU", "es-CU" }, { "CV", "pt-CV" }, { "CW", "nl-CW" }, { "CX", "en-CX" }, { "CY", "el-CY" }, { "CZ", "cs-CZ" }, { "DE", "de-DE" }, { "DJ", "fr-DJ" }, { "DK", "da-DK" }, { "DM", "en-DM" }, { "DO", "es-DO" }, { "DZ", "ar-DZ" }, { "EC", "es-EC" }, { "EE", "et-EE" }, { "EG", "ar-EG" }, { "ER", "tig-ER" }, { "ES", "es-ES" }, { "ET", "am-ET" }, { "FI", "fi-FI" }, { "FJ", "en-FJ" }, { "FK", "en-FK" }, { "FM", "en-FM" }, { "FO", "fo-FO" }, { "FR", "fr-FR" }, { "GA", "fr-GA" }, { "GB", "en-GB" }, { "GD", "en-GD" }, { "GE", "ka-GE" }, { "GF", "fr-GF" }, { "GG", "en-GG" }, { "GH", "en-GH" }, { "GI", "en-GI" }, { "GL", "kl-GL" }, { "GM", "en-GM" }, { "GN", "fr-GN" }, { "GP", "fr-GP" }, { "GQ", "es-GQ" }, { "GR", "el-GR" }, { "GS", "en-G" }, { "GT", "es-GT" }, { "GU", "en-GU" }, { "GW", "pt-GW" }, { "GY", "en-GY" }, { "HK", "zh-HK" }, { "HM", "en-H" }, { "HN", "es-HN" }, { "HR", "hr-HR" }, { "HT", "fr-HT" }, { "HU", "hu-HU" }, { "ID", "id-ID" }, { "IE", "en-IE" }, { "IL", "he-IL" }, { "IM", "gv-IM" }, { "IN", "hi-IN" }, { "IO", "en-IO" }, { "IQ", "ar-IQ" }, { "IR", "fa-IR" }, { "IS", "is-IS" }, { "IT", "it-IT" }, { "IV", "" }, { "JE", "en-JE" }, { "JM", "en-JM" }, { "JO", "ar-JO" }, { "JP", "ja-JP" }, { "KE", "sw-KE" }, { "KG", "ky-KG" }, { "KH", "km-KH" }, { "KI", "en-KI" }, { "KM", "ar-KM" }, { "KN", "en-KN" }, { "KP", "ko-KP" }, { "KR", "ko-KR" }, { "KW", "ar-KW" }, { "KY", "en-KY" }, { "KZ", "kk-KZ" }, { "LA", "lo-LA" }, { "LB", "ar-LB" }, { "LC", "en-LC" }, { "LI", "de-LI" }, { "LK", "si-LK" }, { "LR", "en-LR" }, { "LS", "st-LS" }, { "LT", "lt-LT" }, { "LU", "lb-LU" }, { "LV", "lv-LV" }, { "LY", "ar-LY" }, { "MA", "ar-MA" }, { "MC", "fr-MC" }, { "MD", "ro-MD" }, { "ME", "sr-Latn-ME" }, { "MF", "fr-MF" }, { "MG", "mg-MG" }, { "MH", "en-MH" }, { "MK", "mk-MK" }, { "ML", "fr-ML" }, { "MM", "my-MM" }, { "MN", "mn-MN" }, { "MO", "zh-MO" }, { "MP", "en-MP" }, { "MQ", "fr-MQ" }, { "MR", "ar-MR" }, { "MS", "en-MS" }, { "MT", "mt-MT" }, { "MU", "en-MU" }, { "MV", "dv-MV" }, { "MW", "en-MW" }, { "MX", "es-MX" }, { "MY", "ms-MY" }, { "MZ", "pt-MZ" }, { "NA", "en-NA" }, { "NC", "fr-NC" }, { "NE", "fr-NE" }, { "NF", "en-NF" }, { "NG", "ig-NG" }, { "NI", "es-NI" }, { "NL", "nl-NL" }, { "NO", "nn-NO" }, { "NP", "ne-NP" }, { "NR", "en-NR" }, { "NU", "en-NU" }, { "NZ", "en-NZ" }, { "OM", "ar-OM" }, { "PA", "es-PA" }, { "PE", "es-PE" }, { "PF", "fr-PF" }, { "PG", "en-PG" }, { "PH", "en-PH" }, { "PK", "ur-PK" }, { "PL", "pl-PL" }, { "PM", "fr-PM" }, { "PN", "en-PN" }, { "PR", "es-PR" }, { "PS", "ar-PS" }, { "PT", "pt-PT" }, { "PW", "en-PW" }, { "PY", "es-PY" }, { "QA", "ar-QA" }, { "RE", "fr-RE" }, { "RO", "ro-RO" }, { "RS", "sr-Latn-RS" }, { "RU", "ru-RU" }, { "RW", "rw-RW" }, { "SA", "ar-SA" }, { "SB", "en-SB" }, { "SC", "fr-SC" }, { "SD", "ar-SD" }, { "SE", "sv-SE" }, { "SG", "zh-SG" }, { "SH", "en-SH" }, { "SI", "sl-SI" }, { "SJ", "nb-SJ" }, { "SK", "sk-SK" }, { "SL", "en-SL" }, { "SM", "it-SM" }, { "SN", "wo-SN" }, { "SO", "so-SO" }, { "SR", "nl-SR" }, { "SS", "en-SS" }, { "ST", "pt-ST" }, { "SV", "es-SV" }, { "SX", "nl-SX" }, { "SY", "ar-SY" }, { "SZ", "ss-SZ" }, { "TC", "en-TC" }, { "TD", "fr-TD" }, { "TF", "fr-T" }, { "TG", "fr-TG" }, { "TH", "th-TH" }, { "TJ", "tg-Cyrl-TJ" }, { "TK", "en-TK" }, { "TL", "pt-TL" }, { "TM", "tk-TM" }, { "TN", "ar-TN" }, { "TO", "to-TO" }, { "TR", "tr-TR" }, { "TT", "en-TT" }, { "TV", "en-TV" }, { "TW", "zh-TW" }, { "TZ", "sw-TZ" }, { "UA", "uk-UA" }, { "UG", "sw-UG" }, { "UM", "en-UM" }, { "US", "en-US" }, { "UY", "es-UY" }, { "UZ", "uz-Cyrl-UZ" }, { "VA", "it-VA" }, { "VC", "en-VC" }, { "VE", "es-VE" }, { "VG", "en-VG" }, { "VI", "en-VI" }, { "VN", "vi-VN" }, { "VU", "fr-VU" }, { "WF", "fr-WF" }, { "WS", "en-WS" }, { "XK", "sq-XK" }, { "YE", "ar-YE" }, { "YT", "fr-YT" }, { "ZA", "af-ZA" }, { "ZM", "en-ZM" }, { "ZW", "en-ZW" } }; s_regionNames = (Dictionary)obj; } return (Dictionary)obj; } } internal static CultureData Invariant => s_Invariant ?? (s_Invariant = CreateCultureWithInvariantData()); internal string CultureName { get { string sName = _sName; if (sName == "zh-CHS" || sName == "zh-CHT") { return _sName; } return _sRealName; } } internal bool UseUserOverride => _bUseOverridesUserSetting; internal string Name => _sName ?? string.Empty; internal string ParentName => _sParent ?? (_sParent = GetLocaleInfoCore(_sRealName, LocaleStringData.ParentName)); internal string DisplayName { get { string text = NativeName; if (!GlobalizationMode.Invariant && Name.Length > 0) { try { text = GetLanguageDisplayNameCore(Name.Equals("zh-CHT", StringComparison.OrdinalIgnoreCase) ? "zh-Hant" : (Name.Equals("zh-CHS", StringComparison.OrdinalIgnoreCase) ? "zh-Hans" : Name)); } catch { } if (string.IsNullOrEmpty(text) && IsNeutralCulture) { text = LocalizedLanguageName; } } return text; } } internal string EnglishName { get { string text = _sEnglishDisplayName; if (text == null && !GlobalizationMode.Invariant) { if (IsNeutralCulture) { text = GetLocaleInfoCore(LocaleStringData.EnglishDisplayName); if (string.IsNullOrEmpty(text)) { text = EnglishLanguageName; } string sName = _sName; if (sName == "zh-CHS" || sName == "zh-CHT") { text += " Legacy"; } } else { text = GetLocaleInfoCore(LocaleStringData.EnglishDisplayName); if (string.IsNullOrEmpty(text)) { text = ((EnglishLanguageName[^1] != ')') ? (EnglishLanguageName + " (" + EnglishCountryName + ")") : string.Concat(EnglishLanguageName.AsSpan(0, _sEnglishLanguage.Length - 1), ", ", EnglishCountryName, ")")); } } _sEnglishDisplayName = text; } return text; } } internal string NativeName { get { string text = _sNativeDisplayName; if (text == null && !GlobalizationMode.Invariant) { if (IsNeutralCulture) { text = GetLocaleInfoCore(LocaleStringData.NativeDisplayName); if (string.IsNullOrEmpty(text)) { text = NativeLanguageName; } string sName = _sName; if (!(sName == "zh-CHS")) { if (sName == "zh-CHT") { text += " 舊版"; } } else { text += " 旧版"; } } else { text = GetLocaleInfoCore(LocaleStringData.NativeDisplayName); if (string.IsNullOrEmpty(text)) { text = NativeLanguageName + " (" + NativeCountryName + ")"; } } _sNativeDisplayName = text; } return text; } } internal string SpecificCultureName => _sSpecificCulture; internal string TwoLetterISOLanguageName => _sISO639Language ?? (_sISO639Language = GetLocaleInfoCore(LocaleStringData.Iso639LanguageTwoLetterName)); internal string ThreeLetterISOLanguageName => _sISO639Language2 ?? (_sISO639Language2 = GetLocaleInfoCore(LocaleStringData.Iso639LanguageThreeLetterName)); internal string ThreeLetterWindowsLanguageName => _sAbbrevLang ?? (_sAbbrevLang = (GlobalizationMode.UseNls ? NlsGetThreeLetterWindowsLanguageName(_sRealName) : IcuGetThreeLetterWindowsLanguageName(_sRealName))); private string LocalizedLanguageName { get { string result = NativeLanguageName; if (!GlobalizationMode.Invariant && Name.Length > 0 && (!GlobalizationMode.UseNls || CultureInfo.UserDefaultUICulture?.Name == CultureInfo.CurrentUICulture.Name)) { result = GetLocaleInfoCore(LocaleStringData.LocalizedLanguageName, CultureInfo.CurrentUICulture.Name); } return result; } } private string EnglishLanguageName => _sEnglishLanguage ?? (_sEnglishLanguage = GetLocaleInfoCore(LocaleStringData.EnglishLanguageName)); private string NativeLanguageName => _sNativeLanguage ?? (_sNativeLanguage = GetLocaleInfoCore(LocaleStringData.NativeLanguageName)); internal string RegionName => _sRegionName ?? (_sRegionName = GetLocaleInfoCore(LocaleStringData.Iso3166CountryName)); internal int GeoId { get { if (_iGeoId == -1 && !GlobalizationMode.Invariant) { _iGeoId = (GlobalizationMode.UseNls ? NlsGetLocaleInfo(LocaleNumberData.GeoId) : IcuGetGeoId(_sRealName)); } return _iGeoId; } } internal string LocalizedCountryName { get { string text = _sLocalizedCountry; if (text == null && !GlobalizationMode.Invariant) { try { text = (GlobalizationMode.UseNls ? NlsGetRegionDisplayName() : IcuGetRegionDisplayName()); } catch { } if (text == null) { text = NativeCountryName; } _sLocalizedCountry = text; } return text; } } internal string EnglishCountryName => _sEnglishCountry ?? (_sEnglishCountry = GetLocaleInfoCore(LocaleStringData.EnglishCountryName)); internal string NativeCountryName => _sNativeCountry ?? (_sNativeCountry = GetLocaleInfoCore(LocaleStringData.NativeCountryName)); internal string TwoLetterISOCountryName => _sISO3166CountryName ?? (_sISO3166CountryName = GetLocaleInfoCore(LocaleStringData.Iso3166CountryName)); internal string ThreeLetterISOCountryName => _sISO3166CountryName2 ?? (_sISO3166CountryName2 = GetLocaleInfoCore(LocaleStringData.Iso3166CountryName2)); internal int KeyboardLayoutId { get { if (_iInputLanguageHandle == -1) { if (IsSupplementalCustomCulture) { _iInputLanguageHandle = 1033; } else { _iInputLanguageHandle = LCID; } } return _iInputLanguageHandle; } } internal string SCONSOLEFALLBACKNAME => _sConsoleFallbackName ?? (_sConsoleFallbackName = (GlobalizationMode.UseNls ? NlsGetConsoleFallbackName(_sRealName) : IcuGetConsoleFallbackName(_sRealName))); internal int[] NumberGroupSizes => _waGrouping ?? (_waGrouping = GetLocaleInfoCoreUserOverride(LocaleGroupingData.Digit)); private string NaNSymbol => _sNaN ?? (_sNaN = GetLocaleInfoCore(LocaleStringData.NaNSymbol)); private string PositiveInfinitySymbol => _sPositiveInfinity ?? (_sPositiveInfinity = GetLocaleInfoCore(LocaleStringData.PositiveInfinitySymbol)); private string NegativeInfinitySymbol => _sNegativeInfinity ?? (_sNegativeInfinity = GetLocaleInfoCore(LocaleStringData.NegativeInfinitySymbol)); private int PercentNegativePattern { get { if (_iNegativePercent == -1) { _iNegativePercent = GetLocaleInfoCore(LocaleNumberData.NegativePercentFormat); } return _iNegativePercent; } } private int PercentPositivePattern { get { if (_iPositivePercent == -1) { _iPositivePercent = GetLocaleInfoCore(LocaleNumberData.PositivePercentFormat); } return _iPositivePercent; } } private string PercentSymbol => _sPercent ?? (_sPercent = GetLocaleInfoCore(LocaleStringData.PercentSymbol)); private string PerMilleSymbol => _sPerMille ?? (_sPerMille = GetLocaleInfoCore(LocaleStringData.PerMilleSymbol)); internal string CurrencySymbol => _sCurrency ?? (_sCurrency = GetLocaleInfoCoreUserOverride(LocaleStringData.MonetarySymbol)); internal string ISOCurrencySymbol => _sIntlMonetarySymbol ?? (_sIntlMonetarySymbol = GetLocaleInfoCore(LocaleStringData.Iso4217MonetarySymbol)); internal string CurrencyEnglishName => _sEnglishCurrency ?? (_sEnglishCurrency = GetLocaleInfoCore(LocaleStringData.CurrencyEnglishName)); internal string CurrencyNativeName => _sNativeCurrency ?? (_sNativeCurrency = GetLocaleInfoCore(LocaleStringData.CurrencyNativeName)); internal int[] CurrencyGroupSizes => _waMonetaryGrouping ?? (_waMonetaryGrouping = GetLocaleInfoCoreUserOverride(LocaleGroupingData.Monetary)); internal int MeasurementSystem { get { if (_iMeasure == -1) { _iMeasure = GetLocaleInfoCoreUserOverride(LocaleNumberData.MeasurementSystem); } return _iMeasure; } } internal string ListSeparator => _sListSeparator ?? (_sListSeparator = (ShouldUseUserOverrideNlsData ? NlsGetLocaleInfo(LocaleStringData.ListSeparator) : IcuGetListSeparator(_sWindowsName))); internal string AMDesignator => _sAM1159 ?? (_sAM1159 = GetLocaleInfoCoreUserOverride(LocaleStringData.AMDesignator)); internal string PMDesignator => _sPM2359 ?? (_sPM2359 = GetLocaleInfoCoreUserOverride(LocaleStringData.PMDesignator)); internal string[] LongTimes { get { if (_saLongTimes == null && !GlobalizationMode.Invariant) { string[] timeFormatsCore = GetTimeFormatsCore(shortFormat: false); if (timeFormatsCore == null || timeFormatsCore.Length == 0) { _saLongTimes = Invariant._saLongTimes; } else { _saLongTimes = timeFormatsCore; } } return _saLongTimes; } } internal string[] ShortTimes { get { if (_saShortTimes == null && !GlobalizationMode.Invariant) { string[] array = GetTimeFormatsCore(shortFormat: true); if (array == null || array.Length == 0) { array = DeriveShortTimesFromLong(); } _saShortTimes = array; } return _saShortTimes; } } internal int FirstDayOfWeek { get { if (_iFirstDayOfWeek == -1 && !GlobalizationMode.Invariant) { _iFirstDayOfWeek = (ShouldUseUserOverrideNlsData ? NlsGetFirstDayOfWeek() : IcuGetLocaleInfo(LocaleNumberData.FirstDayOfWeek)); } return _iFirstDayOfWeek; } } internal int CalendarWeekRule { get { if (_iFirstWeekOfYear == -1) { _iFirstWeekOfYear = GetLocaleInfoCoreUserOverride(LocaleNumberData.FirstWeekOfYear); } return _iFirstWeekOfYear; } } internal CalendarId[] CalendarIds { get { if (_waCalendars == null && !GlobalizationMode.Invariant) { CalendarId[] array = new CalendarId[23]; int num = CalendarData.GetCalendarsCore(_sWindowsName, _bUseOverrides, array); if (num == 0) { _waCalendars = Invariant._waCalendars; } else { if (_sWindowsName == "zh-TW") { bool flag = false; for (int i = 0; i < num; i++) { if (array[i] == CalendarId.TAIWAN) { flag = true; break; } } if (!flag) { num++; Array.Copy(array, 1, array, 2, 21); array[1] = CalendarId.TAIWAN; } } CalendarId[] array2 = new CalendarId[num]; Array.Copy(array, array2, num); _waCalendars = array2; } } return _waCalendars; } } internal bool IsRightToLeft => ReadingLayout == 1; private int ReadingLayout { get { if (_iReadingLayout == -1 && !GlobalizationMode.Invariant) { _iReadingLayout = GetLocaleInfoCore(LocaleNumberData.ReadingLayout); } return _iReadingLayout; } } internal string TextInfoName => _sRealName; internal string SortName => _sRealName; internal bool IsSupplementalCustomCulture => IsCustomCultureId(LCID); internal int ANSICodePage { get { if (_iDefaultAnsiCodePage == -1 && !GlobalizationMode.Invariant) { _iDefaultAnsiCodePage = GetAnsiCodePage(_sRealName); } return _iDefaultAnsiCodePage; } } internal int OEMCodePage { get { if (_iDefaultOemCodePage == -1 && !GlobalizationMode.Invariant) { _iDefaultOemCodePage = GetOemCodePage(_sRealName); } return _iDefaultOemCodePage; } } internal int MacCodePage { get { if (_iDefaultMacCodePage == -1 && !GlobalizationMode.Invariant) { _iDefaultMacCodePage = GetMacCodePage(_sRealName); } return _iDefaultMacCodePage; } } internal int EBCDICCodePage { get { if (_iDefaultEbcdicCodePage == -1 && !GlobalizationMode.Invariant) { _iDefaultEbcdicCodePage = GetEbcdicCodePage(_sRealName); } return _iDefaultEbcdicCodePage; } } internal int LCID { get { if (_iLanguage == 0 && !GlobalizationMode.Invariant) { _iLanguage = (GlobalizationMode.UseNls ? NlsLocaleNameToLCID(_sRealName) : IcuLocaleNameToLCID(_sRealName)); } return _iLanguage; } } internal bool IsNeutralCulture => _bNeutral; internal bool IsInvariantCulture => string.IsNullOrEmpty(Name); internal bool IsReplacementCulture { get { if (!GlobalizationMode.UseNls) { return false; } return NlsIsReplacementCulture; } } internal Calendar DefaultCalendar { get { if (GlobalizationMode.Invariant) { return new GregorianCalendar(); } CalendarId calendarId = (CalendarId)GetLocaleInfoCore(LocaleNumberData.CalendarType); if (calendarId == CalendarId.UNINITIALIZED_VALUE) { calendarId = CalendarIds[0]; } return CultureInfo.GetCalendarInstance(calendarId); } } internal string TimeSeparator { get { if (_sTimeSeparator == null && !GlobalizationMode.Invariant) { if (_sName == "fr-CA") { _sTimeSeparator = ":"; } else { string text = (ShouldUseUserOverrideNlsData ? NlsGetTimeFormatString() : IcuGetTimeFormatString()); if (string.IsNullOrEmpty(text)) { text = LongTimes[0]; } _sTimeSeparator = GetTimeSeparator(text); } } return _sTimeSeparator; } } internal unsafe bool NlsIsReplacementCulture { get { EnumData value = default(EnumData); value.strings = new List(); Interop.Kernel32.EnumSystemLocalesEx((delegate* unmanaged)(delegate*)(&EnumAllSystemLocalesProc), 8u, Unsafe.AsPointer(ref value), IntPtr.Zero); for (int i = 0; i < value.strings.Count; i++) { if (string.Equals(value.strings[i], _sRealName, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } } internal static bool IsWin32Installed => true; private bool ShouldUseUserOverrideNlsData { get { if (!GlobalizationMode.UseNls) { return _bUseOverrides; } return true; } } internal static CultureData GetCultureDataForRegion(string cultureName, bool useUserOverride) { if (string.IsNullOrEmpty(cultureName)) { return Invariant; } CultureData cultureData = null; cultureData = GetCultureData(cultureName, useUserOverride); if (cultureData != null && !cultureData.IsNeutralCulture) { return cultureData; } CultureData cultureData2 = cultureData; string key = AnsiToLower(useUserOverride ? cultureName : (cultureName + "*")); Dictionary dictionary = s_cachedRegions; if (dictionary == null) { dictionary = new Dictionary(); } else { lock (s_lock) { dictionary.TryGetValue(key, out cultureData); } if (cultureData != null) { return cultureData; } } if ((cultureData == null || cultureData.IsNeutralCulture) && RegionNames.TryGetValue(cultureName, out var value)) { cultureData = GetCultureData(value, useUserOverride); } if (!GlobalizationMode.Invariant && (cultureData == null || cultureData.IsNeutralCulture)) { cultureData = (GlobalizationMode.UseNls ? NlsGetCultureDataFromRegionName(cultureName) : IcuGetCultureDataFromRegionName(cultureName)); } if (cultureData != null && !cultureData.IsNeutralCulture) { lock (s_lock) { dictionary[key] = cultureData; } s_cachedRegions = dictionary; } else { cultureData = cultureData2; } return cultureData; } internal static void ClearCachedData() { s_cachedCultures = null; s_cachedRegions = null; } internal static CultureInfo[] GetCultures(CultureTypes types) { if (types <= (CultureTypes)0 || ((uint)types & 0xFFFFFF80u) != 0) { throw new ArgumentOutOfRangeException("types", SR.Format(SR.ArgumentOutOfRange_Range, CultureTypes.NeutralCultures, CultureTypes.FrameworkCultures)); } if ((types & CultureTypes.WindowsOnlyCultures) != 0) { types &= ~CultureTypes.WindowsOnlyCultures; } if (GlobalizationMode.Invariant) { return new CultureInfo[1] { new CultureInfo("") }; } if (!GlobalizationMode.UseNls) { return IcuEnumCultures(types); } return NlsEnumCultures(types); } private static CultureData CreateCultureWithInvariantData() { CultureData cultureData = new CultureData(); cultureData._bUseOverrides = false; cultureData._bUseOverridesUserSetting = false; cultureData._sRealName = ""; cultureData._sWindowsName = ""; cultureData._sName = ""; cultureData._sParent = ""; cultureData._bNeutral = false; cultureData._sEnglishDisplayName = "Invariant Language (Invariant Country)"; cultureData._sNativeDisplayName = "Invariant Language (Invariant Country)"; cultureData._sSpecificCulture = ""; cultureData._sISO639Language = "iv"; cultureData._sISO639Language2 = "ivl"; cultureData._sEnglishLanguage = "Invariant Language"; cultureData._sNativeLanguage = "Invariant Language"; cultureData._sAbbrevLang = "IVL"; cultureData._sConsoleFallbackName = ""; cultureData._iInputLanguageHandle = 127; cultureData._sRegionName = "IV"; cultureData._sEnglishCountry = "Invariant Country"; cultureData._sNativeCountry = "Invariant Country"; cultureData._sISO3166CountryName = "IV"; cultureData._sISO3166CountryName2 = "ivc"; cultureData._iGeoId = 244; cultureData._sPositiveSign = "+"; cultureData._sNegativeSign = "-"; cultureData._iDigits = 2; cultureData._iNegativeNumber = 1; cultureData._waGrouping = new int[1] { 3 }; cultureData._sDecimalSeparator = "."; cultureData._sThousandSeparator = ","; cultureData._sNaN = "NaN"; cultureData._sPositiveInfinity = "Infinity"; cultureData._sNegativeInfinity = "-Infinity"; cultureData._iNegativePercent = 0; cultureData._iPositivePercent = 0; cultureData._sPercent = "%"; cultureData._sPerMille = "‰"; cultureData._sCurrency = "¤"; cultureData._sIntlMonetarySymbol = "XDR"; cultureData._sEnglishCurrency = "International Monetary Fund"; cultureData._sNativeCurrency = "International Monetary Fund"; cultureData._iCurrencyDigits = 2; cultureData._iCurrency = 0; cultureData._iNegativeCurrency = 0; cultureData._waMonetaryGrouping = new int[1] { 3 }; cultureData._sMonetaryDecimal = "."; cultureData._sMonetaryThousand = ","; cultureData._iMeasure = 0; cultureData._sListSeparator = ","; cultureData._sTimeSeparator = ":"; cultureData._sAM1159 = "AM"; cultureData._sPM2359 = "PM"; cultureData._saLongTimes = new string[1] { "HH:mm:ss" }; cultureData._saShortTimes = new string[4] { "HH:mm", "hh:mm tt", "H:mm", "h:mm tt" }; cultureData._saDurationFormats = new string[1] { "HH:mm:ss" }; cultureData._iFirstDayOfWeek = 0; cultureData._iFirstWeekOfYear = 0; cultureData._waCalendars = new CalendarId[1] { CalendarId.GREGORIAN }; if (!GlobalizationMode.Invariant) { cultureData._calendars = new CalendarData[23]; cultureData._calendars[0] = CalendarData.Invariant; } cultureData._iReadingLayout = 0; cultureData._iLanguage = 127; cultureData._iDefaultAnsiCodePage = 1252; cultureData._iDefaultOemCodePage = 437; cultureData._iDefaultMacCodePage = 10000; cultureData._iDefaultEbcdicCodePage = 37; if (GlobalizationMode.Invariant) { cultureData._sLocalizedCountry = cultureData._sNativeCountry; } return cultureData; } internal static CultureData GetCultureData(string cultureName, bool useUserOverride) { if (string.IsNullOrEmpty(cultureName)) { return Invariant; } if (GlobalizationMode.PredefinedCulturesOnly && (GlobalizationMode.Invariant || (GlobalizationMode.UseNls ? (!NlsIsEnsurePredefinedLocaleName(cultureName)) : (!IcuIsEnsurePredefinedLocaleName(cultureName))))) { return null; } string key = AnsiToLower(useUserOverride ? cultureName : (cultureName + "*")); Dictionary dictionary = s_cachedCultures; if (dictionary == null) { dictionary = new Dictionary(); } else { bool flag; CultureData value; lock (s_lock) { flag = dictionary.TryGetValue(key, out value); } if (flag && value != null) { return value; } } CultureData cultureData = CreateCultureData(cultureName, useUserOverride); if (cultureData == null) { return null; } lock (s_lock) { dictionary[key] = cultureData; } s_cachedCultures = dictionary; return cultureData; } private static string NormalizeCultureName(string name, out bool isNeutralName) { isNeutralName = true; int i = 0; if (name.Length > 85) { throw new ArgumentException(SR.Format(SR.Argument_InvalidId, "name")); } Span span = stackalloc char[name.Length]; bool flag = false; for (; i < name.Length && name[i] != '-' && name[i] != '_'; i++) { if (name[i] >= 'A' && name[i] <= 'Z') { span[i] = (char)(name[i] + 32); flag = true; } else { span[i] = name[i]; } } if (i < name.Length) { isNeutralName = false; } for (; i < name.Length; i++) { if (name[i] >= 'a' && name[i] <= 'z') { span[i] = (char)(name[i] - 32); flag = true; } else { span[i] = name[i]; } } if (flag) { return new string(span); } return name; } private static CultureData CreateCultureData(string cultureName, bool useUserOverride) { if (GlobalizationMode.Invariant) { if (cultureName.Length > 85 || !CultureInfo.VerifyCultureName(cultureName, throwException: false)) { return null; } CultureData cultureData = CreateCultureWithInvariantData(); cultureData._sName = NormalizeCultureName(cultureName, out cultureData._bNeutral); cultureData._bUseOverridesUserSetting = useUserOverride; cultureData._sRealName = cultureData._sName; cultureData._sWindowsName = cultureData._sName; cultureData._iLanguage = 4096; return cultureData; } if (cultureName.Length == 1 && (cultureName[0] == 'C' || cultureName[0] == 'c')) { return Invariant; } CultureData cultureData2 = new CultureData(); cultureData2._sRealName = cultureName; cultureData2._bUseOverridesUserSetting = useUserOverride; if (!cultureData2.InitCultureDataCore() && !cultureData2.InitCompatibilityCultureData()) { return null; } cultureData2.InitUserOverride(useUserOverride); return cultureData2; } private bool InitCompatibilityCultureData() { string sRealName = _sRealName; string text = AnsiToLower(sRealName); string text2; string sName; if (!(text == "zh-chs")) { if (!(text == "zh-cht")) { return false; } text2 = "zh-Hant"; sName = "zh-CHT"; } else { text2 = "zh-Hans"; sName = "zh-CHS"; } _sRealName = text2; if (!InitCultureDataCore()) { return false; } _sName = sName; _sParent = text2; return true; } internal static CultureData GetCultureData(int culture, bool bUseUserOverride) { string text = null; CultureData cultureData = null; if (culture == 127) { return Invariant; } if (GlobalizationMode.Invariant) { throw new CultureNotFoundException("culture", culture, SR.Argument_CultureNotSupportedInInvariantMode); } text = LCIDToLocaleName(culture); if (!string.IsNullOrEmpty(text)) { cultureData = GetCultureData(text, bUseUserOverride); } if (cultureData == null) { throw new CultureNotFoundException("culture", culture, SR.Argument_CultureNotSupported); } return cultureData; } private string GetLanguageDisplayNameCore(string cultureName) { if (!GlobalizationMode.UseNls) { return IcuGetLanguageDisplayName(cultureName); } return NlsGetLanguageDisplayName(cultureName); } private string[] DeriveShortTimesFromLong() { string[] longTimes = LongTimes; string[] array = new string[longTimes.Length]; for (int i = 0; i < longTimes.Length; i++) { array[i] = StripSecondsFromPattern(longTimes[i]); } return array; } private static string StripSecondsFromPattern(string time) { bool flag = false; int num = -1; for (int i = 0; i < time.Length; i++) { if (time[i] == '\'') { flag = !flag; } else if (time[i] == '\\') { i++; } else { if (flag) { continue; } switch (time[i]) { case 's': { if (i - num <= 4 && i - num > 1 && time[num + 1] != '\'' && time[i - 1] != '\'' && num >= 0) { i = num + 1; } bool containsSpace; int indexOfNextTokenAfterSeconds = GetIndexOfNextTokenAfterSeconds(time, i, out containsSpace); time = string.Concat(str1: (!containsSpace) ? "" : " ", str0: time.AsSpan(0, i), str2: time.AsSpan(indexOfNextTokenAfterSeconds)); break; } case 'H': case 'h': case 'm': num = i; break; } } } return time; } private static int GetIndexOfNextTokenAfterSeconds(string time, int index, out bool containsSpace) { bool flag = false; containsSpace = false; while (index < time.Length) { switch (time[index]) { case '\'': flag = !flag; break; case '\\': index++; if (time[index] == ' ') { containsSpace = true; } break; case ' ': containsSpace = true; break; case 'H': case 'h': case 'm': case 't': if (!flag) { return index; } break; } index++; } containsSpace = false; return index; } internal string[] ShortDates(CalendarId calendarId) { return GetCalendar(calendarId).saShortDates; } internal string[] LongDates(CalendarId calendarId) { return GetCalendar(calendarId).saLongDates; } internal string[] YearMonths(CalendarId calendarId) { return GetCalendar(calendarId).saYearMonths; } internal string[] DayNames(CalendarId calendarId) { return GetCalendar(calendarId).saDayNames; } internal string[] AbbreviatedDayNames(CalendarId calendarId) { return GetCalendar(calendarId).saAbbrevDayNames; } internal string[] SuperShortDayNames(CalendarId calendarId) { return GetCalendar(calendarId).saSuperShortDayNames; } internal string[] MonthNames(CalendarId calendarId) { return GetCalendar(calendarId).saMonthNames; } internal string[] GenitiveMonthNames(CalendarId calendarId) { return GetCalendar(calendarId).saMonthGenitiveNames; } internal string[] AbbreviatedMonthNames(CalendarId calendarId) { return GetCalendar(calendarId).saAbbrevMonthNames; } internal string[] AbbreviatedGenitiveMonthNames(CalendarId calendarId) { return GetCalendar(calendarId).saAbbrevMonthGenitiveNames; } internal string[] LeapYearMonthNames(CalendarId calendarId) { return GetCalendar(calendarId).saLeapYearMonthNames; } internal string MonthDay(CalendarId calendarId) { return GetCalendar(calendarId).sMonthDay; } internal string CalendarName(CalendarId calendarId) { return GetCalendar(calendarId).sNativeName; } internal CalendarData GetCalendar(CalendarId calendarId) { if (GlobalizationMode.Invariant) { return CalendarData.Invariant; } int num = (int)(calendarId - 1); if (_calendars == null) { _calendars = new CalendarData[23]; } CalendarData calendarData = _calendars[num]; if (calendarData == null) { calendarData = new CalendarData(_sWindowsName, calendarId, _bUseOverrides); _calendars[num] = calendarData; } return calendarData; } internal string[] EraNames(CalendarId calendarId) { return GetCalendar(calendarId).saEraNames; } internal string[] AbbrevEraNames(CalendarId calendarId) { return GetCalendar(calendarId).saAbbrevEraNames; } internal string[] AbbreviatedEnglishEraNames(CalendarId calendarId) { return GetCalendar(calendarId).saAbbrevEnglishEraNames; } internal string DateSeparator(CalendarId calendarId) { if (GlobalizationMode.Invariant) { return "/"; } if (calendarId == CalendarId.JAPAN && !LocalAppContextSwitches.EnforceLegacyJapaneseDateParsing) { return "/"; } return GetDateSeparator(ShortDates(calendarId)[0]); } private static string UnescapeNlsString(string str, int start, int end) { StringBuilder stringBuilder = null; for (int i = start; i < str.Length && i <= end; i++) { switch (str[i]) { case '\'': if (stringBuilder == null) { stringBuilder = new StringBuilder(str, start, i - start, str.Length); } break; case '\\': if (stringBuilder == null) { stringBuilder = new StringBuilder(str, start, i - start, str.Length); } i++; if (i < str.Length) { stringBuilder.Append(str[i]); } break; default: stringBuilder?.Append(str[i]); break; } } if (stringBuilder == null) { return str.Substring(start, end - start + 1); } return stringBuilder.ToString(); } private static string GetTimeSeparator(string format) { return GetSeparator(format, "Hhms"); } private static string GetDateSeparator(string format) { return GetSeparator(format, "dyM"); } private static string GetSeparator(string format, string timeParts) { int num = IndexOfTimePart(format, 0, timeParts); if (num != -1) { char c = format[num]; do { num++; } while (num < format.Length && format[num] == c); int num2 = num; if (num2 < format.Length) { int num3 = IndexOfTimePart(format, num2, timeParts); if (num3 != -1) { return UnescapeNlsString(format, num2, num3 - 1); } } } return string.Empty; } private static int IndexOfTimePart(string format, int startIndex, string timeParts) { bool flag = false; for (int i = startIndex; i < format.Length; i++) { if (!flag && timeParts.Contains(format[i])) { return i; } switch (format[i]) { case '\\': if (i + 1 < format.Length) { i++; char c = format[i]; if (c != '\'' && c != '\\') { i--; } } break; case '\'': flag = !flag; break; } } return -1; } internal static bool IsCustomCultureId(int cultureId) { if (cultureId != 3072) { return cultureId == 4096; } return true; } internal void GetNFIValues(NumberFormatInfo nfi) { if (GlobalizationMode.Invariant || IsInvariantCulture) { nfi._positiveSign = _sPositiveSign; nfi._negativeSign = _sNegativeSign; nfi._numberGroupSeparator = _sThousandSeparator; nfi._numberDecimalSeparator = _sDecimalSeparator; nfi._numberDecimalDigits = _iDigits; nfi._numberNegativePattern = _iNegativeNumber; nfi._currencySymbol = _sCurrency; nfi._currencyGroupSeparator = _sMonetaryThousand; nfi._currencyDecimalSeparator = _sMonetaryDecimal; nfi._currencyDecimalDigits = _iCurrencyDigits; nfi._currencyNegativePattern = _iNegativeCurrency; nfi._currencyPositivePattern = _iCurrency; } else { nfi._positiveSign = GetLocaleInfoCoreUserOverride(LocaleStringData.PositiveSign); nfi._negativeSign = GetLocaleInfoCoreUserOverride(LocaleStringData.NegativeSign); nfi._numberDecimalSeparator = GetLocaleInfoCoreUserOverride(LocaleStringData.DecimalSeparator); nfi._numberGroupSeparator = GetLocaleInfoCoreUserOverride(LocaleStringData.ThousandSeparator); nfi._currencyGroupSeparator = GetLocaleInfoCoreUserOverride(LocaleStringData.MonetaryThousandSeparator); nfi._currencyDecimalSeparator = GetLocaleInfoCoreUserOverride(LocaleStringData.MonetaryDecimalSeparator); nfi._currencySymbol = GetLocaleInfoCoreUserOverride(LocaleStringData.MonetarySymbol); nfi._numberDecimalDigits = GetLocaleInfoCoreUserOverride(LocaleNumberData.FractionalDigitsCount); nfi._currencyDecimalDigits = GetLocaleInfoCoreUserOverride(LocaleNumberData.MonetaryFractionalDigitsCount); nfi._currencyPositivePattern = GetLocaleInfoCoreUserOverride(LocaleNumberData.PositiveMonetaryNumberFormat); nfi._currencyNegativePattern = GetLocaleInfoCoreUserOverride(LocaleNumberData.NegativeMonetaryNumberFormat); nfi._numberNegativePattern = GetLocaleInfoCoreUserOverride(LocaleNumberData.NegativeNumberFormat); string localeInfoCoreUserOverride = GetLocaleInfoCoreUserOverride(LocaleStringData.Digits); nfi._nativeDigits = new string[10]; for (int i = 0; i < nfi._nativeDigits.Length; i++) { nfi._nativeDigits[i] = char.ToString(localeInfoCoreUserOverride[i]); } nfi._digitSubstitution = (ShouldUseUserOverrideNlsData ? NlsGetLocaleInfo(LocaleNumberData.DigitSubstitution) : IcuGetDigitSubstitution(_sRealName)); } nfi._numberGroupSizes = NumberGroupSizes; nfi._currencyGroupSizes = CurrencyGroupSizes; nfi._percentNegativePattern = PercentNegativePattern; nfi._percentPositivePattern = PercentPositivePattern; nfi._percentSymbol = PercentSymbol; nfi._perMilleSymbol = PerMilleSymbol; nfi._negativeInfinitySymbol = NegativeInfinitySymbol; nfi._positiveInfinitySymbol = PositiveInfinitySymbol; nfi._nanSymbol = NaNSymbol; nfi._percentDecimalDigits = nfi._numberDecimalDigits; nfi._percentDecimalSeparator = nfi._numberDecimalSeparator; nfi._percentGroupSizes = nfi._numberGroupSizes; nfi._percentGroupSeparator = nfi._numberGroupSeparator; if (string.IsNullOrEmpty(nfi._positiveSign)) { nfi._positiveSign = "+"; } if (string.IsNullOrEmpty(nfi._currencyDecimalSeparator)) { nfi._currencyDecimalSeparator = nfi._numberDecimalSeparator; } } internal static string AnsiToLower(string testString) { return TextInfo.ToLowerAsciiInvariant(testString); } private int GetLocaleInfoCore(LocaleNumberData type) { if (GlobalizationMode.Invariant) { return 0; } if (!GlobalizationMode.UseNls) { return IcuGetLocaleInfo(type); } return NlsGetLocaleInfo(type); } private int GetLocaleInfoCoreUserOverride(LocaleNumberData type) { if (GlobalizationMode.Invariant) { return 0; } if (!ShouldUseUserOverrideNlsData) { return IcuGetLocaleInfo(type); } return NlsGetLocaleInfo(type); } private string GetLocaleInfoCoreUserOverride(LocaleStringData type) { if (GlobalizationMode.Invariant) { return null; } if (!ShouldUseUserOverrideNlsData) { return IcuGetLocaleInfo(type); } return NlsGetLocaleInfo(type); } private string GetLocaleInfoCore(LocaleStringData type, string uiCultureName = null) { if (GlobalizationMode.Invariant) { return null; } if (!GlobalizationMode.UseNls) { return IcuGetLocaleInfo(type, uiCultureName); } return NlsGetLocaleInfo(type); } private string GetLocaleInfoCore(string localeName, LocaleStringData type, string uiCultureName = null) { if (GlobalizationMode.Invariant) { return null; } if (!GlobalizationMode.UseNls) { return IcuGetLocaleInfo(localeName, type, uiCultureName); } return NlsGetLocaleInfo(localeName, type); } private int[] GetLocaleInfoCoreUserOverride(LocaleGroupingData type) { if (GlobalizationMode.Invariant) { return null; } if (!ShouldUseUserOverrideNlsData) { return IcuGetLocaleInfo(type); } return NlsGetLocaleInfo(type); } private bool InitIcuCultureDataCore() { string text = _sRealName; if (!IsValidCultureName(text, out var indexOfUnderscore)) { return false; } ReadOnlySpan readOnlySpan = default(ReadOnlySpan); if (indexOfUnderscore > 0) { readOnlySpan = text.AsSpan(indexOfUnderscore + 1); text = string.Concat(text.AsSpan(0, indexOfUnderscore), "@collation=", readOnlySpan); } if (!GetLocaleName(text, out _sWindowsName)) { return false; } indexOfUnderscore = _sWindowsName.IndexOf("@collation=", StringComparison.Ordinal); if (indexOfUnderscore >= 0) { _sName = string.Concat(_sWindowsName.AsSpan(0, indexOfUnderscore), "_", readOnlySpan); } else { _sName = _sWindowsName; } _sRealName = _sName; _iLanguage = LCID; if (_iLanguage == 0) { _iLanguage = 4096; } _bNeutral = TwoLetterISOCountryName.Length == 0; _sSpecificCulture = (_bNeutral ? IcuLocaleData.GetSpecificCultureName(_sRealName) : _sRealName); if (indexOfUnderscore > 0 && !_bNeutral && !IsCustomCultureId(_iLanguage)) { _sName = _sWindowsName.Substring(0, indexOfUnderscore); } return true; } internal unsafe static bool GetLocaleName(string localeName, out string windowsName) { char* value = stackalloc char[157]; if (!Interop.Globalization.GetLocaleName(localeName, value, 157)) { windowsName = null; return false; } windowsName = new string(value); return true; } private string IcuGetLocaleInfo(LocaleStringData type, string uiCultureName = null) { return IcuGetLocaleInfo(_sWindowsName, type, uiCultureName); } private unsafe string IcuGetLocaleInfo(string localeName, LocaleStringData type, string uiCultureName = null) { if (type == LocaleStringData.NegativeInfinitySymbol) { return IcuGetLocaleInfo(localeName, LocaleStringData.NegativeSign) + IcuGetLocaleInfo(localeName, LocaleStringData.PositiveInfinitySymbol); } char* value = stackalloc char[100]; if (!Interop.Globalization.GetLocaleInfoString(localeName, (uint)type, value, 100, uiCultureName)) { return string.Empty; } return new string(value); } private int IcuGetLocaleInfo(LocaleNumberData type) { if (type == LocaleNumberData.CalendarType) { return 0; } int value = 0; bool localeInfoInt = Interop.Globalization.GetLocaleInfoInt(_sWindowsName, (uint)type, ref value); return value; } private int[] IcuGetLocaleInfo(LocaleGroupingData type) { int primaryGroupSize = 0; int secondaryGroupSize = 0; bool localeInfoGroupingSizes = Interop.Globalization.GetLocaleInfoGroupingSizes(_sWindowsName, (uint)type, ref primaryGroupSize, ref secondaryGroupSize); if (secondaryGroupSize != 0) { return new int[2] { primaryGroupSize, secondaryGroupSize }; } return new int[1] { primaryGroupSize }; } private string IcuGetTimeFormatString() { return IcuGetTimeFormatString(shortFormat: false); } private unsafe string IcuGetTimeFormatString(bool shortFormat) { char* ptr = stackalloc char[100]; if (!Interop.Globalization.GetLocaleTimeFormat(_sWindowsName, shortFormat, ptr, 100)) { return string.Empty; } ReadOnlySpan span = new ReadOnlySpan(ptr, 100); return ConvertIcuTimeFormatString(span.Slice(0, span.IndexOf('\0'))); } private static CultureData IcuGetCultureDataFromRegionName(string regionName) { return null; } private string IcuGetLanguageDisplayName(string cultureName) { return IcuGetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName, CultureInfo.CurrentUICulture.Name); } private static string IcuGetRegionDisplayName() { return null; } internal static bool IcuIsEnsurePredefinedLocaleName(string name) { return Interop.Globalization.IsPredefinedLocale(name); } private static string ConvertIcuTimeFormatString(ReadOnlySpan icuFormatString) { Span span = stackalloc char[157]; bool flag = false; int length = 0; for (int i = 0; i < icuFormatString.Length; i++) { switch (icuFormatString[i]) { case '\'': span[length++] = icuFormatString[i++]; for (; i < icuFormatString.Length; i++) { char c = icuFormatString[i]; span[length++] = c; if (c == '\'') { break; } } break; case '.': case ':': case 'H': case 'h': case 'm': case 's': span[length++] = icuFormatString[i]; break; case ' ': case '\u00a0': span[length++] = ' '; break; case 'a': if (!flag) { flag = true; span[length++] = 't'; span[length++] = 't'; } break; } } return span.Slice(0, length).ToString(); } private static int IcuLocaleNameToLCID(string cultureName) { int localeDataNumericPart = IcuLocaleData.GetLocaleDataNumericPart(cultureName, IcuLocaleDataParts.Lcid); if (localeDataNumericPart != -1) { return localeDataNumericPart; } return 4096; } private static int IcuGetGeoId(string cultureName) { int localeDataNumericPart = IcuLocaleData.GetLocaleDataNumericPart(cultureName, IcuLocaleDataParts.GeoId); if (localeDataNumericPart != -1) { return localeDataNumericPart; } return Invariant.GeoId; } private static int IcuGetDigitSubstitution(string cultureName) { int localeDataNumericPart = IcuLocaleData.GetLocaleDataNumericPart(cultureName, IcuLocaleDataParts.DigitSubstitutionOrListSeparator); if (localeDataNumericPart != -1) { return (int)((long)localeDataNumericPart & 0xFFFFL); } return 1; } private static string IcuGetListSeparator(string cultureName) { int localeDataNumericPart = IcuLocaleData.GetLocaleDataNumericPart(cultureName, IcuLocaleDataParts.DigitSubstitutionOrListSeparator); if (localeDataNumericPart != -1) { switch (localeDataNumericPart & 0xFFFF0000u) { case 0L: return ","; case 65536L: return ";"; case 131072L: return "،"; case 196608L: return "؛"; case 262144L: return ",,"; } } return ","; } private static string IcuGetThreeLetterWindowsLanguageName(string cultureName) { return IcuLocaleData.GetThreeLetterWindowsLanguageName(cultureName) ?? "ZZZ"; } private static CultureInfo[] IcuEnumCultures(CultureTypes types) { if ((types & (CultureTypes.NeutralCultures | CultureTypes.SpecificCultures)) == 0) { return Array.Empty(); } int locales = Interop.Globalization.GetLocales(null, 0); if (locales <= 0) { return Array.Empty(); } char[] array = new char[locales]; locales = Interop.Globalization.GetLocales(array, locales); if (locales <= 0) { return Array.Empty(); } bool flag = (types & CultureTypes.NeutralCultures) != 0; bool flag2 = (types & CultureTypes.SpecificCultures) != 0; List list = new List(); if (flag) { list.Add(CultureInfo.InvariantCulture); } int num; for (int i = 0; i < locales; i += num) { num = array[i++]; if (i + num <= locales) { CultureInfo cultureInfo = CultureInfo.GetCultureInfo(new string(array, i, num)); if ((flag && cultureInfo.IsNeutralCulture) || (flag2 && !cultureInfo.IsNeutralCulture)) { list.Add(cultureInfo); } } } return list.ToArray(); } private static string IcuGetConsoleFallbackName(string cultureName) { return IcuLocaleData.GetConsoleUICulture(cultureName); } private static bool IsValidCultureName(string subject, out int indexOfUnderscore) { indexOfUnderscore = -1; if (subject.Length == 0) { return true; } if (subject.Length == 1 || subject.Length > 85) { return false; } bool flag = false; for (int i = 0; i < subject.Length; i++) { char c = subject[i]; switch (c) { case '-': case '_': if (i == 0 || i == subject.Length - 1) { return false; } if (subject[i - 1] == '_' || subject[i - 1] == '-') { return false; } if (c == '_') { if (flag) { return false; } flag = true; indexOfUnderscore = i; } break; default: return false; case '\0': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': break; } } return true; } internal unsafe static string GetLocaleInfoEx(string localeName, uint field) { char* ptr = stackalloc char[530]; int localeInfoEx = GetLocaleInfoEx(localeName, field, ptr, 530); if (localeInfoEx > 0) { return new string(ptr); } return null; } internal unsafe static int GetLocaleInfoExInt(string localeName, uint field) { field |= 0x20000000u; int result = 0; GetLocaleInfoEx(localeName, field, (char*)(&result), 4); return result; } internal unsafe static int GetLocaleInfoEx(string lpLocaleName, uint lcType, char* lpLCData, int cchData) { return Interop.Kernel32.GetLocaleInfoEx(lpLocaleName, lcType, lpLCData, cchData); } private string NlsGetLocaleInfo(LocaleStringData type) { return NlsGetLocaleInfo(_sRealName, type); } private string NlsGetLocaleInfo(string localeName, LocaleStringData type) { return GetLocaleInfoFromLCType(localeName, (uint)type, _bUseOverrides); } private int NlsGetLocaleInfo(LocaleNumberData type) { uint num = (uint)type; if (!_bUseOverrides) { num |= 0x80000000u; } return GetLocaleInfoExInt(_sRealName, num); } private int[] NlsGetLocaleInfo(LocaleGroupingData type) { return ConvertWin32GroupString(GetLocaleInfoFromLCType(_sRealName, (uint)type, _bUseOverrides)); } internal static bool NlsIsEnsurePredefinedLocaleName(string name) { return GetLocaleInfoExInt(name, 125u) != 1; } private string NlsGetTimeFormatString() { return ReescapeWin32String(GetLocaleInfoFromLCType(_sRealName, 4099u, _bUseOverrides)); } private int NlsGetFirstDayOfWeek() { int localeInfoExInt = GetLocaleInfoExInt(_sRealName, 0x100Cu | ((!_bUseOverrides) ? 2147483648u : 0u)); return ConvertFirstDayOfWeekMonToSun(localeInfoExInt); } private unsafe static CultureData NlsGetCultureDataFromRegionName(string regionName) { System.Runtime.CompilerServices.Unsafe.SkipInit(out EnumLocaleData value); value.cultureName = null; value.regionName = regionName; Interop.Kernel32.EnumSystemLocalesEx((delegate* unmanaged)(delegate*)(&EnumSystemLocalesProc), 34u, Unsafe.AsPointer(ref value), IntPtr.Zero); if (value.cultureName != null) { return GetCultureData(value.cultureName, useUserOverride: true); } return null; } private string NlsGetLanguageDisplayName(string cultureName) { CultureInfo userDefaultCulture; if (CultureInfo.DefaultThreadCurrentUICulture != null && (userDefaultCulture = CultureInfo.GetUserDefaultCulture()) != null && !CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(userDefaultCulture.Name)) { return NativeName; } return NlsGetLocaleInfo(cultureName, LocaleStringData.LocalizedDisplayName); } private string NlsGetRegionDisplayName() { if (CultureInfo.CurrentUICulture.Name.Equals(CultureInfo.UserDefaultUICulture.Name)) { return NlsGetLocaleInfo(LocaleStringData.LocalizedCountryName); } return NativeCountryName; } private static string GetLocaleInfoFromLCType(string localeName, uint lctype, bool useUserOverride) { if (!useUserOverride) { lctype |= 0x80000000u; } return GetLocaleInfoEx(localeName, lctype) ?? string.Empty; } [return: NotNullIfNotNull("str")] internal static string ReescapeWin32String(string str) { if (str == null) { return null; } StringBuilder stringBuilder = null; bool flag = false; for (int i = 0; i < str.Length; i++) { if (str[i] == '\'') { if (flag) { if (i + 1 < str.Length && str[i + 1] == '\'') { if (stringBuilder == null) { stringBuilder = new StringBuilder(str, 0, i, str.Length * 2); } stringBuilder.Append("\\'"); i++; continue; } flag = false; } else { flag = true; } } else if (str[i] == '\\') { if (stringBuilder == null) { stringBuilder = new StringBuilder(str, 0, i, str.Length * 2); } stringBuilder.Append("\\\\"); continue; } stringBuilder?.Append(str[i]); } if (stringBuilder == null) { return str; } return stringBuilder.ToString(); } [return: NotNullIfNotNull("array")] internal static string[] ReescapeWin32Strings(string[] array) { if (array != null) { for (int i = 0; i < array.Length; i++) { array[i] = ReescapeWin32String(array[i]); } } return array; } private static int[] ConvertWin32GroupString(string win32Str) { if (string.IsNullOrEmpty(win32Str)) { return new int[1] { 3 }; } if (win32Str[0] == '0') { return new int[1]; } int[] array; if (win32Str[^1] == '0') { array = new int[win32Str.Length / 2]; } else { array = new int[win32Str.Length / 2 + 2]; array[^1] = 0; } int num = 0; int num2 = 0; while (num < win32Str.Length && num2 < array.Length) { if (win32Str[num] < '1' || win32Str[num] > '9') { return new int[1] { 3 }; } array[num2] = win32Str[num] - 48; num += 2; num2++; } return array; } private static int ConvertFirstDayOfWeekMonToSun(int iTemp) { iTemp++; if (iTemp > 6) { iTemp = 0; } return iTemp; } [UnmanagedCallersOnly] private unsafe static Interop.BOOL EnumSystemLocalesProc(char* lpLocaleString, uint flags, void* contextHandle) { ref EnumLocaleData reference = ref Unsafe.As(ref *(byte*)contextHandle); try { string text = new string(lpLocaleString); string localeInfoEx = GetLocaleInfoEx(text, 90u); if (localeInfoEx != null && localeInfoEx.Equals(reference.regionName, StringComparison.OrdinalIgnoreCase)) { reference.cultureName = text; return Interop.BOOL.FALSE; } return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } [UnmanagedCallersOnly] private unsafe static Interop.BOOL EnumAllSystemLocalesProc(char* lpLocaleString, uint flags, void* contextHandle) { ref EnumData reference = ref Unsafe.As(ref *(byte*)contextHandle); try { reference.strings.Add(new string(lpLocaleString)); return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } [UnmanagedCallersOnly] private unsafe static Interop.BOOL EnumTimeCallback(char* lpTimeFormatString, void* lParam) { ref EnumData reference = ref Unsafe.As(ref *(byte*)lParam); try { reference.strings.Add(new string(lpTimeFormatString)); return Interop.BOOL.TRUE; } catch (Exception) { return Interop.BOOL.FALSE; } } private unsafe static string[] nativeEnumTimeFormats(string localeName, uint dwFlags, bool useUserOverride) { EnumData value = default(EnumData); value.strings = new List(); Interop.Kernel32.EnumTimeFormatsEx((delegate* unmanaged)(delegate*)(&EnumTimeCallback), localeName, dwFlags, Unsafe.AsPointer(ref value)); if (value.strings.Count > 0) { string[] array = value.strings.ToArray(); if (!useUserOverride && value.strings.Count > 1) { uint lctype = ((dwFlags == 2) ? 121u : 4099u); string localeInfoFromLCType = GetLocaleInfoFromLCType(localeName, lctype, useUserOverride); if (localeInfoFromLCType != "") { string text = array[0]; if (localeInfoFromLCType != text) { array[0] = array[1]; array[1] = text; } } } return array; } return null; } private static int NlsLocaleNameToLCID(string cultureName) { return Interop.Kernel32.LocaleNameToLCID(cultureName, 134217728u); } private string NlsGetThreeLetterWindowsLanguageName(string cultureName) { return NlsGetLocaleInfo(cultureName, LocaleStringData.AbbreviatedWindowsLanguageName); } private unsafe static CultureInfo[] NlsEnumCultures(CultureTypes types) { uint num = 0u; if ((types & (CultureTypes.InstalledWin32Cultures | CultureTypes.ReplacementCultures | CultureTypes.FrameworkCultures)) != 0) { num |= 0x30u; } if ((types & CultureTypes.NeutralCultures) != 0) { num |= 0x10u; } if ((types & CultureTypes.SpecificCultures) != 0) { num |= 0x20u; } if ((types & CultureTypes.UserCustomCulture) != 0) { num |= 2u; } if ((types & CultureTypes.ReplacementCultures) != 0) { num |= 2u; } EnumData value = default(EnumData); value.strings = new List(); Interop.Kernel32.EnumSystemLocalesEx((delegate* unmanaged)(delegate*)(&EnumAllSystemLocalesProc), num, Unsafe.AsPointer(ref value), IntPtr.Zero); CultureInfo[] array = new CultureInfo[value.strings.Count]; for (int i = 0; i < array.Length; i++) { array[i] = new CultureInfo(value.strings[i]); } return array; } private string NlsGetConsoleFallbackName(string cultureName) { return NlsGetLocaleInfo(cultureName, LocaleStringData.ConsoleFallbackName); } private unsafe bool InitCultureDataCore() { char* ptr = stackalloc char[85]; if (!GlobalizationMode.UseNls) { if (InitIcuCultureDataCore()) { return GetLocaleInfoEx(_sRealName, 92u, ptr, 85) != 0; } return false; } string sRealName = _sRealName; int localeInfoEx = GetLocaleInfoEx(sRealName, 92u, ptr, 85); if (localeInfoEx == 0) { return false; } _sRealName = new string(ptr, 0, localeInfoEx - 1); sRealName = _sRealName; if (GetLocaleInfoEx(sRealName, 536871025u, ptr, 2) == 0) { return false; } _bNeutral = *(uint*)ptr != 0; _sWindowsName = sRealName; if (_bNeutral) { _sName = sRealName; localeInfoEx = Interop.Kernel32.ResolveLocaleName(sRealName, ptr, 85); if (localeInfoEx < 1) { return false; } _sSpecificCulture = new string(ptr, 0, localeInfoEx - 1); } else { _sSpecificCulture = sRealName; _sName = sRealName; if (GetLocaleInfoEx(sRealName, 536870913u, ptr, 2) == 0) { return false; } _iLanguage = *(int*)ptr; if (!IsCustomCultureId(_iLanguage)) { int num = sRealName.IndexOf('_'); if (num > 0) { _sName = sRealName.Substring(0, num); } } } return true; } private void InitUserOverride(bool useUserOverride) { _bUseOverrides = useUserOverride && _sWindowsName == CultureInfo.UserDefaultLocaleName; } internal unsafe static CultureData GetCurrentRegionData() { Span span = stackalloc char[10]; int userGeoID = Interop.Kernel32.GetUserGeoID(16); if (userGeoID != -1) { int geoInfo; fixed (char* lpGeoData = span) { geoInfo = Interop.Kernel32.GetGeoInfo(userGeoID, 4, lpGeoData, span.Length, 0); } if (geoInfo != 0) { geoInfo -= ((span[geoInfo - 1] == '\0') ? 1 : 0); CultureData cultureDataForRegion = GetCultureDataForRegion(span.Slice(0, geoInfo).ToString(), useUserOverride: true); if (cultureDataForRegion != null) { return cultureDataForRegion; } } } return CultureInfo.CurrentCulture._cultureData; } private unsafe static string LCIDToLocaleName(int culture) { char* ptr = stackalloc char[86]; int num = Interop.Kernel32.LCIDToLocaleName(culture, ptr, 86, 134217728u); if (num > 0) { return new string(ptr); } return null; } private string[] GetTimeFormatsCore(bool shortFormat) { if (GlobalizationMode.UseNls) { return ReescapeWin32Strings(nativeEnumTimeFormats(_sWindowsName, shortFormat ? 2u : 0u, _bUseOverrides)); } string text = IcuGetTimeFormatString(shortFormat); if (_bUseOverrides) { string localeInfoFromLCType = GetLocaleInfoFromLCType(_sWindowsName, shortFormat ? 121u : 4099u, useUserOverride: true); if (localeInfoFromLCType != text) { return new string[2] { localeInfoFromLCType, text }; } return new string[1] { localeInfoFromLCType }; } return new string[1] { text }; } private int GetAnsiCodePage(string cultureName) { return NlsGetLocaleInfo(LocaleNumberData.AnsiCodePage); } private int GetOemCodePage(string cultureName) { return NlsGetLocaleInfo(LocaleNumberData.OemCodePage); } private int GetMacCodePage(string cultureName) { return NlsGetLocaleInfo(LocaleNumberData.MacCodePage); } private int GetEbcdicCodePage(string cultureName) { return NlsGetLocaleInfo(LocaleNumberData.EbcdicCodePage); } } public class CultureInfo : IFormatProvider, ICloneable { private bool _isReadOnly; private CompareInfo _compareInfo; private TextInfo _textInfo; internal NumberFormatInfo _numInfo; internal DateTimeFormatInfo _dateTimeInfo; private Calendar _calendar; internal CultureData _cultureData; internal bool _isInherited; private CultureInfo _consoleFallbackCulture; internal string _name; private string _nonSortName; private string _sortName; private static volatile CultureInfo s_userDefaultCulture; private static volatile CultureInfo s_userDefaultUICulture; private static readonly CultureInfo s_InvariantCultureInfo = new CultureInfo(CultureData.Invariant, isReadOnly: true); private static volatile CultureInfo s_DefaultThreadCurrentUICulture; private static volatile CultureInfo s_DefaultThreadCurrentCulture; [ThreadStatic] private static CultureInfo s_currentThreadCulture; [ThreadStatic] private static CultureInfo s_currentThreadUICulture; private static AsyncLocal s_asyncLocalCurrentCulture; private static AsyncLocal s_asyncLocalCurrentUICulture; private static volatile Dictionary s_cachedCulturesByName; private static volatile Dictionary s_cachedCulturesByLcid; private CultureInfo _parent; internal const int LOCALE_NEUTRAL = 0; private const int LOCALE_USER_DEFAULT = 1024; private const int LOCALE_SYSTEM_DEFAULT = 2048; internal const int LOCALE_CUSTOM_UNSPECIFIED = 4096; internal const int LOCALE_CUSTOM_DEFAULT = 3072; internal const int LOCALE_INVARIANT = 127; public static CultureInfo CurrentCulture { get { return s_currentThreadCulture ?? s_DefaultThreadCurrentCulture ?? s_userDefaultCulture ?? InitializeUserDefaultCulture(); } set { if (value == null) { throw new ArgumentNullException("value"); } if (s_asyncLocalCurrentCulture == null) { Interlocked.CompareExchange(ref s_asyncLocalCurrentCulture, new AsyncLocal(AsyncLocalSetCurrentCulture), null); } s_asyncLocalCurrentCulture.Value = value; } } public static CultureInfo CurrentUICulture { get { return s_currentThreadUICulture ?? s_DefaultThreadCurrentUICulture ?? UserDefaultUICulture; } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyCultureName(value, throwException: true); if (s_asyncLocalCurrentUICulture == null) { Interlocked.CompareExchange(ref s_asyncLocalCurrentUICulture, new AsyncLocal(AsyncLocalSetCurrentUICulture), null); } s_asyncLocalCurrentUICulture.Value = value; } } internal static CultureInfo UserDefaultUICulture => s_userDefaultUICulture ?? InitializeUserDefaultUICulture(); public static CultureInfo InstalledUICulture => s_userDefaultCulture ?? InitializeUserDefaultCulture(); public static CultureInfo? DefaultThreadCurrentCulture { get { return s_DefaultThreadCurrentCulture; } set { s_DefaultThreadCurrentCulture = value; } } public static CultureInfo? DefaultThreadCurrentUICulture { get { return s_DefaultThreadCurrentUICulture; } set { if (value != null) { VerifyCultureName(value, throwException: true); } s_DefaultThreadCurrentUICulture = value; } } public static CultureInfo InvariantCulture => s_InvariantCultureInfo; public virtual CultureInfo Parent { get { if (_parent == null) { string text = _cultureData.ParentName; if (text == "zh") { if (_name.Length == 5 && _name[2] == '-') { if ((_name[3] == 'C' && _name[4] == 'N') || (_name[3] == 'S' && _name[4] == 'G')) { text = "zh-Hans"; } else if ((_name[3] == 'H' && _name[4] == 'K') || (_name[3] == 'M' && _name[4] == 'O') || (_name[3] == 'T' && _name[4] == 'W')) { text = "zh-Hant"; } } else if (_name.Length > 8 && MemoryExtensions.Equals(_name.AsSpan(2, 4), "-Han", StringComparison.Ordinal) && _name[7] == '-') { if (_name[6] == 't') { text = "zh-Hant"; } else if (_name[6] == 's') { text = "zh-Hans"; } } } Interlocked.CompareExchange(value: (!string.IsNullOrEmpty(text)) ? (CreateCultureInfoNoThrow(text, _cultureData.UseUserOverride) ?? InvariantCulture) : InvariantCulture, location1: ref _parent, comparand: null); } return _parent; } } public virtual int LCID => _cultureData.LCID; public virtual int KeyboardLayoutId => _cultureData.KeyboardLayoutId; public virtual string Name { get { string text = _nonSortName; if (text == null) { string obj = _cultureData.Name ?? string.Empty; string text2 = obj; _nonSortName = obj; text = text2; } return text; } } internal string SortName => _sortName ?? (_sortName = _cultureData.SortName); public string IetfLanguageTag { get { string name = Name; if (!(name == "zh-CHT")) { if (name == "zh-CHS") { return "zh-Hans"; } return Name; } return "zh-Hant"; } } public virtual string DisplayName => _cultureData.DisplayName; public virtual string NativeName => _cultureData.NativeName; public virtual string EnglishName => _cultureData.EnglishName; public virtual string TwoLetterISOLanguageName => _cultureData.TwoLetterISOLanguageName; public virtual string ThreeLetterISOLanguageName => _cultureData.ThreeLetterISOLanguageName; public virtual string ThreeLetterWindowsLanguageName => _cultureData.ThreeLetterWindowsLanguageName; public virtual CompareInfo CompareInfo => _compareInfo ?? (_compareInfo = (UseUserOverride ? GetCultureInfo(_name).CompareInfo : new CompareInfo(this))); public virtual TextInfo TextInfo { get { if (_textInfo == null) { TextInfo textInfo = new TextInfo(_cultureData); textInfo.SetReadOnlyState(_isReadOnly); _textInfo = textInfo; } return _textInfo; } } public virtual bool IsNeutralCulture => _cultureData.IsNeutralCulture; public CultureTypes CultureTypes { get { CultureTypes cultureTypes = (_cultureData.IsNeutralCulture ? CultureTypes.NeutralCultures : CultureTypes.SpecificCultures); _ = CultureData.IsWin32Installed; cultureTypes |= CultureTypes.InstalledWin32Cultures; if (_cultureData.IsSupplementalCustomCulture) { cultureTypes |= CultureTypes.UserCustomCulture; } if (_cultureData.IsReplacementCulture) { cultureTypes |= CultureTypes.ReplacementCultures; } return cultureTypes; } } public virtual NumberFormatInfo NumberFormat { get { if (_numInfo == null) { NumberFormatInfo numberFormatInfo = new NumberFormatInfo(_cultureData); numberFormatInfo._isReadOnly = _isReadOnly; Interlocked.CompareExchange(ref _numInfo, numberFormatInfo, null); } return _numInfo; } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyWritable(); _numInfo = value; } } public virtual DateTimeFormatInfo DateTimeFormat { get { if (_dateTimeInfo == null) { DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo(_cultureData, Calendar); dateTimeFormatInfo._isReadOnly = _isReadOnly; Interlocked.CompareExchange(ref _dateTimeInfo, dateTimeFormatInfo, null); } return _dateTimeInfo; } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyWritable(); _dateTimeInfo = value; } } public virtual Calendar Calendar { get { if (_calendar == null) { Calendar defaultCalendar = _cultureData.DefaultCalendar; Interlocked.MemoryBarrier(); defaultCalendar.SetReadOnlyState(_isReadOnly); _calendar = defaultCalendar; } return _calendar; } } public virtual Calendar[] OptionalCalendars { get { if (GlobalizationMode.Invariant) { return new GregorianCalendar[1] { new GregorianCalendar() }; } CalendarId[] calendarIds = _cultureData.CalendarIds; Calendar[] array = new Calendar[calendarIds.Length]; for (int i = 0; i < array.Length; i++) { array[i] = GetCalendarInstance(calendarIds[i]); } return array; } } public bool UseUserOverride => _cultureData.UseUserOverride; public bool IsReadOnly => _isReadOnly; internal bool HasInvariantCultureName => Name == InvariantCulture.Name; private static Dictionary CachedCulturesByName { get { Dictionary dictionary = s_cachedCulturesByName; if (dictionary == null) { dictionary = new Dictionary(); dictionary = Interlocked.CompareExchange(ref s_cachedCulturesByName, dictionary, null) ?? dictionary; } return dictionary; } } private static Dictionary CachedCulturesByLcid { get { Dictionary dictionary = s_cachedCulturesByLcid; if (dictionary == null) { dictionary = new Dictionary(); dictionary = Interlocked.CompareExchange(ref s_cachedCulturesByLcid, dictionary, null) ?? dictionary; } return dictionary; } } internal static string? UserDefaultLocaleName { get; set; } = GetUserDefaultLocaleName(); private static void AsyncLocalSetCurrentCulture(AsyncLocalValueChangedArgs args) { s_currentThreadCulture = args.CurrentValue; } private static void AsyncLocalSetCurrentUICulture(AsyncLocalValueChangedArgs args) { s_currentThreadUICulture = args.CurrentValue; } private static CultureInfo InitializeUserDefaultCulture() { Interlocked.CompareExchange(ref s_userDefaultCulture, GetUserDefaultCulture(), null); return s_userDefaultCulture; } private static CultureInfo InitializeUserDefaultUICulture() { Interlocked.CompareExchange(ref s_userDefaultUICulture, GetUserDefaultUICulture(), null); return s_userDefaultUICulture; } private static string GetCultureNotSupportedExceptionMessage() { if (!GlobalizationMode.Invariant) { return SR.Argument_CultureNotSupported; } return SR.Argument_CultureNotSupportedInInvariantMode; } public CultureInfo(string name) : this(name, useUserOverride: true) { } public CultureInfo(string name, bool useUserOverride) { if (name == null) { throw new ArgumentNullException("name"); } CultureData cultureData = CultureData.GetCultureData(name, useUserOverride); if (cultureData == null) { throw new CultureNotFoundException("name", name, GetCultureNotSupportedExceptionMessage()); } _cultureData = cultureData; _name = _cultureData.CultureName; _isInherited = GetType() != typeof(CultureInfo); } private CultureInfo(CultureData cultureData, bool isReadOnly = false) { _cultureData = cultureData; _name = cultureData.CultureName; _isReadOnly = isReadOnly; } private static CultureInfo CreateCultureInfoNoThrow(string name, bool useUserOverride) { CultureData cultureData = CultureData.GetCultureData(name, useUserOverride); if (cultureData == null) { return null; } return new CultureInfo(cultureData); } public CultureInfo(int culture) : this(culture, useUserOverride: true) { } public CultureInfo(int culture, bool useUserOverride) { if (culture < 0) { throw new ArgumentOutOfRangeException("culture", SR.ArgumentOutOfRange_NeedPosNum); } switch (culture) { case 0: case 1024: case 2048: case 3072: case 4096: throw new CultureNotFoundException("culture", culture, SR.Argument_CultureNotSupported); } _cultureData = CultureData.GetCultureData(culture, useUserOverride); _isInherited = GetType() != typeof(CultureInfo); _name = _cultureData.CultureName; } internal CultureInfo(string cultureName, string textAndCompareCultureName) { if (cultureName == null) { throw new ArgumentNullException("cultureName", SR.ArgumentNull_String); } CultureData cultureData = CultureData.GetCultureData(cultureName, useUserOverride: false) ?? throw new CultureNotFoundException("cultureName", cultureName, GetCultureNotSupportedExceptionMessage()); _cultureData = cultureData; _name = _cultureData.CultureName; CultureInfo cultureInfo = GetCultureInfo(textAndCompareCultureName); _compareInfo = cultureInfo.CompareInfo; _textInfo = cultureInfo.TextInfo; } private static CultureInfo GetCultureByName(string name) { try { return new CultureInfo(name) { _isReadOnly = true }; } catch (ArgumentException) { return InvariantCulture; } } public static CultureInfo CreateSpecificCulture(string name) { CultureInfo cultureInfo; try { cultureInfo = new CultureInfo(name); } catch (ArgumentException) { cultureInfo = null; for (int i = 0; i < name.Length; i++) { if ('-' == name[i]) { try { cultureInfo = new CultureInfo(name.Substring(0, i)); } catch (ArgumentException) { throw; } break; } } if (cultureInfo == null) { throw; } } if (!cultureInfo.IsNeutralCulture) { return cultureInfo; } return new CultureInfo(cultureInfo._cultureData.SpecificCultureName); } internal static bool VerifyCultureName(string cultureName, bool throwException) { foreach (char c in cultureName) { if (!char.IsLetterOrDigit(c) && c != '-' && c != '_') { if (throwException) { throw new ArgumentException(SR.Format(SR.Argument_InvalidResourceCultureName, cultureName)); } return false; } } return true; } internal static bool VerifyCultureName(CultureInfo culture, bool throwException) { if (!culture._isInherited) { return true; } return VerifyCultureName(culture.Name, throwException); } public static CultureInfo[] GetCultures(CultureTypes types) { if ((types & CultureTypes.UserCustomCulture) == CultureTypes.UserCustomCulture) { types |= CultureTypes.ReplacementCultures; } return CultureData.GetCultures(types); } public override bool Equals([NotNullWhen(true)] object? value) { if (this == value) { return true; } if (value is CultureInfo cultureInfo) { if (Name.Equals(cultureInfo.Name)) { return CompareInfo.Equals(cultureInfo.CompareInfo); } return false; } return false; } public override int GetHashCode() { return Name.GetHashCode() + CompareInfo.GetHashCode(); } public override string ToString() { return _name; } public virtual object? GetFormat(Type? formatType) { if (formatType == typeof(NumberFormatInfo)) { return NumberFormat; } if (formatType == typeof(DateTimeFormatInfo)) { return DateTimeFormat; } return null; } public void ClearCachedData() { UserDefaultLocaleName = GetUserDefaultLocaleName(); s_userDefaultCulture = GetUserDefaultCulture(); s_userDefaultUICulture = GetUserDefaultUICulture(); RegionInfo.s_currentRegionInfo = null; TimeZone.ResetTimeZone(); TimeZoneInfo.ClearCachedData(); s_cachedCulturesByLcid = null; s_cachedCulturesByName = null; CultureData.ClearCachedData(); } internal static Calendar GetCalendarInstance(CalendarId calType) { if (calType == CalendarId.GREGORIAN) { return new GregorianCalendar(); } return GetCalendarInstanceRare(calType); } internal static Calendar GetCalendarInstanceRare(CalendarId calType) { switch (calType) { case CalendarId.GREGORIAN_US: case CalendarId.GREGORIAN_ME_FRENCH: case CalendarId.GREGORIAN_ARABIC: case CalendarId.GREGORIAN_XLIT_ENGLISH: case CalendarId.GREGORIAN_XLIT_FRENCH: return new GregorianCalendar((GregorianCalendarTypes)calType); case CalendarId.TAIWAN: return new TaiwanCalendar(); case CalendarId.JAPAN: return new JapaneseCalendar(); case CalendarId.KOREA: return new KoreanCalendar(); case CalendarId.THAI: return new ThaiBuddhistCalendar(); case CalendarId.HIJRI: return new HijriCalendar(); case CalendarId.HEBREW: return new HebrewCalendar(); case CalendarId.UMALQURA: return new UmAlQuraCalendar(); case CalendarId.PERSIAN: return new PersianCalendar(); default: return new GregorianCalendar(); } } public CultureInfo GetConsoleFallbackUICulture() { CultureInfo cultureInfo = _consoleFallbackCulture; if (cultureInfo == null) { cultureInfo = CreateSpecificCulture(_cultureData.SCONSOLEFALLBACKNAME); cultureInfo._isReadOnly = true; _consoleFallbackCulture = cultureInfo; } return cultureInfo; } public virtual object Clone() { CultureInfo cultureInfo = (CultureInfo)MemberwiseClone(); cultureInfo._isReadOnly = false; if (!_isInherited) { if (_dateTimeInfo != null) { cultureInfo._dateTimeInfo = (DateTimeFormatInfo)_dateTimeInfo.Clone(); } if (_numInfo != null) { cultureInfo._numInfo = (NumberFormatInfo)_numInfo.Clone(); } } else { cultureInfo.DateTimeFormat = (DateTimeFormatInfo)DateTimeFormat.Clone(); cultureInfo.NumberFormat = (NumberFormatInfo)NumberFormat.Clone(); } if (_textInfo != null) { cultureInfo._textInfo = (TextInfo)_textInfo.Clone(); } if (_dateTimeInfo != null && _dateTimeInfo.Calendar == _calendar) { cultureInfo._calendar = cultureInfo.DateTimeFormat.Calendar; } else if (_calendar != null) { cultureInfo._calendar = (Calendar)_calendar.Clone(); } return cultureInfo; } public static CultureInfo ReadOnly(CultureInfo ci) { if (ci == null) { throw new ArgumentNullException("ci"); } if (ci.IsReadOnly) { return ci; } CultureInfo cultureInfo = (CultureInfo)ci.MemberwiseClone(); if (!ci.IsNeutralCulture) { if (!ci._isInherited) { if (ci._dateTimeInfo != null) { cultureInfo._dateTimeInfo = DateTimeFormatInfo.ReadOnly(ci._dateTimeInfo); } if (ci._numInfo != null) { cultureInfo._numInfo = NumberFormatInfo.ReadOnly(ci._numInfo); } } else { cultureInfo.DateTimeFormat = DateTimeFormatInfo.ReadOnly(ci.DateTimeFormat); cultureInfo.NumberFormat = NumberFormatInfo.ReadOnly(ci.NumberFormat); } } if (ci._textInfo != null) { cultureInfo._textInfo = System.Globalization.TextInfo.ReadOnly(ci._textInfo); } if (ci._calendar != null) { cultureInfo._calendar = System.Globalization.Calendar.ReadOnly(ci._calendar); } cultureInfo._isReadOnly = true; return cultureInfo; } private void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } public static CultureInfo GetCultureInfo(int culture) { if (culture <= 0) { throw new ArgumentOutOfRangeException("culture", SR.ArgumentOutOfRange_NeedPosNum); } Dictionary cachedCulturesByLcid = CachedCulturesByLcid; CultureInfo value; lock (cachedCulturesByLcid) { if (cachedCulturesByLcid.TryGetValue(culture, out value)) { return value; } } try { value = new CultureInfo(culture, useUserOverride: false) { _isReadOnly = true }; } catch (ArgumentException) { throw new CultureNotFoundException("culture", culture, GetCultureNotSupportedExceptionMessage()); } lock (cachedCulturesByLcid) { cachedCulturesByLcid[culture] = value; return value; } } public static CultureInfo GetCultureInfo(string name) { if (name == null) { throw new ArgumentNullException("name"); } name = CultureData.AnsiToLower(name); Dictionary cachedCulturesByName = CachedCulturesByName; CultureInfo value; lock (cachedCulturesByName) { if (cachedCulturesByName.TryGetValue(name, out value)) { return value; } } value = CreateCultureInfoNoThrow(name, useUserOverride: false) ?? throw new CultureNotFoundException("name", name, GetCultureNotSupportedExceptionMessage()); value._isReadOnly = true; name = CultureData.AnsiToLower(value._name); lock (cachedCulturesByName) { cachedCulturesByName[name] = value; return value; } } public static CultureInfo GetCultureInfo(string name, string altName) { if (name == null) { throw new ArgumentNullException("name"); } if (altName == null) { throw new ArgumentNullException("altName"); } name = CultureData.AnsiToLower(name); altName = CultureData.AnsiToLower(altName); string key = name + "\ufffd" + altName; Dictionary cachedCulturesByName = CachedCulturesByName; CultureInfo value; lock (cachedCulturesByName) { if (cachedCulturesByName.TryGetValue(key, out value)) { return value; } } try { value = new CultureInfo(name, altName) { _isReadOnly = true }; value.TextInfo.SetReadOnlyState(readOnly: true); } catch (ArgumentException) { throw new CultureNotFoundException("name/altName", SR.Format(SR.Argument_OneOfCulturesNotSupported, name, altName)); } lock (cachedCulturesByName) { cachedCulturesByName[key] = value; return value; } } public static CultureInfo GetCultureInfo(string name, bool predefinedOnly) { if (name == null) { throw new ArgumentNullException("name"); } if (predefinedOnly && !GlobalizationMode.Invariant && (GlobalizationMode.UseNls ? (!CultureData.NlsIsEnsurePredefinedLocaleName(name)) : (!CultureData.IcuIsEnsurePredefinedLocaleName(name)))) { throw new CultureNotFoundException("name", name, SR.Format(SR.Argument_InvalidPredefinedCultureName, name)); } return GetCultureInfo(name); } public static CultureInfo GetCultureInfoByIetfLanguageTag(string name) { if (name == "zh-CHT" || name == "zh-CHS") { throw new CultureNotFoundException("name", SR.Format(SR.Argument_CultureIetfNotSupported, name)); } CultureInfo cultureInfo = GetCultureInfo(name); if (cultureInfo.LCID > 65535 || cultureInfo.LCID == 1034) { throw new CultureNotFoundException("name", SR.Format(SR.Argument_CultureIetfNotSupported, name)); } return cultureInfo; } internal static CultureInfo GetUserDefaultCulture() { if (GlobalizationMode.Invariant) { return InvariantCulture; } string userDefaultLocaleName = UserDefaultLocaleName; if (userDefaultLocaleName == null) { return InvariantCulture; } return GetCultureByName(userDefaultLocaleName); } private unsafe static CultureInfo GetUserDefaultUICulture() { if (GlobalizationMode.Invariant) { return InvariantCulture; } uint num = 0u; uint num2 = 0u; if (Interop.Kernel32.GetUserPreferredUILanguages(8u, &num, null, &num2) != 0) { Span span = ((num2 > 256) ? ((Span)new char[num2]) : stackalloc char[(int)num2]); Span span2 = span; fixed (char* pwszLanguagesBuffer = span2) { if (Interop.Kernel32.GetUserPreferredUILanguages(8u, &num, pwszLanguagesBuffer, &num2) != 0) { return GetCultureByName(span2.ToString()); } } } return InitializeUserDefaultCulture(); } private static string GetUserDefaultLocaleName() { string text; if (!GlobalizationMode.Invariant) { text = CultureData.GetLocaleInfoEx(null, 92u); if (text == null) { return CultureData.GetLocaleInfoEx("!x-sys-default-locale", 92u); } } else { text = InvariantCulture.Name; } return text; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class CultureNotFoundException : ArgumentException { private readonly string _invalidCultureName; private readonly int? _invalidCultureId; public virtual int? InvalidCultureId => _invalidCultureId; public virtual string? InvalidCultureName => _invalidCultureName; private static string DefaultMessage => SR.Argument_CultureNotSupported; private string? FormattedInvalidCultureId { get { if (!InvalidCultureId.HasValue) { return InvalidCultureName; } return string.Format(CultureInfo.InvariantCulture, "{0} (0x{0:x4})", InvalidCultureId.Value); } } public override string Message { get { string message = base.Message; if (_invalidCultureId.HasValue || _invalidCultureName != null) { string text = SR.Format(SR.Argument_CultureInvalidIdentifier, FormattedInvalidCultureId); if (message == null) { return text; } return message + "\r\n" + text; } return message; } } public CultureNotFoundException() : base(DefaultMessage) { } public CultureNotFoundException(string? message) : base(message) { } public CultureNotFoundException(string? paramName, string? message) : base(message, paramName) { } public CultureNotFoundException(string? message, Exception? innerException) : base(message, innerException) { } public CultureNotFoundException(string? paramName, string? invalidCultureName, string? message) : base(message, paramName) { _invalidCultureName = invalidCultureName; } public CultureNotFoundException(string? message, string? invalidCultureName, Exception? innerException) : base(message, innerException) { _invalidCultureName = invalidCultureName; } public CultureNotFoundException(string? message, int invalidCultureId, Exception? innerException) : base(message, innerException) { _invalidCultureId = invalidCultureId; } public CultureNotFoundException(string? paramName, int invalidCultureId, string? message) : base(message, paramName) { _invalidCultureId = invalidCultureId; } protected CultureNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { _invalidCultureId = (int?)info.GetValue("InvalidCultureId", typeof(int?)); _invalidCultureName = (string)info.GetValue("InvalidCultureName", typeof(string)); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("InvalidCultureId", _invalidCultureId, typeof(int?)); info.AddValue("InvalidCultureName", _invalidCultureName, typeof(string)); } } [Flags] public enum CultureTypes { NeutralCultures = 1, SpecificCultures = 2, InstalledWin32Cultures = 4, AllCultures = 7, UserCustomCulture = 8, ReplacementCultures = 0x10, [Obsolete("CultureTypes.WindowsOnlyCultures has been deprecated. Use other values in CultureTypes instead.")] WindowsOnlyCultures = 0x20, [Obsolete("CultureTypes.FrameworkCultures has been deprecated. Use other values in CultureTypes instead.")] FrameworkCultures = 0x40 } [Flags] internal enum MonthNameStyles { Regular = 0, Genitive = 1, LeapYear = 2 } [Flags] internal enum DateTimeFormatFlags { None = 0, UseGenitiveMonth = 1, UseLeapYearMonth = 2, UseSpacesInMonthNames = 4, UseHebrewRule = 8, UseSpacesInDayNames = 0x10, UseDigitPrefixInTokens = 0x20, NotInitialized = -1 } public sealed class DateTimeFormatInfo : IFormatProvider, ICloneable { internal sealed class TokenHashValue { internal string tokenString; internal TokenType tokenType; internal int tokenValue; internal TokenHashValue(string tokenString, TokenType tokenType, int tokenValue) { this.tokenString = tokenString; this.tokenType = tokenType; this.tokenValue = tokenValue; } } private static volatile DateTimeFormatInfo s_invariantInfo; private readonly CultureData _cultureData; private string _name; private string _langName; private CompareInfo _compareInfo; private CultureInfo _cultureInfo; private string amDesignator; private string pmDesignator; private string dateSeparator; private string generalShortTimePattern; private string generalLongTimePattern; private string timeSeparator; private string monthDayPattern; private string dateTimeOffsetPattern; private Calendar calendar; private int firstDayOfWeek = -1; private int calendarWeekRule = -1; private string fullDateTimePattern; private string[] abbreviatedDayNames; private string[] m_superShortDayNames; private string[] dayNames; private string[] abbreviatedMonthNames; private string[] monthNames; private string[] genitiveMonthNames; private string[] m_genitiveAbbreviatedMonthNames; private string[] leapYearMonthNames; private string longDatePattern; private string shortDatePattern; private string yearMonthPattern; private string longTimePattern; private string shortTimePattern; private string[] allYearMonthPatterns; private string[] allShortDatePatterns; private string[] allLongDatePatterns; private string[] allShortTimePatterns; private string[] allLongTimePatterns; private string[] m_eraNames; private string[] m_abbrevEraNames; private string[] m_abbrevEnglishEraNames; private CalendarId[] optionalCalendars; internal bool _isReadOnly; private DateTimeFormatFlags formatFlags = DateTimeFormatFlags.NotInitialized; private string _decimalSeparator; private string _fullTimeSpanPositivePattern; private string _fullTimeSpanNegativePattern; private TokenHashValue[] _dtfiTokenHash; private static volatile DateTimeFormatInfo s_jajpDTFI; private static volatile DateTimeFormatInfo s_zhtwDTFI; private string CultureName => _name ?? (_name = _cultureData.CultureName); private CultureInfo Culture => _cultureInfo ?? (_cultureInfo = CultureInfo.GetCultureInfo(CultureName)); private string LanguageName => _langName ?? (_langName = _cultureData.TwoLetterISOLanguageName); public static DateTimeFormatInfo InvariantInfo { get { if (s_invariantInfo == null) { DateTimeFormatInfo dateTimeFormatInfo = new DateTimeFormatInfo(); dateTimeFormatInfo.Calendar.SetReadOnlyState(readOnly: true); dateTimeFormatInfo._isReadOnly = true; s_invariantInfo = dateTimeFormatInfo; } return s_invariantInfo; } } public static DateTimeFormatInfo CurrentInfo { get { CultureInfo currentCulture = CultureInfo.CurrentCulture; if (!currentCulture._isInherited) { DateTimeFormatInfo dateTimeInfo = currentCulture._dateTimeInfo; if (dateTimeInfo != null) { return dateTimeInfo; } } return (DateTimeFormatInfo)currentCulture.GetFormat(typeof(DateTimeFormatInfo)); } } public string AMDesignator { get { if (amDesignator == null) { amDesignator = _cultureData.AMDesignator; } return amDesignator; } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } ClearTokenHashTable(); amDesignator = value; } } public Calendar Calendar { get { return calendar; } [MemberNotNull("calendar")] set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } if (value == calendar) { return; } for (int i = 0; i < OptionalCalendars.Length; i++) { if (OptionalCalendars[i] == value.ID) { if (calendar != null) { m_eraNames = null; m_abbrevEraNames = null; m_abbrevEnglishEraNames = null; monthDayPattern = null; dayNames = null; abbreviatedDayNames = null; m_superShortDayNames = null; monthNames = null; abbreviatedMonthNames = null; genitiveMonthNames = null; m_genitiveAbbreviatedMonthNames = null; leapYearMonthNames = null; formatFlags = DateTimeFormatFlags.NotInitialized; allShortDatePatterns = null; allLongDatePatterns = null; allYearMonthPatterns = null; dateTimeOffsetPattern = null; longDatePattern = null; shortDatePattern = null; yearMonthPattern = null; fullDateTimePattern = null; generalShortTimePattern = null; generalLongTimePattern = null; dateSeparator = null; ClearTokenHashTable(); } calendar = value; InitializeOverridableProperties(_cultureData, calendar.ID); return; } } throw new ArgumentOutOfRangeException("value", value, SR.Argument_InvalidCalendar); } } private CalendarId[] OptionalCalendars => optionalCalendars ?? (optionalCalendars = _cultureData.CalendarIds); internal string[] EraNames => m_eraNames ?? (m_eraNames = _cultureData.EraNames(Calendar.ID)); internal string[] AbbreviatedEraNames => m_abbrevEraNames ?? (m_abbrevEraNames = _cultureData.AbbrevEraNames(Calendar.ID)); internal string[] AbbreviatedEnglishEraNames { get { if (m_abbrevEnglishEraNames == null) { m_abbrevEnglishEraNames = _cultureData.AbbreviatedEnglishEraNames(Calendar.ID); } return m_abbrevEnglishEraNames; } } public string DateSeparator { get { if (dateSeparator == null) { dateSeparator = _cultureData.DateSeparator(Calendar.ID); } return dateSeparator; } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } ClearTokenHashTable(); dateSeparator = value; } } public DayOfWeek FirstDayOfWeek { get { if (firstDayOfWeek == -1) { firstDayOfWeek = _cultureData.FirstDayOfWeek; } return (DayOfWeek)firstDayOfWeek; } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value < DayOfWeek.Sunday || value > DayOfWeek.Saturday) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, DayOfWeek.Sunday, DayOfWeek.Saturday)); } firstDayOfWeek = (int)value; } } public CalendarWeekRule CalendarWeekRule { get { if (calendarWeekRule == -1) { calendarWeekRule = _cultureData.CalendarWeekRule; } return (CalendarWeekRule)calendarWeekRule; } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value < CalendarWeekRule.FirstDay || value > CalendarWeekRule.FirstFourDayWeek) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek)); } calendarWeekRule = (int)value; } } public string FullDateTimePattern { get { return fullDateTimePattern ?? (fullDateTimePattern = LongDatePattern + " " + LongTimePattern); } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } fullDateTimePattern = value; } } public string LongDatePattern { get { return longDatePattern ?? (longDatePattern = UnclonedLongDatePatterns[0]); } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } longDatePattern = value; OnLongDatePatternChanged(); } } public string LongTimePattern { get { return longTimePattern ?? (longTimePattern = UnclonedLongTimePatterns[0]); } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } longTimePattern = value; OnLongTimePatternChanged(); } } public string MonthDayPattern { get { if (monthDayPattern == null) { monthDayPattern = _cultureData.MonthDay(Calendar.ID); } return monthDayPattern; } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } monthDayPattern = value; } } public string PMDesignator { get { if (pmDesignator == null) { pmDesignator = _cultureData.PMDesignator; } return pmDesignator; } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } ClearTokenHashTable(); pmDesignator = value; } } public string RFC1123Pattern => "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"; public string ShortDatePattern { get { return shortDatePattern ?? (shortDatePattern = UnclonedShortDatePatterns[0]); } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } shortDatePattern = value; OnShortDatePatternChanged(); } } public string ShortTimePattern { get { return shortTimePattern ?? (shortTimePattern = UnclonedShortTimePatterns[0]); } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } shortTimePattern = value; OnShortTimePatternChanged(); } } public string SortableDateTimePattern => "yyyy'-'MM'-'dd'T'HH':'mm':'ss"; internal string GeneralShortTimePattern => generalShortTimePattern ?? (generalShortTimePattern = ShortDatePattern + " " + ShortTimePattern); internal string GeneralLongTimePattern => generalLongTimePattern ?? (generalLongTimePattern = ShortDatePattern + " " + LongTimePattern); internal string DateTimeOffsetPattern { get { if (dateTimeOffsetPattern == null) { bool flag = false; bool flag2 = false; char c = '\''; int num = 0; while (!flag && num < LongTimePattern.Length) { switch (LongTimePattern[num]) { case 'z': flag = !flag2; break; case '"': case '\'': if (flag2 && c == LongTimePattern[num]) { flag2 = false; } else if (!flag2) { c = LongTimePattern[num]; flag2 = true; } break; case '%': case '\\': num++; break; } num++; } dateTimeOffsetPattern = (flag ? (ShortDatePattern + " " + LongTimePattern) : (ShortDatePattern + " " + LongTimePattern + " zzz")); } return dateTimeOffsetPattern; } } public string TimeSeparator { get { if (timeSeparator == null) { timeSeparator = _cultureData.TimeSeparator; } return timeSeparator; } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } ClearTokenHashTable(); timeSeparator = value; } } public string UniversalSortableDateTimePattern => "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"; public string YearMonthPattern { get { return yearMonthPattern ?? (yearMonthPattern = UnclonedYearMonthPatterns[0]); } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } yearMonthPattern = value; OnYearMonthPatternChanged(); } } public string[] AbbreviatedDayNames { get { return (string[])InternalGetAbbreviatedDayOfWeekNames().Clone(); } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } if (value.Length != 7) { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 7), "value"); } CheckNullValue(value, value.Length); ClearTokenHashTable(); abbreviatedDayNames = value; } } public string[] ShortestDayNames { get { return (string[])InternalGetSuperShortDayNames().Clone(); } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } if (value.Length != 7) { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 7), "value"); } CheckNullValue(value, value.Length); m_superShortDayNames = value; } } public string[] DayNames { get { return (string[])InternalGetDayOfWeekNames().Clone(); } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } if (value.Length != 7) { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 7), "value"); } CheckNullValue(value, value.Length); ClearTokenHashTable(); dayNames = value; } } public string[] AbbreviatedMonthNames { get { return (string[])InternalGetAbbreviatedMonthNames().Clone(); } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } if (value.Length != 13) { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), "value"); } CheckNullValue(value, value.Length - 1); ClearTokenHashTable(); abbreviatedMonthNames = value; } } public string[] MonthNames { get { return (string[])InternalGetMonthNames().Clone(); } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } if (value.Length != 13) { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), "value"); } CheckNullValue(value, value.Length - 1); monthNames = value; ClearTokenHashTable(); } } internal bool HasSpacesInMonthNames => (FormatFlags & DateTimeFormatFlags.UseSpacesInMonthNames) != 0; internal bool HasSpacesInDayNames => (FormatFlags & DateTimeFormatFlags.UseSpacesInDayNames) != 0; private string[] AllYearMonthPatterns => GetMergedPatterns(UnclonedYearMonthPatterns, YearMonthPattern); private string[] AllShortDatePatterns => GetMergedPatterns(UnclonedShortDatePatterns, ShortDatePattern); private string[] AllShortTimePatterns => GetMergedPatterns(UnclonedShortTimePatterns, ShortTimePattern); private string[] AllLongDatePatterns => GetMergedPatterns(UnclonedLongDatePatterns, LongDatePattern); private string[] AllLongTimePatterns => GetMergedPatterns(UnclonedLongTimePatterns, LongTimePattern); private string[] UnclonedYearMonthPatterns { get { if (allYearMonthPatterns == null) { allYearMonthPatterns = _cultureData.YearMonths(Calendar.ID); } return allYearMonthPatterns; } } private string[] UnclonedShortDatePatterns { get { if (allShortDatePatterns == null) { allShortDatePatterns = _cultureData.ShortDates(Calendar.ID); } return allShortDatePatterns; } } private string[] UnclonedLongDatePatterns { get { if (allLongDatePatterns == null) { allLongDatePatterns = _cultureData.LongDates(Calendar.ID); } return allLongDatePatterns; } } private string[] UnclonedShortTimePatterns { get { if (allShortTimePatterns == null) { allShortTimePatterns = _cultureData.ShortTimes; } return allShortTimePatterns; } } private string[] UnclonedLongTimePatterns { get { if (allLongTimePatterns == null) { allLongTimePatterns = _cultureData.LongTimes; } return allLongTimePatterns; } } public bool IsReadOnly => _isReadOnly; public string NativeCalendarName => _cultureData.CalendarName(Calendar.ID); public string[] AbbreviatedMonthGenitiveNames { get { return (string[])InternalGetGenitiveMonthNames(abbreviated: true).Clone(); } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } if (value.Length != 13) { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), "value"); } CheckNullValue(value, value.Length - 1); ClearTokenHashTable(); m_genitiveAbbreviatedMonthNames = value; } } public string[] MonthGenitiveNames { get { return (string[])InternalGetGenitiveMonthNames(abbreviated: false).Clone(); } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } if (value.Length != 13) { throw new ArgumentException(SR.Format(SR.Argument_InvalidArrayLength, 13), "value"); } CheckNullValue(value, value.Length - 1); genitiveMonthNames = value; ClearTokenHashTable(); } } internal string DecimalSeparator => _decimalSeparator ?? (_decimalSeparator = new NumberFormatInfo(_cultureData.UseUserOverride ? CultureData.GetCultureData(_cultureData.CultureName, useUserOverride: false) : _cultureData).NumberDecimalSeparator); internal string FullTimeSpanPositivePattern => _fullTimeSpanPositivePattern ?? (_fullTimeSpanPositivePattern = "d':'h':'mm':'ss'" + DecimalSeparator + "'FFFFFFF"); internal string FullTimeSpanNegativePattern => _fullTimeSpanNegativePattern ?? (_fullTimeSpanNegativePattern = "'-'" + FullTimeSpanPositivePattern); internal CompareInfo CompareInfo => _compareInfo ?? (_compareInfo = System.Globalization.CompareInfo.GetCompareInfo(_cultureData.SortName)); internal DateTimeFormatFlags FormatFlags { get { if (formatFlags == DateTimeFormatFlags.NotInitialized) { return InitializeFormatFlags(); } return formatFlags; } } internal bool HasForceTwoDigitYears { get { CalendarId iD = calendar.ID; if (iD - 3 <= CalendarId.GREGORIAN) { return true; } return false; } } internal bool HasYearMonthAdjustment => (FormatFlags & DateTimeFormatFlags.UseHebrewRule) != 0; private string[] InternalGetAbbreviatedDayOfWeekNames() { return abbreviatedDayNames ?? InternalGetAbbreviatedDayOfWeekNamesCore(); } [MethodImpl(MethodImplOptions.NoInlining)] private string[] InternalGetAbbreviatedDayOfWeekNamesCore() { abbreviatedDayNames = _cultureData.AbbreviatedDayNames(Calendar.ID); return abbreviatedDayNames; } private string[] InternalGetSuperShortDayNames() { return m_superShortDayNames ?? InternalGetSuperShortDayNamesCore(); } [MethodImpl(MethodImplOptions.NoInlining)] private string[] InternalGetSuperShortDayNamesCore() { m_superShortDayNames = _cultureData.SuperShortDayNames(Calendar.ID); return m_superShortDayNames; } private string[] InternalGetDayOfWeekNames() { return dayNames ?? InternalGetDayOfWeekNamesCore(); } [MethodImpl(MethodImplOptions.NoInlining)] private string[] InternalGetDayOfWeekNamesCore() { dayNames = _cultureData.DayNames(Calendar.ID); return dayNames; } private string[] InternalGetAbbreviatedMonthNames() { return abbreviatedMonthNames ?? InternalGetAbbreviatedMonthNamesCore(); } [MethodImpl(MethodImplOptions.NoInlining)] private string[] InternalGetAbbreviatedMonthNamesCore() { abbreviatedMonthNames = _cultureData.AbbreviatedMonthNames(Calendar.ID); return abbreviatedMonthNames; } private string[] InternalGetMonthNames() { return monthNames ?? internalGetMonthNamesCore(); } [MethodImpl(MethodImplOptions.NoInlining)] private string[] internalGetMonthNamesCore() { monthNames = _cultureData.MonthNames(Calendar.ID); return monthNames; } public DateTimeFormatInfo() : this(CultureInfo.InvariantCulture._cultureData, GregorianCalendar.GetDefaultInstance()) { } internal DateTimeFormatInfo(CultureData cultureData, Calendar cal) { _cultureData = cultureData; calendar = cal; InitializeOverridableProperties(cultureData, calendar.ID); } private void InitializeOverridableProperties(CultureData cultureData, CalendarId calendarId) { if (firstDayOfWeek == -1) { firstDayOfWeek = cultureData.FirstDayOfWeek; } if (calendarWeekRule == -1) { calendarWeekRule = cultureData.CalendarWeekRule; } if (amDesignator == null) { amDesignator = cultureData.AMDesignator; } if (pmDesignator == null) { pmDesignator = cultureData.PMDesignator; } if (timeSeparator == null) { timeSeparator = cultureData.TimeSeparator; } if (dateSeparator == null) { dateSeparator = cultureData.DateSeparator(calendarId); } allLongTimePatterns = _cultureData.LongTimes; allShortTimePatterns = _cultureData.ShortTimes; allLongDatePatterns = cultureData.LongDates(calendarId); allShortDatePatterns = cultureData.ShortDates(calendarId); allYearMonthPatterns = cultureData.YearMonths(calendarId); } public static DateTimeFormatInfo GetInstance(IFormatProvider? provider) { if (provider != null) { if (!(provider is CultureInfo cultureInfo) || cultureInfo._isInherited) { if (!(provider is DateTimeFormatInfo result)) { if (!(provider.GetFormat(typeof(DateTimeFormatInfo)) is DateTimeFormatInfo result2)) { return CurrentInfo; } return result2; } return result; } return cultureInfo.DateTimeFormat; } return CurrentInfo; } public object? GetFormat(Type? formatType) { if (!(formatType == typeof(DateTimeFormatInfo))) { return null; } return this; } public object Clone() { DateTimeFormatInfo dateTimeFormatInfo = (DateTimeFormatInfo)MemberwiseClone(); dateTimeFormatInfo.calendar = (Calendar)Calendar.Clone(); dateTimeFormatInfo._isReadOnly = false; return dateTimeFormatInfo; } public int GetEra(string eraName) { if (eraName == null) { throw new ArgumentNullException("eraName"); } if (eraName.Length == 0) { return -1; } for (int i = 0; i < EraNames.Length; i++) { if (m_eraNames[i].Length > 0 && Culture.CompareInfo.Compare(eraName, m_eraNames[i], CompareOptions.IgnoreCase) == 0) { return i + 1; } } for (int j = 0; j < AbbreviatedEraNames.Length; j++) { if (Culture.CompareInfo.Compare(eraName, m_abbrevEraNames[j], CompareOptions.IgnoreCase) == 0) { return j + 1; } } for (int k = 0; k < AbbreviatedEnglishEraNames.Length; k++) { if (System.Globalization.CompareInfo.Invariant.Compare(eraName, m_abbrevEnglishEraNames[k], CompareOptions.IgnoreCase) == 0) { return k + 1; } } return -1; } public string GetEraName(int era) { if (era == 0) { era = Calendar.CurrentEraValue; } if (--era < EraNames.Length && era >= 0) { return m_eraNames[era]; } throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } public string GetAbbreviatedEraName(int era) { if (AbbreviatedEraNames.Length == 0) { return GetEraName(era); } if (era == 0) { era = Calendar.CurrentEraValue; } if (--era < m_abbrevEraNames.Length && era >= 0) { return m_abbrevEraNames[era]; } throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } private void OnLongDatePatternChanged() { ClearTokenHashTable(); fullDateTimePattern = null; } private void OnLongTimePatternChanged() { ClearTokenHashTable(); fullDateTimePattern = null; generalLongTimePattern = null; dateTimeOffsetPattern = null; } private void OnShortDatePatternChanged() { ClearTokenHashTable(); generalLongTimePattern = null; generalShortTimePattern = null; dateTimeOffsetPattern = null; } private void OnShortTimePatternChanged() { ClearTokenHashTable(); generalShortTimePattern = null; } private void OnYearMonthPatternChanged() { ClearTokenHashTable(); } private static void CheckNullValue(string[] values, int length) { for (int i = 0; i < length; i++) { if (values[i] == null) { throw new ArgumentNullException("value", SR.ArgumentNull_ArrayValue); } } } internal string InternalGetMonthName(int month, MonthNameStyles style, bool abbreviated) { string[] array = style switch { MonthNameStyles.Genitive => InternalGetGenitiveMonthNames(abbreviated), MonthNameStyles.LeapYear => InternalGetLeapYearMonthNames(), _ => abbreviated ? InternalGetAbbreviatedMonthNames() : InternalGetMonthNames(), }; if (month < 1 || month > array.Length) { throw new ArgumentOutOfRangeException("month", month, SR.Format(SR.ArgumentOutOfRange_Range, 1, array.Length)); } return array[month - 1]; } private string[] InternalGetGenitiveMonthNames(bool abbreviated) { if (abbreviated) { if (m_genitiveAbbreviatedMonthNames == null) { m_genitiveAbbreviatedMonthNames = _cultureData.AbbreviatedGenitiveMonthNames(Calendar.ID); } return m_genitiveAbbreviatedMonthNames; } if (genitiveMonthNames == null) { genitiveMonthNames = _cultureData.GenitiveMonthNames(Calendar.ID); } return genitiveMonthNames; } internal string[] InternalGetLeapYearMonthNames() { if (leapYearMonthNames == null) { leapYearMonthNames = _cultureData.LeapYearMonthNames(Calendar.ID); } return leapYearMonthNames; } public string GetAbbreviatedDayName(DayOfWeek dayofweek) { if (dayofweek < DayOfWeek.Sunday || dayofweek > DayOfWeek.Saturday) { throw new ArgumentOutOfRangeException("dayofweek", dayofweek, SR.Format(SR.ArgumentOutOfRange_Range, DayOfWeek.Sunday, DayOfWeek.Saturday)); } return InternalGetAbbreviatedDayOfWeekNames()[(int)dayofweek]; } public string GetShortestDayName(DayOfWeek dayOfWeek) { if (dayOfWeek < DayOfWeek.Sunday || dayOfWeek > DayOfWeek.Saturday) { throw new ArgumentOutOfRangeException("dayOfWeek", dayOfWeek, SR.Format(SR.ArgumentOutOfRange_Range, DayOfWeek.Sunday, DayOfWeek.Saturday)); } return InternalGetSuperShortDayNames()[(int)dayOfWeek]; } private static string[] GetCombinedPatterns(string[] patterns1, string[] patterns2, string connectString) { string[] array = new string[patterns1.Length * patterns2.Length]; int num = 0; for (int i = 0; i < patterns1.Length; i++) { for (int j = 0; j < patterns2.Length; j++) { array[num++] = patterns1[i] + connectString + patterns2[j]; } } return array; } public string[] GetAllDateTimePatterns() { List list = new List(132); for (int i = 0; i < DateTimeFormat.allStandardFormats.Length; i++) { string[] allDateTimePatterns = GetAllDateTimePatterns(DateTimeFormat.allStandardFormats[i]); for (int j = 0; j < allDateTimePatterns.Length; j++) { list.Add(allDateTimePatterns[j]); } } return list.ToArray(); } public string[] GetAllDateTimePatterns(char format) { switch (format) { case 'd': return AllShortDatePatterns; case 'D': return AllLongDatePatterns; case 'f': return GetCombinedPatterns(AllLongDatePatterns, AllShortTimePatterns, " "); case 'F': case 'U': return GetCombinedPatterns(AllLongDatePatterns, AllLongTimePatterns, " "); case 'g': return GetCombinedPatterns(AllShortDatePatterns, AllShortTimePatterns, " "); case 'G': return GetCombinedPatterns(AllShortDatePatterns, AllLongTimePatterns, " "); case 'M': case 'm': return new string[1] { MonthDayPattern }; case 'O': case 'o': return new string[1] { "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK" }; case 'R': case 'r': return new string[1] { "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'" }; case 's': return new string[1] { "yyyy'-'MM'-'dd'T'HH':'mm':'ss" }; case 't': return AllShortTimePatterns; case 'T': return AllLongTimePatterns; case 'u': return new string[1] { UniversalSortableDateTimePattern }; case 'Y': case 'y': return AllYearMonthPatterns; default: throw new ArgumentException(SR.Format(SR.Format_BadFormatSpecifier, format), "format"); } } public string GetDayName(DayOfWeek dayofweek) { if (dayofweek < DayOfWeek.Sunday || dayofweek > DayOfWeek.Saturday) { throw new ArgumentOutOfRangeException("dayofweek", dayofweek, SR.Format(SR.ArgumentOutOfRange_Range, DayOfWeek.Sunday, DayOfWeek.Saturday)); } return InternalGetDayOfWeekNames()[(int)dayofweek]; } public string GetAbbreviatedMonthName(int month) { if (month < 1 || month > 13) { throw new ArgumentOutOfRangeException("month", month, SR.Format(SR.ArgumentOutOfRange_Range, 1, 13)); } return InternalGetAbbreviatedMonthNames()[month - 1]; } public string GetMonthName(int month) { if (month < 1 || month > 13) { throw new ArgumentOutOfRangeException("month", month, SR.Format(SR.ArgumentOutOfRange_Range, 1, 13)); } return InternalGetMonthNames()[month - 1]; } private static string[] GetMergedPatterns(string[] patterns, string defaultPattern) { if (defaultPattern == patterns[0]) { return (string[])patterns.Clone(); } int i; for (i = 0; i < patterns.Length && !(defaultPattern == patterns[i]); i++) { } string[] array; if (i < patterns.Length) { array = (string[])patterns.Clone(); array[i] = array[0]; } else { array = new string[patterns.Length + 1]; Array.Copy(patterns, 0, array, 1, patterns.Length); } array[0] = defaultPattern; return array; } public static DateTimeFormatInfo ReadOnly(DateTimeFormatInfo dtfi) { if (dtfi == null) { throw new ArgumentNullException("dtfi"); } if (dtfi.IsReadOnly) { return dtfi; } DateTimeFormatInfo dateTimeFormatInfo = (DateTimeFormatInfo)dtfi.MemberwiseClone(); dateTimeFormatInfo.calendar = System.Globalization.Calendar.ReadOnly(dtfi.Calendar); dateTimeFormatInfo._isReadOnly = true; return dateTimeFormatInfo; } public void SetAllDateTimePatterns(string[] patterns, char format) { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (patterns == null) { throw new ArgumentNullException("patterns"); } if (patterns.Length == 0) { throw new ArgumentException(SR.Arg_ArrayZeroError, "patterns"); } for (int i = 0; i < patterns.Length; i++) { if (patterns[i] == null) { throw new ArgumentNullException("patterns[" + i + "]", SR.ArgumentNull_ArrayValue); } } switch (format) { case 'd': allShortDatePatterns = patterns; shortDatePattern = allShortDatePatterns[0]; OnShortDatePatternChanged(); break; case 'D': allLongDatePatterns = patterns; longDatePattern = allLongDatePatterns[0]; OnLongDatePatternChanged(); break; case 't': allShortTimePatterns = patterns; shortTimePattern = allShortTimePatterns[0]; OnShortTimePatternChanged(); break; case 'T': allLongTimePatterns = patterns; longTimePattern = allLongTimePatterns[0]; OnLongTimePatternChanged(); break; case 'Y': case 'y': allYearMonthPatterns = patterns; yearMonthPattern = allYearMonthPatterns[0]; OnYearMonthPatternChanged(); break; default: throw new ArgumentException(SR.Format(SR.Format_BadFormatSpecifier, format), "format"); } } internal static void ValidateStyles(DateTimeStyles style, bool styles = false) { if (((uint)style & 0xFFFFFF00u) != 0 || (style & (DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal)) == (DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal) || (style & (DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal | DateTimeStyles.RoundtripKind)) > DateTimeStyles.RoundtripKind) { ThrowInvalid(style, styles); } static void ThrowInvalid(DateTimeStyles style, bool styles) { string message = ((((uint)style & 0xFFFFFF00u) != 0) ? SR.Argument_InvalidDateTimeStyles : (((style & (DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal)) == (DateTimeStyles.AssumeLocal | DateTimeStyles.AssumeUniversal)) ? SR.Argument_ConflictingDateTimeStyles : SR.Argument_ConflictingDateTimeRoundtripStyles)); throw new ArgumentException(message, styles ? "styles" : "style"); } } [MethodImpl(MethodImplOptions.NoInlining)] private DateTimeFormatFlags InitializeFormatFlags() { formatFlags = (DateTimeFormatFlags)(DateTimeFormatInfoScanner.GetFormatFlagGenitiveMonth(MonthNames, InternalGetGenitiveMonthNames(abbreviated: false), AbbreviatedMonthNames, InternalGetGenitiveMonthNames(abbreviated: true)) | DateTimeFormatInfoScanner.GetFormatFlagUseSpaceInMonthNames(MonthNames, InternalGetGenitiveMonthNames(abbreviated: false), AbbreviatedMonthNames, InternalGetGenitiveMonthNames(abbreviated: true)) | DateTimeFormatInfoScanner.GetFormatFlagUseSpaceInDayNames(DayNames, AbbreviatedDayNames) | DateTimeFormatInfoScanner.GetFormatFlagUseHebrewCalendar((int)Calendar.ID)); return formatFlags; } internal bool YearMonthAdjustment(ref int year, ref int month, bool parsedMonthName) { if ((FormatFlags & DateTimeFormatFlags.UseHebrewRule) != 0) { if (year < 1000) { year += 5000; } if (year < Calendar.GetYear(Calendar.MinSupportedDateTime) || year > Calendar.GetYear(Calendar.MaxSupportedDateTime)) { return false; } if (parsedMonthName && !Calendar.IsLeapYear(year)) { if (month >= 8) { month--; } else if (month == 7) { return false; } } } return true; } internal static DateTimeFormatInfo GetJapaneseCalendarDTFI() { DateTimeFormatInfo dateTimeFormat = s_jajpDTFI; if (dateTimeFormat == null) { dateTimeFormat = new CultureInfo("ja-JP", useUserOverride: false).DateTimeFormat; dateTimeFormat.Calendar = JapaneseCalendar.GetDefaultInstance(); s_jajpDTFI = dateTimeFormat; } return dateTimeFormat; } internal static DateTimeFormatInfo GetTaiwanCalendarDTFI() { DateTimeFormatInfo dateTimeFormat = s_zhtwDTFI; if (dateTimeFormat == null) { dateTimeFormat = new CultureInfo("zh-TW", useUserOverride: false).DateTimeFormat; dateTimeFormat.Calendar = TaiwanCalendar.GetDefaultInstance(); s_zhtwDTFI = dateTimeFormat; } return dateTimeFormat; } private void ClearTokenHashTable() { _dtfiTokenHash = null; formatFlags = DateTimeFormatFlags.NotInitialized; } internal TokenHashValue[] CreateTokenHashTable() { TokenHashValue[] array = _dtfiTokenHash; if (array == null) { array = new TokenHashValue[199]; string text = TimeSeparator.Trim(); if ("," != text) { InsertHash(array, ",", TokenType.IgnorableSymbol, 0); } if ("." != text) { InsertHash(array, ".", TokenType.IgnorableSymbol, 0); } if ("시" != text && "時" != text && "时" != text) { InsertHash(array, TimeSeparator, TokenType.SEP_Time, 0); } if (_name == "fr-CA") { InsertHash(array, " h", TokenType.SEP_HourSuff, 0); InsertHash(array, " h ", TokenType.SEP_HourSuff, 0); InsertHash(array, " min", TokenType.SEP_MinuteSuff, 0); InsertHash(array, " min ", TokenType.SEP_MinuteSuff, 0); InsertHash(array, " s", TokenType.SEP_SecondSuff, 0); InsertHash(array, " s ", TokenType.SEP_SecondSuff, 0); } InsertHash(array, AMDesignator, (TokenType)1027, 0); InsertHash(array, PMDesignator, (TokenType)1284, 1); if (LanguageName.Equals("sq")) { InsertHash(array, "." + AMDesignator, (TokenType)1027, 0); InsertHash(array, "." + PMDesignator, (TokenType)1284, 1); } InsertHash(array, "年", TokenType.SEP_YearSuff, 0); InsertHash(array, "년", TokenType.SEP_YearSuff, 0); InsertHash(array, "月", TokenType.SEP_MonthSuff, 0); InsertHash(array, "월", TokenType.SEP_MonthSuff, 0); InsertHash(array, "日", TokenType.SEP_DaySuff, 0); InsertHash(array, "일", TokenType.SEP_DaySuff, 0); InsertHash(array, "時", TokenType.SEP_HourSuff, 0); InsertHash(array, "时", TokenType.SEP_HourSuff, 0); InsertHash(array, "分", TokenType.SEP_MinuteSuff, 0); InsertHash(array, "秒", TokenType.SEP_SecondSuff, 0); if (!LocalAppContextSwitches.EnforceLegacyJapaneseDateParsing && Calendar.ID == CalendarId.JAPAN) { InsertHash(array, "元", TokenType.YearNumberToken, 1); InsertHash(array, "(", TokenType.IgnorableSymbol, 0); InsertHash(array, ")", TokenType.IgnorableSymbol, 0); } if (LanguageName.Equals("ko")) { InsertHash(array, "시", TokenType.SEP_HourSuff, 0); InsertHash(array, "분", TokenType.SEP_MinuteSuff, 0); InsertHash(array, "초", TokenType.SEP_SecondSuff, 0); } if (LanguageName.Equals("ky")) { InsertHash(array, "-", TokenType.IgnorableSymbol, 0); } else { InsertHash(array, "-", TokenType.SEP_DateOrOffset, 0); } DateTimeFormatInfoScanner dateTimeFormatInfoScanner = new DateTimeFormatInfoScanner(); string[] dateWordsOfDTFI = dateTimeFormatInfoScanner.GetDateWordsOfDTFI(this); _ = FormatFlags; bool flag = false; if (dateWordsOfDTFI != null) { for (int i = 0; i < dateWordsOfDTFI.Length; i++) { switch (dateWordsOfDTFI[i][0]) { case '\ue000': { ReadOnlySpan monthPostfix = dateWordsOfDTFI[i].AsSpan(1); AddMonthNames(array, monthPostfix); break; } case '\ue001': { string text2 = dateWordsOfDTFI[i].Substring(1); InsertHash(array, text2, TokenType.IgnorableSymbol, 0); if (DateSeparator.Trim().Equals(text2)) { flag = true; } break; } default: InsertHash(array, dateWordsOfDTFI[i], TokenType.DateWordToken, 0); if (LanguageName.Equals("eu")) { InsertHash(array, "." + dateWordsOfDTFI[i], TokenType.DateWordToken, 0); } break; } } } if (!flag) { InsertHash(array, DateSeparator, TokenType.SEP_Date, 0); } AddMonthNames(array); for (int j = 1; j <= 13; j++) { InsertHash(array, GetAbbreviatedMonthName(j), TokenType.MonthToken, j); } if ((FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) != 0) { string[] array2 = InternalGetGenitiveMonthNames(abbreviated: false); string[] array3 = InternalGetGenitiveMonthNames(abbreviated: true); for (int k = 1; k <= 13; k++) { InsertHash(array, array2[k - 1], TokenType.MonthToken, k); InsertHash(array, array3[k - 1], TokenType.MonthToken, k); } } if ((FormatFlags & DateTimeFormatFlags.UseLeapYearMonth) != 0) { for (int l = 1; l <= 13; l++) { string str = InternalGetMonthName(l, MonthNameStyles.LeapYear, abbreviated: false); InsertHash(array, str, TokenType.MonthToken, l); } } for (int m = 0; m < 7; m++) { string dayName = GetDayName((DayOfWeek)m); InsertHash(array, dayName, TokenType.DayOfWeekToken, m); dayName = GetAbbreviatedDayName((DayOfWeek)m); InsertHash(array, dayName, TokenType.DayOfWeekToken, m); } int[] eras = calendar.Eras; for (int n = 1; n <= eras.Length; n++) { InsertHash(array, GetEraName(n), TokenType.EraToken, n); InsertHash(array, GetAbbreviatedEraName(n), TokenType.EraToken, n); } if (!GlobalizationMode.Invariant) { if (LanguageName.Equals("ja")) { for (int num = 0; num < 7; num++) { string str2 = "(" + GetAbbreviatedDayName((DayOfWeek)num) + ")"; InsertHash(array, str2, TokenType.DayOfWeekToken, num); } if (Calendar.GetType() != typeof(JapaneseCalendar)) { DateTimeFormatInfo japaneseCalendarDTFI = GetJapaneseCalendarDTFI(); for (int num2 = 1; num2 <= japaneseCalendarDTFI.Calendar.Eras.Length; num2++) { InsertHash(array, japaneseCalendarDTFI.GetEraName(num2), TokenType.JapaneseEraToken, num2); InsertHash(array, japaneseCalendarDTFI.GetAbbreviatedEraName(num2), TokenType.JapaneseEraToken, num2); InsertHash(array, japaneseCalendarDTFI.AbbreviatedEnglishEraNames[num2 - 1], TokenType.JapaneseEraToken, num2); } } } else if (CultureName.Equals("zh-TW")) { DateTimeFormatInfo taiwanCalendarDTFI = GetTaiwanCalendarDTFI(); for (int num3 = 1; num3 <= taiwanCalendarDTFI.Calendar.Eras.Length; num3++) { if (taiwanCalendarDTFI.GetEraName(num3).Length > 0) { InsertHash(array, taiwanCalendarDTFI.GetEraName(num3), TokenType.TEraToken, num3); } } } } InsertHash(array, InvariantInfo.AMDesignator, (TokenType)1027, 0); InsertHash(array, InvariantInfo.PMDesignator, (TokenType)1284, 1); for (int num4 = 1; num4 <= 12; num4++) { string monthName = InvariantInfo.GetMonthName(num4); InsertHash(array, monthName, TokenType.MonthToken, num4); monthName = InvariantInfo.GetAbbreviatedMonthName(num4); InsertHash(array, monthName, TokenType.MonthToken, num4); } for (int num5 = 0; num5 < 7; num5++) { string dayName2 = InvariantInfo.GetDayName((DayOfWeek)num5); InsertHash(array, dayName2, TokenType.DayOfWeekToken, num5); dayName2 = InvariantInfo.GetAbbreviatedDayName((DayOfWeek)num5); InsertHash(array, dayName2, TokenType.DayOfWeekToken, num5); } for (int num6 = 0; num6 < AbbreviatedEnglishEraNames.Length; num6++) { InsertHash(array, AbbreviatedEnglishEraNames[num6], TokenType.EraToken, num6 + 1); } InsertHash(array, "T", TokenType.SEP_LocalTimeMark, 0); InsertHash(array, "GMT", TokenType.TimeZoneToken, 0); InsertHash(array, "Z", TokenType.TimeZoneToken, 0); InsertHash(array, "/", TokenType.SEP_Date, 0); InsertHash(array, ":", TokenType.SEP_Time, 0); _dtfiTokenHash = array; } return array; } private void AddMonthNames(TokenHashValue[] temp, ReadOnlySpan monthPostfix = default(ReadOnlySpan)) { for (int i = 1; i <= 13; i++) { string monthName = GetMonthName(i); if (monthName.Length > 0) { if (!monthPostfix.IsEmpty) { InsertHash(temp, monthName + monthPostfix, TokenType.MonthToken, i); } else { InsertHash(temp, monthName, TokenType.MonthToken, i); } } monthName = GetAbbreviatedMonthName(i); InsertHash(temp, monthName, TokenType.MonthToken, i); } } private static bool TryParseHebrewNumber(ref __DTString str, out bool badFormat, out int number) { number = -1; badFormat = false; int index = str.Index; if (!HebrewNumber.IsDigit(str.Value[index])) { return false; } HebrewNumberParsingContext context = new HebrewNumberParsingContext(0); HebrewNumberParsingState hebrewNumberParsingState; do { hebrewNumberParsingState = HebrewNumber.ParseByChar(str.Value[index++], ref context); if ((uint)hebrewNumberParsingState <= 1u) { return false; } } while (index < str.Value.Length && hebrewNumberParsingState != HebrewNumberParsingState.FoundEndOfHebrewNumber); if (hebrewNumberParsingState != HebrewNumberParsingState.FoundEndOfHebrewNumber) { return false; } str.Advance(index - str.Index); number = context.result; return true; } private static bool IsHebrewChar(char ch) { if (ch >= '\u0590') { return ch <= '\u05ff'; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool IsAllowedJapaneseTokenFollowedByNonSpaceLetter(string tokenString, char nextCh) { if (!LocalAppContextSwitches.EnforceLegacyJapaneseDateParsing && Calendar.ID == CalendarId.JAPAN && (nextCh == "元"[0] || (tokenString == "元" && nextCh == "年"[0]))) { return true; } return false; } internal bool Tokenize(TokenType TokenMask, out TokenType tokenType, out int tokenValue, ref __DTString str) { tokenType = TokenType.UnknownToken; tokenValue = 0; char c = str.m_current; bool flag = char.IsLetter(c); if (flag) { c = Culture.TextInfo.ToLower(c); if (!GlobalizationMode.Invariant && IsHebrewChar(c) && TokenMask == TokenType.RegularTokenMask && TryParseHebrewNumber(ref str, out var badFormat, out tokenValue)) { if (badFormat) { tokenType = TokenType.UnknownToken; return false; } tokenType = TokenType.HebrewNumber; return true; } } int num = c % 199; int num2 = 1 + c % 197; int num3 = str.Length - str.Index; int num4 = 0; TokenHashValue[] array = _dtfiTokenHash ?? CreateTokenHashTable(); do { TokenHashValue tokenHashValue = array[num]; if (tokenHashValue == null) { break; } if ((tokenHashValue.tokenType & TokenMask) > (TokenType)0 && tokenHashValue.tokenString.Length <= num3) { bool flag2 = true; if (flag) { int num5 = str.Index + tokenHashValue.tokenString.Length; if (num5 > str.Length) { flag2 = false; } else if (num5 < str.Length) { char c2 = str.Value[num5]; flag2 = !char.IsLetter(c2) || IsAllowedJapaneseTokenFollowedByNonSpaceLetter(tokenHashValue.tokenString, c2); } } if (flag2 && ((tokenHashValue.tokenString.Length == 1 && str.Value[str.Index] == tokenHashValue.tokenString[0]) || Culture.CompareInfo.Compare(str.Value.Slice(str.Index, tokenHashValue.tokenString.Length), tokenHashValue.tokenString, CompareOptions.IgnoreCase) == 0)) { tokenType = tokenHashValue.tokenType & TokenMask; tokenValue = tokenHashValue.tokenValue; str.Advance(tokenHashValue.tokenString.Length); return true; } if ((tokenHashValue.tokenType == TokenType.MonthToken && HasSpacesInMonthNames) || (tokenHashValue.tokenType == TokenType.DayOfWeekToken && HasSpacesInDayNames)) { int matchLength = 0; if (str.MatchSpecifiedWords(tokenHashValue.tokenString, checkWordBoundary: true, ref matchLength)) { tokenType = tokenHashValue.tokenType & TokenMask; tokenValue = tokenHashValue.tokenValue; str.Advance(matchLength); return true; } } } num4++; num += num2; if (num >= 199) { num -= 199; } } while (num4 < 199); return false; } private void InsertAtCurrentHashNode(TokenHashValue[] hashTable, string str, char ch, TokenType tokenType, int tokenValue, int pos, int hashcode, int hashProbe) { TokenHashValue tokenHashValue = hashTable[hashcode]; hashTable[hashcode] = new TokenHashValue(str, tokenType, tokenValue); while (++pos < 199) { hashcode += hashProbe; if (hashcode >= 199) { hashcode -= 199; } TokenHashValue tokenHashValue2 = hashTable[hashcode]; if (tokenHashValue2 == null || Culture.TextInfo.ToLower(tokenHashValue2.tokenString[0]) == ch) { hashTable[hashcode] = tokenHashValue; if (tokenHashValue2 == null) { break; } tokenHashValue = tokenHashValue2; } } } private void InsertHash(TokenHashValue[] hashTable, string str, TokenType tokenType, int tokenValue) { if (string.IsNullOrEmpty(str)) { return; } int num = 0; if (char.IsWhiteSpace(str[0]) || char.IsWhiteSpace(str[^1])) { str = str.Trim(); if (str.Length == 0) { return; } } char c = Culture.TextInfo.ToLower(str[0]); int num2 = c % 199; int num3 = 1 + c % 197; do { TokenHashValue tokenHashValue = hashTable[num2]; if (tokenHashValue == null) { hashTable[num2] = new TokenHashValue(str, tokenType, tokenValue); break; } if (str.Length >= tokenHashValue.tokenString.Length && CompareStringIgnoreCaseOptimized(str, 0, tokenHashValue.tokenString.Length, tokenHashValue.tokenString, 0, tokenHashValue.tokenString.Length)) { if (str.Length > tokenHashValue.tokenString.Length) { InsertAtCurrentHashNode(hashTable, str, c, tokenType, tokenValue, num, num2, num3); break; } int tokenType2 = (int)tokenHashValue.tokenType; if (((tokenType2 & 0xFF) == 0 && (tokenType & TokenType.RegularTokenMask) != 0) || ((tokenType2 & 0xFF00) == 0 && (tokenType & TokenType.SeparatorTokenMask) != 0)) { tokenHashValue.tokenType |= tokenType; if (tokenValue != 0) { tokenHashValue.tokenValue = tokenValue; } } break; } num++; num2 += num3; if (num2 >= 199) { num2 -= 199; } } while (num < 199); } private bool CompareStringIgnoreCaseOptimized(string string1, int offset1, int length1, string string2, int offset2, int length2) { if (length1 == 1 && length2 == 1 && string1[offset1] == string2[offset2]) { return true; } return Culture.CompareInfo.Compare(string1, offset1, length1, string2, offset2, length2, CompareOptions.IgnoreCase) == 0; } } internal enum FORMATFLAGS { None = 0, UseGenitiveMonth = 1, UseLeapYearMonth = 2, UseSpacesInMonthNames = 4, UseHebrewParsing = 8, UseSpacesInDayNames = 0x10, UseDigitPrefixInTokens = 0x20 } internal enum CalendarId : ushort { UNINITIALIZED_VALUE = 0, GREGORIAN = 1, GREGORIAN_US = 2, JAPAN = 3, TAIWAN = 4, KOREA = 5, HIJRI = 6, THAI = 7, HEBREW = 8, GREGORIAN_ME_FRENCH = 9, GREGORIAN_ARABIC = 10, GREGORIAN_XLIT_ENGLISH = 11, GREGORIAN_XLIT_FRENCH = 12, JULIAN = 13, JAPANESELUNISOLAR = 14, CHINESELUNISOLAR = 15, SAKA = 16, LUNAR_ETO_CHN = 17, LUNAR_ETO_KOR = 18, LUNAR_ETO_ROKUYOU = 19, KOREANLUNISOLAR = 20, TAIWANLUNISOLAR = 21, PERSIAN = 22, UMALQURA = 23, LAST_CALENDAR = 23 } internal sealed class DateTimeFormatInfoScanner { private enum FoundDatePattern { None = 0, FoundYearPatternFlag = 1, FoundMonthPatternFlag = 2, FoundDayPatternFlag = 4, FoundYMDPatternFlag = 7 } internal List m_dateWords = new List(); private FoundDatePattern _ymdFlags; internal static int SkipWhiteSpacesAndNonLetter(string pattern, int currentIndex) { while (currentIndex < pattern.Length) { char c = pattern[currentIndex]; if (c == '\\') { currentIndex++; if (currentIndex >= pattern.Length) { break; } c = pattern[currentIndex]; if (c == '\'') { continue; } } if (char.IsLetter(c) || c == '\'' || c == '.') { break; } currentIndex++; } return currentIndex; } internal void AddDateWordOrPostfix(string formatPostfix, string str) { if (str.Length == 0) { return; } if (str.Length == 1) { switch (str[0]) { case '.': AddIgnorableSymbols("."); return; case '-': case '/': case '分': case '年': case '日': case '时': case '時': case '月': case '秒': case '년': case '분': case '시': case '월': case '일': case '초': return; } } if (m_dateWords == null) { m_dateWords = new List(); } if (formatPostfix == "MMMM") { string item = "\ue000" + str; if (!m_dateWords.Contains(item)) { m_dateWords.Add(item); } return; } if (!m_dateWords.Contains(str)) { m_dateWords.Add(str); } if (str[^1] == '.') { string item2 = str[0..^1]; if (!m_dateWords.Contains(item2)) { m_dateWords.Add(item2); } } } internal int AddDateWords(string pattern, int index, string formatPostfix) { int num = SkipWhiteSpacesAndNonLetter(pattern, index); if (num != index && formatPostfix != null) { formatPostfix = null; } index = num; StringBuilder stringBuilder = new StringBuilder(); while (index < pattern.Length) { char c = pattern[index]; switch (c) { case '\'': break; case '\\': index++; if (index < pattern.Length) { stringBuilder.Append(pattern[index]); index++; } continue; default: if (char.IsWhiteSpace(c)) { AddDateWordOrPostfix(formatPostfix, stringBuilder.ToString()); if (formatPostfix != null) { formatPostfix = null; } stringBuilder.Length = 0; index++; } else { stringBuilder.Append(c); index++; } continue; } AddDateWordOrPostfix(formatPostfix, stringBuilder.ToString()); index++; break; } return index; } internal static int ScanRepeatChar(string pattern, char ch, int index, out int count) { count = 1; while (++index < pattern.Length && pattern[index] == ch) { count++; } return index; } internal void AddIgnorableSymbols(string text) { if (m_dateWords == null) { m_dateWords = new List(); } string item = "\ue001" + text; if (!m_dateWords.Contains(item)) { m_dateWords.Add(item); } } internal void ScanDateWord(string pattern) { _ymdFlags = FoundDatePattern.None; int num = 0; while (num < pattern.Length) { char c = pattern[num]; int count; switch (c) { case '\'': num = AddDateWords(pattern, num + 1, null); break; case 'M': num = ScanRepeatChar(pattern, 'M', num, out count); if (count >= 4 && num < pattern.Length && pattern[num] == '\'') { num = AddDateWords(pattern, num + 1, "MMMM"); } _ymdFlags |= FoundDatePattern.FoundMonthPatternFlag; break; case 'y': { num = ScanRepeatChar(pattern, 'y', num, out var _); _ymdFlags |= FoundDatePattern.FoundYearPatternFlag; break; } case 'd': num = ScanRepeatChar(pattern, 'd', num, out count); if (count <= 2) { _ymdFlags |= FoundDatePattern.FoundDayPatternFlag; } break; case '\\': num += 2; break; case '.': if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag) { AddIgnorableSymbols("."); _ymdFlags = FoundDatePattern.None; } num++; break; default: if (_ymdFlags == FoundDatePattern.FoundYMDPatternFlag && !char.IsWhiteSpace(c)) { _ymdFlags = FoundDatePattern.None; } num++; break; } } } internal string[] GetDateWordsOfDTFI(DateTimeFormatInfo dtfi) { string[] allDateTimePatterns = dtfi.GetAllDateTimePatterns('D'); for (int i = 0; i < allDateTimePatterns.Length; i++) { ScanDateWord(allDateTimePatterns[i]); } allDateTimePatterns = dtfi.GetAllDateTimePatterns('d'); for (int i = 0; i < allDateTimePatterns.Length; i++) { ScanDateWord(allDateTimePatterns[i]); } allDateTimePatterns = dtfi.GetAllDateTimePatterns('y'); for (int i = 0; i < allDateTimePatterns.Length; i++) { ScanDateWord(allDateTimePatterns[i]); } ScanDateWord(dtfi.MonthDayPattern); allDateTimePatterns = dtfi.GetAllDateTimePatterns('T'); for (int i = 0; i < allDateTimePatterns.Length; i++) { ScanDateWord(allDateTimePatterns[i]); } allDateTimePatterns = dtfi.GetAllDateTimePatterns('t'); for (int i = 0; i < allDateTimePatterns.Length; i++) { ScanDateWord(allDateTimePatterns[i]); } string[] array = null; if (m_dateWords != null && m_dateWords.Count > 0) { array = new string[m_dateWords.Count]; for (int i = 0; i < m_dateWords.Count; i++) { array[i] = m_dateWords[i]; } } return array; } internal static FORMATFLAGS GetFormatFlagGenitiveMonth(string[] monthNames, string[] genitveMonthNames, string[] abbrevMonthNames, string[] genetiveAbbrevMonthNames) { if (EqualStringArrays(monthNames, genitveMonthNames) && EqualStringArrays(abbrevMonthNames, genetiveAbbrevMonthNames)) { return FORMATFLAGS.None; } return FORMATFLAGS.UseGenitiveMonth; } internal static FORMATFLAGS GetFormatFlagUseSpaceInMonthNames(string[] monthNames, string[] genitveMonthNames, string[] abbrevMonthNames, string[] genetiveAbbrevMonthNames) { FORMATFLAGS fORMATFLAGS = FORMATFLAGS.None; fORMATFLAGS |= ((ArrayElementsBeginWithDigit(monthNames) || ArrayElementsBeginWithDigit(genitveMonthNames) || ArrayElementsBeginWithDigit(abbrevMonthNames) || ArrayElementsBeginWithDigit(genetiveAbbrevMonthNames)) ? FORMATFLAGS.UseDigitPrefixInTokens : FORMATFLAGS.None); return fORMATFLAGS | ((ArrayElementsHaveSpace(monthNames) || ArrayElementsHaveSpace(genitveMonthNames) || ArrayElementsHaveSpace(abbrevMonthNames) || ArrayElementsHaveSpace(genetiveAbbrevMonthNames)) ? FORMATFLAGS.UseSpacesInMonthNames : FORMATFLAGS.None); } internal static FORMATFLAGS GetFormatFlagUseSpaceInDayNames(string[] dayNames, string[] abbrevDayNames) { if (!ArrayElementsHaveSpace(dayNames) && !ArrayElementsHaveSpace(abbrevDayNames)) { return FORMATFLAGS.None; } return FORMATFLAGS.UseSpacesInDayNames; } internal static FORMATFLAGS GetFormatFlagUseHebrewCalendar(int calID) { if (calID != 8) { return FORMATFLAGS.None; } return (FORMATFLAGS)10; } private static bool EqualStringArrays(string[] array1, string[] array2) { if (array1 == array2) { return true; } if (array1.Length != array2.Length) { return false; } for (int i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) { return false; } } return true; } private static bool ArrayElementsHaveSpace(string[] array) { for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array[i].Length; j++) { if (char.IsWhiteSpace(array[i][j])) { return true; } } } return false; } private static bool ArrayElementsBeginWithDigit(string[] array) { for (int i = 0; i < array.Length; i++) { if (array[i].Length <= 0 || array[i][0] < '0' || array[i][0] > '9') { continue; } int j; for (j = 1; j < array[i].Length && array[i][j] >= '0' && array[i][j] <= '9'; j++) { } if (j == array[i].Length) { return false; } if (j == array[i].Length - 1) { char c = array[i][j]; if (c == '月' || c == '월') { return false; } } if (j == array[i].Length - 4 && array[i][j] == '\'' && array[i][j + 1] == ' ' && array[i][j + 2] == '月' && array[i][j + 3] == '\'') { return false; } return true; } return false; } } [Flags] public enum DateTimeStyles { None = 0, AllowLeadingWhite = 1, AllowTrailingWhite = 2, AllowInnerWhite = 4, AllowWhiteSpaces = 7, NoCurrentDateDefault = 8, AdjustToUniversal = 0x10, AssumeLocal = 0x20, AssumeUniversal = 0x40, RoundtripKind = 0x80 } public class DaylightTime { private readonly DateTime _start; private readonly DateTime _end; private readonly TimeSpan _delta; public DateTime Start => _start; public DateTime End => _end; public TimeSpan Delta => _delta; public DaylightTime(DateTime start, DateTime end, TimeSpan delta) { _start = start; _end = end; _delta = delta; } } internal readonly struct DaylightTimeStruct { public readonly DateTime Start; public readonly DateTime End; public readonly TimeSpan Delta; public DaylightTimeStruct(DateTime start, DateTime end, TimeSpan delta) { Start = start; End = end; Delta = delta; } } public enum DigitShapes { Context, None, NativeNational } public abstract class EastAsianLunisolarCalendar : Calendar { private static readonly int[] s_daysToMonth365 = new int[12] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }; private static readonly int[] s_daysToMonth366 = new int[12] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 }; public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.LunisolarCalendar; internal abstract int MinCalendarYear { get; } internal abstract int MaxCalendarYear { get; } internal abstract EraInfo[]? CalEraInfo { get; } internal abstract DateTime MinDate { get; } internal abstract DateTime MaxDate { get; } public override int TwoDigitYearMax { get { if (_twoDigitYearMax == -1) { _twoDigitYearMax = Calendar.GetSystemTwoDigitYearSetting(BaseCalendarID, GetYear(new DateTime(2029, 1, 1))); } return _twoDigitYearMax; } set { VerifyWritable(); if (value < 99 || value > MaxCalendarYear) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 99, MaxCalendarYear)); } _twoDigitYearMax = value; } } public virtual int GetSexagenaryYear(DateTime time) { CheckTicksRange(time.Ticks); TimeToLunar(time, out var year, out var _, out var _); return (year - 4) % 60 + 1; } public int GetCelestialStem(int sexagenaryYear) { if (sexagenaryYear < 1 || sexagenaryYear > 60) { throw new ArgumentOutOfRangeException("sexagenaryYear", sexagenaryYear, SR.Format(SR.ArgumentOutOfRange_Range, 1, 60)); } return (sexagenaryYear - 1) % 10 + 1; } public int GetTerrestrialBranch(int sexagenaryYear) { if (sexagenaryYear < 1 || sexagenaryYear > 60) { throw new ArgumentOutOfRangeException("sexagenaryYear", sexagenaryYear, SR.Format(SR.ArgumentOutOfRange_Range, 1, 60)); } return (sexagenaryYear - 1) % 12 + 1; } internal abstract int GetYearInfo(int LunarYear, int Index); internal abstract int GetYear(int year, DateTime time); internal abstract int GetGregorianYear(int year, int era); internal int MinEraCalendarYear(int era) { EraInfo[] calEraInfo = CalEraInfo; if (calEraInfo == null) { return MinCalendarYear; } if (era == 0) { era = CurrentEraValue; } if (era == GetEra(MinDate)) { return GetYear(MinCalendarYear, MinDate); } for (int i = 0; i < calEraInfo.Length; i++) { if (era == calEraInfo[i].era) { return calEraInfo[i].minEraYear; } } throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } internal int MaxEraCalendarYear(int era) { EraInfo[] calEraInfo = CalEraInfo; if (calEraInfo == null) { return MaxCalendarYear; } if (era == 0) { era = CurrentEraValue; } if (era == GetEra(MaxDate)) { return GetYear(MaxCalendarYear, MaxDate); } for (int i = 0; i < calEraInfo.Length; i++) { if (era == calEraInfo[i].era) { return calEraInfo[i].maxEraYear; } } throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } internal EastAsianLunisolarCalendar() { } internal void CheckTicksRange(long ticks) { if (ticks < MinSupportedDateTime.Ticks || ticks > MaxSupportedDateTime.Ticks) { throw new ArgumentOutOfRangeException("time", ticks, SR.Format(CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, MinSupportedDateTime, MaxSupportedDateTime)); } } internal void CheckEraRange(int era) { if (era == 0) { era = CurrentEraValue; } if (era < GetEra(MinDate) || era > GetEra(MaxDate)) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } } internal int CheckYearRange(int year, int era) { CheckEraRange(era); year = GetGregorianYear(year, era); if (year < MinCalendarYear || year > MaxCalendarYear) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, MinEraCalendarYear(era), MaxEraCalendarYear(era))); } return year; } internal int CheckYearMonthRange(int year, int month, int era) { year = CheckYearRange(year, era); if (month == 13 && GetYearInfo(year, 0) == 0) { ThrowHelper.ThrowArgumentOutOfRange_Month(month); } if (month < 1 || month > 13) { ThrowHelper.ThrowArgumentOutOfRange_Month(month); } return year; } internal int InternalGetDaysInMonth(int year, int month) { int num = 32768; num >>= month - 1; if ((GetYearInfo(year, 3) & num) == 0) { return 29; } return 30; } public override int GetDaysInMonth(int year, int month, int era) { year = CheckYearMonthRange(year, month, era); return InternalGetDaysInMonth(year, month); } private static bool GregorianIsLeapYear(int y) { if (y % 4 != 0) { return false; } if (y % 100 != 0) { return true; } return y % 400 == 0; } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { year = CheckYearMonthRange(year, month, era); int num = InternalGetDaysInMonth(year, month); if (day < 1 || day > num) { throw new ArgumentOutOfRangeException("day", day, SR.Format(SR.ArgumentOutOfRange_Day, num, month)); } if (!LunarToGregorian(year, month, day, out var solarYear, out var solarMonth, out var solarDay)) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } return new DateTime(solarYear, solarMonth, solarDay, hour, minute, second, millisecond); } private void GregorianToLunar(int solarYear, int solarMonth, int solarDate, out int lunarYear, out int lunarMonth, out int lunarDate) { int num = (GregorianIsLeapYear(solarYear) ? s_daysToMonth366[solarMonth - 1] : s_daysToMonth365[solarMonth - 1]); num += solarDate; int num2 = num; lunarYear = solarYear; int yearInfo; int yearInfo2; if (lunarYear == MaxCalendarYear + 1) { lunarYear--; num2 += (GregorianIsLeapYear(lunarYear) ? 366 : 365); yearInfo = GetYearInfo(lunarYear, 1); yearInfo2 = GetYearInfo(lunarYear, 2); } else { yearInfo = GetYearInfo(lunarYear, 1); yearInfo2 = GetYearInfo(lunarYear, 2); if (solarMonth < yearInfo || (solarMonth == yearInfo && solarDate < yearInfo2)) { lunarYear--; num2 += (GregorianIsLeapYear(lunarYear) ? 366 : 365); yearInfo = GetYearInfo(lunarYear, 1); yearInfo2 = GetYearInfo(lunarYear, 2); } } num2 -= s_daysToMonth365[yearInfo - 1]; num2 -= yearInfo2 - 1; int num3 = 32768; int yearInfo3 = GetYearInfo(lunarYear, 3); int num4 = (((yearInfo3 & num3) != 0) ? 30 : 29); lunarMonth = 1; while (num2 > num4) { num2 -= num4; lunarMonth++; num3 >>= 1; num4 = (((yearInfo3 & num3) != 0) ? 30 : 29); } lunarDate = num2; } private bool LunarToGregorian(int lunarYear, int lunarMonth, int lunarDate, out int solarYear, out int solarMonth, out int solarDay) { if (lunarDate < 1 || lunarDate > 30) { solarYear = 0; solarMonth = 0; solarDay = 0; return false; } int num = lunarDate - 1; for (int i = 1; i < lunarMonth; i++) { num += InternalGetDaysInMonth(lunarYear, i); } int yearInfo = GetYearInfo(lunarYear, 1); int yearInfo2 = GetYearInfo(lunarYear, 2); bool flag = GregorianIsLeapYear(lunarYear); int[] array = (flag ? s_daysToMonth366 : s_daysToMonth365); solarDay = yearInfo2; if (yearInfo > 1) { solarDay += array[yearInfo - 1]; } solarDay += num; if (solarDay > 365 + (flag ? 1 : 0)) { solarYear = lunarYear + 1; solarDay -= 365 + (flag ? 1 : 0); } else { solarYear = lunarYear; } solarMonth = 1; while (solarMonth < 12 && array[solarMonth] < solarDay) { solarMonth++; } solarDay -= array[solarMonth - 1]; return true; } private DateTime LunarToTime(DateTime time, int year, int month, int day) { LunarToGregorian(year, month, day, out var solarYear, out var solarMonth, out var solarDay); time.GetTime(out var hour, out var minute, out var second, out var millisecond); return GregorianCalendar.GetDefaultInstance().ToDateTime(solarYear, solarMonth, solarDay, hour, minute, second, millisecond); } private void TimeToLunar(DateTime time, out int year, out int month, out int day) { Calendar defaultInstance = GregorianCalendar.GetDefaultInstance(); int year2 = defaultInstance.GetYear(time); int month2 = defaultInstance.GetMonth(time); int dayOfMonth = defaultInstance.GetDayOfMonth(time); GregorianToLunar(year2, month2, dayOfMonth, out year, out month, out day); } public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException("months", months, SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000)); } CheckTicksRange(time.Ticks); TimeToLunar(time, out var year, out var month, out var day); int num = month + months; if (num > 0) { int num2 = (InternalIsLeapYear(year) ? 13 : 12); while (num - num2 > 0) { num -= num2; year++; num2 = (InternalIsLeapYear(year) ? 13 : 12); } month = num; } else { while (num <= 0) { int num3 = (InternalIsLeapYear(year - 1) ? 13 : 12); num += num3; year--; } month = num; } int num4 = InternalGetDaysInMonth(year, month); if (day > num4) { day = num4; } DateTime result = LunarToTime(time, year, month, day); Calendar.CheckAddResult(result.Ticks, MinSupportedDateTime, MaxSupportedDateTime); return result; } public override DateTime AddYears(DateTime time, int years) { CheckTicksRange(time.Ticks); TimeToLunar(time, out var year, out var month, out var day); year += years; if (month == 13 && !InternalIsLeapYear(year)) { month = 12; day = InternalGetDaysInMonth(year, month); } int num = InternalGetDaysInMonth(year, month); if (day > num) { day = num; } DateTime result = LunarToTime(time, year, month, day); Calendar.CheckAddResult(result.Ticks, MinSupportedDateTime, MaxSupportedDateTime); return result; } public override int GetDayOfYear(DateTime time) { CheckTicksRange(time.Ticks); TimeToLunar(time, out var year, out var month, out var day); for (int i = 1; i < month; i++) { day += InternalGetDaysInMonth(year, i); } return day; } public override int GetDayOfMonth(DateTime time) { CheckTicksRange(time.Ticks); TimeToLunar(time, out var _, out var _, out var day); return day; } public override int GetDaysInYear(int year, int era) { year = CheckYearRange(year, era); int num = 0; int num2 = (InternalIsLeapYear(year) ? 13 : 12); while (num2 != 0) { num += InternalGetDaysInMonth(year, num2--); } return num; } public override int GetMonth(DateTime time) { CheckTicksRange(time.Ticks); TimeToLunar(time, out var _, out var month, out var _); return month; } public override int GetYear(DateTime time) { CheckTicksRange(time.Ticks); TimeToLunar(time, out var year, out var _, out var _); return GetYear(year, time); } public override DayOfWeek GetDayOfWeek(DateTime time) { CheckTicksRange(time.Ticks); return (DayOfWeek)((int)(time.Ticks / 864000000000L + 1) % 7); } public override int GetMonthsInYear(int year, int era) { year = CheckYearRange(year, era); if (!InternalIsLeapYear(year)) { return 12; } return 13; } public override bool IsLeapDay(int year, int month, int day, int era) { year = CheckYearMonthRange(year, month, era); int num = InternalGetDaysInMonth(year, month); if (day < 1 || day > num) { throw new ArgumentOutOfRangeException("day", day, SR.Format(SR.ArgumentOutOfRange_Day, num, month)); } int yearInfo = GetYearInfo(year, 0); if (yearInfo != 0) { return month == yearInfo + 1; } return false; } public override bool IsLeapMonth(int year, int month, int era) { year = CheckYearMonthRange(year, month, era); int yearInfo = GetYearInfo(year, 0); if (yearInfo != 0) { return month == yearInfo + 1; } return false; } public override int GetLeapMonth(int year, int era) { year = CheckYearRange(year, era); int yearInfo = GetYearInfo(year, 0); if (yearInfo <= 0) { return 0; } return yearInfo + 1; } internal bool InternalIsLeapYear(int year) { return GetYearInfo(year, 0) != 0; } public override bool IsLeapYear(int year, int era) { year = CheckYearRange(year, era); return InternalIsLeapYear(year); } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", year, SR.ArgumentOutOfRange_NeedNonNegNum); } year = base.ToFourDigitYear(year); CheckYearRange(year, 0); return year; } } public static class GlobalizationExtensions { public static StringComparer GetStringComparer(this CompareInfo compareInfo, CompareOptions options) { if (compareInfo == null) { throw new ArgumentNullException("compareInfo"); } return options switch { CompareOptions.Ordinal => StringComparer.Ordinal, CompareOptions.OrdinalIgnoreCase => StringComparer.OrdinalIgnoreCase, _ => new CultureAwareComparer(compareInfo, options), }; } } internal static class GlobalizationMode { private static class Settings { internal static bool Invariant { get; } = AppContextConfigHelper.GetBooleanConfig("System.Globalization.Invariant", "DOTNET_SYSTEM_GLOBALIZATION_INVARIANT"); internal static bool PredefinedCulturesOnly { get; } = AppContextConfigHelper.GetBooleanConfig("System.Globalization.PredefinedCulturesOnly", "DOTNET_SYSTEM_GLOBALIZATION_PREDEFINED_CULTURES_ONLY", GlobalizationMode.Invariant); } internal static bool Invariant => Settings.Invariant; internal static bool PredefinedCulturesOnly => Settings.PredefinedCulturesOnly; internal static bool UseNls { get; } = !Invariant && (AppContextConfigHelper.GetBooleanConfig("System.Globalization.UseNls", "DOTNET_SYSTEM_GLOBALIZATION_USENLS") || !LoadIcu()); private static bool TryGetAppLocalIcuSwitchValue([NotNullWhen(true)] out string value) { return TryGetStringValue("System.Globalization.AppLocalIcu", "DOTNET_SYSTEM_GLOBALIZATION_APPLOCALICU", out value); } private static bool TryGetStringValue(string switchName, string envVariable, [NotNullWhen(true)] out string value) { value = AppContext.GetData(switchName) as string; if (string.IsNullOrEmpty(value)) { value = Environment.GetEnvironmentVariable(envVariable); if (string.IsNullOrEmpty(value)) { return false; } } return true; } private static void LoadAppLocalIcu(string icuSuffixAndVersion) { ReadOnlySpan suffix = default(ReadOnlySpan); int num = icuSuffixAndVersion.IndexOf(':'); ReadOnlySpan version; if (num >= 0) { suffix = icuSuffixAndVersion.AsSpan(0, num); version = icuSuffixAndVersion.AsSpan(suffix.Length + 1); } else { version = icuSuffixAndVersion; } LoadAppLocalIcuCore(version, suffix); } private static string CreateLibraryName(ReadOnlySpan baseName, ReadOnlySpan suffix, ReadOnlySpan extension, ReadOnlySpan version, bool versionAtEnd = false) { if (!versionAtEnd) { return string.Concat(baseName, suffix, version, extension); } return string.Concat(baseName, suffix, extension, version); } private static IntPtr LoadLibrary(string library, bool failOnLoadFailure) { if (!NativeLibrary.TryLoad(library, typeof(object).Assembly, DllImportSearchPath.ApplicationDirectory | DllImportSearchPath.System32, out var handle) && failOnLoadFailure) { Environment.FailFast("Failed to load app-local ICU: " + library); } return handle; } private static bool LoadIcu() { if (!TryGetAppLocalIcuSwitchValue(out var value)) { return Interop.Globalization.LoadICU() != 0; } LoadAppLocalIcu(value); return true; } private static void LoadAppLocalIcuCore(ReadOnlySpan version, ReadOnlySpan suffix) { IntPtr intPtr = IntPtr.Zero; IntPtr intPtr2 = IntPtr.Zero; int num = version.IndexOf('.'); if (num > 0) { ReadOnlySpan version2 = version.Slice(0, num); intPtr = LoadLibrary(CreateLibraryName("icuuc", suffix, ".dll", version2), failOnLoadFailure: false); if (intPtr != IntPtr.Zero) { intPtr2 = LoadLibrary(CreateLibraryName("icuin", suffix, ".dll", version2), failOnLoadFailure: false); } } if (intPtr == IntPtr.Zero) { intPtr = LoadLibrary(CreateLibraryName("icuuc", suffix, ".dll", version), failOnLoadFailure: true); } if (intPtr2 == IntPtr.Zero) { intPtr2 = LoadLibrary(CreateLibraryName("icuin", suffix, ".dll", version), failOnLoadFailure: true); } Interop.Globalization.InitICUFunctions(intPtr, intPtr2, version, suffix); } } public class GregorianCalendar : Calendar { public const int ADEra = 1; private GregorianCalendarTypes _type; private static readonly int[] DaysToMonth365 = new int[13] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; private static readonly int[] DaysToMonth366 = new int[13] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; private static volatile Calendar s_defaultInstance; public override DateTime MinSupportedDateTime => DateTime.MinValue; public override DateTime MaxSupportedDateTime => DateTime.MaxValue; public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.SolarCalendar; public virtual GregorianCalendarTypes CalendarType { get { return _type; } set { VerifyWritable(); if (value < GregorianCalendarTypes.Localized || value > GregorianCalendarTypes.TransliteratedFrench) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench)); } _type = value; } } internal override CalendarId ID => (CalendarId)_type; public override int[] Eras => new int[1] { 1 }; public override int TwoDigitYearMax { get { if (_twoDigitYearMax == -1) { _twoDigitYearMax = Calendar.GetSystemTwoDigitYearSetting(ID, 2029); } return _twoDigitYearMax; } set { VerifyWritable(); if (value < 99 || value > 9999) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 99, 9999)); } _twoDigitYearMax = value; } } internal static Calendar GetDefaultInstance() { return s_defaultInstance ?? (s_defaultInstance = new GregorianCalendar()); } public GregorianCalendar() : this(GregorianCalendarTypes.Localized) { } public GregorianCalendar(GregorianCalendarTypes type) { if (type < GregorianCalendarTypes.Localized || type > GregorianCalendarTypes.TransliteratedFrench) { throw new ArgumentOutOfRangeException("type", type, SR.Format(SR.ArgumentOutOfRange_Range, GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench)); } _type = type; } internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) { int[] array = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); if (day >= 1 && day <= array[month] - array[month - 1]) { int num = year - 1; return num * 365 + num / 4 - num / 100 + num / 400 + array[month - 1] + day - 1; } } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } internal virtual long DateToTicks(int year, int month, int day) { return GetAbsoluteDate(year, month, day) * 864000000000L; } public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException("months", months, SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000)); } time.GetDate(out var year, out var month, out var day); int num = month - 1 + months; if (num >= 0) { month = num % 12 + 1; year += num / 12; } else { month = 12 + (num + 1) % 12; year += (num - 11) / 12; } int[] array = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); int num2 = array[month] - array[month - 1]; if (day > num2) { day = num2; } long ticks = DateToTicks(year, month, day) + time.Ticks % 864000000000L; Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return new DateTime(ticks); } public override DateTime AddYears(DateTime time, int years) { return AddMonths(time, years * 12); } public override int GetDayOfMonth(DateTime time) { return time.Day; } public override DayOfWeek GetDayOfWeek(DateTime time) { return time.DayOfWeek; } public override int GetDayOfYear(DateTime time) { return time.DayOfYear; } public override int GetDaysInMonth(int year, int month, int era) { if (era != 0 && era != 1) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } return DateTime.DaysInMonth(year, month); } public override int GetDaysInYear(int year, int era) { if (era != 0 && era != 1) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } if (!DateTime.IsLeapYear(year)) { return 365; } return 366; } public override int GetEra(DateTime time) { return 1; } public override int GetMonth(DateTime time) { return time.Month; } public override int GetMonthsInYear(int year, int era) { if (era != 0 && era != 1) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > 9999) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 1, 9999)); } return 12; } public override int GetYear(DateTime time) { return time.Year; } internal override bool IsValidYear(int year, int era) { if (year >= 1) { return year <= 9999; } return false; } internal override bool IsValidDay(int year, int month, int day, int era) { if ((era != 0 && era != 1) || year < 1 || year > 9999 || month < 1 || month > 12 || day < 1) { return false; } int[] array = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); return day <= array[month] - array[month - 1]; } public override bool IsLeapDay(int year, int month, int day, int era) { if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", month, SR.Format(SR.ArgumentOutOfRange_Range, 1, 12)); } if (era != 0 && era != 1) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > 9999) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 1, 9999)); } if (day < 1 || day > GetDaysInMonth(year, month)) { throw new ArgumentOutOfRangeException("day", day, SR.Format(SR.ArgumentOutOfRange_Range, 1, GetDaysInMonth(year, month))); } if (IsLeapYear(year) && month == 2) { return day == 29; } return false; } public override int GetLeapMonth(int year, int era) { if (era != 0 && era != 1) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > 9999) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 1, 9999)); } return 0; } public override bool IsLeapMonth(int year, int month, int era) { if (era != 0 && era != 1) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > 9999) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 1, 9999)); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", month, SR.Format(SR.ArgumentOutOfRange_Range, 1, 12)); } return false; } public override bool IsLeapYear(int year, int era) { if (era != 0 && era != 1) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } return DateTime.IsLeapYear(year); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { if (era != 0 && era != 1) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } return new DateTime(year, month, day, hour, minute, second, millisecond); } internal override bool TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { if (era != 0 && era != 1) { result = DateTime.MinValue; return false; } return DateTime.TryCreate(year, month, day, hour, minute, second, millisecond, out result); } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", year, SR.ArgumentOutOfRange_NeedNonNegNum); } if (year > 9999) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 1, 9999)); } return base.ToFourDigitYear(year); } } internal sealed class EraInfo { internal int era; internal long ticks; internal int yearOffset; internal int minEraYear; internal int maxEraYear; internal string eraName; internal string abbrevEraName; internal string englishEraName; internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; ticks = new DateTime(startYear, startMonth, startDay).Ticks; } internal EraInfo(int era, int startYear, int startMonth, int startDay, int yearOffset, int minEraYear, int maxEraYear, string eraName, string abbrevEraName, string englishEraName) { this.era = era; this.yearOffset = yearOffset; this.minEraYear = minEraYear; this.maxEraYear = maxEraYear; ticks = new DateTime(startYear, startMonth, startDay).Ticks; this.eraName = eraName; this.abbrevEraName = abbrevEraName; this.englishEraName = englishEraName; } } internal sealed class GregorianCalendarHelper { internal static readonly int[] DaysToMonth365 = new int[13] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = new int[13] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; internal int m_maxYear; internal int m_minYear; internal Calendar m_Cal; internal EraInfo[] m_EraInfo; internal int[] m_eras; internal int MaxYear => m_maxYear; public int[] Eras { get { if (m_eras == null) { m_eras = new int[m_EraInfo.Length]; for (int i = 0; i < m_EraInfo.Length; i++) { m_eras[i] = m_EraInfo[i].era; } } return (int[])m_eras.Clone(); } } internal GregorianCalendarHelper(Calendar cal, EraInfo[] eraInfo) { m_Cal = cal; m_EraInfo = eraInfo; m_maxYear = m_EraInfo[0].maxEraYear; m_minYear = m_EraInfo[0].minEraYear; } private int GetYearOffset(int year, int era, bool throwOnError) { if (year < 0) { if (throwOnError) { throw new ArgumentOutOfRangeException("year", SR.ArgumentOutOfRange_NeedNonNegNum); } return -1; } if (era == 0) { era = m_Cal.CurrentEraValue; } for (int i = 0; i < m_EraInfo.Length; i++) { if (era != m_EraInfo[i].era) { continue; } if (year >= m_EraInfo[i].minEraYear) { if (year <= m_EraInfo[i].maxEraYear) { return m_EraInfo[i].yearOffset; } if (!LocalAppContextSwitches.EnforceJapaneseEraYearRanges) { int num = year - m_EraInfo[i].maxEraYear; for (int num2 = i - 1; num2 >= 0; num2--) { if (num <= m_EraInfo[num2].maxEraYear) { return m_EraInfo[i].yearOffset; } num -= m_EraInfo[num2].maxEraYear; } } } if (!throwOnError) { break; } throw new ArgumentOutOfRangeException("year", SR.Format(SR.ArgumentOutOfRange_Range, m_EraInfo[i].minEraYear, m_EraInfo[i].maxEraYear)); } if (throwOnError) { throw new ArgumentOutOfRangeException("era", SR.ArgumentOutOfRange_InvalidEraValue); } return -1; } internal int GetGregorianYear(int year, int era) { return GetYearOffset(year, era, throwOnError: true) + year; } internal bool IsValidYear(int year, int era) { return GetYearOffset(year, era, throwOnError: false) >= 0; } internal int GetDatePart(long ticks, int part) { CheckTicksRange(ticks); int num = (int)(ticks / 864000000000L); int num2 = num / 146097; num -= num2 * 146097; int num3 = num / 36524; if (num3 == 4) { num3 = 3; } num -= num3 * 36524; int num4 = num / 1461; num -= num4 * 1461; int num5 = num / 365; if (num5 == 4) { num5 = 3; } if (part == 0) { return num2 * 400 + num3 * 100 + num4 * 4 + num5 + 1; } num -= num5 * 365; if (part == 1) { return num + 1; } int[] array = ((num5 == 3 && (num4 != 24 || num3 == 3)) ? DaysToMonth366 : DaysToMonth365); int i; for (i = (num >> 5) + 1; num >= array[i]; i++) { } if (part == 2) { return i; } return num - array[i - 1] + 1; } internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= 9999 && month >= 1 && month <= 12) { int[] array = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); if (day >= 1 && day <= array[month] - array[month - 1]) { int num = year - 1; int num2 = num * 365 + num / 4 - num / 100 + num / 400 + array[month - 1] + day - 1; return num2; } } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } internal static long DateToTicks(int year, int month, int day) { return GetAbsoluteDate(year, month, day) * 864000000000L; } internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) { if (millisecond < 0 || millisecond >= 1000) { throw new ArgumentOutOfRangeException("millisecond", SR.Format(SR.ArgumentOutOfRange_Range, 0, 999)); } return InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + (long)millisecond * 10000L; } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } internal void CheckTicksRange(long ticks) { if (ticks < m_Cal.MinSupportedDateTime.Ticks || ticks > m_Cal.MaxSupportedDateTime.Ticks) { throw new ArgumentOutOfRangeException("time", SR.Format(CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime)); } } public DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException("months", SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000)); } CheckTicksRange(time.Ticks); int datePart = GetDatePart(time.Ticks, 0); int datePart2 = GetDatePart(time.Ticks, 2); int num = GetDatePart(time.Ticks, 3); int num2 = datePart2 - 1 + months; if (num2 >= 0) { datePart2 = num2 % 12 + 1; datePart += num2 / 12; } else { datePart2 = 12 + (num2 + 1) % 12; datePart += (num2 - 11) / 12; } int[] array = ((datePart % 4 == 0 && (datePart % 100 != 0 || datePart % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); int num3 = array[datePart2] - array[datePart2 - 1]; if (num > num3) { num = num3; } long ticks = DateToTicks(datePart, datePart2, num) + time.Ticks % 864000000000L; Calendar.CheckAddResult(ticks, m_Cal.MinSupportedDateTime, m_Cal.MaxSupportedDateTime); return new DateTime(ticks); } public DateTime AddYears(DateTime time, int years) { return AddMonths(time, years * 12); } public int GetDayOfMonth(DateTime time) { return GetDatePart(time.Ticks, 3); } public DayOfWeek GetDayOfWeek(DateTime time) { CheckTicksRange(time.Ticks); return (DayOfWeek)((time.Ticks / 864000000000L + 1) % 7); } public int GetDayOfYear(DateTime time) { return GetDatePart(time.Ticks, 1); } public int GetDaysInMonth(int year, int month, int era) { year = GetGregorianYear(year, era); if (month < 1 || month > 12) { ThrowHelper.ThrowArgumentOutOfRange_Month(month); } int[] array = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); return array[month] - array[month - 1]; } public int GetDaysInYear(int year, int era) { year = GetGregorianYear(year, era); if (year % 4 != 0 || (year % 100 == 0 && year % 400 != 0)) { return 365; } return 366; } public int GetEra(DateTime time) { long ticks = time.Ticks; for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return m_EraInfo[i].era; } } throw new ArgumentOutOfRangeException("time", SR.ArgumentOutOfRange_Era); } public int GetMonth(DateTime time) { return GetDatePart(time.Ticks, 2); } public int GetMonthsInYear(int year, int era) { ValidateYearInEra(year, era); return 12; } public int GetYear(DateTime time) { long ticks = time.Ticks; int datePart = GetDatePart(ticks, 0); for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks) { return datePart - m_EraInfo[i].yearOffset; } } throw new ArgumentException(SR.Argument_NoEra); } public int GetYear(int year, DateTime time) { long ticks = time.Ticks; for (int i = 0; i < m_EraInfo.Length; i++) { if (ticks >= m_EraInfo[i].ticks && year > m_EraInfo[i].yearOffset) { return year - m_EraInfo[i].yearOffset; } } throw new ArgumentException(SR.Argument_NoEra); } public bool IsLeapDay(int year, int month, int day, int era) { if (day < 1 || day > GetDaysInMonth(year, month, era)) { throw new ArgumentOutOfRangeException("day", SR.Format(SR.ArgumentOutOfRange_Range, 1, GetDaysInMonth(year, month, era))); } if (!IsLeapYear(year, era)) { return false; } if (month == 2 && day == 29) { return true; } return false; } public void ValidateYearInEra(int year, int era) { GetYearOffset(year, era, throwOnError: true); } public int GetLeapMonth(int year, int era) { ValidateYearInEra(year, era); return 0; } public bool IsLeapMonth(int year, int month, int era) { ValidateYearInEra(year, era); if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException("month", SR.Format(SR.ArgumentOutOfRange_Range, 1, 12)); } return false; } public bool IsLeapYear(int year, int era) { year = GetGregorianYear(year, era); if (year % 4 == 0) { if (year % 100 == 0) { return year % 400 == 0; } return true; } return false; } public DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { year = GetGregorianYear(year, era); long ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second, millisecond); CheckTicksRange(ticks); return new DateTime(ticks); } public int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { CheckTicksRange(time.Ticks); return GregorianCalendar.GetDefaultInstance().GetWeekOfYear(time, rule, firstDayOfWeek); } public int ToFourDigitYear(int year, int twoDigitYearMax) { if (year < 0) { throw new ArgumentOutOfRangeException("year", SR.ArgumentOutOfRange_NeedPosNum); } if (year < 100) { int num = year % 100; return (twoDigitYearMax / 100 - ((num > twoDigitYearMax % 100) ? 1 : 0)) * 100 + num; } if (year < m_minYear || year > m_maxYear) { throw new ArgumentOutOfRangeException("year", SR.Format(SR.ArgumentOutOfRange_Range, m_minYear, m_maxYear)); } return year; } } public enum GregorianCalendarTypes { Localized = 1, USEnglish = 2, MiddleEastFrench = 9, Arabic = 10, TransliteratedEnglish = 11, TransliteratedFrench = 12 } public class HebrewCalendar : Calendar { internal sealed class DateBuffer { internal int year; internal int month; internal int day; } public static readonly int HebrewEra = 1; private static readonly DateTime s_calendarMinValue = new DateTime(1583, 1, 1); private static readonly DateTime s_calendarMaxValue = new DateTime(new DateTime(2239, 9, 29, 23, 59, 59, 999).Ticks + 9999); private static ReadOnlySpan HebrewTable => new byte[1316] { 7, 3, 17, 3, 0, 4, 11, 2, 21, 6, 1, 3, 13, 2, 25, 4, 5, 3, 16, 2, 27, 6, 9, 1, 20, 2, 0, 6, 11, 3, 23, 4, 4, 2, 14, 3, 27, 4, 8, 2, 18, 3, 28, 6, 11, 1, 22, 5, 2, 3, 12, 3, 25, 4, 6, 2, 16, 3, 26, 6, 8, 2, 20, 1, 0, 6, 11, 2, 24, 4, 4, 3, 15, 2, 25, 6, 8, 1, 19, 2, 29, 6, 9, 3, 22, 4, 3, 2, 13, 3, 25, 4, 6, 3, 17, 2, 27, 6, 7, 3, 19, 2, 31, 4, 11, 3, 23, 4, 5, 2, 15, 3, 25, 6, 6, 2, 19, 1, 29, 6, 10, 2, 22, 4, 3, 3, 14, 2, 24, 6, 6, 1, 17, 3, 28, 5, 8, 3, 20, 1, 32, 5, 12, 3, 22, 6, 4, 1, 16, 2, 26, 6, 6, 3, 17, 2, 0, 4, 10, 3, 22, 4, 3, 2, 14, 3, 24, 6, 5, 2, 17, 1, 28, 6, 9, 2, 19, 3, 31, 4, 13, 2, 23, 6, 3, 3, 15, 1, 27, 5, 7, 3, 17, 3, 29, 4, 11, 2, 21, 6, 3, 1, 14, 2, 25, 6, 5, 3, 16, 2, 28, 4, 9, 3, 20, 2, 0, 6, 12, 1, 23, 6, 4, 2, 14, 3, 26, 4, 8, 2, 18, 3, 0, 4, 10, 3, 21, 5, 1, 3, 13, 1, 24, 5, 5, 3, 15, 3, 27, 4, 8, 2, 19, 3, 29, 6, 10, 2, 22, 4, 3, 3, 14, 2, 26, 4, 6, 3, 18, 2, 28, 6, 10, 1, 20, 6, 2, 2, 12, 3, 24, 4, 5, 2, 16, 3, 28, 4, 8, 3, 19, 2, 0, 6, 12, 1, 23, 5, 3, 3, 14, 3, 26, 4, 7, 2, 17, 3, 28, 6, 9, 2, 21, 4, 1, 3, 13, 2, 25, 4, 5, 3, 16, 2, 27, 6, 9, 1, 19, 3, 0, 5, 11, 3, 23, 4, 4, 2, 14, 3, 25, 6, 7, 1, 18, 2, 28, 6, 9, 3, 21, 4, 2, 2, 12, 3, 25, 4, 6, 2, 16, 3, 26, 6, 8, 2, 20, 1, 0, 6, 11, 2, 22, 6, 4, 1, 15, 2, 25, 6, 6, 3, 18, 1, 29, 5, 9, 3, 22, 4, 2, 3, 13, 2, 23, 6, 4, 3, 15, 2, 27, 4, 7, 3, 19, 2, 31, 4, 11, 3, 21, 6, 3, 2, 15, 1, 25, 6, 6, 2, 17, 3, 29, 4, 10, 2, 20, 6, 3, 1, 13, 3, 24, 5, 4, 3, 16, 1, 27, 5, 7, 3, 17, 3, 0, 4, 11, 2, 21, 6, 1, 3, 13, 2, 25, 4, 5, 3, 16, 2, 29, 4, 9, 3, 19, 6, 30, 2, 13, 1, 23, 6, 4, 2, 14, 3, 27, 4, 8, 2, 18, 3, 0, 4, 11, 3, 22, 5, 2, 3, 14, 1, 26, 5, 6, 3, 16, 3, 28, 4, 10, 2, 20, 6, 30, 3, 11, 2, 24, 4, 4, 3, 15, 2, 25, 6, 8, 1, 19, 2, 29, 6, 9, 3, 22, 4, 3, 2, 13, 3, 25, 4, 7, 2, 17, 3, 27, 6, 9, 1, 21, 5, 1, 3, 11, 3, 23, 4, 5, 2, 15, 3, 25, 6, 6, 2, 19, 1, 29, 6, 10, 2, 22, 4, 3, 3, 14, 2, 24, 6, 6, 1, 18, 2, 28, 6, 8, 3, 20, 4, 2, 2, 12, 3, 24, 4, 4, 3, 16, 2, 26, 6, 6, 3, 17, 2, 0, 4, 10, 3, 22, 4, 3, 2, 14, 3, 24, 6, 5, 2, 17, 1, 28, 6, 9, 2, 21, 4, 1, 3, 13, 2, 23, 6, 5, 1, 15, 3, 27, 5, 7, 3, 19, 1, 0, 5, 10, 3, 22, 4, 2, 3, 13, 2, 24, 6, 4, 3, 15, 2, 27, 4, 8, 3, 20, 4, 1, 2, 11, 3, 22, 6, 3, 2, 15, 1, 25, 6, 7, 2, 17, 3, 29, 4, 10, 2, 21, 6, 1, 3, 13, 1, 24, 5, 5, 3, 15, 3, 27, 4, 8, 2, 19, 6, 1, 1, 12, 2, 22, 6, 3, 3, 14, 2, 26, 4, 6, 3, 18, 2, 28, 6, 10, 1, 20, 6, 2, 2, 12, 3, 24, 4, 5, 2, 16, 3, 28, 4, 9, 2, 19, 6, 30, 3, 12, 1, 23, 5, 3, 3, 14, 3, 26, 4, 7, 2, 17, 3, 28, 6, 9, 2, 21, 4, 1, 3, 13, 2, 25, 4, 5, 3, 16, 2, 27, 6, 9, 1, 19, 6, 30, 2, 11, 3, 23, 4, 4, 2, 14, 3, 27, 4, 7, 3, 18, 2, 28, 6, 11, 1, 22, 5, 2, 3, 12, 3, 25, 4, 6, 2, 16, 3, 26, 6, 8, 2, 20, 4, 30, 3, 11, 2, 24, 4, 4, 3, 15, 2, 25, 6, 8, 1, 18, 3, 29, 5, 9, 3, 22, 4, 3, 2, 13, 3, 23, 6, 6, 1, 17, 2, 27, 6, 7, 3, 20, 4, 1, 2, 11, 3, 23, 4, 5, 2, 15, 3, 25, 6, 6, 2, 19, 1, 29, 6, 10, 2, 20, 6, 3, 1, 14, 2, 24, 6, 4, 3, 17, 1, 28, 5, 8, 3, 20, 4, 1, 3, 12, 2, 22, 6, 2, 3, 14, 2, 26, 4, 6, 3, 17, 2, 0, 4, 10, 3, 20, 6, 1, 2, 14, 1, 24, 6, 5, 2, 15, 3, 28, 4, 9, 2, 19, 6, 1, 1, 12, 3, 23, 5, 3, 3, 15, 1, 27, 5, 7, 3, 17, 3, 29, 4, 11, 2, 21, 6, 1, 3, 12, 2, 25, 4, 5, 3, 16, 2, 28, 4, 9, 3, 19, 6, 30, 2, 12, 1, 23, 6, 4, 2, 14, 3, 26, 4, 8, 2, 18, 3, 0, 4, 10, 3, 22, 5, 2, 3, 14, 1, 25, 5, 6, 3, 16, 3, 28, 4, 9, 2, 20, 6, 30, 3, 11, 2, 23, 4, 4, 3, 15, 2, 27, 4, 7, 3, 19, 2, 29, 6, 11, 1, 21, 6, 3, 2, 13, 3, 25, 4, 6, 2, 17, 3, 27, 6, 9, 1, 20, 5, 30, 3, 10, 3, 22, 4, 3, 2, 14, 3, 24, 6, 5, 2, 17, 1, 28, 6, 9, 2, 21, 4, 1, 3, 13, 2, 23, 6, 5, 1, 16, 2, 27, 6, 7, 3, 19, 4, 30, 2, 11, 3, 23, 4, 3, 3, 14, 2, 25, 6, 5, 3, 16, 2, 28, 4, 9, 3, 21, 4, 2, 2, 12, 3, 23, 6, 4, 2, 16, 1, 26, 6, 8, 2, 20, 4, 30, 3, 11, 2, 22, 6, 4, 1, 14, 3, 25, 5, 6, 3, 18, 1, 29, 5, 9, 3, 22, 4, 2, 3, 13, 2, 23, 6, 4, 3, 15, 2, 27, 4, 7, 3, 20, 4, 1, 2, 11, 3, 21, 6, 3, 2, 15, 1, 25, 6, 6, 2, 17, 3, 29, 4, 10, 2, 20, 6, 3, 1, 13, 3, 24, 5, 4, 3, 17, 1, 28, 5, 8, 3, 18, 6, 1, 1, 12, 2, 22, 6, 2, 3, 14, 2, 26, 4, 6, 3, 17, 2, 28, 6, 10, 1, 20, 6, 1, 2, 12, 3, 24, 4, 5, 2, 15, 3, 28, 4, 9, 2, 19, 6, 33, 3, 12, 1, 23, 5, 3, 3, 13, 3, 25, 4, 6, 2, 16, 3, 26, 6, 8, 2, 20, 4, 30, 3, 11, 2, 24, 4, 4, 3, 15, 2, 25, 6, 8, 1, 18, 6, 33, 2, 9, 3, 22, 4, 3, 2, 13, 3, 25, 4, 6, 3, 17, 2, 27, 6, 9, 1, 21, 5, 1, 3, 11, 3, 23, 4, 5, 2, 15, 3, 25, 6, 6, 2, 19, 4, 33, 3, 10, 2, 22, 4, 3, 3, 14, 2, 24, 6, 6, 1 }; private static ReadOnlySpan LunarMonthLen => new byte[98] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30, 29, 29, 29, 30, 29, 30, 29, 30, 29, 30, 29, 0, 0, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 0, 0, 30, 30, 30, 29, 30, 29, 30, 29, 30, 29, 30, 29, 0, 0, 30, 29, 29, 29, 30, 30, 29, 30, 29, 30, 29, 30, 29, 0, 30, 29, 30, 29, 30, 30, 29, 30, 29, 30, 29, 30, 29, 0, 30, 30, 30, 29, 30, 30, 29, 30, 29, 30, 29, 30, 29 }; public override DateTime MinSupportedDateTime => s_calendarMinValue; public override DateTime MaxSupportedDateTime => s_calendarMaxValue; public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.LunisolarCalendar; internal override CalendarId ID => CalendarId.HEBREW; public override int[] Eras => new int[1] { HebrewEra }; public override int TwoDigitYearMax { get { if (_twoDigitYearMax == -1) { _twoDigitYearMax = Calendar.GetSystemTwoDigitYearSetting(ID, 5790); } return _twoDigitYearMax; } set { VerifyWritable(); if (value != 99) { CheckHebrewYearValue(value, HebrewEra, "value"); } _twoDigitYearMax = value; } } private static void CheckHebrewYearValue(int y, int era, string varName) { CheckEraRange(era); if (y > 5999 || y < 5343) { throw new ArgumentOutOfRangeException(varName, y, SR.Format(SR.ArgumentOutOfRange_Range, 5343, 5999)); } } private void CheckHebrewMonthValue(int year, int month, int era) { int monthsInYear = GetMonthsInYear(year, era); if (month < 1 || month > monthsInYear) { throw new ArgumentOutOfRangeException("month", month, SR.Format(SR.ArgumentOutOfRange_Range, 1, monthsInYear)); } } private void CheckHebrewDayValue(int year, int month, int day, int era) { int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException("day", day, SR.Format(SR.ArgumentOutOfRange_Range, 1, daysInMonth)); } } private static void CheckEraRange(int era) { if (era != 0 && era != HebrewEra) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } } private static void CheckTicksRange(long ticks) { if (ticks < s_calendarMinValue.Ticks || ticks > s_calendarMaxValue.Ticks) { throw new ArgumentOutOfRangeException("time", ticks, SR.Format(CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, s_calendarMinValue, s_calendarMaxValue)); } } private static int GetResult(DateBuffer result, int part) { return part switch { 0 => result.year, 2 => result.month, 3 => result.day, _ => throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing), }; } internal static int GetLunarMonthDay(int gregorianYear, DateBuffer lunarDate) { int num = gregorianYear - 1583; if (num < 0 || num > 656) { throw new ArgumentOutOfRangeException("gregorianYear"); } num *= 2; lunarDate.day = HebrewTable[num]; int result = HebrewTable[num + 1]; switch (lunarDate.day) { case 0: lunarDate.month = 5; lunarDate.day = 1; break; case 30: lunarDate.month = 3; break; case 31: lunarDate.month = 5; lunarDate.day = 2; break; case 32: lunarDate.month = 5; lunarDate.day = 3; break; case 33: lunarDate.month = 3; lunarDate.day = 29; break; default: lunarDate.month = 4; break; } return result; } internal virtual int GetDatePart(long ticks, int part) { CheckTicksRange(ticks); new DateTime(ticks).GetDate(out var year, out var month, out var day); DateBuffer dateBuffer = new DateBuffer(); dateBuffer.year = year + 3760; int num = GetLunarMonthDay(year, dateBuffer); DateBuffer dateBuffer2 = new DateBuffer(); dateBuffer2.year = dateBuffer.year; dateBuffer2.month = dateBuffer.month; dateBuffer2.day = dateBuffer.day; long absoluteDate = GregorianCalendar.GetAbsoluteDate(year, month, day); if (month == 1 && day == 1) { return GetResult(dateBuffer2, part); } long num2 = absoluteDate - GregorianCalendar.GetAbsoluteDate(year, 1, 1); if (num2 + dateBuffer.day <= LunarMonthLen[num * 14 + dateBuffer.month]) { dateBuffer2.day += (int)num2; return GetResult(dateBuffer2, part); } dateBuffer2.month++; dateBuffer2.day = 1; num2 -= LunarMonthLen[num * 14 + dateBuffer.month] - dateBuffer.day; if (num2 > 1) { while (num2 > LunarMonthLen[num * 14 + dateBuffer2.month]) { num2 -= LunarMonthLen[num * 14 + dateBuffer2.month++]; if (dateBuffer2.month > 13 || LunarMonthLen[num * 14 + dateBuffer2.month] == 0) { dateBuffer2.year++; num = HebrewTable[(year + 1 - 1583) * 2 + 1]; dateBuffer2.month = 1; } } dateBuffer2.day += (int)(num2 - 1); } return GetResult(dateBuffer2, part); } public override DateTime AddMonths(DateTime time, int months) { try { int num = GetDatePart(time.Ticks, 0); int datePart = GetDatePart(time.Ticks, 2); int num2 = GetDatePart(time.Ticks, 3); int num3; if (months >= 0) { int monthsInYear; for (num3 = datePart + months; num3 > (monthsInYear = GetMonthsInYear(num, 0)); num3 -= monthsInYear) { num++; } } else if ((num3 = datePart + months) <= 0) { months = -months; months -= datePart; num--; int monthsInYear; while (months > (monthsInYear = GetMonthsInYear(num, 0))) { num--; months -= monthsInYear; } monthsInYear = GetMonthsInYear(num, 0); num3 = monthsInYear - months; } int daysInMonth = GetDaysInMonth(num, num3); if (num2 > daysInMonth) { num2 = daysInMonth; } return new DateTime(ToDateTime(num, num3, num2, 0, 0, 0, 0).Ticks + time.Ticks % 864000000000L); } catch (ArgumentException) { throw new ArgumentOutOfRangeException("months", months, SR.ArgumentOutOfRange_AddValue); } } public override DateTime AddYears(DateTime time, int years) { int datePart = GetDatePart(time.Ticks, 0); int num = GetDatePart(time.Ticks, 2); int num2 = GetDatePart(time.Ticks, 3); datePart += years; CheckHebrewYearValue(datePart, 0, "years"); int monthsInYear = GetMonthsInYear(datePart, 0); if (num > monthsInYear) { num = monthsInYear; } int daysInMonth = GetDaysInMonth(datePart, num); if (num2 > daysInMonth) { num2 = daysInMonth; } long ticks = ToDateTime(datePart, num, num2, 0, 0, 0, 0).Ticks + time.Ticks % 864000000000L; Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return new DateTime(ticks); } public override int GetDayOfMonth(DateTime time) { return GetDatePart(time.Ticks, 3); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (DayOfWeek)((int)(time.Ticks / 864000000000L + 1) % 7); } internal static int GetHebrewYearType(int year, int era) { CheckHebrewYearValue(year, era, "year"); return HebrewTable[(year - 3760 - 1583) * 2 + 1]; } public override int GetDayOfYear(DateTime time) { int year = GetYear(time); DateTime dateTime = ((year != 5343) ? ToDateTime(year, 1, 1, 0, 0, 0, 0, 0) : new DateTime(1582, 9, 27)); return (int)((time.Ticks - dateTime.Ticks) / 864000000000L) + 1; } public override int GetDaysInMonth(int year, int month, int era) { CheckEraRange(era); int hebrewYearType = GetHebrewYearType(year, era); CheckHebrewMonthValue(year, month, era); int num = LunarMonthLen[hebrewYearType * 14 + month]; if (num == 0) { ThrowHelper.ThrowArgumentOutOfRange_Month(month); } return num; } public override int GetDaysInYear(int year, int era) { CheckEraRange(era); int hebrewYearType = GetHebrewYearType(year, era); if (hebrewYearType < 4) { return 352 + hebrewYearType; } return 382 + (hebrewYearType - 3); } public override int GetEra(DateTime time) { return HebrewEra; } public override int GetMonth(DateTime time) { return GetDatePart(time.Ticks, 2); } public override int GetMonthsInYear(int year, int era) { if (!IsLeapYear(year, era)) { return 12; } return 13; } public override int GetYear(DateTime time) { return GetDatePart(time.Ticks, 0); } public override bool IsLeapDay(int year, int month, int day, int era) { if (IsLeapMonth(year, month, era)) { CheckHebrewDayValue(year, month, day, era); return true; } if (IsLeapYear(year, 0) && month == 6 && day == 30) { return true; } CheckHebrewDayValue(year, month, day, era); return false; } public override int GetLeapMonth(int year, int era) { if (IsLeapYear(year, era)) { return 7; } return 0; } public override bool IsLeapMonth(int year, int month, int era) { bool flag = IsLeapYear(year, era); CheckHebrewMonthValue(year, month, era); if (flag) { return month == 7; } return false; } public override bool IsLeapYear(int year, int era) { CheckHebrewYearValue(year, era, "year"); return (7L * (long)year + 1) % 19 < 7; } private static int GetDayDifference(int lunarYearType, int month1, int day1, int month2, int day2) { if (month1 == month2) { return day1 - day2; } bool flag = month1 > month2; if (flag) { int num = month1; int num2 = day1; month1 = month2; day1 = day2; month2 = num; day2 = num2; } int num3 = LunarMonthLen[lunarYearType * 14 + month1] - day1; month1++; while (month1 < month2) { num3 += LunarMonthLen[lunarYearType * 14 + month1++]; } num3 += day2; if (!flag) { return -num3; } return num3; } private static DateTime HebrewToGregorian(int hebrewYear, int hebrewMonth, int hebrewDay, int hour, int minute, int second, int millisecond) { int num = hebrewYear - 3760; DateBuffer dateBuffer = new DateBuffer(); int lunarMonthDay = GetLunarMonthDay(num, dateBuffer); if (hebrewMonth == dateBuffer.month && hebrewDay == dateBuffer.day) { return new DateTime(num, 1, 1, hour, minute, second, millisecond); } int dayDifference = GetDayDifference(lunarMonthDay, hebrewMonth, hebrewDay, dateBuffer.month, dateBuffer.day); return new DateTime(new DateTime(num, 1, 1).Ticks + dayDifference * 864000000000L + Calendar.TimeToTicks(hour, minute, second, millisecond)); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { CheckHebrewYearValue(year, era, "year"); CheckHebrewMonthValue(year, month, era); CheckHebrewDayValue(year, month, day, era); DateTime result = HebrewToGregorian(year, month, day, hour, minute, second, millisecond); CheckTicksRange(result.Ticks); return result; } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", year, SR.ArgumentOutOfRange_NeedNonNegNum); } if (year < 100) { return base.ToFourDigitYear(year); } if (year > 5999 || year < 5343) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 5343, 5999)); } return year; } } internal struct HebrewNumberParsingContext { internal HebrewNumber.HS state; internal int result; public HebrewNumberParsingContext(int result) { state = HebrewNumber.HS.Start; this.result = result; } } internal enum HebrewNumberParsingState { InvalidHebrewNumber, NotHebrewDigit, FoundEndOfHebrewNumber, ContinueParsing } internal static class HebrewNumber { private enum HebrewToken : short { Invalid = -1, Digit400, Digit200_300, Digit100, Digit10, Digit1, Digit6_7, Digit7, Digit9, SingleQuote, DoubleQuote } private struct HebrewValue { internal HebrewToken token; internal short value; internal HebrewValue(HebrewToken token, short value) { this.token = token; this.value = value; } } internal enum HS : sbyte { _err = -1, Start = 0, S400 = 1, S400_400 = 2, S400_X00 = 3, S400_X0 = 4, X00_DQ = 5, S400_X00_X0 = 6, X0_DQ = 7, X = 8, X0 = 9, X00 = 10, S400_DQ = 11, S400_400_DQ = 12, S400_400_100 = 13, S9 = 14, X00_S9 = 15, S9_DQ = 16, END = 100 } private static readonly HebrewValue[] s_hebrewValues = new HebrewValue[27] { new HebrewValue(HebrewToken.Digit1, 1), new HebrewValue(HebrewToken.Digit1, 2), new HebrewValue(HebrewToken.Digit1, 3), new HebrewValue(HebrewToken.Digit1, 4), new HebrewValue(HebrewToken.Digit1, 5), new HebrewValue(HebrewToken.Digit6_7, 6), new HebrewValue(HebrewToken.Digit6_7, 7), new HebrewValue(HebrewToken.Digit1, 8), new HebrewValue(HebrewToken.Digit9, 9), new HebrewValue(HebrewToken.Digit10, 10), new HebrewValue(HebrewToken.Invalid, -1), new HebrewValue(HebrewToken.Digit10, 20), new HebrewValue(HebrewToken.Digit10, 30), new HebrewValue(HebrewToken.Invalid, -1), new HebrewValue(HebrewToken.Digit10, 40), new HebrewValue(HebrewToken.Invalid, -1), new HebrewValue(HebrewToken.Digit10, 50), new HebrewValue(HebrewToken.Digit10, 60), new HebrewValue(HebrewToken.Digit10, 70), new HebrewValue(HebrewToken.Invalid, -1), new HebrewValue(HebrewToken.Digit10, 80), new HebrewValue(HebrewToken.Invalid, -1), new HebrewValue(HebrewToken.Digit10, 90), new HebrewValue(HebrewToken.Digit100, 100), new HebrewValue(HebrewToken.Digit200_300, 200), new HebrewValue(HebrewToken.Digit200_300, 300), new HebrewValue(HebrewToken.Digit400, 400) }; private static readonly char s_maxHebrewNumberCh = (char)(1488 + s_hebrewValues.Length - 1); private static readonly HS[] s_numberPasingState = new HS[170] { HS.S400, HS.X00, HS.X00, HS.X0, HS.X, HS.X, HS.X, HS.S9, HS._err, HS._err, HS.S400_400, HS.S400_X00, HS.S400_X00, HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS.END, HS.S400_DQ, HS._err, HS._err, HS.S400_400_100, HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS._err, HS.S400_400_DQ, HS._err, HS._err, HS._err, HS.S400_X00_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS._err, HS.X00_DQ, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.X0_DQ, HS._err, HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.X0_DQ, HS._err, HS._err, HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.X0_DQ, HS._err, HS._err, HS._err, HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS.END, HS.X00_DQ, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err, HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err, HS._err, HS._err, HS._err, HS.S400_X00_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS._err, HS.X00_DQ, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.S9_DQ, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.S9_DQ, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.END, HS._err, HS._err, HS._err }; internal static void Append(StringBuilder outputBuffer, int Number) { int length = outputBuffer.Length; char c = '\0'; if (Number > 5000) { Number -= 5000; } int num = Number / 100; if (num > 0) { Number -= num * 100; for (int i = 0; i < num / 4; i++) { outputBuffer.Append('ת'); } int num2 = num % 4; if (num2 > 0) { outputBuffer.Append((char)(1510 + num2)); } } int num3 = Number / 10; Number %= 10; switch (num3) { case 0: c = '\0'; break; case 1: c = 'י'; break; case 2: c = 'כ'; break; case 3: c = 'ל'; break; case 4: c = 'מ'; break; case 5: c = 'נ'; break; case 6: c = 'ס'; break; case 7: c = 'ע'; break; case 8: c = 'פ'; break; case 9: c = 'צ'; break; } char c2 = (char)((Number > 0) ? ((uint)(1488 + Number - 1)) : 0u); if (c2 == 'ה' && c == 'י') { c2 = 'ו'; c = 'ט'; } if (c2 == 'ו' && c == 'י') { c2 = 'ז'; c = 'ט'; } if (c != 0) { outputBuffer.Append(c); } if (c2 != 0) { outputBuffer.Append(c2); } if (outputBuffer.Length - length > 1) { outputBuffer.Insert(outputBuffer.Length - 1, '"'); } else { outputBuffer.Append('\''); } } internal static HebrewNumberParsingState ParseByChar(char ch, ref HebrewNumberParsingContext context) { HebrewToken hebrewToken; switch (ch) { case '\'': hebrewToken = HebrewToken.SingleQuote; break; case '"': hebrewToken = HebrewToken.DoubleQuote; break; default: { int num = ch - 1488; if (num >= 0 && num < s_hebrewValues.Length) { hebrewToken = s_hebrewValues[num].token; if (hebrewToken == HebrewToken.Invalid) { return HebrewNumberParsingState.NotHebrewDigit; } context.result += s_hebrewValues[num].value; break; } return HebrewNumberParsingState.NotHebrewDigit; } } context.state = s_numberPasingState[(int)context.state * 10 + (int)hebrewToken]; if (context.state == HS._err) { return HebrewNumberParsingState.InvalidHebrewNumber; } if (context.state == HS.END) { return HebrewNumberParsingState.FoundEndOfHebrewNumber; } return HebrewNumberParsingState.ContinueParsing; } internal static bool IsDigit(char ch) { if (ch >= 'א' && ch <= s_maxHebrewNumberCh) { return s_hebrewValues[ch - 1488].value >= 0; } if (ch != '\'') { return ch == '"'; } return true; } } public class HijriCalendar : Calendar { public static readonly int HijriEra = 1; private static readonly int[] s_hijriMonthDays = new int[13] { 0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355 }; private int _hijriAdvance = int.MinValue; private static readonly DateTime s_calendarMinValue = new DateTime(622, 7, 18); private static readonly DateTime s_calendarMaxValue = DateTime.MaxValue; public override DateTime MinSupportedDateTime => s_calendarMinValue; public override DateTime MaxSupportedDateTime => s_calendarMaxValue; public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.LunarCalendar; internal override CalendarId ID => CalendarId.HIJRI; protected override int DaysInYearBeforeMinSupportedYear => 354; public int HijriAdjustment { get { if (_hijriAdvance == int.MinValue) { _hijriAdvance = GetHijriDateAdjustment(); } return _hijriAdvance; } set { if (value < -2 || value > 2) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, -2, 2)); } VerifyWritable(); _hijriAdvance = value; } } public override int[] Eras => new int[1] { HijriEra }; public override int TwoDigitYearMax { get { if (_twoDigitYearMax == -1) { _twoDigitYearMax = Calendar.GetSystemTwoDigitYearSetting(ID, 1451); } return _twoDigitYearMax; } set { VerifyWritable(); if (value < 99 || value > 9666) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 99, 9666)); } _twoDigitYearMax = value; } } private long GetAbsoluteDateHijri(int y, int m, int d) { return DaysUpToHijriYear(y) + s_hijriMonthDays[m - 1] + d - 1 - HijriAdjustment; } private long DaysUpToHijriYear(int HijriYear) { int num = (HijriYear - 1) / 30 * 30; int num2 = HijriYear - num - 1; long num3 = (long)num * 10631L / 30 + 227013; while (num2 > 0) { num3 += 354 + (IsLeapYear(num2, 0) ? 1 : 0); num2--; } return num3; } internal static void CheckTicksRange(long ticks) { if (ticks < s_calendarMinValue.Ticks || ticks > s_calendarMaxValue.Ticks) { throw new ArgumentOutOfRangeException("time", ticks, SR.Format(CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, s_calendarMinValue, s_calendarMaxValue)); } } internal static void CheckEraRange(int era) { if (era != 0 && era != HijriEra) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } } internal static void CheckYearRange(int year, int era) { CheckEraRange(era); if (year < 1 || year > 9666) { throw new ArgumentOutOfRangeException("year", SR.Format(SR.ArgumentOutOfRange_Range, 1, 9666)); } } internal static void CheckYearMonthRange(int year, int month, int era) { CheckYearRange(year, era); if (year == 9666 && month > 4) { throw new ArgumentOutOfRangeException("month", month, SR.Format(SR.ArgumentOutOfRange_Range, 1, 4)); } if (month < 1 || month > 12) { ThrowHelper.ThrowArgumentOutOfRange_Month(month); } } internal virtual int GetDatePart(long ticks, int part) { CheckTicksRange(ticks); long num = ticks / 864000000000L + 1; num += HijriAdjustment; int num2 = (int)((num - 227013) * 30 / 10631) + 1; long num3 = DaysUpToHijriYear(num2); long num4 = GetDaysInYear(num2, 0); if (num < num3) { num3 -= num4; num2--; } else if (num == num3) { num2--; num3 -= GetDaysInYear(num2, 0); } else if (num > num3 + num4) { num3 += num4; num2++; } if (part == 0) { return num2; } int i = 1; num -= num3; if (part == 1) { return (int)num; } for (; i <= 12 && num > s_hijriMonthDays[i - 1]; i++) { } i--; if (part == 2) { return i; } int result = (int)(num - s_hijriMonthDays[i - 1]); if (part == 3) { return result; } throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing); } public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException("months", months, SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000)); } int datePart = GetDatePart(time.Ticks, 0); int datePart2 = GetDatePart(time.Ticks, 2); int num = GetDatePart(time.Ticks, 3); int num2 = datePart2 - 1 + months; if (num2 >= 0) { datePart2 = num2 % 12 + 1; datePart += num2 / 12; } else { datePart2 = 12 + (num2 + 1) % 12; datePart += (num2 - 11) / 12; } int daysInMonth = GetDaysInMonth(datePart, datePart2); if (num > daysInMonth) { num = daysInMonth; } long ticks = GetAbsoluteDateHijri(datePart, datePart2, num) * 864000000000L + time.Ticks % 864000000000L; Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return new DateTime(ticks); } public override DateTime AddYears(DateTime time, int years) { return AddMonths(time, years * 12); } public override int GetDayOfMonth(DateTime time) { return GetDatePart(time.Ticks, 3); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (DayOfWeek)((int)(time.Ticks / 864000000000L + 1) % 7); } public override int GetDayOfYear(DateTime time) { return GetDatePart(time.Ticks, 1); } public override int GetDaysInMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); if (month == 12) { if (!IsLeapYear(year, 0)) { return 29; } return 30; } if (month % 2 != 1) { return 29; } return 30; } public override int GetDaysInYear(int year, int era) { CheckYearRange(year, era); if (!IsLeapYear(year, 0)) { return 354; } return 355; } public override int GetEra(DateTime time) { CheckTicksRange(time.Ticks); return HijriEra; } public override int GetMonth(DateTime time) { return GetDatePart(time.Ticks, 2); } public override int GetMonthsInYear(int year, int era) { CheckYearRange(year, era); return 12; } public override int GetYear(DateTime time) { return GetDatePart(time.Ticks, 0); } public override bool IsLeapDay(int year, int month, int day, int era) { int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException("day", day, SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month)); } if (IsLeapYear(year, era) && month == 12) { return day == 30; } return false; } public override int GetLeapMonth(int year, int era) { CheckYearRange(year, era); return 0; } public override bool IsLeapMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); return false; } public override bool IsLeapYear(int year, int era) { CheckYearRange(year, era); return (year * 11 + 14) % 30 < 11; } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException("day", day, SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month)); } long absoluteDateHijri = GetAbsoluteDateHijri(year, month, day); if (absoluteDateHijri < 0) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } return new DateTime(absoluteDateHijri * 864000000000L + Calendar.TimeToTicks(hour, minute, second, millisecond)); } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", year, SR.ArgumentOutOfRange_NeedNonNegNum); } if (year < 100) { return base.ToFourDigitYear(year); } if (year > 9666) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 1, 9666)); } return year; } private int GetHijriDateAdjustment() { if (_hijriAdvance == int.MinValue) { _hijriAdvance = GetAdvanceHijriDate(); } return _hijriAdvance; } private static int GetAdvanceHijriDate() { using RegistryKey registryKey = Registry.CurrentUser.OpenSubKey("Control Panel\\International"); if (registryKey == null) { return 0; } object value = registryKey.GetValue("AddHijriDate"); if (value == null) { return 0; } int result = 0; string text = value.ToString(); if (string.Compare(text, 0, "AddHijriDate", 0, "AddHijriDate".Length, StringComparison.OrdinalIgnoreCase) == 0) { if (text.Length == "AddHijriDate".Length) { result = -1; } else { try { int num = int.Parse(text.AsSpan("AddHijriDate".Length), NumberStyles.Integer, CultureInfo.InvariantCulture); if (num >= -2 && num <= 2) { result = num; } } catch (ArgumentException) { } catch (FormatException) { } catch (OverflowException) { } } } return result; } } internal enum IcuLocaleDataParts { Lcid, AnsiCodePage, OemCodePage, MacCodePage, EbcdicCodePage, GeoId, DigitSubstitutionOrListSeparator, SpecificLocaleIndex, ConsoleLocaleIndex } internal static class IcuLocaleData { private static ReadOnlySpan CultureNames => "aa-djaa-eraa-etaf-naaf-zaagq-cmak-gham-etar-001ar-aear-bhar-djar-dzar-egar-erar-ilar-iqar-joar-kmar-kwar-lbar-lyar-maar-mrar-omar-psar-qaar-saar-sdar-soar-ssar-syar-tdar-tnar-yearn-clas-inasa-tzast-esaz-cyrl-azaz-latn-azba-rubas-cmbe-bybem-zmbez-tzbg-bgbin-ngbm-latn-mlbn-bdbn-inbo-cnbo-inbr-frbrx-inbs-cyrl-babs-latn-babyn-erca-adca-es-valenciaca-frca-itce-rucgg-ugchr-cher-usco-frcs-czcu-rucy-gbda-dkda-gldav-kede-atde-bede-chde-de_phonebde-itde-lide-ludje-nedsb-dedua-cmdv-mvdyo-sndz-btebu-keee-ghee-tgel-cyel-gren-001en-029en-150en-agen-aien-asen-aten-auen-bben-been-bien-bmen-bsen-bwen-bzen-caen-ccen-chen-cken-cmen-cxen-cyen-deen-dken-dmen-eren-fien-fjen-fken-fmen-gben-gden-ggen-ghen-gien-gmen-guen-gyen-hken-iden-ieen-ilen-imen-inen-ioen-jeen-jmen-keen-kien-knen-kyen-lcen-lren-lsen-mgen-mhen-moen-mpen-msen-mten-muen-mwen-myen-naen-nfen-ngen-nlen-nren-nuen-nzen-pgen-phen-pken-pnen-pren-pwen-rwen-sben-scen-sden-seen-sgen-shen-sien-slen-ssen-sxen-szen-tcen-tken-toen-tten-tven-tzen-ugen-umen-usen-vcen-vgen-vien-vuen-wsen-zaen-zmen-zweo-001es-419es-ares-boes-bres-cles-coes-cres-cues-does-eces-es_tradnles-gqes-gtes-hnes-mxes-nies-paes-pees-phes-pres-pyes-sves-uses-uyes-veet-eeeu-esewo-cmfa-irff-cmff-gnff-latn-snff-mrff-ngfi-fifil-phfo-dkfo-fofr-029fr-befr-bffr-bifr-bjfr-blfr-cafr-cdfr-cffr-cgfr-chfr-cifr-cmfr-djfr-dzfr-frfr-gafr-gffr-gnfr-gpfr-gqfr-htfr-kmfr-lufr-mafr-mcfr-mffr-mgfr-mlfr-mqfr-mrfr-mufr-ncfr-nefr-pffr-pmfr-refr-rwfr-scfr-snfr-syfr-tdfr-tgfr-tnfr-vufr-wffr-ytfur-itfy-nlga-iegd-gbgl-esgn-pygsw-chgsw-frgsw-ligu-inguz-kegv-imha-latn-ghha-latn-neha-latn-nghaw-ushe-ilhi-inhr-bahr-hrhsb-dehu-hu_technlhy-amia-001ia-fribb-ngid-idig-ngii-cnis-isit-chit-itit-smiu-cans-caiu-latn-caja-jp_radstrjgo-cmjmc-tzjv-java-idjv-latn-idka-ge_modernkab-dzkam-kekde-tzkea-cvkhq-mlki-kekk-kzkkj-cmkl-glkln-kekm-khkn-inko-kpko-krkok-inkr-ngks-arab-inks-deva-inksb-tzksf-cmksh-deku-arab-iqku-arab-irkw-gbky-kgla-001lag-tzlb-lulg-uglkt-usln-aoln-cdln-cfln-cglo-lalrc-iqlrc-irlt-ltlu-cdluo-keluy-kelv-lvmas-kemas-tzmer-kemfe-mumg-mgmgh-mzmgo-cmmi-nzmk-mkml-inmn-cyrlmn-mnmn-mong-cnmn-mong-mnmni-inmoh-camr-inms-bnms-myms-sgmt-mtmua-cmmy-mmmzn-irnaq-nanb-nonb-sjnd-zwnds-dends-nlne-inne-npnl-awnl-benl-bqnl-cwnl-nlnl-srnl-sxnmg-cmnn-nonnh-cmnonqo-gnnr-zanso-zanus-ssnyn-ugoc-from-etom-keor-inos-geos-rupa-arab-pkpa-inpap-029pl-plprg-001prs-afps-afpt-aopt-brpt-chpt-cvpt-gqpt-gwpt-lupt-mopt-mzpt-ptpt-stpt-tlqps-latn-x-shqps-plocaqps-plocmquc-latn-gtquz-boquz-ecquz-perm-chrn-biro-mdro-rorof-tzru-byru-kgru-kzru-mdru-ruru-uarw-rwrwk-tzsa-insah-rusaq-kesbp-tzsd-arab-pksd-deva-inse-fise-nose-seseh-mzses-mlsg-cfshi-latn-mashi-tfng-masi-lksk-sksl-sisma-nosma-sesmj-nosmj-sesmn-fisms-fisn-latn-zwso-djso-etso-keso-sosq-alsq-mksq-xksr-cyrl-basr-cyrl-cssr-cyrl-mesr-cyrl-rssr-cyrl-xksr-latn-basr-latn-cssr-latn-mesr-latn-rssr-latn-xkss-szss-zassy-erst-lsst-zasv-axsv-fisv-sesw-cdsw-kesw-tzsw-ugswc-cdsyr-syta-inta-lkta-myta-sgte-inteo-keteo-ugtg-cyrl-tjth-thti-erti-ettig-ertk-tmtn-bwtn-zato-totr-cytr-trts-zatt-rutwq-netzm-arab-matzm-latn-dztzm-latn-matzm-tfng-maug-cnuk-uaur-inur-pkuz-arab-afuz-cyrl-uzuz-latn-uzvai-latn-lrvai-vaii-lrve-zavi-vnvo-001vun-tzwae-chwal-etwo-snx-iv_mathanxh-zaxog-ugyav-cmyi-001yo-bjyo-ngyue-hkzgh-tfng-mazh-chszh-chtzh-cn_phonebzh-cn_strokezh-hans-hkzh-hans-mozh-hantzh-hk_radstrzh-mo_radstrzh-mo_strokezh-sg_phonebzh-sg_strokezh-tw_pronunzh-tw_radstrzu-za"u8; private static ReadOnlySpan LocalesNamesIndexes => new byte[1728] { 0, 2, 0, 5, 0, 85, 0, 165, 0, 242, 0, 245, 1, 69, 1, 147, 1, 150, 1, 242, 1, 245, 2, 66, 2, 69, 2, 146, 2, 150, 2, 245, 3, 69, 3, 149, 3, 229, 4, 53, 4, 133, 4, 213, 5, 37, 5, 117, 5, 197, 6, 21, 6, 101, 6, 181, 7, 5, 7, 85, 7, 165, 7, 245, 8, 69, 8, 149, 8, 229, 9, 53, 9, 133, 9, 213, 10, 37, 10, 117, 10, 197, 11, 19, 11, 22, 11, 114, 11, 117, 11, 195, 11, 198, 12, 35, 12, 38, 12, 130, 12, 135, 12, 138, 13, 39, 13, 42, 13, 194, 13, 197, 14, 19, 14, 22, 14, 114, 14, 117, 14, 195, 14, 198, 15, 35, 15, 38, 15, 130, 15, 133, 15, 211, 15, 214, 16, 50, 16, 55, 16, 58, 16, 210, 16, 213, 17, 37, 17, 114, 17, 117, 17, 197, 18, 18, 18, 21, 18, 99, 18, 102, 18, 194, 18, 199, 18, 202, 19, 103, 19, 106, 20, 3, 20, 6, 20, 98, 20, 101, 20, 181, 20, 190, 21, 149, 21, 229, 22, 50, 22, 53, 22, 131, 22, 134, 22, 227, 22, 232, 22, 235, 23, 146, 23, 149, 23, 226, 23, 229, 24, 50, 24, 53, 24, 130, 24, 133, 24, 210, 24, 213, 25, 37, 25, 115, 25, 118, 25, 210, 25, 213, 26, 37, 26, 117, 26, 197, 26, 204, 27, 133, 27, 213, 28, 37, 28, 115, 28, 118, 28, 211, 28, 214, 29, 51, 29, 54, 29, 146, 29, 149, 29, 227, 29, 230, 30, 66, 30, 69, 30, 147, 30, 150, 30, 242, 30, 245, 31, 69, 31, 146, 31, 149, 31, 229, 32, 50, 32, 54, 32, 150, 32, 246, 33, 85, 33, 165, 33, 245, 34, 69, 34, 149, 34, 229, 35, 53, 35, 133, 35, 213, 36, 37, 36, 117, 36, 197, 37, 21, 37, 101, 37, 181, 38, 5, 38, 85, 38, 165, 38, 245, 39, 69, 39, 149, 39, 229, 40, 53, 40, 133, 40, 213, 41, 37, 41, 117, 41, 197, 42, 21, 42, 101, 42, 181, 43, 5, 43, 85, 43, 165, 43, 245, 44, 69, 44, 149, 44, 229, 45, 53, 45, 133, 45, 213, 46, 37, 46, 117, 46, 197, 47, 21, 47, 101, 47, 181, 48, 5, 48, 85, 48, 165, 48, 245, 49, 69, 49, 149, 49, 229, 50, 53, 50, 133, 50, 213, 51, 37, 51, 117, 51, 197, 52, 21, 52, 101, 52, 181, 53, 5, 53, 85, 53, 165, 53, 245, 54, 69, 54, 149, 54, 229, 55, 53, 55, 133, 55, 213, 56, 37, 56, 117, 56, 197, 57, 21, 57, 101, 57, 181, 58, 5, 58, 85, 58, 165, 58, 245, 59, 69, 59, 149, 59, 229, 60, 53, 60, 133, 60, 213, 61, 37, 61, 117, 61, 197, 62, 21, 62, 101, 62, 181, 63, 5, 63, 85, 63, 165, 63, 245, 64, 69, 64, 149, 64, 229, 65, 50, 65, 54, 65, 146, 65, 150, 65, 245, 66, 69, 66, 149, 66, 229, 67, 53, 67, 133, 67, 213, 68, 37, 68, 117, 68, 197, 68, 204, 69, 133, 69, 213, 70, 37, 70, 117, 70, 197, 71, 21, 71, 101, 71, 181, 72, 5, 72, 85, 72, 165, 72, 245, 73, 69, 73, 149, 73, 226, 73, 229, 74, 50, 74, 53, 74, 131, 74, 134, 74, 226, 74, 229, 75, 50, 75, 53, 75, 133, 75, 215, 75, 218, 76, 117, 76, 197, 77, 18, 77, 21, 77, 99, 77, 102, 77, 194, 77, 197, 78, 21, 78, 98, 78, 102, 78, 197, 79, 21, 79, 101, 79, 181, 80, 5, 80, 85, 80, 165, 80, 245, 81, 69, 81, 149, 81, 229, 82, 53, 82, 133, 82, 213, 83, 37, 83, 117, 83, 197, 84, 21, 84, 101, 84, 181, 85, 5, 85, 85, 85, 165, 85, 245, 86, 69, 86, 149, 86, 229, 87, 53, 87, 133, 87, 213, 88, 37, 88, 117, 88, 197, 89, 21, 89, 101, 89, 181, 90, 5, 90, 85, 90, 165, 90, 245, 91, 69, 91, 149, 91, 229, 92, 53, 92, 133, 92, 213, 93, 35, 93, 38, 93, 130, 93, 133, 93, 210, 93, 213, 94, 34, 94, 37, 94, 114, 94, 117, 94, 194, 94, 197, 95, 19, 95, 22, 95, 118, 95, 214, 96, 50, 96, 53, 96, 131, 96, 134, 96, 226, 96, 229, 97, 50, 97, 55, 97, 58, 97, 218, 98, 122, 99, 19, 99, 22, 99, 114, 99, 117, 99, 194, 99, 197, 100, 18, 100, 21, 100, 101, 100, 179, 100, 182, 101, 18, 101, 21, 101, 28, 101, 210, 101, 213, 102, 34, 102, 38, 102, 133, 102, 211, 102, 214, 103, 50, 103, 53, 103, 130, 103, 133, 103, 210, 103, 213, 104, 34, 104, 37, 104, 114, 104, 117, 104, 197, 105, 21, 105, 98, 105, 103, 105, 106, 106, 7, 106, 10, 106, 162, 106, 165, 106, 172, 107, 99, 107, 102, 107, 195, 107, 198, 108, 34, 108, 39, 108, 42, 108, 199, 108, 202, 109, 98, 109, 101, 109, 108, 110, 35, 110, 38, 110, 131, 110, 134, 110, 227, 110, 230, 111, 67, 111, 70, 111, 163, 111, 166, 112, 2, 112, 5, 112, 82, 112, 85, 112, 163, 112, 166, 113, 2, 113, 5, 113, 83, 113, 86, 113, 178, 113, 181, 114, 2, 114, 5, 114, 82, 114, 85, 114, 165, 114, 243, 114, 246, 115, 82, 115, 85, 115, 162, 115, 167, 115, 170, 116, 71, 116, 74, 116, 227, 116, 230, 117, 67, 117, 70, 117, 163, 117, 166, 118, 2, 118, 7, 118, 10, 118, 170, 119, 66, 119, 69, 119, 146, 119, 149, 119, 226, 119, 230, 120, 67, 120, 70, 120, 162, 120, 165, 120, 242, 120, 245, 121, 67, 121, 70, 121, 162, 121, 165, 121, 245, 122, 69, 122, 149, 122, 226, 122, 229, 123, 51, 123, 54, 123, 150, 123, 242, 123, 245, 124, 66, 124, 69, 124, 147, 124, 150, 124, 243, 124, 246, 125, 82, 125, 85, 125, 163, 125, 166, 126, 6, 126, 99, 126, 102, 126, 195, 126, 198, 127, 34, 127, 37, 127, 115, 127, 118, 127, 211, 127, 214, 128, 50, 128, 53, 128, 130, 128, 133, 128, 210, 128, 213, 129, 34, 129, 39, 129, 149, 129, 231, 129, 234, 130, 138, 131, 35, 131, 38, 131, 131, 131, 134, 131, 226, 131, 229, 132, 50, 132, 53, 132, 133, 132, 213, 133, 34, 133, 37, 133, 115, 133, 118, 133, 210, 133, 213, 134, 35, 134, 38, 134, 131, 134, 134, 134, 226, 134, 229, 135, 53, 135, 130, 135, 133, 135, 211, 135, 214, 136, 54, 136, 146, 136, 149, 136, 229, 137, 50, 137, 53, 137, 133, 137, 213, 138, 37, 138, 117, 138, 197, 139, 21, 139, 99, 139, 102, 139, 194, 139, 197, 140, 19, 140, 22, 140, 114, 140, 147, 140, 150, 140, 242, 140, 245, 141, 67, 141, 70, 141, 163, 141, 166, 142, 3, 142, 6, 142, 98, 142, 101, 142, 178, 142, 181, 143, 5, 143, 82, 143, 85, 143, 162, 143, 165, 143, 245, 144, 66, 144, 71, 144, 74, 144, 229, 145, 51, 145, 55, 145, 162, 145, 165, 145, 243, 145, 247, 146, 99, 146, 102, 146, 194, 146, 197, 147, 18, 147, 21, 147, 101, 147, 181, 148, 5, 148, 85, 148, 165, 148, 245, 149, 69, 149, 149, 149, 229, 150, 53, 150, 133, 150, 221, 151, 168, 151, 169, 152, 57, 152, 195, 152, 200, 152, 203, 153, 115, 153, 118, 153, 214, 154, 54, 154, 146, 154, 149, 154, 226, 154, 229, 155, 50, 155, 53, 155, 133, 155, 211, 155, 214, 156, 50, 156, 53, 156, 133, 156, 213, 157, 37, 157, 117, 157, 197, 158, 18, 158, 21, 158, 99, 158, 102, 158, 194, 158, 197, 159, 19, 159, 22, 159, 115, 159, 118, 159, 211, 159, 214, 160, 50, 160, 55, 160, 58, 160, 215, 160, 218, 161, 114, 161, 117, 161, 197, 162, 21, 162, 99, 162, 102, 162, 195, 162, 198, 163, 34, 163, 37, 163, 115, 163, 120, 163, 123, 164, 40, 164, 43, 164, 210, 164, 213, 165, 34, 165, 37, 165, 114, 165, 117, 165, 195, 165, 198, 166, 38, 166, 131, 166, 134, 166, 230, 167, 67, 167, 70, 167, 163, 167, 166, 168, 2, 168, 7, 168, 10, 168, 162, 168, 165, 168, 245, 169, 69, 169, 149, 169, 226, 169, 229, 170, 53, 170, 133, 170, 210, 170, 215, 170, 218, 171, 122, 172, 26, 172, 186, 173, 90, 173, 247, 173, 250, 174, 154, 175, 58, 175, 218, 176, 122, 177, 18, 177, 21, 177, 101, 177, 179, 177, 182, 178, 18, 178, 21, 178, 101, 178, 178, 178, 181, 179, 5, 179, 85, 179, 162, 179, 165, 179, 245, 180, 69, 180, 149, 180, 227, 180, 230, 181, 67, 181, 70, 181, 162, 181, 165, 181, 245, 182, 69, 182, 149, 182, 226, 182, 229, 183, 51, 183, 54, 183, 150, 183, 242, 183, 247, 183, 250, 184, 146, 184, 149, 184, 226, 184, 229, 185, 53, 185, 131, 185, 134, 185, 226, 185, 229, 186, 50, 186, 53, 186, 133, 186, 210, 186, 213, 187, 34, 187, 37, 187, 117, 187, 194, 187, 197, 188, 18, 188, 21, 188, 99, 188, 102, 188, 195, 188, 200, 188, 203, 189, 120, 189, 123, 190, 43, 190, 216, 190, 219, 191, 130, 191, 133, 191, 210, 191, 213, 192, 34, 192, 37, 192, 117, 192, 194, 192, 199, 192, 202, 193, 103, 193, 106, 194, 7, 194, 10, 194, 163, 194, 168, 194, 171, 195, 88, 195, 91, 196, 2, 196, 5, 196, 82, 196, 85, 196, 162, 196, 166, 197, 3, 197, 6, 197, 99, 197, 102, 197, 195, 197, 198, 198, 34, 198, 37, 198, 123, 199, 34, 199, 37, 199, 115, 199, 118, 199, 211, 199, 214, 200, 50, 200, 54, 200, 146, 200, 149, 200, 229, 201, 51, 201, 54, 201, 147, 201, 152, 201, 155, 202, 66, 202, 70, 202, 166, 203, 5, 203, 12, 203, 204, 204, 135, 204, 138, 205, 42, 205, 199, 206, 53, 206, 60, 206, 245, 206, 252, 207, 188, 208, 117, 208, 124, 209, 60, 209, 245, 209, 252, 210, 188, 211, 114, 211, 117 }; private static ReadOnlySpan ThreeLetterWindowsLanguageName => "ZZZZZZZZZZZZAFKZZZAFKZZZZZZZZZZZZAMHAMHARAZZZARUARHZZZARGAREZZZZZZARIARJZZZARKARBARLARMZZZAROZZZARQARAZZZZZZZZZARSZZZARTARYMPDMPDASMASMZZZZZZZZZZZZAZEAZCAZCAZEAZEBASBASZZZZZZBELBELZZZZZZZZZZZZBGRBGRZZZZZZZZZZZZZZZBNBBNBBNGBOBBOBZZZBREBREZZZZZZBSBBSCBSCBSBBSBZZZZZZCATZZZCATVALZZZZZZZZZZZZZZZZZZCRECRECRECOSCOSCSYCSYZZZZZZCYMCYMDANDANZZZZZZZZZDEUDEAZZZDESDEUDEUZZZDECDELZZZZZZDSBDSBZZZZZZDIVDIVZZZZZZZZZZZZZZZZZZZZZZZZZZZELLZZZELLENUZZZENBZZZZZZZZZZZZZZZENAZZZZZZZZZZZZZZZZZZENLENCZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZENGZZZZZZZZZZZZZZZZZZZZZENHZZZENIZZZZZZENNZZZZZZENJZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZENMZZZZZZZZZZZZZZZZZZENZZZZENPZZZZZZZZZZZZZZZZZZZZZZZZZZZENEZZZZZZZZZZZZZZZZZZZZZZZZZZZENTZZZZZZZZZZZZENUZZZZZZZZZZZZZZZENSZZZENWZZZZZZESPESJESSESBZZZESLESOESCESKESDESFESNESPZZZESGESHESMESIESAESRZZZESUESZESEESTESYESVETIETIEUQEUQZZZZZZFARFARFULZZZZZZFULFULZZZZZZFINFINFPOFPOFOSZZZFOSFRAZZZFRBZZZZZZZZZZZZFRCFRDZZZZZZFRSFRIFREZZZZZZFRAZZZZZZZZZZZZZZZFRHZZZFRLFROFRMZZZZZZFRFZZZZZZZZZZZZZZZZZZZZZFRRZZZZZZFRNZZZZZZZZZZZZZZZZZZZZZZZZZZZFYNFYNIREIREGLAGLAGLCGLCGRNGRNZZZZZZGSWZZZGUJGUJZZZZZZZZZZZZHAUHAUZZZZZZHAUHAWHAWHEBHEBHINHINHRVHRBHRVHSBHSBHUNHUNHUNHYEHYEZZZZZZZZZZZZZZZINDINDIBOIBOIIIIIIISLISLITAITSITAZZZIUKIUSIUSIUKIUKJPNJPNJPNZZZZZZZZZZZZJAVZZZZZZJAVJAVKATKATKATZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZKKZKKZZZZZZZKALKALZZZZZZKHMKHMKDIKDIKORZZZKORKNKKNKZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZKURKURKURZZZZZZZZZKYRKYRZZZZZZZZZZZZLBXLBXZZZZZZZZZZZZZZZZZZZZZZZZZZZLAOLAOZZZZZZZZZLTHLTHZZZZZZZZZZZZZZZZZZLVILVIZZZZZZZZZZZZZZZZZZZZZMLGMLGZZZZZZZZZZZZMRIMRIMKIMKIMYMMYMMONMNNMNNMNGMNGMNMZZZZZZMWKMWKMARMARMSLMSBMSLZZZMLTMLTZZZZZZMYAMYAZZZZZZZZZZZZNORNORZZZZZZZZZZZZZZZZZZNEPNEINEPNLDZZZNLBZZZZZZNLDZZZZZZZZZZZZNONNONZZZZZZNORNQONQOZZZZZZNSONSOZZZZZZZZZZZZOCIOCIORMORMZZZORIORIZZZZZZZZZPANPAPPAPPANZZZZZZPLKPLKZZZZZZPRSPRSPASPASPTBPTAPTBZZZZZZZZZZZZZZZZZZZZZPTGZZZZZZENJENUJPNARAQUCQUTQUTQUBQUBQUEQUPRMCRMCZZZZZZROMRODROMZZZZZZRUSZZZZZZZZZRUMRUSZZZKINKINZZZZZZSANSANSAHSAHZZZZZZZZZZZZSIPSIPSIPZZZZZZSMESMGSMESMFZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZSINSINSKYSKYSLVSLVSMBSMASMBSMKSMJSMKSMNSMNSMSSMSSNASNASNASOMZZZZZZZZZSOMSQISQIZZZZZZSRBSROSRNSRBSRQSROZZZSRMSRSSRLSRPSRMZZZZZZZZZZZZZZZZZZSOTZZZSOTSVEZZZSVFSVESWKZZZSWKZZZZZZZZZZZZSYRSYRTAITAITAMZZZZZZTELTELZZZZZZZZZTAJTAJTAJTHATHATIRTIRTIEZZZZZZTUKTUKTSNTSBTSNZZZZZZTRKZZZTRKTSOTSOTTTTTTZZZZZZTZAZZZZZZTZATZAZZZTZMTZMUIGUIGUKRUKRURDURIURDUZBZZZZZZUZCUZCUZBUZBZZZZZZZZZZZZZZZZZZZZZVITVITZZZZZZZZZZZZZZZZZZZZZZZZWOLWOLIVLXHOXHOZZZZZZZZZZZZZZZZZZYORZZZYORZZZZZZZHGZHGZHGCHSCHSCHTCHSCHSCHSCHSZZZZZZZHHZHHZHHZHMZHMZHMZHIZHIZHICHTCHTCHTZULZUL"u8; private static ReadOnlySpan NameIndexToNumericData => new byte[15552] { 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 73, 17, 0, 48, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 62, 17, 0, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 71, 17, 0, 32, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 73, 17, 0, 48, 240, 0, 0, 54, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 209, 17, 0, 96, 6, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 254, 17, 0, 80, 240, 0, 4, 54, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 209, 17, 0, 96, 6, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 0, 128, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 0, 128, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 89, 17, 0, 160, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 89, 17, 0, 160, 240, 0, 0, 94, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 73, 17, 0, 192, 143, 0, 4, 94, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 73, 17, 0, 192, 143, 0, 0, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 205, 16, 2, 16, 143, 0, 16, 0, 78, 130, 208, 39, 20, 79, 196, 0, 0, 152, 158, 16, 0, 224, 240, 0, 56, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 224, 16, 0, 240, 143, 0, 60, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 17, 16, 1, 0, 143, 0, 16, 0, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 62, 16, 1, 16, 240, 0, 20, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 4, 17, 1, 33, 44, 0, 12, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 67, 16, 1, 48, 143, 0, 16, 0, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 71, 16, 1, 64, 240, 0, 16, 0, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 117, 16, 1, 80, 240, 0, 8, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 121, 16, 1, 96, 143, 0, 44, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 126, 16, 1, 112, 143, 0, 16, 0, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 50, 16, 1, 128, 240, 0, 52, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 136, 16, 1, 144, 143, 0, 48, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 139, 16, 1, 160, 143, 0, 16, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 148, 17, 1, 176, 143, 0, 24, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 159, 17, 1, 193, 44, 0, 16, 0, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 162, 16, 1, 208, 240, 0, 32, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 164, 16, 1, 224, 143, 0, 16, 0, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 184, 16, 1, 240, 240, 0, 64, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 197, 16, 2, 0, 143, 0, 4, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 205, 16, 2, 16, 143, 0, 16, 0, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 219, 16, 2, 32, 240, 0, 16, 0, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 216, 16, 2, 48, 240, 0, 16, 0, 78, 130, 208, 39, 20, 79, 196, 0, 0, 1, 20, 16, 2, 64, 240, 0, 40, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 222, 16, 2, 80, 143, 0, 16, 0, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 41, 16, 2, 96, 240, 0, 28, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 234, 17, 2, 113, 44, 0, 36, 1, 78, 130, 208, 39, 20, 79, 196, 0, 0, 1, 5, 16, 2, 128, 143, 0, 0, 122, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 46, 1, 2, 160, 42, 0, 4, 122, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 46, 1, 2, 160, 42, 0, 0, 77, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 2, 192, 143, 0, 4, 77, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 2, 192, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 2, 224, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 2, 224, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 217, 17, 3, 0, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 217, 17, 3, 0, 240, 0, 0, 44, 78, 99, 89, 39, 97, 81, 169, 0, 0, 0, 5, 17, 3, 80, 53, 0, 116, 44, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 5, 17, 3, 48, 51, 0, 8, 44, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 5, 17, 3, 48, 51, 0, 120, 44, 78, 99, 89, 39, 97, 81, 169, 0, 0, 0, 5, 17, 3, 80, 53, 0, 4, 44, 78, 99, 89, 39, 97, 81, 169, 0, 0, 0, 5, 17, 3, 80, 53, 0, 0, 109, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 203, 17, 3, 112, 55, 0, 4, 109, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 203, 17, 3, 112, 55, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 3, 144, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 3, 144, 240, 0, 0, 35, 78, 51, 98, 39, 23, 1, 244, 0, 0, 0, 29, 17, 3, 176, 59, 0, 4, 35, 78, 51, 98, 39, 23, 1, 244, 0, 0, 0, 29, 17, 3, 176, 59, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 1, 7, 17, 3, 208, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 1, 7, 17, 3, 208, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 3, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 3, 240, 240, 0, 0, 2, 78, 51, 98, 39, 23, 82, 33, 0, 0, 0, 35, 17, 4, 16, 65, 0, 4, 2, 78, 51, 98, 39, 23, 82, 33, 0, 0, 0, 35, 17, 4, 16, 65, 0, 0, 102, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 175, 17, 4, 48, 240, 0, 4, 102, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 175, 17, 4, 48, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 157, 17, 4, 96, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 157, 17, 4, 96, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 157, 17, 4, 96, 240, 0, 0, 69, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 23, 1, 4, 128, 143, 0, 8, 69, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 23, 1, 4, 128, 143, 0, 4, 69, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 4, 144, 143, 0, 0, 81, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 45, 1, 4, 176, 143, 0, 4, 81, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 45, 1, 4, 176, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 17, 4, 192, 240, 0, 0, 126, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 84, 17, 4, 224, 78, 0, 4, 126, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 84, 17, 4, 224, 78, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 17, 5, 0, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 17, 5, 0, 240, 0, 120, 26, 78, 35, 84, 39, 98, 3, 102, 0, 0, 0, 25, 17, 5, 80, 85, 0, 100, 26, 78, 51, 87, 39, 98, 3, 102, 0, 0, 0, 25, 17, 5, 48, 83, 0, 32, 26, 78, 51, 87, 39, 98, 3, 102, 0, 0, 0, 25, 17, 5, 48, 83, 0, 104, 26, 78, 35, 84, 39, 98, 3, 102, 0, 0, 0, 25, 17, 5, 80, 85, 0, 20, 26, 78, 35, 84, 39, 98, 3, 102, 0, 0, 0, 25, 17, 5, 80, 85, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 71, 17, 5, 112, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 71, 17, 5, 112, 240, 0, 0, 3, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 217, 17, 5, 160, 90, 0, 16, 0, 78, 67, 82, 0, 2, 1, 244, 0, 0, 0, 8, 17, 5, 144, 240, 0, 4, 3, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 217, 17, 5, 160, 90, 0, 8, 3, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 217, 17, 5, 176, 90, 0, 16, 0, 78, 67, 82, 0, 2, 1, 244, 0, 0, 0, 84, 17, 5, 192, 240, 0, 16, 0, 78, 67, 82, 0, 2, 1, 244, 0, 0, 0, 118, 17, 5, 208, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 203, 17, 5, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 203, 17, 5, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 240, 17, 6, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 240, 17, 6, 16, 240, 0, 0, 92, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 244, 1, 6, 64, 240, 0, 124, 92, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 244, 1, 6, 64, 240, 0, 4, 92, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 244, 1, 6, 64, 240, 0, 0, 131, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 84, 17, 6, 96, 102, 0, 4, 131, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 84, 17, 6, 96, 102, 0, 0, 5, 78, 35, 84, 39, 45, 1, 244, 0, 0, 0, 75, 17, 6, 128, 104, 0, 4, 5, 78, 35, 84, 39, 45, 1, 244, 0, 0, 0, 75, 17, 6, 128, 104, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 203, 17, 6, 160, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 203, 17, 6, 160, 240, 0, 0, 82, 78, 67, 82, 39, 16, 79, 61, 0, 0, 0, 242, 17, 6, 192, 108, 0, 4, 82, 78, 67, 82, 39, 16, 79, 61, 0, 0, 0, 242, 17, 6, 192, 108, 0, 0, 6, 78, 67, 82, 39, 16, 79, 53, 0, 0, 0, 61, 17, 6, 224, 110, 0, 4, 6, 78, 67, 82, 39, 16, 79, 53, 0, 0, 0, 61, 17, 6, 224, 110, 0, 16, 0, 78, 67, 82, 0, 2, 1, 244, 0, 0, 0, 93, 17, 6, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 7, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 7, 16, 240, 0, 0, 7, 78, 67, 82, 39, 16, 79, 49, 0, 0, 0, 94, 17, 7, 96, 118, 0, 12, 7, 78, 67, 82, 39, 16, 79, 49, 0, 0, 0, 14, 17, 7, 48, 115, 0, 16, 0, 78, 67, 82, 39, 16, 79, 49, 0, 0, 0, 21, 17, 7, 64, 240, 0, 8, 7, 78, 67, 82, 39, 16, 79, 49, 0, 0, 0, 223, 17, 7, 80, 117, 0, 4, 7, 78, 67, 82, 39, 16, 79, 49, 0, 0, 0, 94, 17, 7, 96, 118, 1, 4, 7, 78, 67, 82, 39, 16, 79, 49, 0, 0, 0, 94, 17, 7, 96, 118, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 118, 17, 7, 128, 240, 0, 20, 7, 78, 67, 82, 39, 16, 79, 49, 0, 0, 0, 145, 17, 7, 144, 121, 0, 16, 7, 78, 67, 82, 39, 16, 79, 49, 0, 0, 0, 147, 17, 7, 160, 122, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 173, 17, 7, 192, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 173, 17, 7, 192, 240, 0, 124, 46, 78, 67, 82, 39, 16, 3, 102, 0, 0, 0, 94, 17, 7, 224, 126, 0, 8, 46, 78, 67, 82, 39, 16, 3, 102, 0, 0, 0, 94, 17, 7, 224, 126, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 8, 0, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 8, 0, 240, 0, 0, 101, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 165, 33, 8, 32, 143, 0, 4, 101, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 165, 33, 8, 32, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 210, 17, 8, 64, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 210, 17, 8, 64, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 34, 18, 8, 96, 240, 0, 12, 81, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 34, 18, 8, 96, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 8, 128, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 8, 128, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 89, 17, 8, 160, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 89, 17, 8, 160, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 232, 17, 8, 176, 240, 0, 0, 8, 78, 82, 225, 39, 22, 79, 49, 0, 0, 0, 98, 17, 8, 224, 142, 0, 16, 0, 78, 82, 225, 39, 22, 79, 49, 0, 0, 0, 59, 17, 8, 208, 240, 0, 4, 8, 78, 82, 225, 39, 22, 79, 49, 0, 0, 0, 98, 17, 8, 224, 142, 0, 0, 9, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 244, 1, 15, 0, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 152, 158, 1, 9, 0, 240, 0, 36, 9, 78, 67, 82, 39, 16, 1, 244, 0, 153, 50, 72, 1, 9, 16, 145, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 41, 45, 1, 9, 32, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 2, 1, 9, 48, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 44, 1, 9, 64, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 10, 1, 9, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 14, 1, 9, 96, 240, 0, 12, 9, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 12, 1, 9, 112, 151, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 18, 1, 9, 128, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 21, 1, 9, 144, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 38, 1, 9, 160, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 20, 1, 9, 176, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 22, 1, 9, 192, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 19, 1, 9, 208, 240, 0, 40, 9, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 24, 1, 9, 224, 158, 0, 16, 9, 78, 67, 82, 39, 16, 0, 37, 0, 0, 0, 39, 1, 9, 240, 159, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 55, 1, 10, 0, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 223, 1, 10, 16, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 56, 1, 10, 32, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 49, 1, 10, 48, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 53, 1, 10, 64, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 59, 1, 10, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 94, 1, 10, 96, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 61, 1, 10, 112, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 63, 1, 10, 128, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 71, 1, 10, 144, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 77, 1, 10, 160, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 78, 1, 10, 176, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 59, 1, 10, 192, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 80, 1, 10, 208, 240, 0, 8, 9, 78, 67, 82, 39, 16, 79, 61, 0, 0, 0, 242, 1, 10, 224, 174, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 91, 1, 10, 240, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 68, 1, 11, 0, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 89, 1, 11, 16, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 90, 1, 11, 32, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 86, 1, 11, 48, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 66, 1, 11, 64, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 101, 1, 11, 80, 240, 0, 60, 9, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 104, 1, 11, 96, 240, 0, 56, 9, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 111, 17, 11, 112, 240, 0, 24, 9, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 68, 1, 11, 128, 184, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 117, 1, 11, 144, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 59, 22, 1, 11, 160, 240, 0, 64, 9, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 113, 1, 11, 176, 187, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 114, 1, 11, 192, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 72, 1, 11, 208, 240, 0, 32, 9, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 124, 1, 11, 224, 190, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 129, 1, 11, 240, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 133, 1, 12, 0, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 207, 1, 12, 16, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 51, 1, 12, 32, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 218, 1, 12, 48, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 142, 1, 12, 64, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 146, 1, 12, 80, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 149, 1, 12, 96, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 199, 1, 12, 112, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 151, 1, 12, 128, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 81, 1, 12, 144, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 76, 1, 12, 160, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 163, 1, 12, 176, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 160, 1, 12, 192, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 156, 1, 12, 208, 240, 0, 68, 9, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 167, 1, 12, 224, 206, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 254, 1, 12, 240, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 80, 1, 13, 0, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 175, 1, 13, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 176, 1, 13, 32, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 180, 1, 13, 48, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 79, 1, 13, 64, 240, 0, 20, 9, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 183, 1, 13, 80, 213, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 194, 1, 13, 96, 240, 0, 52, 9, 78, 65, 181, 39, 16, 1, 244, 0, 0, 0, 201, 1, 13, 112, 215, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 190, 1, 13, 128, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 83, 1, 13, 144, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 202, 1, 13, 160, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 195, 1, 13, 176, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 204, 1, 13, 192, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 30, 1, 13, 208, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 208, 1, 13, 224, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 219, 1, 13, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 221, 1, 14, 0, 240, 0, 72, 9, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 215, 1, 14, 16, 225, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 87, 1, 14, 32, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 212, 1, 14, 48, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 213, 1, 14, 64, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 20, 1, 14, 80, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 120, 247, 1, 14, 96, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 4, 1, 14, 112, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 93, 1, 14, 128, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 91, 1, 14, 144, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 231, 1, 14, 160, 240, 0, 44, 9, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 225, 1, 14, 176, 235, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 236, 1, 14, 192, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 239, 1, 14, 208, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 240, 1, 14, 224, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 9, 165, 93, 64, 1, 14, 240, 240, 0, 4, 9, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 244, 1, 15, 0, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 248, 1, 15, 16, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 95, 1, 15, 32, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 252, 1, 15, 48, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 174, 1, 15, 64, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 3, 1, 15, 80, 240, 0, 28, 9, 78, 65, 181, 39, 16, 1, 244, 0, 0, 0, 209, 1, 15, 96, 246, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 7, 1, 15, 112, 240, 0, 48, 9, 78, 65, 181, 39, 16, 1, 244, 0, 0, 1, 8, 1, 15, 128, 248, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 152, 158, 17, 15, 160, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 152, 158, 17, 15, 160, 240, 0, 0, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 217, 17, 16, 97, 6, 0, 88, 10, 78, 67, 82, 39, 16, 79, 60, 9, 165, 93, 65, 17, 15, 192, 240, 0, 44, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 11, 17, 15, 208, 253, 0, 64, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 26, 17, 15, 224, 254, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 32, 17, 15, 240, 240, 0, 52, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 46, 17, 16, 1, 0, 0, 36, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 51, 17, 16, 17, 1, 0, 20, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 54, 17, 16, 33, 2, 0, 92, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 56, 17, 16, 48, 240, 0, 28, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 65, 17, 16, 65, 4, 0, 48, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 66, 17, 16, 81, 5, 0, 12, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 217, 17, 16, 97, 6, 0, 4, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 217, 17, 16, 113, 7, 0, 16, 0, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 69, 17, 16, 128, 240, 0, 16, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 99, 17, 16, 145, 9, 0, 72, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 106, 17, 16, 161, 10, 0, 8, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 166, 1, 16, 177, 11, 0, 76, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 182, 17, 16, 193, 12, 0, 24, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 192, 17, 16, 209, 13, 0, 40, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 187, 17, 16, 225, 14, 0, 16, 0, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 201, 17, 16, 240, 240, 0, 80, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 202, 17, 17, 1, 16, 0, 60, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 185, 17, 17, 17, 17, 0, 68, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 72, 17, 17, 33, 18, 0, 84, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 244, 1, 17, 49, 19, 0, 56, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 246, 17, 17, 65, 20, 0, 32, 10, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 249, 17, 17, 81, 21, 0, 0, 37, 78, 147, 7, 39, 45, 1, 244, 0, 0, 0, 70, 17, 17, 113, 23, 0, 4, 37, 78, 147, 7, 39, 45, 1, 244, 0, 0, 0, 70, 17, 17, 113, 23, 0, 0, 45, 78, 67, 82, 0, 2, 1, 244, 0, 0, 0, 217, 17, 17, 144, 240, 0, 4, 45, 78, 67, 82, 0, 2, 1, 244, 0, 0, 0, 217, 17, 17, 144, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 17, 176, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 17, 176, 240, 0, 0, 41, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 116, 48, 17, 208, 143, 0, 4, 41, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 116, 48, 17, 208, 143, 0, 0, 103, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 210, 17, 18, 33, 34, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 49, 17, 17, 240, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 100, 17, 18, 0, 240, 0, 124, 103, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 210, 17, 18, 33, 34, 0, 8, 103, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 210, 17, 18, 33, 34, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 162, 17, 18, 48, 240, 0, 4, 103, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 175, 17, 18, 64, 240, 0, 0, 11, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 77, 17, 18, 97, 38, 0, 4, 11, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 77, 17, 18, 97, 38, 0, 0, 100, 78, 65, 181, 39, 16, 1, 244, 0, 0, 0, 201, 17, 18, 129, 40, 0, 4, 100, 78, 65, 181, 39, 16, 1, 244, 0, 0, 0, 201, 17, 18, 129, 40, 0, 0, 56, 78, 67, 82, 39, 95, 79, 53, 0, 0, 0, 81, 17, 18, 177, 43, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 61, 17, 18, 160, 240, 0, 4, 56, 78, 67, 82, 39, 95, 79, 53, 0, 0, 0, 81, 17, 18, 177, 43, 0, 0, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 84, 17, 19, 193, 60, 0, 28, 12, 78, 67, 82, 39, 16, 79, 73, 0, 153, 50, 72, 17, 18, 209, 60, 0, 8, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 21, 17, 18, 225, 46, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 245, 17, 18, 240, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 38, 17, 19, 0, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 28, 17, 19, 16, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 9, 165, 92, 79, 17, 19, 32, 240, 0, 12, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 39, 17, 19, 49, 51, 0, 36, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 44, 17, 19, 64, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 55, 17, 19, 80, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 43, 17, 19, 96, 240, 0, 16, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 223, 17, 19, 113, 55, 0, 48, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 119, 17, 19, 128, 240, 0, 44, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 49, 17, 19, 144, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 62, 17, 19, 160, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 4, 17, 19, 176, 240, 0, 4, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 84, 17, 19, 193, 60, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 87, 17, 19, 208, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 1, 61, 17, 19, 224, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 100, 17, 19, 240, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 1, 65, 17, 20, 0, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 69, 17, 20, 16, 240, 0, 60, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 103, 17, 20, 32, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 50, 17, 20, 48, 240, 0, 20, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 147, 17, 20, 65, 68, 0, 56, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 159, 17, 20, 80, 240, 0, 24, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 158, 17, 20, 97, 70, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 123, 218, 17, 20, 112, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 149, 17, 20, 128, 240, 0, 52, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 157, 17, 20, 144, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 1, 74, 17, 20, 160, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 162, 17, 20, 176, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 160, 17, 20, 192, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 1, 78, 17, 20, 208, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 173, 17, 20, 224, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 1, 62, 17, 20, 240, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 206, 17, 21, 0, 240, 0, 32, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 198, 17, 21, 16, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 204, 17, 21, 32, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 208, 17, 21, 48, 240, 0, 40, 12, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 210, 17, 21, 64, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 222, 17, 21, 80, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 41, 17, 21, 96, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 232, 17, 21, 112, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 234, 17, 21, 128, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 174, 17, 21, 144, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 1, 96, 17, 21, 160, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 1, 75, 17, 21, 176, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 118, 17, 21, 208, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 118, 17, 21, 208, 240, 0, 0, 98, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 176, 17, 21, 241, 95, 0, 4, 98, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 176, 17, 21, 241, 95, 0, 0, 60, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 68, 17, 22, 17, 97, 0, 8, 60, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 68, 17, 22, 17, 97, 0, 0, 145, 78, 67, 82, 39, 16, 79, 61, 0, 0, 0, 242, 17, 22, 49, 99, 0, 4, 145, 78, 67, 82, 39, 16, 79, 61, 0, 0, 0, 242, 17, 22, 49, 99, 0, 0, 86, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 217, 17, 22, 81, 101, 0, 4, 86, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 217, 17, 22, 81, 101, 0, 0, 116, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 185, 1, 22, 113, 103, 0, 4, 116, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 185, 1, 22, 113, 103, 0, 0, 132, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 223, 17, 22, 144, 240, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 223, 17, 22, 144, 240, 0, 4, 132, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 84, 17, 22, 161, 106, 0, 16, 0, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 145, 17, 22, 176, 240, 0, 0, 71, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 22, 208, 143, 0, 4, 71, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 22, 208, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 22, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 22, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 59, 22, 17, 23, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 59, 22, 17, 23, 16, 240, 0, 0, 104, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 175, 17, 23, 97, 118, 0, 124, 104, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 175, 17, 23, 97, 118, 0, 16, 0, 78, 65, 181, 39, 16, 1, 244, 0, 0, 0, 89, 17, 23, 64, 240, 0, 16, 0, 78, 65, 181, 39, 16, 1, 244, 0, 0, 0, 173, 17, 23, 80, 240, 0, 4, 104, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 175, 17, 23, 97, 118, 0, 0, 117, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 244, 17, 23, 129, 120, 0, 4, 117, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 244, 17, 23, 129, 120, 0, 0, 13, 78, 115, 94, 39, 21, 1, 244, 0, 0, 0, 117, 1, 23, 160, 143, 0, 4, 13, 78, 115, 94, 39, 21, 1, 244, 0, 0, 0, 117, 1, 23, 160, 143, 0, 0, 57, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 23, 192, 143, 0, 4, 57, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 23, 192, 143, 0, 0, 26, 78, 35, 84, 39, 98, 1, 244, 0, 0, 0, 108, 17, 23, 241, 127, 0, 16, 26, 78, 35, 84, 39, 98, 3, 102, 0, 0, 0, 25, 17, 23, 225, 126, 0, 4, 26, 78, 35, 84, 39, 98, 1, 244, 0, 0, 0, 108, 17, 23, 241, 127, 0, 0, 46, 78, 67, 82, 39, 16, 3, 102, 0, 0, 0, 94, 17, 24, 17, 129, 0, 4, 46, 78, 67, 82, 39, 16, 3, 102, 0, 0, 0, 94, 17, 24, 17, 129, 0, 0, 14, 78, 35, 84, 39, 45, 1, 244, 0, 0, 0, 109, 17, 24, 49, 131, 0, 4, 14, 78, 35, 84, 39, 45, 1, 244, 0, 0, 0, 109, 17, 24, 49, 131, 1, 4, 14, 78, 35, 84, 39, 45, 1, 244, 0, 0, 0, 109, 17, 24, 49, 131, 0, 0, 43, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 7, 1, 24, 97, 134, 0, 4, 43, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 7, 1, 24, 97, 134, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 84, 17, 24, 144, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 152, 158, 17, 24, 128, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 84, 17, 24, 144, 240, 0, 0, 105, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 175, 17, 24, 176, 240, 0, 4, 105, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 175, 17, 24, 176, 240, 0, 0, 33, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 111, 17, 24, 209, 141, 0, 4, 33, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 111, 17, 24, 209, 141, 0, 0, 112, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 175, 17, 24, 241, 143, 0, 4, 112, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 175, 17, 24, 241, 143, 0, 0, 120, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 45, 17, 25, 16, 143, 0, 4, 120, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 45, 17, 25, 16, 143, 0, 0, 15, 78, 67, 82, 39, 95, 81, 135, 0, 0, 0, 110, 17, 25, 49, 147, 0, 4, 15, 78, 67, 82, 39, 95, 81, 135, 0, 0, 0, 110, 17, 25, 49, 147, 0, 0, 16, 78, 67, 82, 39, 16, 79, 56, 0, 0, 0, 118, 17, 25, 97, 150, 0, 8, 16, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 223, 17, 25, 81, 149, 0, 4, 16, 78, 67, 82, 39, 16, 79, 56, 0, 0, 0, 118, 17, 25, 97, 150, 0, 16, 0, 78, 67, 82, 39, 16, 79, 56, 0, 0, 0, 214, 17, 25, 112, 240, 0, 0, 93, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 39, 1, 25, 193, 156, 0, 120, 93, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 39, 1, 25, 160, 143, 0, 4, 93, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 39, 1, 25, 160, 143, 0, 124, 93, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 39, 1, 25, 193, 156, 0, 8, 93, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 39, 1, 25, 193, 156, 0, 0, 17, 58, 67, 164, 39, 17, 79, 66, 0, 0, 0, 122, 1, 25, 225, 158, 0, 4, 17, 58, 67, 164, 39, 17, 79, 66, 0, 0, 0, 122, 1, 25, 225, 158, 4, 4, 17, 58, 67, 164, 39, 17, 79, 66, 0, 0, 0, 122, 1, 25, 225, 158, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 26, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 26, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 26, 48, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 26, 48, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 111, 17, 26, 129, 168, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 111, 17, 26, 97, 168, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 111, 17, 26, 97, 168, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 111, 17, 26, 129, 168, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 111, 17, 26, 129, 168, 0, 0, 55, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 88, 17, 26, 161, 170, 0, 4, 55, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 88, 17, 26, 161, 170, 1, 4, 55, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 88, 17, 26, 161, 170, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 4, 17, 26, 208, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 4, 17, 26, 208, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 26, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 26, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 27, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 27, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 57, 17, 27, 48, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 57, 17, 27, 48, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 157, 17, 27, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 157, 17, 27, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 27, 112, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 27, 112, 240, 0, 0, 63, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 137, 17, 27, 145, 185, 0, 4, 63, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 137, 17, 27, 145, 185, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 27, 176, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 27, 176, 240, 0, 0, 111, 78, 67, 82, 39, 16, 79, 53, 0, 0, 0, 93, 17, 27, 209, 189, 0, 4, 111, 78, 67, 82, 39, 16, 79, 53, 0, 0, 0, 93, 17, 27, 209, 189, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 27, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 27, 240, 240, 0, 0, 83, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 40, 2, 28, 16, 143, 0, 4, 83, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 40, 2, 28, 16, 143, 0, 0, 75, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 28, 48, 143, 0, 4, 75, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 28, 48, 143, 0, 0, 18, 59, 83, 181, 39, 19, 81, 97, 0, 0, 0, 134, 1, 28, 97, 198, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 131, 17, 28, 80, 240, 0, 4, 18, 59, 83, 181, 39, 19, 81, 97, 0, 0, 0, 134, 1, 28, 97, 198, 0, 0, 87, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 28, 128, 143, 0, 4, 87, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 28, 128, 143, 0, 0, 113, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 175, 17, 28, 160, 240, 0, 4, 113, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 175, 17, 28, 160, 240, 0, 0, 96, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 18, 28, 208, 240, 0, 4, 96, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 18, 28, 208, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 18, 28, 208, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 28, 240, 187, 0, 8, 96, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 28, 240, 187, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 29, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 29, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 29, 48, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 29, 48, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 94, 17, 29, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 94, 17, 29, 80, 240, 0, 0, 146, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 121, 48, 29, 128, 143, 0, 124, 146, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 121, 48, 29, 128, 143, 0, 4, 146, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 121, 48, 29, 128, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 116, 16, 29, 144, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 242, 17, 29, 176, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 242, 17, 29, 176, 240, 0, 0, 64, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 130, 17, 29, 209, 221, 0, 4, 64, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 130, 17, 29, 209, 221, 0, 0, 118, 78, 65, 181, 39, 16, 0, 37, 0, 0, 152, 158, 1, 29, 240, 143, 0, 4, 118, 78, 65, 181, 39, 16, 0, 37, 0, 0, 152, 158, 1, 29, 240, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 30, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 30, 16, 240, 0, 0, 110, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 147, 17, 30, 49, 227, 0, 4, 110, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 147, 17, 30, 49, 227, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 240, 17, 30, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 240, 17, 30, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 244, 17, 30, 112, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 244, 17, 30, 112, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 44, 17, 30, 160, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 9, 17, 30, 144, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 44, 17, 30, 160, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 55, 17, 30, 176, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 43, 17, 30, 192, 240, 0, 0, 84, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 138, 17, 30, 224, 143, 0, 4, 84, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 138, 17, 30, 224, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 116, 18, 31, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 121, 18, 31, 0, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 116, 18, 31, 16, 240, 0, 0, 39, 78, 147, 7, 39, 45, 1, 244, 0, 0, 0, 141, 17, 31, 49, 243, 0, 4, 39, 78, 147, 7, 39, 45, 1, 244, 0, 0, 0, 141, 17, 31, 49, 243, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 44, 17, 31, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 44, 17, 31, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 31, 112, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 31, 112, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 31, 144, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 31, 144, 240, 0, 0, 38, 78, 147, 7, 39, 45, 1, 244, 0, 0, 0, 140, 17, 31, 177, 251, 0, 4, 38, 78, 147, 7, 39, 45, 1, 244, 0, 0, 0, 140, 17, 31, 177, 251, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 31, 208, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 31, 208, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 31, 224, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 32, 0, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 32, 0, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 160, 17, 32, 32, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 160, 17, 32, 32, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 149, 17, 32, 64, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 149, 17, 32, 64, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 168, 17, 32, 96, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 168, 17, 32, 96, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 32, 128, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 32, 128, 240, 0, 0, 129, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 183, 1, 32, 162, 10, 0, 4, 129, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 183, 1, 32, 162, 10, 0, 0, 47, 78, 51, 98, 39, 23, 1, 244, 0, 0, 76, 162, 17, 32, 194, 12, 0, 4, 47, 78, 51, 98, 39, 23, 1, 244, 0, 0, 76, 162, 17, 32, 194, 12, 0, 0, 76, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 17, 32, 224, 143, 0, 4, 76, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 17, 32, 224, 143, 0, 0, 80, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 154, 17, 33, 18, 17, 0, 120, 80, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 154, 17, 33, 18, 17, 0, 4, 80, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 154, 17, 33, 18, 17, 0, 124, 80, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 45, 1, 33, 50, 19, 0, 8, 80, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 45, 1, 33, 50, 19, 0, 12, 80, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 154, 1, 33, 66, 20, 0, 0, 88, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 33, 96, 187, 0, 4, 88, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 33, 96, 187, 0, 0, 124, 78, 67, 82, 39, 16, 0, 37, 0, 0, 0, 39, 1, 33, 128, 240, 0, 4, 124, 78, 67, 82, 39, 16, 0, 37, 0, 0, 0, 39, 1, 33, 128, 240, 0, 0, 78, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 33, 160, 143, 0, 4, 78, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 33, 160, 143, 0, 0, 62, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 167, 17, 33, 210, 29, 0, 8, 62, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 37, 17, 33, 194, 28, 0, 4, 62, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 167, 17, 33, 210, 29, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 215, 17, 33, 224, 240, 0, 0, 58, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 163, 17, 34, 2, 32, 0, 4, 58, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 163, 17, 34, 2, 32, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 34, 32, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 34, 32, 240, 0, 0, 85, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 27, 18, 34, 64, 240, 0, 4, 85, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 27, 18, 34, 64, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 116, 18, 34, 96, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 116, 18, 34, 96, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 254, 17, 34, 128, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 254, 17, 34, 128, 240, 0, 124, 20, 78, 67, 82, 39, 16, 79, 53, 0, 0, 0, 177, 17, 34, 162, 42, 0, 4, 20, 78, 67, 82, 39, 16, 79, 53, 0, 0, 0, 177, 17, 34, 162, 42, 0, 16, 0, 78, 67, 82, 39, 16, 79, 53, 0, 0, 0, 220, 17, 34, 176, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 1, 8, 17, 34, 208, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 1, 8, 17, 34, 208, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 94, 17, 34, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 94, 17, 34, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 176, 17, 35, 0, 240, 0, 0, 97, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 178, 1, 35, 48, 143, 0, 8, 97, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 18, 35, 32, 240, 0, 4, 97, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 178, 1, 35, 48, 143, 0, 0, 19, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 176, 17, 35, 146, 57, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 46, 17, 35, 80, 240, 0, 8, 19, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 21, 17, 35, 98, 54, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 9, 165, 93, 66, 17, 35, 112, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 1, 17, 17, 35, 128, 240, 0, 4, 19, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 176, 17, 35, 146, 57, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 181, 17, 35, 160, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 120, 247, 17, 35, 176, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 35, 208, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 35, 208, 240, 0, 120, 20, 78, 67, 82, 39, 16, 79, 53, 0, 0, 0, 177, 17, 35, 242, 63, 0, 8, 20, 78, 67, 82, 39, 16, 79, 53, 0, 0, 0, 177, 17, 35, 242, 63, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 36, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 36, 16, 240, 0, 0, 20, 78, 67, 82, 39, 16, 79, 53, 0, 0, 0, 177, 17, 34, 162, 42, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 100, 34, 36, 64, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 100, 34, 36, 64, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 209, 17, 36, 96, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 209, 17, 36, 96, 240, 0, 0, 108, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 209, 17, 36, 130, 72, 0, 4, 108, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 209, 17, 36, 130, 72, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 1, 20, 17, 36, 160, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 1, 20, 17, 36, 160, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 240, 17, 36, 192, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 240, 17, 36, 192, 240, 0, 0, 130, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 84, 17, 36, 226, 78, 0, 4, 130, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 84, 17, 36, 226, 78, 0, 0, 114, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 73, 17, 37, 0, 240, 0, 4, 114, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 73, 17, 37, 0, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 37, 16, 240, 0, 0, 72, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 37, 48, 143, 0, 4, 72, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 37, 48, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 88, 17, 37, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 88, 17, 37, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 203, 17, 37, 96, 240, 0, 0, 70, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 37, 160, 143, 0, 124, 70, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 190, 18, 37, 144, 143, 0, 8, 70, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 190, 18, 37, 144, 143, 0, 4, 70, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 37, 160, 143, 0, 0, 121, 78, 67, 82, 39, 16, 1, 244, 0, 153, 50, 72, 1, 37, 192, 145, 0, 4, 121, 78, 67, 82, 39, 16, 1, 244, 0, 153, 50, 72, 1, 37, 192, 145, 0, 0, 21, 78, 35, 84, 39, 45, 81, 144, 0, 0, 0, 191, 17, 37, 226, 94, 0, 4, 21, 78, 35, 84, 39, 45, 81, 144, 0, 0, 0, 191, 17, 37, 226, 94, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 152, 158, 17, 38, 0, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 152, 158, 17, 38, 0, 240, 0, 0, 140, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 3, 18, 38, 32, 143, 0, 4, 140, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 3, 18, 38, 32, 143, 0, 0, 99, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 3, 18, 38, 64, 143, 0, 4, 99, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 3, 18, 38, 64, 143, 0, 0, 22, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 32, 17, 38, 114, 103, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 9, 17, 38, 96, 240, 0, 4, 22, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 32, 17, 38, 114, 103, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 223, 17, 38, 128, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 57, 17, 38, 144, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 69, 17, 38, 160, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 196, 17, 38, 176, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 147, 17, 38, 192, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 151, 17, 38, 208, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 168, 17, 38, 224, 240, 0, 8, 22, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 193, 17, 38, 242, 111, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 233, 17, 39, 0, 240, 0, 16, 0, 78, 67, 82, 39, 16, 1, 244, 0, 111, 96, 231, 17, 39, 16, 240, 0, 9, 1, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 124, 1, 39, 32, 190, 0, 5, 1, 78, 35, 84, 39, 45, 81, 144, 0, 0, 0, 244, 65, 39, 50, 115, 0, 5, 254, 58, 67, 164, 39, 17, 79, 66, 0, 0, 0, 122, 1, 39, 66, 116, 0, 9, 255, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 205, 16, 39, 80, 143, 0, 0, 134, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 99, 1, 39, 130, 120, 0, 124, 134, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 99, 1, 39, 130, 120, 0, 4, 134, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 99, 1, 39, 130, 120, 0, 0, 107, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 26, 1, 39, 162, 122, 0, 4, 107, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 26, 1, 39, 162, 122, 0, 8, 107, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 66, 1, 39, 178, 123, 0, 12, 107, 78, 67, 82, 39, 16, 79, 60, 0, 0, 0, 187, 1, 39, 194, 124, 0, 0, 23, 78, 67, 82, 39, 16, 79, 49, 0, 0, 0, 223, 17, 39, 226, 126, 0, 4, 23, 78, 67, 82, 39, 16, 79, 49, 0, 0, 0, 223, 17, 39, 226, 126, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 38, 17, 40, 0, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 38, 17, 40, 0, 240, 0, 0, 24, 78, 35, 84, 39, 45, 81, 144, 0, 0, 0, 200, 17, 40, 50, 131, 0, 8, 24, 78, 35, 84, 0, 2, 1, 244, 0, 0, 0, 152, 17, 40, 32, 240, 0, 4, 24, 78, 35, 84, 39, 45, 81, 144, 0, 0, 0, 200, 17, 40, 50, 131, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 40, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 40, 80, 240, 0, 0, 25, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 203, 17, 40, 178, 139, 0, 16, 0, 78, 51, 98, 0, 2, 1, 244, 0, 0, 0, 29, 17, 40, 112, 240, 0, 16, 0, 78, 51, 98, 0, 2, 1, 244, 0, 0, 0, 130, 17, 40, 128, 240, 0, 16, 0, 78, 51, 98, 0, 2, 1, 244, 0, 0, 0, 137, 17, 40, 144, 240, 0, 8, 25, 78, 51, 98, 0, 2, 1, 244, 0, 0, 0, 152, 17, 40, 160, 240, 0, 4, 25, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 203, 17, 40, 178, 139, 0, 16, 0, 78, 51, 98, 0, 2, 1, 244, 0, 0, 0, 241, 17, 40, 192, 240, 0, 0, 135, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 204, 17, 40, 226, 142, 0, 4, 135, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 204, 17, 40, 226, 142, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 41, 0, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 41, 0, 240, 0, 0, 79, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 41, 32, 143, 0, 4, 79, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 41, 32, 143, 0, 0, 133, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 203, 17, 41, 66, 148, 0, 4, 133, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 203, 17, 41, 66, 148, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 41, 96, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 41, 96, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 41, 128, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 41, 128, 240, 0, 0, 89, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 190, 18, 41, 176, 143, 0, 124, 89, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 190, 18, 41, 176, 143, 0, 8, 89, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 190, 18, 41, 176, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 41, 208, 187, 0, 4, 89, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 41, 208, 187, 0, 0, 59, 78, 67, 82, 39, 16, 79, 53, 0, 0, 0, 177, 17, 42, 2, 160, 0, 12, 59, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 77, 17, 41, 242, 159, 0, 4, 59, 78, 67, 82, 39, 16, 79, 53, 0, 0, 0, 177, 17, 42, 2, 160, 0, 8, 59, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 221, 17, 42, 18, 161, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 168, 17, 42, 48, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 168, 17, 42, 48, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 157, 17, 42, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 157, 17, 42, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 55, 17, 42, 112, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 55, 17, 42, 112, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 159, 17, 42, 192, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 159, 17, 42, 160, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 159, 17, 42, 160, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 159, 17, 42, 192, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 159, 17, 42, 192, 240, 0, 0, 91, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 42, 17, 42, 224, 143, 0, 4, 91, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 42, 17, 42, 224, 143, 0, 0, 27, 78, 35, 84, 39, 45, 81, 144, 0, 0, 0, 143, 17, 43, 2, 176, 0, 4, 27, 78, 35, 84, 39, 45, 81, 144, 0, 0, 0, 143, 17, 43, 2, 176, 0, 0, 36, 78, 35, 84, 39, 45, 81, 144, 0, 0, 0, 212, 17, 43, 34, 178, 0, 4, 36, 78, 35, 84, 39, 45, 81, 144, 0, 0, 0, 212, 17, 43, 34, 178, 0, 120, 59, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 221, 17, 43, 82, 181, 0, 24, 59, 78, 67, 82, 39, 16, 79, 53, 0, 0, 0, 177, 17, 43, 66, 180, 0, 28, 59, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 221, 17, 43, 82, 181, 0, 124, 59, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 221, 17, 43, 130, 184, 0, 16, 59, 78, 67, 82, 39, 16, 79, 53, 0, 0, 0, 177, 17, 43, 114, 183, 0, 20, 59, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 221, 17, 43, 130, 184, 0, 112, 59, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 77, 17, 43, 162, 186, 0, 36, 59, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 77, 17, 43, 162, 186, 0, 116, 59, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 77, 17, 43, 194, 188, 0, 32, 59, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 77, 17, 43, 194, 188, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 1, 8, 17, 43, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 1, 8, 17, 43, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 1, 8, 17, 43, 240, 240, 0, 0, 119, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 216, 17, 44, 64, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 62, 17, 44, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 73, 17, 44, 32, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 44, 48, 240, 0, 4, 119, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 216, 17, 44, 64, 240, 0, 0, 28, 78, 35, 84, 39, 45, 81, 144, 0, 0, 0, 6, 17, 44, 98, 198, 0, 4, 28, 78, 35, 84, 39, 45, 81, 144, 0, 0, 0, 6, 17, 44, 98, 198, 0, 16, 0, 78, 35, 84, 39, 45, 81, 144, 0, 0, 76, 162, 17, 44, 112, 240, 0, 16, 0, 78, 35, 84, 39, 45, 81, 144, 0, 151, 73, 65, 17, 44, 128, 240, 0, 124, 26, 78, 35, 84, 39, 45, 1, 244, 0, 0, 1, 15, 17, 45, 66, 212, 0, 108, 26, 78, 51, 87, 39, 23, 82, 33, 0, 0, 1, 15, 17, 44, 226, 206, 0, 28, 26, 78, 51, 87, 39, 23, 82, 33, 0, 0, 0, 25, 17, 44, 178, 203, 0, 12, 26, 78, 51, 87, 39, 23, 82, 33, 0, 0, 1, 13, 17, 44, 194, 204, 0, 48, 26, 78, 51, 87, 39, 23, 82, 33, 0, 0, 1, 14, 17, 44, 210, 205, 0, 40, 26, 78, 51, 87, 39, 23, 82, 33, 0, 0, 1, 15, 17, 44, 226, 206, 0, 16, 0, 78, 51, 87, 39, 23, 82, 33, 0, 151, 73, 65, 17, 44, 240, 240, 0, 112, 26, 78, 35, 84, 39, 45, 1, 244, 0, 0, 1, 15, 17, 45, 66, 212, 0, 24, 26, 78, 35, 84, 39, 98, 3, 102, 0, 0, 0, 25, 17, 45, 18, 209, 0, 8, 26, 78, 35, 84, 39, 45, 1, 244, 0, 0, 1, 13, 17, 45, 34, 210, 0, 44, 26, 78, 35, 84, 39, 45, 1, 244, 0, 0, 1, 14, 17, 45, 50, 211, 0, 36, 26, 78, 35, 84, 39, 45, 1, 244, 0, 0, 1, 15, 17, 45, 66, 212, 0, 16, 0, 78, 35, 84, 39, 45, 1, 244, 0, 151, 73, 65, 17, 45, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 209, 17, 45, 128, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 1, 4, 17, 45, 112, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 209, 17, 45, 128, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 71, 17, 45, 160, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 71, 17, 45, 160, 240, 0, 0, 48, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 209, 17, 45, 208, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 146, 17, 45, 192, 240, 0, 4, 48, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 209, 17, 45, 208, 240, 0, 0, 29, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 221, 17, 46, 18, 225, 0, 16, 0, 78, 67, 82, 39, 16, 79, 54, 0, 153, 6, 245, 17, 45, 240, 240, 0, 8, 29, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 77, 17, 46, 2, 224, 0, 4, 29, 78, 67, 82, 39, 16, 79, 54, 0, 0, 0, 221, 17, 46, 18, 225, 0, 0, 65, 78, 65, 181, 39, 16, 1, 244, 0, 0, 0, 129, 17, 46, 66, 228, 0, 16, 0, 78, 65, 181, 39, 16, 1, 244, 0, 0, 0, 44, 17, 46, 50, 228, 0, 4, 65, 78, 65, 181, 39, 16, 1, 244, 0, 0, 0, 129, 17, 46, 66, 228, 0, 16, 0, 78, 65, 181, 39, 16, 1, 244, 0, 0, 0, 239, 17, 46, 80, 240, 0, 16, 0, 78, 65, 181, 39, 16, 1, 244, 0, 0, 0, 240, 17, 46, 96, 240, 0, 16, 0, 0, 0, 1, 0, 0, 1, 244, 0, 0, 0, 44, 1, 46, 128, 240, 0, 16, 0, 0, 0, 1, 0, 0, 1, 244, 0, 0, 0, 44, 17, 46, 128, 240, 0, 0, 90, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 222, 1, 46, 160, 143, 0, 4, 90, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 222, 1, 46, 160, 143, 0, 0, 73, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 46, 192, 143, 0, 4, 73, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 1, 46, 192, 143, 0, 8, 73, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 42, 17, 46, 208, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 167, 17, 46, 224, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 215, 17, 46, 240, 240, 0, 0, 74, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 17, 47, 16, 143, 0, 4, 74, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 113, 17, 47, 16, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 240, 17, 47, 64, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 129, 17, 47, 48, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 240, 17, 47, 64, 240, 0, 0, 40, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 228, 17, 47, 114, 247, 0, 124, 40, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 228, 17, 47, 114, 247, 0, 4, 40, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 228, 17, 47, 114, 247, 0, 0, 30, 54, 163, 106, 39, 37, 81, 102, 0, 0, 0, 227, 1, 47, 144, 143, 0, 4, 30, 54, 163, 106, 39, 37, 81, 102, 0, 0, 0, 227, 1, 47, 144, 143, 0, 0, 115, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 71, 17, 47, 176, 143, 0, 8, 115, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 71, 17, 47, 176, 143, 0, 4, 115, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 73, 17, 47, 192, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 71, 17, 47, 224, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 71, 17, 47, 224, 240, 0, 0, 66, 78, 35, 84, 39, 45, 81, 144, 0, 0, 0, 238, 17, 48, 3, 0, 0, 4, 66, 78, 35, 84, 39, 45, 81, 144, 0, 0, 0, 238, 17, 48, 3, 0, 0, 0, 50, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 209, 17, 48, 51, 3, 0, 8, 50, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 19, 17, 48, 35, 2, 0, 4, 50, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 209, 17, 48, 51, 3, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 231, 17, 48, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 231, 17, 48, 80, 240, 0, 0, 31, 78, 99, 89, 39, 97, 81, 169, 0, 0, 0, 235, 17, 48, 131, 8, 0, 16, 0, 78, 99, 89, 39, 97, 81, 169, 0, 0, 0, 59, 17, 48, 112, 240, 0, 4, 31, 78, 99, 89, 39, 97, 81, 169, 0, 0, 0, 235, 17, 48, 131, 8, 0, 0, 49, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 209, 17, 48, 160, 240, 0, 4, 49, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 209, 17, 48, 160, 240, 0, 0, 68, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 203, 17, 48, 195, 12, 0, 4, 68, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 203, 17, 48, 195, 12, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 173, 17, 48, 224, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 173, 17, 48, 224, 240, 0, 0, 95, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 4, 17, 49, 51, 19, 0, 16, 0, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 159, 17, 49, 16, 240, 0, 4, 95, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 159, 17, 49, 16, 240, 0, 124, 95, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 4, 17, 49, 51, 19, 0, 8, 95, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 4, 17, 49, 51, 19, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 159, 17, 49, 64, 240, 0, 120, 95, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 159, 17, 49, 97, 60, 0, 16, 95, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 159, 17, 49, 97, 60, 0, 0, 128, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 45, 1, 49, 128, 143, 0, 4, 128, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 45, 1, 49, 128, 143, 0, 0, 34, 78, 51, 98, 39, 33, 1, 244, 0, 0, 0, 241, 17, 49, 163, 26, 0, 4, 34, 78, 51, 98, 39, 33, 1, 244, 0, 0, 0, 241, 17, 49, 163, 26, 0, 0, 32, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 190, 17, 49, 208, 143, 0, 8, 32, 78, 130, 208, 0, 2, 1, 244, 0, 0, 0, 113, 18, 49, 192, 240, 0, 4, 32, 78, 130, 208, 39, 20, 79, 196, 0, 0, 0, 190, 17, 49, 208, 143, 0, 0, 67, 78, 99, 89, 39, 45, 1, 244, 0, 0, 0, 247, 17, 50, 67, 36, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 3, 18, 50, 0, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 3, 18, 50, 0, 240, 0, 120, 67, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 247, 17, 50, 35, 34, 0, 8, 67, 78, 51, 98, 39, 23, 81, 144, 0, 0, 0, 247, 17, 50, 35, 34, 0, 124, 67, 78, 99, 89, 39, 45, 1, 244, 0, 0, 0, 247, 17, 50, 67, 36, 0, 4, 67, 78, 99, 89, 39, 45, 1, 244, 0, 0, 0, 247, 17, 50, 67, 36, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 142, 17, 50, 144, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 142, 17, 50, 112, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 142, 17, 50, 112, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 142, 17, 50, 144, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 142, 17, 50, 144, 240, 0, 0, 51, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 209, 17, 50, 176, 240, 0, 4, 51, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 209, 17, 50, 176, 240, 0, 0, 42, 78, 164, 234, 39, 16, 1, 244, 0, 0, 0, 251, 1, 50, 208, 143, 0, 4, 42, 78, 164, 234, 39, 16, 1, 244, 0, 0, 0, 251, 1, 50, 208, 143, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 152, 158, 17, 50, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 152, 158, 17, 50, 240, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 51, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 239, 17, 51, 16, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 223, 17, 51, 48, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 223, 17, 51, 48, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 73, 17, 51, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 73, 17, 51, 80, 240, 0, 0, 136, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 210, 17, 51, 115, 55, 0, 4, 136, 78, 67, 82, 39, 16, 79, 73, 0, 0, 0, 210, 17, 51, 115, 55, 1, 0, 127, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 244, 1, 255, 255, 255, 0, 0, 52, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 209, 17, 51, 163, 58, 0, 4, 52, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 209, 17, 51, 163, 58, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 240, 17, 51, 192, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 240, 17, 51, 192, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 51, 224, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 49, 17, 51, 224, 240, 0, 0, 61, 0, 0, 1, 0, 2, 1, 244, 0, 0, 152, 158, 17, 52, 0, 240, 0, 4, 61, 0, 0, 1, 0, 2, 1, 244, 0, 0, 152, 158, 17, 52, 0, 240, 0, 0, 106, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 175, 17, 52, 51, 67, 0, 16, 0, 78, 65, 181, 39, 16, 1, 244, 0, 0, 0, 28, 17, 52, 32, 240, 0, 4, 106, 78, 65, 181, 39, 16, 0, 37, 0, 0, 0, 175, 17, 52, 51, 67, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 104, 1, 52, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 104, 1, 52, 80, 240, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 159, 17, 52, 129, 60, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 159, 17, 52, 129, 60, 0, 16, 0, 0, 0, 1, 0, 2, 1, 244, 0, 0, 0, 159, 17, 52, 129, 60, 0, 120, 4, 58, 131, 168, 39, 24, 1, 244, 0, 0, 0, 45, 1, 52, 195, 76, 0, 0, 4, 58, 131, 168, 0, 0, 1, 244, 0, 0, 0, 45, 1, 52, 195, 76, 0, 124, 4, 59, 99, 182, 0, 0, 1, 244, 0, 0, 0, 104, 1, 53, 51, 83, 0, 8, 4, 58, 131, 168, 39, 24, 1, 244, 0, 0, 0, 45, 1, 52, 195, 76, 5, 8, 4, 58, 131, 168, 39, 24, 1, 244, 0, 0, 0, 45, 1, 52, 195, 76, 2, 8, 4, 58, 131, 168, 39, 24, 1, 244, 0, 0, 0, 45, 1, 52, 195, 76, 0, 0, 4, 58, 131, 168, 39, 24, 1, 244, 0, 0, 0, 45, 1, 52, 195, 76, 0, 16, 0, 58, 131, 168, 39, 24, 1, 244, 0, 0, 0, 104, 17, 53, 0, 240, 0, 16, 0, 58, 131, 168, 39, 24, 1, 244, 0, 0, 0, 151, 17, 53, 16, 240, 0, 124, 4, 59, 99, 182, 39, 18, 1, 244, 0, 0, 0, 104, 1, 53, 51, 83, 0, 12, 4, 59, 99, 182, 39, 18, 1, 244, 0, 0, 0, 104, 1, 53, 51, 83, 4, 12, 4, 59, 99, 182, 39, 18, 1, 244, 0, 0, 0, 104, 1, 53, 51, 83, 0, 20, 4, 59, 99, 182, 39, 18, 1, 244, 0, 0, 0, 151, 1, 53, 83, 85, 4, 20, 4, 59, 99, 182, 39, 18, 1, 244, 0, 0, 0, 151, 1, 53, 83, 85, 2, 20, 4, 59, 99, 182, 39, 18, 1, 244, 0, 0, 0, 151, 1, 53, 83, 85, 0, 16, 4, 58, 131, 168, 39, 24, 1, 244, 0, 0, 0, 215, 1, 53, 131, 88, 5, 16, 4, 58, 131, 168, 39, 24, 1, 244, 0, 0, 0, 215, 1, 53, 131, 88, 2, 16, 4, 58, 131, 168, 39, 24, 1, 244, 0, 0, 0, 215, 1, 53, 131, 88, 0, 4, 4, 59, 99, 182, 39, 18, 1, 244, 0, 0, 0, 237, 1, 53, 179, 91, 3, 4, 4, 59, 99, 182, 39, 18, 1, 244, 0, 0, 0, 237, 1, 53, 179, 91, 4, 4, 4, 59, 99, 182, 39, 18, 1, 244, 0, 0, 0, 237, 1, 53, 179, 91, 0, 0, 53, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 209, 17, 53, 243, 95, 0, 4, 53, 78, 67, 82, 39, 16, 1, 244, 0, 0, 0, 209, 17, 53, 243, 95 }; internal static int GetLocaleDataNumericPart(string cultureName, IcuLocaleDataParts part) { int num = SearchCultureName(cultureName); if (num < 0) { return -1; } ReadOnlySpan readOnlySpan = NameIndexToNumericData.Slice(num * 18, 18); return part switch { IcuLocaleDataParts.Lcid => readOnlySpan[2] | (readOnlySpan[1] << 8) | (readOnlySpan[0] << 16), IcuLocaleDataParts.AnsiCodePage => ((readOnlySpan[4] & 0xF0) >> 4) | ((readOnlySpan[3] & 0xFF) << 4), IcuLocaleDataParts.OemCodePage => readOnlySpan[5] | ((readOnlySpan[4] & 0xF) << 8), IcuLocaleDataParts.MacCodePage => readOnlySpan[7] | (readOnlySpan[6] << 8), IcuLocaleDataParts.EbcdicCodePage => readOnlySpan[9] | (readOnlySpan[8] << 8), IcuLocaleDataParts.GeoId => readOnlySpan[13] | (readOnlySpan[12] << 8) | (readOnlySpan[11] << 16) | (readOnlySpan[10] << 24), IcuLocaleDataParts.DigitSubstitutionOrListSeparator => ResolveDigitListSeparator(readOnlySpan[14]), IcuLocaleDataParts.SpecificLocaleIndex => ResolveIndex(((readOnlySpan[16] & 0xF0) >> 4) | ((readOnlySpan[15] & 0xFF) << 4)), IcuLocaleDataParts.ConsoleLocaleIndex => ResolveIndex(readOnlySpan[17] | ((readOnlySpan[16] & 0xF) << 8)), _ => -1, }; static int ResolveDigitListSeparator(int value) { return ((value & 0xF0) << 12) | (value & 0xF); } static int ResolveIndex(int value) { if (value != 4095) { return value; } return -1; } } internal static string GetThreeLetterWindowsLanguageName(string cultureName) { int num = SearchCultureName(cultureName); if (num < 0) { return null; } return GetString(ThreeLetterWindowsLanguageName.Slice(num * 3, 3)); } private static string GetLocaleDataMappedCulture(string cultureName, IcuLocaleDataParts part) { int localeDataNumericPart = GetLocaleDataNumericPart(cultureName, part); if (localeDataNumericPart < 0) { return ""; } return GetString(GetCultureName(localeDataNumericPart)); } internal static string GetSpecificCultureName(string cultureName) { return GetLocaleDataMappedCulture(cultureName, IcuLocaleDataParts.SpecificLocaleIndex); } internal static string GetConsoleUICulture(string cultureName) { return GetLocaleDataMappedCulture(cultureName, IcuLocaleDataParts.ConsoleLocaleIndex); } private static int SearchCultureName(string name) { if (name.Length > 14) { return -1; } Span span = stackalloc byte[name.Length]; for (int i = 0; i < name.Length; i++) { char c = name[i]; span[i] = (((uint)(c - 65) <= 25u) ? ((byte)(c | 0x20u)) : ((byte)c)); } ReadOnlySpan other = span; int num = 0; int num2 = 863; while (num <= num2) { int num3 = num + (num2 - num >> 1); int num4 = GetCultureName(num3).SequenceCompareTo(other); if (num4 == 0) { return num3; } if (num4 < 0) { num = num3 + 1; } else { num2 = num3 - 1; } } return ~num; } private static ReadOnlySpan GetCultureName(int localeNameIndice) { ReadOnlySpan localesNamesIndexes = LocalesNamesIndexes; int num = localeNameIndice * 2; int num2 = localesNamesIndexes[num]; int num3 = localesNamesIndexes[num + 1]; int start = (num2 << 4) | (num3 >> 4); int length = num3 & 0xF; return CultureNames.Slice(start, length); } private static string GetString(ReadOnlySpan buffer) { string text = string.FastAllocateString(buffer.Length); Span span = new Span(ref text.GetRawStringData(), buffer.Length); for (int i = 0; i < buffer.Length; i++) { span[i] = (char)buffer[i]; } return text; } } public sealed class IdnMapping { private bool _allowUnassigned; private bool _useStd3AsciiRules; private static readonly char[] s_dotSeparators = new char[4] { '.', '。', '.', '。' }; public bool AllowUnassigned { get { return _allowUnassigned; } set { _allowUnassigned = value; } } public bool UseStd3AsciiRules { get { return _useStd3AsciiRules; } set { _useStd3AsciiRules = value; } } private uint IcuFlags => (AllowUnassigned ? 1u : 0u) | (UseStd3AsciiRules ? 2u : 0u); private uint NlsFlags => (AllowUnassigned ? 1u : 0u) | (UseStd3AsciiRules ? 2u : 0u); public string GetAscii(string unicode) { return GetAscii(unicode, 0); } public string GetAscii(string unicode, int index) { if (unicode == null) { throw new ArgumentNullException("unicode"); } return GetAscii(unicode, index, unicode.Length - index); } public unsafe string GetAscii(string unicode, int index, int count) { if (unicode == null) { throw new ArgumentNullException("unicode"); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (index > unicode.Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (index > unicode.Length - count) { throw new ArgumentOutOfRangeException("unicode", SR.ArgumentOutOfRange_IndexCountBuffer); } if (count == 0) { throw new ArgumentException(SR.Argument_IdnBadLabelSize, "unicode"); } if (unicode[index + count - 1] == '\0') { throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, index + count - 1), "unicode"); } if (GlobalizationMode.Invariant) { return GetAsciiInvariant(unicode, index, count); } fixed (char* ptr = unicode) { if (!GlobalizationMode.UseNls) { return IcuGetAsciiCore(unicode, ptr + index, count); } return NlsGetAsciiCore(unicode, ptr + index, count); } } public string GetUnicode(string ascii) { return GetUnicode(ascii, 0); } public string GetUnicode(string ascii, int index) { if (ascii == null) { throw new ArgumentNullException("ascii"); } return GetUnicode(ascii, index, ascii.Length - index); } public unsafe string GetUnicode(string ascii, int index, int count) { if (ascii == null) { throw new ArgumentNullException("ascii"); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (index > ascii.Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (index > ascii.Length - count) { throw new ArgumentOutOfRangeException("ascii", SR.ArgumentOutOfRange_IndexCountBuffer); } if (count > 0 && ascii[index + count - 1] == '\0') { throw new ArgumentException(SR.Argument_IdnBadPunycode, "ascii"); } if (GlobalizationMode.Invariant) { return GetUnicodeInvariant(ascii, index, count); } fixed (char* ptr = ascii) { if (!GlobalizationMode.UseNls) { return IcuGetUnicodeCore(ascii, ptr + index, count); } return NlsGetUnicodeCore(ascii, ptr + index, count); } } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is IdnMapping idnMapping && _allowUnassigned == idnMapping._allowUnassigned) { return _useStd3AsciiRules == idnMapping._useStd3AsciiRules; } return false; } public override int GetHashCode() { return (_allowUnassigned ? 100 : 200) + (_useStd3AsciiRules ? 1000 : 2000); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static string GetStringForOutput(string originalString, char* input, int inputLength, char* output, int outputLength) { if (originalString.Length == inputLength && inputLength == outputLength && Ordinal.EqualsIgnoreCase(ref *input, ref *output, inputLength)) { return originalString; } return new string(output, 0, outputLength); } private string GetAsciiInvariant(string unicode, int index, int count) { if (index > 0 || count < unicode.Length) { unicode = unicode.Substring(index, count); } if (ValidateStd3AndAscii(unicode, UseStd3AsciiRules, bCheckAscii: true)) { return unicode; } if (unicode[^1] <= '\u001f') { throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, unicode.Length - 1), "unicode"); } if (UseStd3AsciiRules) { ValidateStd3AndAscii(unicode, bUseStd3: true, bCheckAscii: false); } return PunycodeEncode(unicode); } private static bool ValidateStd3AndAscii(string unicode, bool bUseStd3, bool bCheckAscii) { if (unicode.Length == 0) { throw new ArgumentException(SR.Argument_IdnBadLabelSize, "unicode"); } int num = -1; for (int i = 0; i < unicode.Length; i++) { if (unicode[i] <= '\u001f') { throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequence, i), "unicode"); } if (bCheckAscii && unicode[i] >= '\u007f') { return false; } if (IsDot(unicode[i])) { if (i == num + 1) { throw new ArgumentException(SR.Argument_IdnBadLabelSize, "unicode"); } if (i - num > 64) { throw new ArgumentException(SR.Argument_IdnBadLabelSize, "unicode"); } if (bUseStd3 && i > 0) { ValidateStd3(unicode[i - 1], bNextToDot: true); } num = i; } else if (bUseStd3) { ValidateStd3(unicode[i], i == num + 1); } } if (num == -1 && unicode.Length > 63) { throw new ArgumentException(SR.Argument_IdnBadLabelSize, "unicode"); } if (unicode.Length > 255 - ((!IsDot(unicode[^1])) ? 1 : 0)) { throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, 255 - ((!IsDot(unicode[^1])) ? 1 : 0)), "unicode"); } if (bUseStd3 && !IsDot(unicode[^1])) { ValidateStd3(unicode[^1], bNextToDot: true); } return true; } private static string PunycodeEncode(string unicode) { if (unicode.Length == 0) { throw new ArgumentException(SR.Argument_IdnBadLabelSize, "unicode"); } StringBuilder stringBuilder = new StringBuilder(unicode.Length); int num = 0; int num2 = 0; int num3 = 0; while (num < unicode.Length) { num = unicode.IndexOfAny(s_dotSeparators, num2); if (num < 0) { num = unicode.Length; } if (num == num2) { if (num == unicode.Length) { break; } throw new ArgumentException(SR.Argument_IdnBadLabelSize, "unicode"); } stringBuilder.Append("xn--"); bool flag = false; StrongBidiCategory bidiCategory = CharUnicodeInfo.GetBidiCategory(unicode, num2); if (bidiCategory == StrongBidiCategory.StrongRightToLeft) { flag = true; int num4 = num - 1; if (char.IsLowSurrogate(unicode, num4)) { num4--; } bidiCategory = CharUnicodeInfo.GetBidiCategory(unicode, num4); if (bidiCategory != StrongBidiCategory.StrongRightToLeft) { throw new ArgumentException(SR.Argument_IdnBadBidi, "unicode"); } } int num5 = 0; for (int i = num2; i < num; i++) { StrongBidiCategory bidiCategory2 = CharUnicodeInfo.GetBidiCategory(unicode, i); if (flag && bidiCategory2 == StrongBidiCategory.StrongLeftToRight) { throw new ArgumentException(SR.Argument_IdnBadBidi, "unicode"); } if (!flag && bidiCategory2 == StrongBidiCategory.StrongRightToLeft) { throw new ArgumentException(SR.Argument_IdnBadBidi, "unicode"); } if (Basic(unicode[i])) { stringBuilder.Append(EncodeBasic(unicode[i])); num5++; } else if (char.IsSurrogatePair(unicode, i)) { i++; } } int num6 = num5; if (num6 == num - num2) { stringBuilder.Remove(num3, "xn--".Length); } else { if (unicode.Length - num2 >= "xn--".Length && unicode.Substring(num2, "xn--".Length).Equals("xn--", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(SR.Argument_IdnBadPunycode, "unicode"); } 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 = 134217727; for (int j = num2; j < num; j += ((!IsSupplementary(num11)) ? 1 : 2)) { num11 = char.ConvertToUtf32(unicode, j); if (num11 >= num8 && num11 < num12) { num12 = num11; } } num9 += (num12 - num8) * (num5 - num7 + 1); num8 = num12; for (int j = num2; j < num; j += ((!IsSupplementary(num11)) ? 1 : 2)) { num11 = char.ConvertToUtf32(unicode, j); if (num11 < num8) { num9++; } if (num11 != num8) { continue; } int num13 = num9; int num14 = 36; while (true) { int num15 = ((num14 <= num10) ? 1 : ((num14 >= num10 + 26) ? 26 : (num14 - num10))); if (num13 < num15) { break; } stringBuilder.Append(EncodeDigit(num15 + (num13 - num15) % (36 - num15))); num13 = (num13 - num15) / (36 - num15); num14 += 36; } stringBuilder.Append(EncodeDigit(num13)); num10 = Adapt(num9, num5 - num7 + 1, num5 == num6); num9 = 0; num5++; if (IsSupplementary(num12)) { num5++; num7++; } } num9++; num8++; } } if (stringBuilder.Length - num3 > 63) { throw new ArgumentException(SR.Argument_IdnBadLabelSize, "unicode"); } if (num != unicode.Length) { stringBuilder.Append('.'); } num2 = num + 1; num3 = stringBuilder.Length; } if (stringBuilder.Length > 255 - ((!IsDot(unicode[^1])) ? 1 : 0)) { throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, 255 - ((!IsDot(unicode[^1])) ? 1 : 0)), "unicode"); } return stringBuilder.ToString(); } private static bool IsDot(char c) { if (c != '.' && c != '。' && c != '.') { return c == '。'; } return true; } private static bool IsSupplementary(int cTest) { return cTest >= 65536; } private static bool Basic(uint cp) { return cp < 128; } private static void ValidateStd3(char c, bool bNextToDot) { if (c > ',') { switch (c) { default: if ((c < '[' || c > '`') && (c < '{' || c > '\u007f') && !(c == '-' && bNextToDot)) { return; } break; case '/': case ':': case ';': case '<': case '=': case '>': case '?': case '@': break; } } throw new ArgumentException(SR.Format(SR.Argument_IdnBadStd3, c), "c"); } private string GetUnicodeInvariant(string ascii, int index, int count) { if (index > 0 || count < ascii.Length) { ascii = ascii.Substring(index, count); } string text = PunycodeDecode(ascii); if (!ascii.Equals(GetAscii(text), StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(SR.Argument_IdnIllegalName, "ascii"); } return text; } private static string PunycodeDecode(string ascii) { if (ascii.Length == 0) { throw new ArgumentException(SR.Argument_IdnBadLabelSize, "ascii"); } if (ascii.Length > 255 - ((!IsDot(ascii[^1])) ? 1 : 0)) { throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, 255 - ((!IsDot(ascii[^1])) ? 1 : 0)), "ascii"); } StringBuilder stringBuilder = new StringBuilder(ascii.Length); int num = 0; int num2 = 0; int num3 = 0; while (num < ascii.Length) { num = ascii.IndexOf('.', num2); if (num < 0 || num > ascii.Length) { num = ascii.Length; } if (num == num2) { if (num == ascii.Length) { break; } throw new ArgumentException(SR.Argument_IdnBadLabelSize, "ascii"); } if (num - num2 > 63) { throw new ArgumentException(SR.Argument_IdnBadLabelSize, "ascii"); } if (ascii.Length < "xn--".Length + num2 || string.Compare(ascii, num2, "xn--", 0, "xn--".Length, StringComparison.OrdinalIgnoreCase) != 0) { stringBuilder.Append(ascii, num2, num - num2); } else { num2 += "xn--".Length; int num4 = ascii.LastIndexOf('-', num - 1); if (num4 == num - 1) { throw new ArgumentException(SR.Argument_IdnBadPunycode, "ascii"); } int num5; if (num4 <= num2) { num5 = 0; } else { num5 = num4 - num2; for (int i = num2; i < num2 + num5; i++) { if (ascii[i] > '\u007f') { throw new ArgumentException(SR.Argument_IdnBadPunycode, "ascii"); } stringBuilder.Append((char)((ascii[i] >= 'A' && ascii[i] <= 'Z') ? (ascii[i] - 65 + 97) : ascii[i])); } } int num6 = num2 + ((num5 > 0) ? (num5 + 1) : 0); int num7 = 128; int num8 = 72; int num9 = 0; int num10 = 0; while (num6 < num) { int num11 = num9; int num12 = 1; int num13 = 36; while (true) { if (num6 >= num) { throw new ArgumentException(SR.Argument_IdnBadPunycode, "ascii"); } int num14 = DecodeDigit(ascii[num6++]); if (num14 > (134217727 - num9) / num12) { throw new ArgumentException(SR.Argument_IdnBadPunycode, "ascii"); } num9 += num14 * num12; int num15 = ((num13 <= num8) ? 1 : ((num13 >= num8 + 26) ? 26 : (num13 - num8))); if (num14 < num15) { break; } if (num12 > 134217727 / (36 - num15)) { throw new ArgumentException(SR.Argument_IdnBadPunycode, "ascii"); } num12 *= 36 - num15; num13 += 36; } num8 = Adapt(num9 - num11, stringBuilder.Length - num3 - num10 + 1, num11 == 0); if (num9 / (stringBuilder.Length - num3 - num10 + 1) > 134217727 - num7) { throw new ArgumentException(SR.Argument_IdnBadPunycode, "ascii"); } num7 += num9 / (stringBuilder.Length - num3 - num10 + 1); num9 %= stringBuilder.Length - num3 - num10 + 1; if (num7 < 0 || num7 > 1114111 || (num7 >= 55296 && num7 <= 57343)) { throw new ArgumentException(SR.Argument_IdnBadPunycode, "ascii"); } string value = char.ConvertFromUtf32(num7); int num17; if (num10 > 0) { int num16 = num9; num17 = num3; while (num16 > 0) { if (num17 >= stringBuilder.Length) { throw new ArgumentException(SR.Argument_IdnBadPunycode, "ascii"); } if (char.IsSurrogate(stringBuilder[num17])) { num17++; } num16--; num17++; } } else { num17 = num3 + num9; } stringBuilder.Insert(num17, value); if (IsSupplementary(num7)) { num10++; } num9++; } bool flag = false; StrongBidiCategory bidiCategory = CharUnicodeInfo.GetBidiCategory(stringBuilder, num3); if (bidiCategory == StrongBidiCategory.StrongRightToLeft) { flag = true; } for (int j = num3; j < stringBuilder.Length; j++) { if (!char.IsLowSurrogate(stringBuilder[j])) { bidiCategory = CharUnicodeInfo.GetBidiCategory(stringBuilder, j); if ((flag && bidiCategory == StrongBidiCategory.StrongLeftToRight) || (!flag && bidiCategory == StrongBidiCategory.StrongRightToLeft)) { throw new ArgumentException(SR.Argument_IdnBadBidi, "ascii"); } } } if (flag && bidiCategory != StrongBidiCategory.StrongRightToLeft) { throw new ArgumentException(SR.Argument_IdnBadBidi, "ascii"); } } if (num - num2 > 63) { throw new ArgumentException(SR.Argument_IdnBadLabelSize, "ascii"); } if (num != ascii.Length) { stringBuilder.Append('.'); } num2 = num + 1; num3 = stringBuilder.Length; } if (stringBuilder.Length > 255 - ((!IsDot(stringBuilder[stringBuilder.Length - 1])) ? 1 : 0)) { throw new ArgumentException(SR.Format(SR.Argument_IdnBadNameSize, 255 - ((!IsDot(stringBuilder[stringBuilder.Length - 1])) ? 1 : 0)), "ascii"); } return stringBuilder.ToString(); } private static int DecodeDigit(char cp) { if (cp >= '0' && cp <= '9') { return cp - 48 + 26; } if (cp >= 'a' && cp <= 'z') { return cp - 97; } if (cp >= 'A' && cp <= 'Z') { return cp - 65; } throw new ArgumentException(SR.Argument_IdnBadPunycode, "cp"); } private static int Adapt(int delta, int numpoints, bool firsttime) { delta = (firsttime ? (delta / 700) : (delta / 2)); delta += delta / numpoints; uint num = 0u; while (delta > 455) { delta /= 35; num += 36; } return (int)(num + 36 * delta / (delta + 38)); } private static char EncodeBasic(char bcp) { if (HasUpperCaseFlag(bcp)) { bcp = (char)(bcp + 32); } return bcp; } private static bool HasUpperCaseFlag(char punychar) { if (punychar >= 'A') { return punychar <= 'Z'; } return false; } private static char EncodeDigit(int d) { if (d > 25) { return (char)(d - 26 + 48); } return (char)(d + 97); } private unsafe string IcuGetAsciiCore(string unicodeString, char* unicode, int count) { uint icuFlags = IcuFlags; CheckInvalidIdnCharacters(unicode, count, icuFlags, "unicode"); int num = (int)Math.Min((long)count * 3L + 4, 512L); int num2; if (num < 512) { char* ptr = stackalloc char[num]; num2 = Interop.Globalization.ToAscii(icuFlags, unicode, count, ptr, num); if (num2 > 0 && num2 <= num) { return GetStringForOutput(unicodeString, unicode, count, ptr, num2); } } else { num2 = Interop.Globalization.ToAscii(icuFlags, unicode, count, null, 0); } if (num2 == 0) { throw new ArgumentException(SR.Argument_IdnIllegalName, "unicode"); } char[] array = new char[num2]; fixed (char* ptr2 = &array[0]) { num2 = Interop.Globalization.ToAscii(icuFlags, unicode, count, ptr2, num2); if (num2 == 0 || num2 > array.Length) { throw new ArgumentException(SR.Argument_IdnIllegalName, "unicode"); } return GetStringForOutput(unicodeString, unicode, count, ptr2, num2); } } private unsafe string IcuGetUnicodeCore(string asciiString, char* ascii, int count) { uint icuFlags = IcuFlags; CheckInvalidIdnCharacters(ascii, count, icuFlags, "ascii"); if (count < 512) { char* output = stackalloc char[count]; return IcuGetUnicodeCore(asciiString, ascii, count, icuFlags, output, count, reattempt: true); } char[] array = new char[count]; fixed (char* output2 = &array[0]) { return IcuGetUnicodeCore(asciiString, ascii, count, icuFlags, output2, count, reattempt: true); } } private unsafe string IcuGetUnicodeCore(string asciiString, char* ascii, int count, uint flags, char* output, int outputLength, bool reattempt) { int num = Interop.Globalization.ToUnicode(flags, ascii, count, output, outputLength); if (num == 0) { throw new ArgumentException(SR.Argument_IdnIllegalName, "ascii"); } if (num <= outputLength) { return GetStringForOutput(asciiString, ascii, count, output, num); } if (reattempt) { fixed (char* output2 = new char[num]) { return IcuGetUnicodeCore(asciiString, ascii, count, flags, output2, num, reattempt: false); } } throw new ArgumentException(SR.Argument_IdnIllegalName, "ascii"); } private unsafe static void CheckInvalidIdnCharacters(char* s, int count, uint flags, string paramName) { if ((flags & 2u) != 0) { return; } for (int i = 0; i < count; i++) { char c = s[i]; if (c <= '\u001f' || c == '\u007f') { throw new ArgumentException(SR.Argument_IdnIllegalName, paramName); } } } private unsafe string NlsGetAsciiCore(string unicodeString, char* unicode, int count) { uint nlsFlags = NlsFlags; int num = Interop.Normaliz.IdnToAscii(nlsFlags, unicode, count, null, 0); if (num == 0) { ThrowForZeroLength(unicode: true); } if (num < 512) { char* output = stackalloc char[num]; return NlsGetAsciiCore(unicodeString, unicode, count, nlsFlags, output, num); } char[] array = new char[num]; fixed (char* output2 = &array[0]) { return NlsGetAsciiCore(unicodeString, unicode, count, nlsFlags, output2, num); } } private unsafe static string NlsGetAsciiCore(string unicodeString, char* unicode, int count, uint flags, char* output, int outputLength) { int num = Interop.Normaliz.IdnToAscii(flags, unicode, count, output, outputLength); if (num == 0) { ThrowForZeroLength(unicode: true); } return GetStringForOutput(unicodeString, unicode, count, output, num); } private unsafe string NlsGetUnicodeCore(string asciiString, char* ascii, int count) { uint nlsFlags = NlsFlags; int num = Interop.Normaliz.IdnToUnicode(nlsFlags, ascii, count, null, 0); if (num == 0) { ThrowForZeroLength(unicode: false); } if (num < 512) { char* output = stackalloc char[num]; return NlsGetUnicodeCore(asciiString, ascii, count, nlsFlags, output, num); } char[] array = new char[num]; fixed (char* output2 = &array[0]) { return NlsGetUnicodeCore(asciiString, ascii, count, nlsFlags, output2, num); } } private unsafe static string NlsGetUnicodeCore(string asciiString, char* ascii, int count, uint flags, char* output, int outputLength) { int num = Interop.Normaliz.IdnToUnicode(flags, ascii, count, output, outputLength); if (num == 0) { ThrowForZeroLength(unicode: false); } return GetStringForOutput(asciiString, ascii, count, output, num); } [DoesNotReturn] private static void ThrowForZeroLength(bool unicode) { int lastPInvokeError = Marshal.GetLastPInvokeError(); throw new ArgumentException((lastPInvokeError == 123) ? SR.Argument_IdnIllegalName : (unicode ? SR.Argument_InvalidCharSequenceNoIndex : SR.Argument_IdnBadPunycode), unicode ? "unicode" : "ascii"); } } internal static class InternalGlobalizationHelper { internal static long TimeToTicks(int hour, int minute, int second) { long num = (long)hour * 3600L + (long)minute * 60L + second; if (num > 922337203685L || num < -922337203685L) { throw new ArgumentOutOfRangeException(null, SR.Overflow_TimeSpanTooLong); } return num * 10000000; } } internal static class InvariantModeCasing { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static char ToLower(char c) { return CharUnicodeInfo.ToLower(c); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static char ToUpper(char c) { return CharUnicodeInfo.ToUpper(c); } internal static string ToLower(string s) { if (s.Length == 0) { return string.Empty; } ReadOnlySpan readOnlySpan = s; int num = 0; while (num < s.Length) { if (char.IsHighSurrogate(readOnlySpan[num]) && num < s.Length - 1 && char.IsLowSurrogate(readOnlySpan[num + 1])) { SurrogateCasing.ToLower(readOnlySpan[num], readOnlySpan[num + 1], out var hr, out var lr); if (readOnlySpan[num] != hr || readOnlySpan[num + 1] != lr) { break; } num += 2; } else { if (ToLower(readOnlySpan[num]) != readOnlySpan[num]) { break; } num++; } } if (num >= s.Length) { return s; } return string.Create(s.Length, (s, num), delegate(Span destination, (string s, int i) state) { ReadOnlySpan readOnlySpan2 = state.s; readOnlySpan2.Slice(0, state.i).CopyTo(destination); ToLower(readOnlySpan2.Slice(state.i), destination.Slice(state.i)); }); } internal static string ToUpper(string s) { if (s.Length == 0) { return string.Empty; } ReadOnlySpan readOnlySpan = s; int num = 0; while (num < s.Length) { if (char.IsHighSurrogate(readOnlySpan[num]) && num < s.Length - 1 && char.IsLowSurrogate(readOnlySpan[num + 1])) { SurrogateCasing.ToUpper(readOnlySpan[num], readOnlySpan[num + 1], out var hr, out var lr); if (readOnlySpan[num] != hr || readOnlySpan[num + 1] != lr) { break; } num += 2; } else { if (ToUpper(readOnlySpan[num]) != readOnlySpan[num]) { break; } num++; } } if (num >= s.Length) { return s; } return string.Create(s.Length, (s, num), delegate(Span destination, (string s, int i) state) { ReadOnlySpan readOnlySpan2 = state.s; readOnlySpan2.Slice(0, state.i).CopyTo(destination); ToUpper(readOnlySpan2.Slice(state.i), destination.Slice(state.i)); }); } internal static void ToUpper(ReadOnlySpan source, Span destination) { for (int i = 0; i < source.Length; i++) { char c = source[i]; if (char.IsHighSurrogate(c) && i < source.Length - 1) { char c2 = source[i + 1]; if (char.IsLowSurrogate(c2)) { SurrogateCasing.ToUpper(c, c2, out var hr, out var lr); destination[i] = hr; destination[i + 1] = lr; i++; continue; } } destination[i] = ToUpper(c); } } internal static void ToLower(ReadOnlySpan source, Span destination) { for (int i = 0; i < source.Length; i++) { char c = source[i]; if (char.IsHighSurrogate(c) && i < source.Length - 1) { char c2 = source[i + 1]; if (char.IsLowSurrogate(c2)) { SurrogateCasing.ToLower(c, c2, out var hr, out var lr); destination[i] = hr; destination[i + 1] = lr; i++; continue; } } destination[i] = ToLower(c); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static (uint, int) GetScalar(ref char source, int index, int length) { char c = source; if (!char.IsHighSurrogate(c) || index >= length - 1) { return (c, 1); } char c2 = Unsafe.Add(ref source, 1); if (!char.IsLowSurrogate(c2)) { return (c, 1); } return (UnicodeUtility.GetScalarFromUtf16SurrogatePair(c, c2), 2); } internal static int CompareStringIgnoreCase(ref char strA, int lengthA, ref char strB, int lengthB) { int num = Math.Min(lengthA, lengthB); ref char source = ref strA; ref char source2 = ref strB; int num2 = 0; while (num2 < num) { var (num3, num4) = GetScalar(ref source, num2, lengthA); var (num5, elementOffset) = GetScalar(ref source2, num2, lengthB); if (num3 == num5) { num2 += num4; source = ref Unsafe.Add(ref source, num4); source2 = ref Unsafe.Add(ref source2, elementOffset); continue; } uint num6 = CharUnicodeInfo.ToUpper(num3); uint num7 = CharUnicodeInfo.ToUpper(num5); if (num6 == num7) { num2 += num4; source = ref Unsafe.Add(ref source, num4); source2 = ref Unsafe.Add(ref source2, elementOffset); continue; } return (int)(num3 - num5); } return lengthA - lengthB; } internal unsafe static int IndexOfIgnoreCase(ReadOnlySpan source, ReadOnlySpan value) { fixed (char* ptr = &MemoryMarshal.GetReference(source)) { fixed (char* ptr3 = &MemoryMarshal.GetReference(value)) { char* ptr2 = ptr + (source.Length - value.Length); char* ptr4 = ptr3 + value.Length - 1; for (char* ptr5 = ptr; ptr5 <= ptr2; ptr5++) { char* ptr6 = ptr3; char* ptr7 = ptr5; while (ptr6 <= ptr4) { if (!char.IsHighSurrogate(*ptr6) || ptr6 == ptr4) { if (*ptr6 != *ptr7 && ToUpper(*ptr6) != ToUpper(*ptr7)) { break; } ptr6++; ptr7++; } else if (char.IsHighSurrogate(*ptr7) && char.IsLowSurrogate(ptr7[1]) && char.IsLowSurrogate(ptr6[1])) { if (!SurrogateCasing.Equal(*ptr7, ptr7[1], *ptr6, ptr6[1])) { break; } ptr7 += 2; ptr6 += 2; } else { if (*ptr6 != *ptr7) { break; } ptr7++; ptr6++; } } if (ptr6 > ptr4) { return (int)(ptr5 - ptr); } } return -1; } } } internal unsafe static int LastIndexOfIgnoreCase(ReadOnlySpan source, ReadOnlySpan value) { fixed (char* ptr3 = &MemoryMarshal.GetReference(source)) { fixed (char* ptr = &MemoryMarshal.GetReference(value)) { char* ptr2 = ptr + value.Length - 1; for (char* ptr4 = ptr3 + (source.Length - value.Length); ptr4 >= ptr3; ptr4--) { char* ptr5 = ptr; char* ptr6 = ptr4; while (ptr5 <= ptr2) { if (!char.IsHighSurrogate(*ptr5) || ptr5 == ptr2) { if (*ptr5 != *ptr6 && ToUpper(*ptr5) != ToUpper(*ptr6)) { break; } ptr5++; ptr6++; } else if (char.IsHighSurrogate(*ptr6) && char.IsLowSurrogate(ptr6[1]) && char.IsLowSurrogate(ptr5[1])) { if (!SurrogateCasing.Equal(*ptr6, ptr6[1], *ptr5, ptr5[1])) { break; } ptr6 += 2; ptr5 += 2; } else { if (*ptr5 != *ptr6) { break; } ptr6++; ptr5++; } } if (ptr5 > ptr2) { return (int)(ptr4 - ptr3); } } return -1; } } } } public static class ISOWeek { public static int GetWeekOfYear(DateTime date) { int weekNumber = GetWeekNumber(date); if (weekNumber < 1) { return GetWeeksInYear(date.Year - 1); } if (weekNumber > GetWeeksInYear(date.Year)) { return 1; } return weekNumber; } public static int GetYear(DateTime date) { int weekNumber = GetWeekNumber(date); if (weekNumber < 1) { return date.Year - 1; } if (weekNumber > GetWeeksInYear(date.Year)) { return date.Year + 1; } return date.Year; } public static DateTime GetYearStart(int year) { return ToDateTime(year, 1, DayOfWeek.Monday); } public static DateTime GetYearEnd(int year) { return ToDateTime(year, GetWeeksInYear(year), DayOfWeek.Sunday); } public static int GetWeeksInYear(int year) { if (year < 1 || year > 9999) { throw new ArgumentOutOfRangeException("year", SR.ArgumentOutOfRange_Year); } if (P(year) == 4 || P(year - 1) == 3) { return 53; } return 52; static int P(int y) { return (y + y / 4 - y / 100 + y / 400) % 7; } } public static DateTime ToDateTime(int year, int week, DayOfWeek dayOfWeek) { if (year < 1 || year > 9999) { throw new ArgumentOutOfRangeException("year", SR.ArgumentOutOfRange_Year); } if (week < 1 || week > 53) { throw new ArgumentOutOfRangeException("week", SR.ArgumentOutOfRange_Week_ISO); } if (dayOfWeek < DayOfWeek.Sunday || dayOfWeek > (DayOfWeek)7) { throw new ArgumentOutOfRangeException("dayOfWeek", SR.ArgumentOutOfRange_DayOfWeek); } int num = GetWeekday(new DateTime(year, 1, 4).DayOfWeek) + 3; int num2 = week * 7 + GetWeekday(dayOfWeek) - num; return new DateTime(year, 1, 1).AddDays(num2 - 1); } private static int GetWeekNumber(DateTime date) { return (date.DayOfYear - GetWeekday(date.DayOfWeek) + 10) / 7; } private static int GetWeekday(DayOfWeek dayOfWeek) { if (dayOfWeek != 0) { return (int)dayOfWeek; } return 7; } } public class JapaneseCalendar : Calendar { private static readonly DateTime s_calendarMinValue = new DateTime(1868, 9, 8); private static volatile EraInfo[] s_japaneseEraInfo; internal static volatile Calendar s_defaultInstance; internal GregorianCalendarHelper _helper; private static readonly string[] s_abbreviatedEnglishEraNames = new string[5] { "M", "T", "S", "H", "R" }; public override DateTime MinSupportedDateTime => s_calendarMinValue; public override DateTime MaxSupportedDateTime => DateTime.MaxValue; public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.SolarCalendar; internal override CalendarId ID => CalendarId.JAPAN; public override int[] Eras => _helper.Eras; public override int TwoDigitYearMax { get { if (_twoDigitYearMax == -1) { _twoDigitYearMax = Calendar.GetSystemTwoDigitYearSetting(ID, 99); } return _twoDigitYearMax; } set { VerifyWritable(); if (value < 99 || value > _helper.MaxYear) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 99, _helper.MaxYear)); } _twoDigitYearMax = value; } } internal static EraInfo[] GetEraInfo() { object obj = s_japaneseEraInfo; if (obj == null) { obj = (s_japaneseEraInfo = (GlobalizationMode.UseNls ? NlsGetJapaneseEras() : IcuGetJapaneseEras())); if (obj == null) { obj = new EraInfo[5] { new EraInfo(5, 2019, 5, 1, 2018, 1, 7981, "令和", "令", "R"), new EraInfo(4, 1989, 1, 8, 1988, 1, 31, "平成", "平", "H"), new EraInfo(3, 1926, 12, 25, 1925, 1, 64, "昭和", "昭", "S"), new EraInfo(2, 1912, 7, 30, 1911, 1, 15, "大正", "大", "T"), new EraInfo(1, 1868, 1, 1, 1867, 1, 45, "明治", "明", "M") }; s_japaneseEraInfo = (EraInfo[])obj; } } return (EraInfo[])obj; } internal static Calendar GetDefaultInstance() { return s_defaultInstance ?? (s_defaultInstance = new JapaneseCalendar()); } public JapaneseCalendar() { try { new CultureInfo("ja-JP"); } catch (ArgumentException innerException) { throw new TypeInitializationException(GetType().ToString(), innerException); } _helper = new GregorianCalendarHelper(this, GetEraInfo()); } public override DateTime AddMonths(DateTime time, int months) { return _helper.AddMonths(time, months); } public override DateTime AddYears(DateTime time, int years) { return _helper.AddYears(time, years); } public override int GetDaysInMonth(int year, int month, int era) { return _helper.GetDaysInMonth(year, month, era); } public override int GetDaysInYear(int year, int era) { return _helper.GetDaysInYear(year, era); } public override int GetDayOfMonth(DateTime time) { return _helper.GetDayOfMonth(time); } public override DayOfWeek GetDayOfWeek(DateTime time) { return _helper.GetDayOfWeek(time); } public override int GetDayOfYear(DateTime time) { return _helper.GetDayOfYear(time); } public override int GetMonthsInYear(int year, int era) { return _helper.GetMonthsInYear(year, era); } public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return _helper.GetWeekOfYear(time, rule, firstDayOfWeek); } public override int GetEra(DateTime time) { return _helper.GetEra(time); } public override int GetMonth(DateTime time) { return _helper.GetMonth(time); } public override int GetYear(DateTime time) { return _helper.GetYear(time); } public override bool IsLeapDay(int year, int month, int day, int era) { return _helper.IsLeapDay(year, month, day, era); } public override bool IsLeapYear(int year, int era) { return _helper.IsLeapYear(year, era); } public override int GetLeapMonth(int year, int era) { return _helper.GetLeapMonth(year, era); } public override bool IsLeapMonth(int year, int month, int era) { return _helper.IsLeapMonth(year, month, era); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return _helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era); } public override int ToFourDigitYear(int year) { if (year <= 0) { throw new ArgumentOutOfRangeException("year", year, SR.ArgumentOutOfRange_NeedPosNum); } if (year > _helper.MaxYear) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 1, _helper.MaxYear)); } return year; } internal static string[] EraNames() { EraInfo[] eraInfo = GetEraInfo(); string[] array = new string[eraInfo.Length]; for (int i = 0; i < eraInfo.Length; i++) { array[i] = eraInfo[eraInfo.Length - i - 1].eraName; } return array; } internal static string[] AbbrevEraNames() { EraInfo[] eraInfo = GetEraInfo(); string[] array = new string[eraInfo.Length]; for (int i = 0; i < eraInfo.Length; i++) { array[i] = eraInfo[eraInfo.Length - i - 1].abbrevEraName; } return array; } internal static string[] EnglishEraNames() { EraInfo[] eraInfo = GetEraInfo(); string[] array = new string[eraInfo.Length]; for (int i = 0; i < eraInfo.Length; i++) { array[i] = eraInfo[eraInfo.Length - i - 1].englishEraName; } return array; } internal override bool IsValidYear(int year, int era) { return _helper.IsValidYear(year, era); } private static EraInfo[] IcuGetJapaneseEras() { if (GlobalizationMode.Invariant) { return null; } if (!CalendarData.EnumCalendarInfo("ja-JP", CalendarId.JAPAN, CalendarDataType.EraNames, out var calendarData)) { return null; } List list = new List(); int num = 9999; int latestJapaneseEra = Interop.Globalization.GetLatestJapaneseEra(); for (int num2 = latestJapaneseEra; num2 >= 0; num2--) { if (!GetJapaneseEraStartDate(num2, out var dateTime)) { return null; } if (dateTime < s_calendarMinValue) { break; } list.Add(new EraInfo(num2, dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Year - 1, 1, num - dateTime.Year + 1, calendarData[num2], GetAbbreviatedEraName(calendarData, num2), "")); num = dateTime.Year; } if (!CalendarData.EnumCalendarInfo("ja", CalendarId.JAPAN, CalendarDataType.AbbrevEraNames, out var calendarData2)) { calendarData2 = s_abbreviatedEnglishEraNames; } if (calendarData2[^1].Length == 0 || calendarData2[^1][0] > '\u007f') { calendarData2 = s_abbreviatedEnglishEraNames; } int num3 = ((calendarData2 == s_abbreviatedEnglishEraNames) ? (list.Count - 1) : (calendarData2.Length - 1)); for (int i = 0; i < list.Count; i++) { list[i].era = list.Count - i; if (num3 < calendarData2.Length) { list[i].englishEraName = calendarData2[num3]; } num3--; } return list.ToArray(); } private static string GetAbbreviatedEraName(string[] eraNames, int eraIndex) { return eraNames[eraIndex].Substring(0, 1); } private static bool GetJapaneseEraStartDate(int era, out DateTime dateTime) { dateTime = default(DateTime); int startYear; int startMonth; int startDay; bool japaneseEraStartDate = Interop.Globalization.GetJapaneseEraStartDate(era, out startYear, out startMonth, out startDay); if (japaneseEraStartDate) { dateTime = new DateTime(startYear, startMonth, startDay); } return japaneseEraStartDate; } private static EraInfo[] NlsGetJapaneseEras() { int num = 0; EraInfo[] array = null; try { using RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Control\\Nls\\Calendars\\Japanese\\Eras"); if (registryKey == null) { return null; } string[] valueNames = registryKey.GetValueNames(); if (valueNames != null && valueNames.Length != 0) { array = new EraInfo[valueNames.Length]; for (int i = 0; i < valueNames.Length; i++) { EraInfo eraFromValue = GetEraFromValue(valueNames[i], registryKey.GetValue(valueNames[i])?.ToString()); if (eraFromValue != null) { array[num] = eraFromValue; num++; } } } } catch (SecurityException) { return null; } catch (IOException) { return null; } catch (UnauthorizedAccessException) { return null; } if (num < 4) { return null; } Array.Resize(ref array, num); Array.Sort(array, CompareEraRanges); for (int j = 0; j < array.Length; j++) { array[j].era = array.Length - j; if (j == 0) { array[0].maxEraYear = 9999 - array[0].yearOffset; } else { array[j].maxEraYear = array[j - 1].yearOffset + 1 - array[j].yearOffset; } } return array; } private static int CompareEraRanges(EraInfo a, EraInfo b) { return b.ticks.CompareTo(a.ticks); } private static EraInfo GetEraFromValue(string value, string data) { if (value == null || data == null) { return null; } if (value.Length != 10) { return null; } ReadOnlySpan readOnlySpan = value.AsSpan(); if (!int.TryParse(readOnlySpan.Slice(0, 4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out var result) || !int.TryParse(readOnlySpan.Slice(5, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out var result2) || !int.TryParse(readOnlySpan.Slice(8, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out var result3)) { return null; } string[] array = data.Split('_'); if (array.Length != 4) { return null; } if (array[0].Length == 0 || array[1].Length == 0 || array[2].Length == 0 || array[3].Length == 0) { return null; } return new EraInfo(0, result, result2, result3, result - 1, 1, 0, array[0], array[1], array[3]); } } public class JapaneseLunisolarCalendar : EastAsianLunisolarCalendar { public const int JapaneseEra = 1; private readonly GregorianCalendarHelper _helper; private static readonly DateTime s_minDate = new DateTime(1960, 1, 28); private static readonly DateTime s_maxDate = new DateTime(new DateTime(2050, 1, 22, 23, 59, 59, 999).Ticks + 9999); private static readonly int[,] s_yinfo = new int[90, 4] { { 6, 1, 28, 44368 }, { 0, 2, 15, 43856 }, { 0, 2, 5, 19296 }, { 4, 1, 25, 42352 }, { 0, 2, 13, 42352 }, { 0, 2, 2, 21104 }, { 3, 1, 22, 26928 }, { 0, 2, 9, 55632 }, { 7, 1, 30, 27304 }, { 0, 2, 17, 22176 }, { 0, 2, 6, 39632 }, { 5, 1, 27, 19176 }, { 0, 2, 15, 19168 }, { 0, 2, 3, 42208 }, { 4, 1, 23, 53864 }, { 0, 2, 11, 53840 }, { 8, 1, 31, 54600 }, { 0, 2, 18, 46400 }, { 0, 2, 7, 54944 }, { 6, 1, 28, 38608 }, { 0, 2, 16, 38320 }, { 0, 2, 5, 18864 }, { 4, 1, 25, 42200 }, { 0, 2, 13, 42160 }, { 10, 2, 2, 45656 }, { 0, 2, 20, 27216 }, { 0, 2, 9, 27968 }, { 6, 1, 29, 46504 }, { 0, 2, 18, 11104 }, { 0, 2, 6, 38320 }, { 5, 1, 27, 18872 }, { 0, 2, 15, 18800 }, { 0, 2, 4, 25776 }, { 3, 1, 23, 27216 }, { 0, 2, 10, 59984 }, { 8, 1, 31, 27976 }, { 0, 2, 19, 23248 }, { 0, 2, 8, 11104 }, { 5, 1, 28, 37744 }, { 0, 2, 16, 37600 }, { 0, 2, 5, 51552 }, { 4, 1, 24, 58536 }, { 0, 2, 12, 54432 }, { 0, 2, 1, 55888 }, { 2, 1, 22, 23208 }, { 0, 2, 9, 22208 }, { 7, 1, 29, 43736 }, { 0, 2, 18, 9680 }, { 0, 2, 7, 37584 }, { 5, 1, 26, 51544 }, { 0, 2, 14, 43344 }, { 0, 2, 3, 46240 }, { 3, 1, 23, 47696 }, { 0, 2, 10, 46416 }, { 9, 1, 31, 21928 }, { 0, 2, 19, 19360 }, { 0, 2, 8, 42416 }, { 5, 1, 28, 21176 }, { 0, 2, 16, 21168 }, { 0, 2, 5, 43344 }, { 4, 1, 25, 46248 }, { 0, 2, 12, 27296 }, { 0, 2, 1, 44368 }, { 2, 1, 22, 21928 }, { 0, 2, 10, 19296 }, { 6, 1, 29, 42352 }, { 0, 2, 17, 42352 }, { 0, 2, 7, 21104 }, { 5, 1, 27, 26928 }, { 0, 2, 13, 55600 }, { 0, 2, 3, 23200 }, { 3, 1, 23, 43856 }, { 0, 2, 11, 38608 }, { 11, 1, 31, 19176 }, { 0, 2, 19, 19168 }, { 0, 2, 8, 42192 }, { 6, 1, 28, 53864 }, { 0, 2, 15, 53840 }, { 0, 2, 4, 54560 }, { 5, 1, 24, 55968 }, { 0, 2, 12, 46752 }, { 0, 2, 1, 38608 }, { 2, 1, 22, 19160 }, { 0, 2, 10, 18864 }, { 7, 1, 30, 42168 }, { 0, 2, 17, 42160 }, { 0, 2, 6, 45648 }, { 5, 1, 26, 46376 }, { 0, 2, 14, 27968 }, { 0, 2, 2, 44448 } }; public override DateTime MinSupportedDateTime => s_minDate; public override DateTime MaxSupportedDateTime => s_maxDate; protected override int DaysInYearBeforeMinSupportedYear => 354; internal override int MinCalendarYear => 1960; internal override int MaxCalendarYear => 2049; internal override DateTime MinDate => s_minDate; internal override DateTime MaxDate => s_maxDate; internal override EraInfo[]? CalEraInfo => JapaneseCalendar.GetEraInfo(); internal override CalendarId BaseCalendarID => CalendarId.JAPAN; internal override CalendarId ID => CalendarId.JAPANESELUNISOLAR; public override int[] Eras => _helper.Eras; internal override int GetYearInfo(int lunarYear, int index) { if (lunarYear < 1960 || lunarYear > 2049) { throw new ArgumentOutOfRangeException("year", lunarYear, SR.Format(SR.ArgumentOutOfRange_Range, 1960, 2049)); } return s_yinfo[lunarYear - 1960, index]; } internal override int GetYear(int year, DateTime time) { return _helper.GetYear(year, time); } internal override int GetGregorianYear(int year, int era) { return _helper.GetGregorianYear(year, era); } private static EraInfo[] TrimEras(EraInfo[] baseEras) { EraInfo[] array = new EraInfo[baseEras.Length]; int num = 0; for (int i = 0; i < baseEras.Length; i++) { if (baseEras[i].yearOffset + baseEras[i].minEraYear < 2049) { if (baseEras[i].yearOffset + baseEras[i].maxEraYear < 1960) { break; } array[num] = baseEras[i]; num++; } } if (num == 0) { return baseEras; } Array.Resize(ref array, num); return array; } public JapaneseLunisolarCalendar() { _helper = new GregorianCalendarHelper(this, TrimEras(JapaneseCalendar.GetEraInfo())); } public override int GetEra(DateTime time) { return _helper.GetEra(time); } } public class JulianCalendar : Calendar { public static readonly int JulianEra = 1; private static readonly int[] s_daysToMonth365 = new int[13] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; private static readonly int[] s_daysToMonth366 = new int[13] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; internal int MaxYear = 9999; public override DateTime MinSupportedDateTime => DateTime.MinValue; public override DateTime MaxSupportedDateTime => DateTime.MaxValue; public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.SolarCalendar; internal override CalendarId ID => CalendarId.JULIAN; public override int[] Eras => new int[1] { JulianEra }; public override int TwoDigitYearMax { get { return _twoDigitYearMax; } set { VerifyWritable(); if (value < 99 || value > MaxYear) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 99, MaxYear)); } _twoDigitYearMax = value; } } public JulianCalendar() { _twoDigitYearMax = 2029; } internal static void CheckEraRange(int era) { if (era != 0 && era != JulianEra) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } } internal void CheckYearEraRange(int year, int era) { CheckEraRange(era); if (year <= 0 || year > MaxYear) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxYear)); } } internal static void CheckMonthRange(int month) { if (month < 1 || month > 12) { ThrowHelper.ThrowArgumentOutOfRange_Month(month); } } internal static void CheckDayRange(int year, int month, int day) { if (year == 1 && month == 1 && day < 3) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } int[] array = ((year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365); int num = array[month] - array[month - 1]; if (day < 1 || day > num) { throw new ArgumentOutOfRangeException("day", day, SR.Format(SR.ArgumentOutOfRange_Range, 1, num)); } } internal static int GetDatePart(long ticks, int part) { long num = ticks + 1728000000000L; int num2 = (int)(num / 864000000000L); int num3 = num2 / 1461; num2 -= num3 * 1461; int num4 = num2 / 365; if (num4 == 4) { num4 = 3; } if (part == 0) { return num3 * 4 + num4 + 1; } num2 -= num4 * 365; if (part == 1) { return num2 + 1; } int[] array = ((num4 == 3) ? s_daysToMonth366 : s_daysToMonth365); int i; for (i = (num2 >> 5) + 1; num2 >= array[i]; i++) { } if (part == 2) { return i; } return num2 - array[i - 1] + 1; } internal static long DateToTicks(int year, int month, int day) { int[] array = ((year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365); int num = year - 1; int num2 = num * 365 + num / 4 + array[month - 1] + day - 1; return (num2 - 2) * 864000000000L; } public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException("months", months, SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000)); } int datePart = GetDatePart(time.Ticks, 0); int datePart2 = GetDatePart(time.Ticks, 2); int num = GetDatePart(time.Ticks, 3); int num2 = datePart2 - 1 + months; if (num2 >= 0) { datePart2 = num2 % 12 + 1; datePart += num2 / 12; } else { datePart2 = 12 + (num2 + 1) % 12; datePart += (num2 - 11) / 12; } int[] array = ((datePart % 4 == 0 && (datePart % 100 != 0 || datePart % 400 == 0)) ? s_daysToMonth366 : s_daysToMonth365); int num3 = array[datePart2] - array[datePart2 - 1]; if (num > num3) { num = num3; } long ticks = DateToTicks(datePart, datePart2, num) + time.Ticks % 864000000000L; Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return new DateTime(ticks); } public override DateTime AddYears(DateTime time, int years) { return AddMonths(time, years * 12); } public override int GetDayOfMonth(DateTime time) { return GetDatePart(time.Ticks, 3); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (DayOfWeek)((int)(time.Ticks / 864000000000L + 1) % 7); } public override int GetDayOfYear(DateTime time) { return GetDatePart(time.Ticks, 1); } public override int GetDaysInMonth(int year, int month, int era) { CheckYearEraRange(year, era); CheckMonthRange(month); int[] array = ((year % 4 == 0) ? s_daysToMonth366 : s_daysToMonth365); return array[month] - array[month - 1]; } public override int GetDaysInYear(int year, int era) { if (!IsLeapYear(year, era)) { return 365; } return 366; } public override int GetEra(DateTime time) { return JulianEra; } public override int GetMonth(DateTime time) { return GetDatePart(time.Ticks, 2); } public override int GetMonthsInYear(int year, int era) { CheckYearEraRange(year, era); return 12; } public override int GetYear(DateTime time) { return GetDatePart(time.Ticks, 0); } public override bool IsLeapDay(int year, int month, int day, int era) { CheckMonthRange(month); if (IsLeapYear(year, era)) { CheckDayRange(year, month, day); if (month == 2) { return day == 29; } return false; } CheckDayRange(year, month, day); return false; } public override int GetLeapMonth(int year, int era) { CheckYearEraRange(year, era); return 0; } public override bool IsLeapMonth(int year, int month, int era) { CheckYearEraRange(year, era); CheckMonthRange(month); return false; } public override bool IsLeapYear(int year, int era) { CheckYearEraRange(year, era); return year % 4 == 0; } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { CheckYearEraRange(year, era); CheckMonthRange(month); CheckDayRange(year, month, day); if (millisecond < 0 || millisecond >= 1000) { throw new ArgumentOutOfRangeException("millisecond", millisecond, SR.Format(SR.ArgumentOutOfRange_Range, 0, 999)); } if (hour < 0 || hour >= 24 || minute < 0 || minute >= 60 || second < 0 || second >= 60) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } return new DateTime(DateToTicks(year, month, day) + new TimeSpan(0, hour, minute, second, millisecond).Ticks); } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", year, SR.ArgumentOutOfRange_NeedNonNegNum); } if (year > MaxYear) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, MaxYear)); } return base.ToFourDigitYear(year); } } public class KoreanCalendar : Calendar { public const int KoreanEra = 1; private static readonly EraInfo[] s_koreanEraInfo = new EraInfo[1] { new EraInfo(1, 1, 1, 1, -2333, 2334, 12332) }; private readonly GregorianCalendarHelper _helper; public override DateTime MinSupportedDateTime => DateTime.MinValue; public override DateTime MaxSupportedDateTime => DateTime.MaxValue; public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.SolarCalendar; internal override CalendarId ID => CalendarId.KOREA; public override int[] Eras => _helper.Eras; public override int TwoDigitYearMax { get { if (_twoDigitYearMax == -1) { _twoDigitYearMax = Calendar.GetSystemTwoDigitYearSetting(ID, 4362); } return _twoDigitYearMax; } set { VerifyWritable(); if (value < 99 || value > _helper.MaxYear) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 99, _helper.MaxYear)); } _twoDigitYearMax = value; } } public KoreanCalendar() { try { new CultureInfo("ko-KR"); } catch (ArgumentException innerException) { throw new TypeInitializationException(GetType().ToString(), innerException); } _helper = new GregorianCalendarHelper(this, s_koreanEraInfo); } public override DateTime AddMonths(DateTime time, int months) { return _helper.AddMonths(time, months); } public override DateTime AddYears(DateTime time, int years) { return _helper.AddYears(time, years); } public override int GetDaysInMonth(int year, int month, int era) { return _helper.GetDaysInMonth(year, month, era); } public override int GetDaysInYear(int year, int era) { return _helper.GetDaysInYear(year, era); } public override int GetDayOfMonth(DateTime time) { return _helper.GetDayOfMonth(time); } public override DayOfWeek GetDayOfWeek(DateTime time) { return _helper.GetDayOfWeek(time); } public override int GetDayOfYear(DateTime time) { return _helper.GetDayOfYear(time); } public override int GetMonthsInYear(int year, int era) { return _helper.GetMonthsInYear(year, era); } public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return _helper.GetWeekOfYear(time, rule, firstDayOfWeek); } public override int GetEra(DateTime time) { return _helper.GetEra(time); } public override int GetMonth(DateTime time) { return _helper.GetMonth(time); } public override int GetYear(DateTime time) { return _helper.GetYear(time); } public override bool IsLeapDay(int year, int month, int day, int era) { return _helper.IsLeapDay(year, month, day, era); } public override bool IsLeapYear(int year, int era) { return _helper.IsLeapYear(year, era); } public override int GetLeapMonth(int year, int era) { return _helper.GetLeapMonth(year, era); } public override bool IsLeapMonth(int year, int month, int era) { return _helper.IsLeapMonth(year, month, era); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return _helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era); } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", year, SR.ArgumentOutOfRange_NeedNonNegNum); } return _helper.ToFourDigitYear(year, TwoDigitYearMax); } } public class KoreanLunisolarCalendar : EastAsianLunisolarCalendar { public const int GregorianEra = 1; private static readonly DateTime s_minDate = new DateTime(918, 2, 19); private static readonly DateTime s_maxDate = new DateTime(new DateTime(2051, 2, 10, 23, 59, 59, 999).Ticks + 9999); private static readonly int[,] s_yinfo = new int[1133, 4] { { 0, 2, 19, 21936 }, { 0, 2, 9, 17872 }, { 6, 1, 29, 41688 }, { 0, 2, 16, 41648 }, { 0, 2, 5, 43344 }, { 4, 1, 25, 46248 }, { 0, 2, 13, 27936 }, { 12, 2, 1, 44384 }, { 0, 2, 20, 43872 }, { 0, 2, 10, 21936 }, { 8, 1, 31, 17848 }, { 0, 2, 18, 17776 }, { 0, 2, 7, 21168 }, { 5, 1, 27, 26960 }, { 0, 2, 14, 59728 }, { 0, 2, 3, 27296 }, { 1, 1, 23, 44368 }, { 0, 2, 11, 43856 }, { 11, 2, 1, 21344 }, { 0, 2, 18, 51904 }, { 0, 2, 7, 58720 }, { 7, 1, 28, 53928 }, { 0, 2, 16, 53920 }, { 0, 2, 4, 55632 }, { 3, 1, 25, 23208 }, { 0, 2, 13, 22176 }, { 12, 2, 2, 42704 }, { 0, 2, 20, 38352 }, { 0, 2, 10, 19152 }, { 7, 1, 30, 42200 }, { 0, 2, 18, 42192 }, { 0, 2, 6, 45664 }, { 5, 1, 26, 46416 }, { 0, 2, 14, 45936 }, { 0, 1, 5, 43728 }, { 1, 1, 23, 38352 }, { 0, 2, 11, 38320 }, { 9, 2, 1, 19128 }, { 0, 2, 20, 18864 }, { 0, 2, 8, 42160 }, { 7, 1, 28, 43672 }, { 0, 2, 16, 27296 }, { 0, 2, 5, 44368 }, { 3, 1, 25, 19880 }, { 0, 2, 13, 11104 }, { 12, 2, 2, 38256 }, { 0, 2, 21, 41840 }, { 0, 2, 10, 20848 }, { 8, 1, 30, 25776 }, { 0, 2, 17, 54448 }, { 0, 2, 7, 23184 }, { 5, 1, 26, 27472 }, { 0, 2, 14, 22224 }, { 0, 2, 4, 10976 }, { 2, 1, 24, 37744 }, { 0, 2, 11, 41696 }, { 10, 1, 31, 51560 }, { 0, 2, 19, 43344 }, { 0, 2, 8, 54432 }, { 7, 1, 27, 55952 }, { 0, 2, 15, 46496 }, { 0, 2, 5, 22224 }, { 3, 1, 26, 10968 }, { 0, 2, 13, 9680 }, { 12, 2, 2, 37592 }, { 0, 2, 21, 37552 }, { 0, 2, 10, 43344 }, { 9, 1, 29, 46248 }, { 0, 2, 17, 44192 }, { 0, 2, 6, 44368 }, { 5, 1, 27, 21936 }, { 0, 2, 14, 19376 }, { 0, 2, 4, 9648 }, { 2, 1, 24, 37560 }, { 0, 2, 12, 21168 }, { 10, 1, 31, 26968 }, { 0, 2, 19, 22864 }, { 0, 2, 8, 27296 }, { 7, 1, 28, 43856 }, { 0, 2, 15, 43872 }, { 0, 2, 5, 19296 }, { 3, 1, 25, 42352 }, { 0, 2, 13, 9584 }, { 12, 2, 3, 21168 }, { 0, 2, 21, 53920 }, { 0, 2, 10, 54608 }, { 9, 1, 31, 23208 }, { 0, 2, 18, 22176 }, { 0, 2, 7, 38608 }, { 5, 1, 28, 19176 }, { 0, 2, 16, 19152 }, { 0, 2, 4, 42192 }, { 2, 1, 24, 53864 }, { 0, 2, 12, 45664 }, { 10, 2, 1, 46416 }, { 0, 2, 19, 44368 }, { 0, 2, 9, 13728 }, { 6, 1, 29, 38352 }, { 0, 2, 17, 38320 }, { 0, 2, 6, 18864 }, { 4, 1, 26, 42200 }, { 0, 2, 14, 42160 }, { 12, 2, 3, 43608 }, { 0, 2, 21, 27296 }, { 0, 2, 10, 44368 }, { 9, 1, 31, 11688 }, { 0, 2, 19, 11088 }, { 0, 2, 7, 38256 }, { 5, 1, 28, 18800 }, { 0, 2, 15, 51568 }, { 0, 2, 5, 25776 }, { 2, 1, 24, 27216 }, { 0, 2, 11, 55952 }, { 10, 2, 1, 27472 }, { 0, 2, 20, 26320 }, { 0, 2, 9, 9952 }, { 6, 1, 29, 37744 }, { 0, 2, 17, 37600 }, { 0, 2, 6, 51552 }, { 4, 1, 25, 54440 }, { 0, 2, 13, 54432 }, { 12, 2, 2, 54928 }, { 0, 2, 21, 46464 }, { 0, 2, 9, 54960 }, { 9, 1, 31, 9944 }, { 0, 2, 19, 9680 }, { 0, 2, 8, 37552 }, { 5, 1, 27, 43352 }, { 0, 2, 15, 43344 }, { 0, 2, 4, 46240 }, { 1, 1, 24, 46424 }, { 0, 2, 12, 11600 }, { 11, 2, 1, 21936 }, { 0, 2, 20, 19376 }, { 0, 2, 10, 9648 }, { 7, 1, 29, 21176 }, { 0, 2, 17, 21168 }, { 0, 2, 6, 26960 }, { 3, 1, 26, 27304 }, { 0, 2, 13, 27296 }, { 12, 2, 2, 43864 }, { 0, 2, 22, 10064 }, { 0, 2, 11, 19296 }, { 8, 1, 30, 42352 }, { 0, 2, 18, 42336 }, { 0, 2, 7, 53856 }, { 5, 1, 27, 59696 }, { 0, 2, 14, 54608 }, { 0, 2, 4, 23200 }, { 1, 1, 24, 43856 }, { 0, 2, 12, 38608 }, { 11, 2, 1, 19176 }, { 0, 2, 20, 18896 }, { 0, 2, 9, 42192 }, { 7, 1, 29, 53864 }, { 0, 2, 16, 43616 }, { 0, 2, 5, 46416 }, { 4, 1, 26, 22184 }, { 0, 2, 14, 13728 }, { 0, 2, 2, 38352 }, { 1, 1, 23, 19352 }, { 0, 2, 11, 17840 }, { 9, 1, 31, 42168 }, { 0, 2, 18, 25776 }, { 0, 2, 7, 43600 }, { 6, 1, 27, 46408 }, { 0, 2, 15, 27472 }, { 0, 2, 4, 11680 }, { 2, 1, 24, 38320 }, { 0, 2, 12, 37744 }, { 12, 2, 2, 18800 }, { 0, 2, 19, 51568 }, { 0, 2, 9, 25776 }, { 8, 1, 29, 27216 }, { 0, 2, 16, 55888 }, { 0, 2, 5, 23360 }, { 4, 1, 25, 43880 }, { 0, 2, 14, 10976 }, { 0, 2, 3, 58896 }, { 2, 1, 22, 51568 }, { 0, 2, 10, 51552 }, { 9, 1, 30, 54440 }, { 0, 2, 18, 21664 }, { 0, 2, 7, 54864 }, { 6, 1, 28, 23208 }, { 0, 2, 16, 21968 }, { 0, 2, 6, 9936 }, { 2, 1, 25, 37608 }, { 0, 2, 13, 37552 }, { 10, 2, 2, 43352 }, { 0, 2, 21, 43344 }, { 0, 2, 9, 46240 }, { 8, 1, 29, 46416 }, { 0, 2, 17, 44368 }, { 0, 2, 7, 21936 }, { 4, 1, 27, 9656 }, { 0, 2, 15, 17776 }, { 0, 2, 4, 21168 }, { 1, 1, 24, 43352 }, { 0, 2, 11, 26960 }, { 9, 1, 31, 29352 }, { 0, 2, 19, 23200 }, { 0, 2, 8, 43856 }, { 5, 1, 28, 19304 }, { 0, 2, 16, 19296 }, { 0, 2, 5, 42352 }, { 3, 1, 26, 21104 }, { 0, 2, 12, 53856 }, { 11, 2, 1, 59696 }, { 0, 2, 20, 54608 }, { 0, 2, 10, 23200 }, { 8, 1, 29, 39824 }, { 0, 2, 17, 38608 }, { 0, 2, 7, 19168 }, { 4, 1, 27, 42216 }, { 0, 2, 14, 42192 }, { 0, 2, 3, 53840 }, { 2, 1, 23, 55592 }, { 0, 2, 11, 46400 }, { 10, 1, 30, 54952 }, { 0, 2, 19, 11680 }, { 0, 2, 8, 38352 }, { 6, 1, 29, 19160 }, { 0, 2, 16, 18864 }, { 0, 2, 5, 42160 }, { 4, 1, 25, 45656 }, { 0, 2, 13, 27216 }, { 11, 2, 1, 46376 }, { 0, 2, 20, 27456 }, { 0, 2, 9, 43872 }, { 8, 1, 30, 38320 }, { 0, 2, 17, 39280 }, { 0, 2, 7, 18800 }, { 4, 1, 27, 25784 }, { 0, 2, 15, 21680 }, { 12, 2, 3, 27216 }, { 0, 2, 21, 55888 }, { 0, 2, 11, 23232 }, { 10, 1, 31, 43880 }, { 0, 2, 19, 9952 }, { 0, 2, 8, 37600 }, { 6, 1, 28, 51568 }, { 0, 2, 16, 51552 }, { 0, 2, 4, 54432 }, { 2, 1, 24, 55888 }, { 0, 2, 12, 54608 }, { 11, 2, 2, 22184 }, { 0, 2, 20, 21936 }, { 0, 2, 10, 9680 }, { 7, 1, 30, 37608 }, { 0, 2, 18, 37488 }, { 0, 2, 6, 43344 }, { 5, 1, 26, 54440 }, { 0, 2, 14, 46240 }, { 0, 2, 3, 46416 }, { 1, 1, 23, 22184 }, { 0, 2, 11, 19888 }, { 9, 2, 1, 9648 }, { 0, 2, 19, 42352 }, { 0, 2, 8, 21168 }, { 6, 1, 28, 43352 }, { 0, 2, 16, 26960 }, { 0, 2, 5, 27296 }, { 3, 1, 24, 44368 }, { 0, 2, 12, 43856 }, { 11, 2, 2, 19304 }, { 0, 2, 21, 19168 }, { 0, 2, 9, 42352 }, { 7, 1, 30, 21104 }, { 0, 2, 17, 53392 }, { 0, 1, 8, 29848 }, { 5, 1, 26, 27304 }, { 0, 2, 14, 23200 }, { 0, 2, 3, 39760 }, { 2, 1, 24, 19304 }, { 0, 2, 11, 19168 }, { 10, 1, 31, 42216 }, { 0, 2, 19, 42192 }, { 0, 2, 8, 53856 }, { 6, 1, 27, 54568 }, { 0, 2, 15, 46368 }, { 0, 2, 4, 54944 }, { 2, 1, 25, 22224 }, { 0, 2, 12, 38352 }, { 12, 2, 2, 18904 }, { 0, 2, 21, 18864 }, { 0, 2, 10, 42160 }, { 8, 1, 29, 43608 }, { 0, 2, 17, 27216 }, { 0, 2, 6, 46400 }, { 4, 1, 26, 46496 }, { 0, 2, 13, 43872 }, { 0, 2, 3, 38320 }, { 2, 1, 24, 18872 }, { 0, 2, 12, 18800 }, { 9, 1, 31, 25784 }, { 0, 2, 19, 21680 }, { 0, 2, 8, 27216 }, { 7, 1, 28, 27944 }, { 0, 2, 15, 23232 }, { 0, 2, 4, 43872 }, { 3, 1, 25, 37744 }, { 0, 2, 13, 37600 }, { 12, 2, 1, 51568 }, { 0, 2, 20, 51552 }, { 0, 2, 9, 54432 }, { 8, 1, 29, 55888 }, { 0, 2, 16, 46416 }, { 0, 2, 6, 22176 }, { 5, 1, 26, 43736 }, { 0, 2, 15, 9680 }, { 0, 2, 3, 37600 }, { 2, 1, 23, 51544 }, { 0, 2, 11, 43344 }, { 9, 1, 31, 54440 }, { 0, 2, 18, 45728 }, { 0, 2, 7, 46416 }, { 7, 1, 28, 22184 }, { 0, 2, 16, 19872 }, { 0, 2, 4, 42416 }, { 4, 1, 25, 21176 }, { 0, 2, 13, 21168 }, { 12, 2, 2, 43320 }, { 0, 2, 20, 26928 }, { 0, 2, 9, 27296 }, { 8, 1, 29, 44368 }, { 0, 2, 17, 44624 }, { 0, 2, 6, 19296 }, { 4, 1, 26, 42352 }, { 0, 2, 14, 42352 }, { 0, 2, 4, 21104 }, { 2, 1, 23, 26928 }, { 0, 2, 10, 58672 }, { 10, 1, 31, 27800 }, { 0, 2, 19, 23200 }, { 0, 2, 7, 23248 }, { 6, 1, 28, 19304 }, { 0, 2, 16, 19168 }, { 0, 2, 5, 42208 }, { 4, 1, 24, 53864 }, { 0, 2, 12, 53856 }, { 11, 2, 1, 54568 }, { 0, 2, 20, 46368 }, { 0, 2, 8, 46752 }, { 9, 1, 29, 22224 }, { 0, 2, 17, 21872 }, { 0, 2, 7, 18896 }, { 5, 1, 26, 42200 }, { 0, 2, 14, 42160 }, { 0, 2, 3, 43600 }, { 1, 1, 23, 46376 }, { 0, 2, 10, 46368 }, { 11, 1, 30, 46528 }, { 0, 2, 18, 43872 }, { 0, 2, 8, 38320 }, { 6, 1, 28, 18872 }, { 0, 2, 16, 18800 }, { 0, 2, 5, 25776 }, { 3, 1, 25, 27224 }, { 0, 2, 12, 27216 }, { 11, 2, 1, 27432 }, { 0, 2, 20, 23232 }, { 0, 2, 9, 43872 }, { 8, 1, 29, 10984 }, { 0, 2, 17, 18912 }, { 0, 2, 6, 42192 }, { 5, 1, 26, 53848 }, { 0, 2, 13, 45648 }, { 0, 2, 2, 46368 }, { 2, 1, 22, 62096 }, { 0, 2, 10, 46496 }, { 10, 1, 30, 38352 }, { 0, 2, 18, 38320 }, { 0, 2, 8, 18864 }, { 6, 1, 28, 42168 }, { 0, 2, 15, 42160 }, { 0, 2, 4, 43600 }, { 4, 1, 24, 46376 }, { 0, 2, 12, 27968 }, { 12, 1, 31, 44384 }, { 0, 2, 19, 43872 }, { 0, 2, 9, 37744 }, { 8, 1, 30, 2424 }, { 0, 2, 18, 18800 }, { 0, 2, 7, 25776 }, { 5, 1, 27, 27216 }, { 0, 2, 14, 55888 }, { 0, 2, 3, 23200 }, { 1, 1, 23, 43872 }, { 0, 2, 11, 42720 }, { 11, 2, 1, 37608 }, { 0, 2, 19, 37600 }, { 0, 2, 8, 51552 }, { 7, 1, 28, 54440 }, { 0, 2, 16, 54432 }, { 0, 2, 4, 54608 }, { 3, 1, 25, 23208 }, { 0, 2, 13, 22176 }, { 0, 2, 2, 42704 }, { 1, 1, 22, 37608 }, { 0, 2, 10, 37552 }, { 8, 1, 30, 42328 }, { 0, 2, 18, 43344 }, { 0, 2, 6, 45728 }, { 5, 1, 26, 46416 }, { 0, 2, 14, 44368 }, { 0, 2, 4, 19872 }, { 1, 1, 23, 42448 }, { 0, 2, 11, 42352 }, { 9, 2, 1, 21176 }, { 0, 2, 20, 21104 }, { 0, 2, 8, 26928 }, { 7, 1, 28, 27288 }, { 0, 2, 16, 27296 }, { 0, 2, 5, 43856 }, { 3, 1, 25, 19368 }, { 0, 2, 13, 19296 }, { 12, 2, 2, 42608 }, { 0, 2, 21, 41696 }, { 0, 2, 9, 53600 }, { 8, 1, 29, 59696 }, { 0, 2, 17, 54432 }, { 0, 2, 6, 55968 }, { 5, 1, 26, 23376 }, { 0, 2, 14, 22224 }, { 0, 2, 4, 19168 }, { 2, 1, 24, 41704 }, { 0, 2, 11, 41680 }, { 10, 1, 31, 53592 }, { 0, 2, 19, 43600 }, { 0, 2, 8, 46368 }, { 7, 1, 27, 54944 }, { 0, 2, 15, 44448 }, { 0, 2, 5, 21968 }, { 3, 1, 26, 18904 }, { 0, 2, 13, 17840 }, { 0, 2, 2, 41648 }, { 1, 1, 22, 53592 }, { 0, 2, 10, 43600 }, { 9, 1, 29, 46376 }, { 0, 2, 17, 27424 }, { 0, 2, 6, 44384 }, { 5, 1, 27, 21936 }, { 0, 2, 14, 37744 }, { 0, 2, 4, 17776 }, { 3, 1, 24, 41656 }, { 0, 2, 12, 21168 }, { 10, 1, 31, 43600 }, { 0, 2, 18, 55632 }, { 0, 2, 8, 23200 }, { 7, 1, 28, 43872 }, { 0, 2, 15, 42720 }, { 0, 2, 5, 21216 }, { 3, 1, 25, 50544 }, { 0, 2, 13, 42336 }, { 11, 2, 1, 53928 }, { 0, 2, 20, 53920 }, { 0, 2, 9, 54608 }, { 9, 1, 30, 23208 }, { 0, 2, 17, 22176 }, { 0, 2, 6, 42704 }, { 5, 1, 27, 21224 }, { 0, 2, 15, 21168 }, { 0, 2, 3, 43216 }, { 2, 1, 23, 53928 }, { 0, 2, 11, 45728 }, { 10, 1, 31, 46416 }, { 0, 2, 18, 44368 }, { 0, 2, 8, 19872 }, { 6, 1, 28, 42448 }, { 0, 2, 16, 42352 }, { 0, 2, 5, 20912 }, { 4, 1, 25, 43192 }, { 0, 2, 13, 25904 }, { 12, 2, 2, 27288 }, { 0, 2, 20, 23200 }, { 0, 2, 9, 43856 }, { 9, 1, 30, 11176 }, { 0, 2, 18, 11104 }, { 0, 2, 6, 50032 }, { 5, 1, 27, 20848 }, { 0, 2, 14, 51552 }, { 0, 2, 3, 58544 }, { 3, 1, 24, 27280 }, { 0, 2, 11, 55968 }, { 11, 2, 1, 23376 }, { 0, 2, 20, 22224 }, { 0, 2, 9, 10976 }, { 7, 1, 29, 41704 }, { 0, 2, 17, 41680 }, { 0, 2, 6, 53584 }, { 4, 1, 25, 54440 }, { 0, 2, 13, 46368 }, { 12, 2, 2, 46736 }, { 0, 2, 21, 44448 }, { 0, 2, 10, 21968 }, { 9, 1, 31, 9688 }, { 0, 2, 19, 17840 }, { 0, 2, 8, 41648 }, { 5, 1, 27, 43352 }, { 0, 2, 15, 43344 }, { 0, 2, 4, 46368 }, { 1, 1, 24, 46416 }, { 0, 2, 11, 43872 }, { 12, 2, 1, 21936 }, { 0, 2, 20, 19312 }, { 0, 2, 10, 17776 }, { 7, 1, 29, 21176 }, { 0, 2, 17, 21168 }, { 0, 2, 6, 26960 }, { 4, 1, 26, 27816 }, { 0, 2, 13, 23200 }, { 12, 2, 2, 39760 }, { 0, 2, 21, 42720 }, { 0, 2, 11, 19168 }, { 8, 1, 30, 42352 }, { 0, 2, 18, 42336 }, { 0, 2, 7, 53920 }, { 6, 1, 27, 59728 }, { 0, 2, 14, 54608 }, { 0, 2, 4, 22176 }, { 2, 1, 24, 43728 }, { 0, 2, 12, 38368 }, { 11, 2, 1, 19176 }, { 0, 2, 20, 18864 }, { 0, 2, 9, 42192 }, { 7, 1, 29, 53872 }, { 0, 2, 16, 45728 }, { 0, 2, 5, 46416 }, { 4, 1, 26, 22184 }, { 0, 2, 14, 11680 }, { 0, 2, 2, 38320 }, { 1, 1, 23, 19128 }, { 0, 2, 11, 18864 }, { 9, 1, 31, 42168 }, { 0, 2, 18, 25776 }, { 0, 2, 7, 27280 }, { 6, 1, 27, 44368 }, { 0, 2, 15, 27472 }, { 0, 2, 4, 11104 }, { 2, 1, 24, 38256 }, { 0, 2, 12, 37744 }, { 11, 2, 2, 18800 }, { 0, 2, 19, 51552 }, { 0, 2, 8, 58544 }, { 7, 1, 29, 27280 }, { 0, 2, 16, 55968 }, { 0, 2, 5, 23248 }, { 3, 1, 26, 11112 }, { 0, 2, 14, 9952 }, { 0, 2, 3, 37600 }, { 2, 1, 22, 51560 }, { 0, 2, 10, 51536 }, { 9, 1, 30, 54440 }, { 0, 2, 18, 46240 }, { 0, 2, 6, 46736 }, { 6, 1, 27, 22224 }, { 0, 2, 15, 21936 }, { 0, 2, 5, 9680 }, { 2, 1, 24, 37592 }, { 0, 2, 12, 37552 }, { 10, 2, 1, 43352 }, { 0, 2, 20, 26960 }, { 0, 2, 8, 29856 }, { 8, 1, 28, 46416 }, { 0, 2, 16, 43872 }, { 0, 2, 6, 21424 }, { 4, 1, 26, 9656 }, { 0, 2, 14, 9584 }, { 0, 2, 3, 21168 }, { 1, 1, 23, 43352 }, { 0, 2, 10, 26960 }, { 9, 1, 30, 27304 }, { 0, 2, 18, 23200 }, { 0, 2, 7, 43856 }, { 5, 1, 27, 19304 }, { 0, 2, 15, 19168 }, { 0, 2, 4, 42352 }, { 3, 1, 25, 21104 }, { 0, 2, 11, 53920 }, { 11, 1, 31, 55632 }, { 0, 2, 19, 46416 }, { 0, 2, 9, 22176 }, { 7, 1, 29, 38608 }, { 0, 2, 17, 38352 }, { 0, 2, 7, 19168 }, { 4, 1, 27, 42200 }, { 0, 2, 14, 42192 }, { 0, 2, 3, 53840 }, { 1, 1, 23, 54608 }, { 0, 2, 11, 46416 }, { 9, 1, 31, 22184 }, { 0, 2, 19, 11680 }, { 0, 2, 8, 38320 }, { 5, 1, 29, 18872 }, { 0, 2, 16, 18800 }, { 0, 2, 5, 42160 }, { 4, 1, 25, 45656 }, { 0, 2, 13, 27280 }, { 12, 2, 1, 44368 }, { 0, 2, 20, 23376 }, { 0, 2, 10, 11104 }, { 8, 1, 30, 38256 }, { 0, 2, 17, 37616 }, { 0, 2, 7, 18800 }, { 4, 1, 27, 25776 }, { 0, 2, 14, 54432 }, { 12, 2, 2, 59984 }, { 0, 2, 21, 54928 }, { 0, 2, 11, 22224 }, { 10, 2, 1, 11112 }, { 0, 2, 19, 9952 }, { 0, 2, 8, 21216 }, { 6, 1, 28, 51560 }, { 0, 2, 16, 51536 }, { 0, 2, 4, 54432 }, { 2, 1, 24, 55888 }, { 0, 2, 12, 46480 }, { 12, 2, 2, 22224 }, { 0, 2, 20, 21936 }, { 0, 2, 10, 9680 }, { 7, 1, 30, 37592 }, { 0, 2, 18, 37552 }, { 0, 2, 6, 43344 }, { 5, 1, 26, 46248 }, { 0, 2, 14, 27808 }, { 0, 2, 3, 44368 }, { 1, 1, 23, 21936 }, { 0, 2, 11, 19376 }, { 9, 2, 1, 9656 }, { 0, 2, 20, 9584 }, { 0, 2, 8, 21168 }, { 6, 1, 28, 43344 }, { 0, 2, 15, 59728 }, { 0, 2, 5, 27296 }, { 3, 1, 24, 44368 }, { 0, 2, 12, 43856 }, { 11, 2, 2, 19304 }, { 0, 2, 21, 19168 }, { 0, 2, 9, 42352 }, { 7, 1, 30, 21096 }, { 0, 2, 17, 53856 }, { 0, 2, 6, 55632 }, { 5, 1, 26, 23208 }, { 0, 2, 14, 22176 }, { 0, 2, 3, 38608 }, { 2, 1, 24, 19176 }, { 0, 2, 11, 19168 }, { 10, 1, 31, 42200 }, { 0, 2, 19, 42192 }, { 0, 2, 8, 53840 }, { 6, 1, 27, 54600 }, { 0, 2, 15, 46416 }, { 0, 2, 5, 13728 }, { 2, 1, 25, 38352 }, { 0, 2, 12, 38320 }, { 12, 2, 2, 18872 }, { 0, 2, 21, 18800 }, { 0, 2, 10, 42160 }, { 8, 1, 29, 45656 }, { 0, 2, 17, 27216 }, { 0, 2, 6, 27968 }, { 4, 1, 26, 44456 }, { 0, 2, 14, 11104 }, { 0, 2, 3, 37744 }, { 2, 1, 24, 18808 }, { 0, 2, 12, 18800 }, { 9, 1, 31, 25776 }, { 0, 2, 18, 54432 }, { 0, 2, 7, 59984 }, { 6, 1, 28, 27464 }, { 0, 2, 15, 22224 }, { 0, 2, 5, 11104 }, { 3, 1, 25, 37616 }, { 0, 2, 13, 37600 }, { 11, 2, 1, 51560 }, { 0, 2, 20, 43344 }, { 0, 2, 9, 54432 }, { 8, 1, 29, 55888 }, { 0, 2, 16, 46288 }, { 0, 2, 6, 22192 }, { 4, 1, 27, 9944 }, { 0, 2, 15, 9680 }, { 0, 2, 3, 37584 }, { 2, 1, 23, 51608 }, { 0, 2, 11, 43344 }, { 9, 1, 31, 46248 }, { 0, 2, 18, 27296 }, { 0, 2, 7, 44368 }, { 6, 1, 28, 21928 }, { 0, 2, 16, 19376 }, { 0, 2, 5, 9648 }, { 3, 1, 25, 21176 }, { 0, 2, 13, 21168 }, { 11, 2, 2, 43344 }, { 0, 2, 19, 59728 }, { 0, 2, 9, 27296 }, { 8, 1, 29, 44368 }, { 0, 2, 17, 39760 }, { 0, 2, 6, 19296 }, { 4, 1, 26, 42352 }, { 0, 2, 14, 42224 }, { 0, 2, 4, 21088 }, { 2, 1, 22, 59696 }, { 0, 2, 10, 54608 }, { 10, 1, 31, 23208 }, { 0, 2, 19, 22176 }, { 0, 2, 7, 38608 }, { 6, 1, 28, 19176 }, { 0, 2, 16, 18912 }, { 0, 2, 5, 42192 }, { 4, 1, 24, 53864 }, { 0, 2, 12, 53840 }, { 11, 2, 1, 54568 }, { 0, 2, 20, 46400 }, { 0, 2, 8, 46496 }, { 8, 1, 29, 38352 }, { 0, 2, 17, 38320 }, { 0, 2, 7, 18864 }, { 4, 1, 26, 42168 }, { 0, 2, 14, 42160 }, { 0, 2, 3, 43600 }, { 1, 1, 23, 46376 }, { 0, 2, 10, 27968 }, { 11, 1, 30, 44456 }, { 0, 2, 19, 11104 }, { 0, 2, 8, 37744 }, { 6, 1, 28, 18808 }, { 0, 2, 16, 18800 }, { 0, 2, 5, 25776 }, { 3, 1, 25, 27216 }, { 0, 2, 11, 55888 }, { 11, 2, 1, 27464 }, { 0, 2, 20, 22224 }, { 0, 2, 10, 11168 }, { 7, 1, 29, 37616 }, { 0, 2, 17, 37600 }, { 0, 2, 6, 51552 }, { 5, 1, 26, 54440 }, { 0, 2, 13, 54432 }, { 0, 2, 2, 55888 }, { 3, 1, 23, 23208 }, { 0, 2, 11, 22176 }, { 7, 1, 30, 42704 }, { 0, 2, 18, 42448 }, { 0, 2, 8, 37584 }, { 6, 1, 28, 43352 }, { 0, 2, 15, 43344 }, { 0, 2, 4, 46240 }, { 4, 1, 24, 46416 }, { 0, 2, 12, 44368 }, { 0, 2, 1, 21920 }, { 2, 1, 21, 42448 }, { 0, 2, 9, 42416 }, { 7, 1, 30, 21176 }, { 0, 2, 17, 21168 }, { 0, 2, 6, 26928 }, { 5, 1, 26, 29864 }, { 0, 2, 14, 27296 }, { 0, 2, 2, 44432 }, { 3, 1, 23, 19880 }, { 0, 2, 11, 19296 }, { 8, 1, 31, 42352 }, { 0, 2, 18, 42208 }, { 0, 2, 7, 53856 }, { 6, 1, 27, 59696 }, { 0, 2, 15, 54560 }, { 0, 2, 3, 55968 }, { 4, 1, 24, 27472 }, { 0, 2, 12, 22224 }, { 0, 2, 2, 19168 }, { 3, 1, 21, 42216 }, { 0, 2, 9, 42192 }, { 7, 1, 29, 53848 }, { 0, 2, 17, 45648 }, { 0, 2, 5, 54560 }, { 5, 1, 25, 54944 }, { 0, 2, 13, 46496 }, { 0, 2, 3, 21968 }, { 3, 1, 23, 19160 }, { 0, 2, 11, 18896 }, { 7, 1, 31, 42168 }, { 0, 2, 19, 42160 }, { 0, 2, 8, 43600 }, { 6, 1, 28, 46376 }, { 0, 2, 16, 27936 }, { 0, 2, 5, 44448 }, { 4, 1, 25, 21936 }, { 0, 2, 13, 37744 }, { 0, 2, 3, 18800 }, { 3, 1, 23, 25784 }, { 0, 2, 10, 42192 }, { 7, 1, 30, 27216 }, { 0, 2, 17, 55888 }, { 0, 2, 7, 23200 }, { 5, 1, 26, 43872 }, { 0, 2, 14, 43744 }, { 0, 2, 4, 37600 }, { 3, 1, 24, 51568 }, { 0, 2, 11, 51552 }, { 8, 1, 31, 54440 }, { 0, 2, 19, 54432 }, { 0, 2, 8, 54608 }, { 6, 1, 28, 23208 }, { 0, 2, 16, 22176 }, { 0, 2, 5, 42704 }, { 4, 1, 26, 21224 }, { 0, 2, 13, 21200 }, { 0, 2, 2, 43344 }, { 3, 1, 22, 58536 }, { 0, 2, 10, 46240 }, { 7, 1, 29, 46416 }, { 0, 2, 17, 40272 }, { 0, 2, 7, 21920 }, { 5, 1, 27, 42448 }, { 0, 2, 14, 42416 }, { 0, 2, 4, 21168 }, { 4, 1, 24, 43192 }, { 0, 2, 12, 26928 }, { 9, 1, 31, 27288 }, { 0, 2, 19, 27296 }, { 0, 2, 8, 43856 }, { 6, 1, 29, 19880 }, { 0, 2, 16, 19296 }, { 0, 2, 5, 42352 }, { 4, 1, 26, 20848 }, { 0, 2, 13, 53600 }, { 0, 2, 1, 59696 }, { 3, 1, 22, 27280 }, { 0, 2, 9, 55968 }, { 7, 1, 30, 23376 }, { 0, 2, 17, 22224 }, { 0, 2, 7, 19168 }, { 5, 1, 27, 42200 }, { 0, 2, 15, 41680 }, { 0, 2, 3, 53584 }, { 4, 1, 23, 54568 }, { 0, 2, 11, 46368 }, { 9, 1, 31, 54928 }, { 0, 2, 18, 44448 }, { 0, 2, 8, 21968 }, { 6, 1, 29, 10968 }, { 0, 2, 17, 17840 }, { 0, 2, 5, 41648 }, { 5, 1, 25, 45400 }, { 0, 2, 13, 43344 }, { 0, 2, 2, 46368 }, { 2, 1, 21, 46480 }, { 0, 2, 9, 44384 }, { 7, 1, 30, 21936 }, { 0, 2, 18, 21360 }, { 0, 2, 7, 17776 }, { 5, 1, 27, 25272 }, { 0, 2, 15, 21168 }, { 0, 2, 4, 26960 }, { 3, 1, 23, 27816 }, { 0, 2, 11, 23200 }, { 10, 1, 31, 43856 }, { 0, 2, 19, 42704 }, { 0, 2, 8, 19168 }, { 6, 1, 28, 38256 }, { 0, 2, 16, 42336 }, { 0, 2, 5, 53920 }, { 5, 1, 24, 59728 }, { 0, 2, 12, 54608 }, { 0, 2, 2, 23200 }, { 3, 1, 22, 43856 }, { 0, 2, 9, 42704 }, { 7, 1, 30, 19176 }, { 0, 2, 18, 19120 }, { 0, 2, 7, 43216 }, { 5, 1, 26, 53928 }, { 0, 2, 14, 45728 }, { 0, 2, 3, 46416 }, { 4, 1, 24, 22184 }, { 0, 2, 11, 19872 }, { 0, 1, 31, 38352 }, { 2, 1, 21, 19128 }, { 0, 2, 9, 18864 }, { 6, 1, 28, 43192 }, { 0, 2, 16, 25776 }, { 0, 2, 5, 27280 }, { 4, 1, 25, 46416 }, { 0, 2, 13, 27472 }, { 0, 2, 3, 11168 }, { 2, 1, 23, 38320 }, { 0, 2, 11, 37744 }, { 6, 1, 31, 20848 }, { 0, 2, 18, 53600 }, { 0, 2, 7, 58544 }, { 5, 1, 28, 27280 }, { 0, 2, 14, 55952 }, { 0, 2, 4, 23376 }, { 3, 1, 25, 11112 }, { 0, 2, 13, 10976 }, { 0, 2, 1, 41696 }, { 2, 1, 21, 53608 }, { 0, 2, 9, 51536 }, { 6, 1, 29, 54440 }, { 0, 2, 16, 46368 }, { 0, 2, 5, 46736 }, { 4, 1, 26, 22224 }, { 0, 2, 14, 21968 }, { 0, 2, 3, 9680 }, { 3, 1, 23, 41688 }, { 0, 2, 11, 41648 }, { 7, 1, 31, 43352 }, { 0, 2, 18, 43344 }, { 0, 2, 7, 46240 }, { 5, 1, 27, 46416 }, { 0, 2, 15, 44368 }, { 0, 2, 4, 21936 }, { 4, 1, 25, 9656 }, { 0, 2, 13, 9584 }, { 9, 2, 2, 21176 }, { 0, 2, 20, 21168 }, { 0, 2, 9, 26960 }, { 6, 1, 29, 27816 }, { 0, 2, 17, 23200 }, { 0, 2, 5, 43856 }, { 4, 1, 26, 21352 }, { 0, 2, 14, 19168 }, { 0, 2, 3, 42352 }, { 3, 1, 23, 21168 }, { 0, 2, 10, 53920 }, { 7, 1, 30, 59728 }, { 0, 2, 18, 54608 }, { 0, 2, 7, 23200 }, { 5, 1, 27, 43728 }, { 0, 2, 15, 38352 }, { 0, 2, 5, 19168 }, { 4, 1, 24, 42328 }, { 0, 2, 12, 42192 }, { 8, 2, 1, 53848 }, { 0, 2, 20, 45712 }, { 0, 2, 8, 46416 }, { 7, 1, 29, 22184 }, { 0, 2, 17, 11680 }, { 0, 2, 6, 38352 }, { 5, 1, 26, 19128 }, { 0, 2, 14, 18864 }, { 0, 2, 3, 42160 }, { 3, 1, 23, 45656 }, { 0, 2, 10, 27280 }, { 8, 1, 30, 44360 }, { 0, 2, 18, 27472 }, { 0, 2, 8, 11104 }, { 5, 1, 27, 38320 }, { 0, 2, 15, 37744 }, { 0, 2, 5, 18800 }, { 4, 1, 25, 25776 }, { 0, 2, 11, 58528 }, { 10, 1, 31, 59984 }, { 0, 2, 19, 55952 }, { 0, 2, 9, 23248 }, { 6, 1, 29, 11112 }, { 0, 2, 17, 10976 }, { 0, 2, 6, 37600 }, { 5, 1, 26, 51560 }, { 0, 2, 13, 51536 }, { 0, 2, 2, 54432 }, { 3, 1, 22, 55888 }, { 0, 2, 10, 46736 }, { 7, 1, 30, 22224 }, { 0, 2, 18, 21936 }, { 0, 2, 8, 9680 }, { 5, 1, 28, 37592 }, { 0, 2, 15, 37552 }, { 0, 2, 4, 43344 }, { 4, 1, 24, 54440 }, { 0, 2, 12, 46240 }, { 0, 1, 31, 46416 }, { 2, 1, 21, 22184 }, { 0, 2, 9, 21936 }, { 6, 1, 30, 9656 }, { 0, 2, 17, 9584 }, { 0, 2, 6, 21168 }, { 5, 1, 26, 43344 }, { 0, 2, 13, 59728 }, { 0, 2, 2, 27296 }, { 3, 1, 22, 44368 }, { 0, 2, 10, 43856 }, { 8, 1, 31, 19304 }, { 0, 2, 19, 19168 }, { 0, 2, 8, 42352 }, { 5, 1, 29, 21096 }, { 0, 2, 16, 53856 }, { 0, 2, 4, 55632 }, { 4, 1, 25, 27304 }, { 0, 2, 13, 22176 }, { 0, 2, 2, 39632 }, { 2, 1, 22, 19176 }, { 0, 2, 10, 19168 }, { 6, 1, 30, 42200 }, { 0, 2, 18, 42192 }, { 0, 2, 6, 53840 }, { 5, 1, 26, 55624 }, { 0, 2, 14, 46416 }, { 0, 2, 4, 22176 }, { 2, 1, 23, 38608 }, { 0, 2, 11, 38352 }, { 7, 2, 1, 19160 }, { 0, 2, 20, 18864 }, { 0, 2, 8, 42160 }, { 5, 1, 28, 45656 }, { 0, 2, 16, 27280 }, { 0, 2, 5, 44352 }, { 4, 1, 24, 46504 }, { 0, 2, 13, 11104 }, { 0, 2, 2, 38320 }, { 2, 1, 23, 18872 }, { 0, 2, 10, 18800 }, { 6, 1, 30, 25776 }, { 0, 2, 17, 58528 }, { 0, 2, 6, 59984 }, { 5, 1, 26, 27976 }, { 0, 2, 14, 23376 }, { 0, 2, 4, 11104 }, { 3, 1, 24, 38256 }, { 0, 2, 11, 37600 }, { 7, 1, 31, 51560 }, { 0, 2, 19, 51536 }, { 0, 2, 8, 54432 }, { 6, 1, 27, 55888 }, { 0, 2, 15, 46736 }, { 0, 2, 5, 22224 }, { 4, 1, 26, 10968 }, { 0, 2, 13, 9680 }, { 0, 2, 2, 37584 }, { 2, 1, 22, 51544 }, { 0, 2, 10, 43344 }, { 7, 1, 29, 54440 }, { 0, 2, 17, 46240 }, { 0, 2, 6, 46416 }, { 5, 1, 27, 22184 }, { 0, 2, 14, 19888 }, { 0, 2, 4, 9648 }, { 3, 1, 24, 37560 }, { 0, 2, 12, 21168 }, { 8, 1, 31, 43352 }, { 0, 2, 19, 26960 }, { 0, 2, 8, 27296 }, { 6, 1, 28, 44368 }, { 0, 2, 15, 43856 }, { 0, 2, 5, 19296 }, { 4, 1, 25, 42352 }, { 0, 2, 13, 42352 }, { 0, 2, 2, 21104 }, { 3, 1, 22, 26928 }, { 0, 2, 9, 55632 }, { 7, 1, 30, 27304 }, { 0, 2, 17, 22176 }, { 0, 2, 6, 39632 }, { 5, 1, 27, 19176 }, { 0, 2, 15, 19168 }, { 0, 2, 3, 42208 }, { 4, 1, 23, 53864 }, { 0, 2, 11, 53840 }, { 8, 1, 31, 54600 }, { 0, 2, 18, 46400 }, { 0, 2, 7, 54944 }, { 6, 1, 28, 38608 }, { 0, 2, 16, 38320 }, { 0, 2, 5, 18864 }, { 4, 1, 25, 42200 }, { 0, 2, 13, 42160 }, { 10, 2, 2, 45656 }, { 0, 2, 20, 27216 }, { 0, 2, 9, 27968 }, { 6, 1, 29, 46504 }, { 0, 2, 18, 11104 }, { 0, 2, 6, 38320 }, { 5, 1, 27, 18872 }, { 0, 2, 15, 18800 }, { 0, 2, 4, 25776 }, { 3, 1, 23, 27216 }, { 0, 2, 10, 59984 }, { 8, 1, 31, 27976 }, { 0, 2, 19, 23248 }, { 0, 2, 8, 11104 }, { 5, 1, 28, 37744 }, { 0, 2, 16, 37600 }, { 0, 2, 5, 51552 }, { 4, 1, 24, 58536 }, { 0, 2, 12, 54432 }, { 0, 2, 1, 55888 }, { 2, 1, 22, 23208 }, { 0, 2, 9, 22208 }, { 7, 1, 29, 43736 }, { 0, 2, 18, 9680 }, { 0, 2, 7, 37584 }, { 5, 1, 26, 51544 }, { 0, 2, 14, 43344 }, { 0, 2, 3, 46240 }, { 3, 1, 23, 47696 }, { 0, 2, 10, 46416 }, { 9, 1, 31, 21928 }, { 0, 2, 19, 19360 }, { 0, 2, 8, 42416 }, { 5, 1, 28, 21176 }, { 0, 2, 16, 21168 }, { 0, 2, 5, 43344 }, { 4, 1, 25, 46248 }, { 0, 2, 12, 27296 }, { 0, 2, 1, 44368 }, { 2, 1, 22, 21928 }, { 0, 2, 10, 19296 }, { 6, 1, 29, 42352 }, { 0, 2, 17, 42352 }, { 0, 2, 7, 21104 }, { 5, 1, 27, 26928 }, { 0, 2, 13, 55600 }, { 0, 2, 3, 23200 }, { 3, 1, 23, 43856 }, { 0, 2, 11, 38608 }, { 11, 1, 31, 19176 }, { 0, 2, 19, 19168 }, { 0, 2, 8, 42192 }, { 6, 1, 28, 53864 }, { 0, 2, 15, 53840 }, { 0, 2, 4, 54560 }, { 5, 1, 24, 55968 }, { 0, 2, 12, 46752 }, { 0, 2, 1, 38608 }, { 2, 1, 22, 19160 }, { 0, 2, 10, 18864 }, { 7, 1, 30, 42168 }, { 0, 2, 17, 42160 }, { 0, 2, 6, 45648 }, { 5, 1, 26, 46376 }, { 0, 2, 14, 27968 }, { 0, 2, 2, 44448 }, { 3, 1, 23, 38320 } }; public override DateTime MinSupportedDateTime => s_minDate; public override DateTime MaxSupportedDateTime => s_maxDate; protected override int DaysInYearBeforeMinSupportedYear => 384; internal override int MinCalendarYear => 918; internal override int MaxCalendarYear => 2050; internal override DateTime MinDate => s_minDate; internal override DateTime MaxDate => s_maxDate; internal override EraInfo[]? CalEraInfo => null; internal override CalendarId BaseCalendarID => CalendarId.KOREA; internal override CalendarId ID => CalendarId.KOREANLUNISOLAR; public override int[] Eras => new int[1] { 1 }; internal override int GetYearInfo(int lunarYear, int index) { if (lunarYear < 918 || lunarYear > 2050) { throw new ArgumentOutOfRangeException("year", lunarYear, SR.Format(SR.ArgumentOutOfRange_Range, 918, 2050)); } return s_yinfo[lunarYear - 918, index]; } internal override int GetYear(int year, DateTime time) { return year; } internal override int GetGregorianYear(int year, int era) { if (era != 0 && era != 1) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 918 || year > 2050) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 918, 2050)); } return year; } public override int GetEra(DateTime time) { CheckTicksRange(time.Ticks); return 1; } } internal static class Normalization { internal static bool IsNormalized(string strInput, NormalizationForm normalizationForm) { if (GlobalizationMode.Invariant) { return true; } if (!GlobalizationMode.UseNls) { return IcuIsNormalized(strInput, normalizationForm); } return NlsIsNormalized(strInput, normalizationForm); } internal static string Normalize(string strInput, NormalizationForm normalizationForm) { if (GlobalizationMode.Invariant) { return strInput; } if (!GlobalizationMode.UseNls) { return IcuNormalize(strInput, normalizationForm); } return NlsNormalize(strInput, normalizationForm); } private unsafe static bool IcuIsNormalized(string strInput, NormalizationForm normalizationForm) { ValidateArguments(strInput, normalizationForm); int num; fixed (char* src = strInput) { num = Interop.Globalization.IsNormalized(normalizationForm, src, strInput.Length); } if (num == -1) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, "strInput"); } return num == 1; } private unsafe static string IcuNormalize(string strInput, NormalizationForm normalizationForm) { ValidateArguments(strInput, normalizationForm); char[] array = null; try { Span span = ((strInput.Length > 512) ? ((Span)(array = ArrayPool.Shared.Rent(strInput.Length))) : stackalloc char[512]); Span span2 = span; for (int i = 0; i < 2; i++) { int num; fixed (char* src = strInput) { fixed (char* dstBuffer = &MemoryMarshal.GetReference(span2)) { num = Interop.Globalization.NormalizeString(normalizationForm, src, strInput.Length, dstBuffer, span2.Length); } } if (num == -1) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, "strInput"); } if (num <= span2.Length) { ReadOnlySpan readOnlySpan = span2.Slice(0, num); return readOnlySpan.SequenceEqual(strInput) ? strInput : new string(readOnlySpan); } if (i == 0) { if (array != null) { char[] array2 = array; array = null; ArrayPool.Shared.Return(array2); } span2 = (array = ArrayPool.Shared.Rent(num)); } } throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, "strInput"); } finally { if (array != null) { ArrayPool.Shared.Return(array); } } } private static void ValidateArguments(string strInput, NormalizationForm normalizationForm) { if (OperatingSystem.IsBrowser()) { } if (normalizationForm != NormalizationForm.FormC && normalizationForm != NormalizationForm.FormD && normalizationForm != NormalizationForm.FormKC && normalizationForm != NormalizationForm.FormKD) { throw new ArgumentException(SR.Argument_InvalidNormalizationForm, "normalizationForm"); } if (HasInvalidUnicodeSequence(strInput)) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, "strInput"); } } private static bool HasInvalidUnicodeSequence(string s) { for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c < '\ud800') { continue; } if (c == '\ufffe') { return true; } if (char.IsLowSurrogate(c)) { return true; } if (char.IsHighSurrogate(c)) { if (i + 1 >= s.Length || !char.IsLowSurrogate(s[i + 1])) { return true; } i++; } } return false; } private unsafe static bool NlsIsNormalized(string strInput, NormalizationForm normalizationForm) { Interop.BOOL bOOL; fixed (char* source = strInput) { bOOL = Interop.Normaliz.IsNormalizedString(normalizationForm, source, strInput.Length); } int lastPInvokeError = Marshal.GetLastPInvokeError(); switch (lastPInvokeError) { case 87: case 1113: if (normalizationForm != NormalizationForm.FormC && normalizationForm != NormalizationForm.FormD && normalizationForm != NormalizationForm.FormKC && normalizationForm != NormalizationForm.FormKD) { throw new ArgumentException(SR.Argument_InvalidNormalizationForm, "normalizationForm"); } throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, "strInput"); case 8: throw new OutOfMemoryException(); default: throw new InvalidOperationException(SR.Format(SR.UnknownError_Num, lastPInvokeError)); case 0: return bOOL != Interop.BOOL.FALSE; } } private unsafe static string NlsNormalize(string strInput, NormalizationForm normalizationForm) { if (strInput.Length == 0) { return string.Empty; } char[] array = null; try { Span span = ((strInput.Length > 512) ? ((Span)(array = ArrayPool.Shared.Rent(strInput.Length))) : stackalloc char[512]); Span span2 = span; while (true) { int num; fixed (char* source = strInput) { fixed (char* destination = &MemoryMarshal.GetReference(span2)) { num = Interop.Normaliz.NormalizeString(normalizationForm, source, strInput.Length, destination, span2.Length); } } int lastPInvokeError = Marshal.GetLastPInvokeError(); switch (lastPInvokeError) { case 0: { ReadOnlySpan readOnlySpan = span2.Slice(0, num); return readOnlySpan.SequenceEqual(strInput) ? strInput : new string(readOnlySpan); } case 122: num = Math.Abs(num); if (array != null) { char[] array2 = array; array = null; ArrayPool.Shared.Return(array2); } break; case 87: case 1113: if (normalizationForm != NormalizationForm.FormC && normalizationForm != NormalizationForm.FormD && normalizationForm != NormalizationForm.FormKC && normalizationForm != NormalizationForm.FormKD) { throw new ArgumentException(SR.Argument_InvalidNormalizationForm, "normalizationForm"); } throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex, "strInput"); case 8: throw new OutOfMemoryException(); default: throw new InvalidOperationException(SR.Format(SR.UnknownError_Num, lastPInvokeError)); } span2 = (array = ArrayPool.Shared.Rent(num)); } } finally { if (array != null) { ArrayPool.Shared.Return(array); } } } } public sealed class NumberFormatInfo : IFormatProvider, ICloneable { private static volatile NumberFormatInfo s_invariantInfo; internal int[] _numberGroupSizes = new int[1] { 3 }; internal int[] _currencyGroupSizes = new int[1] { 3 }; internal int[] _percentGroupSizes = new int[1] { 3 }; internal string _positiveSign = "+"; internal string _negativeSign = "-"; internal string _numberDecimalSeparator = "."; internal string _numberGroupSeparator = ","; internal string _currencyGroupSeparator = ","; internal string _currencyDecimalSeparator = "."; internal string _currencySymbol = "¤"; internal string _nanSymbol = "NaN"; internal string _positiveInfinitySymbol = "Infinity"; internal string _negativeInfinitySymbol = "-Infinity"; internal string _percentDecimalSeparator = "."; internal string _percentGroupSeparator = ","; internal string _percentSymbol = "%"; internal string _perMilleSymbol = "‰"; internal string[] _nativeDigits = new string[10] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; internal int _numberDecimalDigits = 2; internal int _currencyDecimalDigits = 2; internal int _currencyPositivePattern; internal int _currencyNegativePattern; internal int _numberNegativePattern = 1; internal int _percentPositivePattern; internal int _percentNegativePattern; internal int _percentDecimalDigits = 2; internal int _digitSubstitution = 1; internal bool _isReadOnly; private bool _hasInvariantNumberSigns = true; private bool _allowHyphenDuringParsing; internal bool HasInvariantNumberSigns => _hasInvariantNumberSigns; internal bool AllowHyphenDuringParsing => _allowHyphenDuringParsing; public static NumberFormatInfo InvariantInfo { get { object obj = s_invariantInfo; if (obj == null) { obj = new NumberFormatInfo { _isReadOnly = true }; s_invariantInfo = (NumberFormatInfo)obj; } return (NumberFormatInfo)obj; } } public int CurrencyDecimalDigits { get { return _currencyDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 99)); } VerifyWritable(); _currencyDecimalDigits = value; } } public string CurrencyDecimalSeparator { get { return _currencyDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, "value"); _currencyDecimalSeparator = value; } } public bool IsReadOnly => _isReadOnly; public int[] CurrencyGroupSizes { get { return (int[])_currencyGroupSizes.Clone(); } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyWritable(); int[] array = (int[])value.Clone(); CheckGroupSize("value", array); _currencyGroupSizes = array; } } public int[] NumberGroupSizes { get { return (int[])_numberGroupSizes.Clone(); } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyWritable(); int[] array = (int[])value.Clone(); CheckGroupSize("value", array); _numberGroupSizes = array; } } public int[] PercentGroupSizes { get { return (int[])_percentGroupSizes.Clone(); } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyWritable(); int[] array = (int[])value.Clone(); CheckGroupSize("value", array); _percentGroupSizes = array; } } public string CurrencyGroupSeparator { get { return _currencyGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, "value"); _currencyGroupSeparator = value; } } public string CurrencySymbol { get { return _currencySymbol; } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyWritable(); _currencySymbol = value; } } public static NumberFormatInfo CurrentInfo { get { CultureInfo currentCulture = CultureInfo.CurrentCulture; if (!currentCulture._isInherited) { NumberFormatInfo numInfo = currentCulture._numInfo; if (numInfo != null) { return numInfo; } } return (NumberFormatInfo)currentCulture.GetFormat(typeof(NumberFormatInfo)); } } public string NaNSymbol { get { return _nanSymbol; } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyWritable(); _nanSymbol = value; } } public int CurrencyNegativePattern { get { return _currencyNegativePattern; } set { if (value < 0 || value > 15) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 15)); } VerifyWritable(); _currencyNegativePattern = value; } } public int NumberNegativePattern { get { return _numberNegativePattern; } set { if (value < 0 || value > 4) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 4)); } VerifyWritable(); _numberNegativePattern = value; } } public int PercentPositivePattern { get { return _percentPositivePattern; } set { if (value < 0 || value > 3) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 3)); } VerifyWritable(); _percentPositivePattern = value; } } public int PercentNegativePattern { get { return _percentNegativePattern; } set { if (value < 0 || value > 11) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 11)); } VerifyWritable(); _percentNegativePattern = value; } } public string NegativeInfinitySymbol { get { return _negativeInfinitySymbol; } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyWritable(); _negativeInfinitySymbol = value; } } public string NegativeSign { get { return _negativeSign; } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyWritable(); _negativeSign = value; InitializeInvariantAndNegativeSignFlags(); } } public int NumberDecimalDigits { get { return _numberDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 99)); } VerifyWritable(); _numberDecimalDigits = value; } } public string NumberDecimalSeparator { get { return _numberDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, "value"); _numberDecimalSeparator = value; } } public string NumberGroupSeparator { get { return _numberGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, "value"); _numberGroupSeparator = value; } } public int CurrencyPositivePattern { get { return _currencyPositivePattern; } set { if (value < 0 || value > 3) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 3)); } VerifyWritable(); _currencyPositivePattern = value; } } public string PositiveInfinitySymbol { get { return _positiveInfinitySymbol; } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyWritable(); _positiveInfinitySymbol = value; } } public string PositiveSign { get { return _positiveSign; } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyWritable(); _positiveSign = value; InitializeInvariantAndNegativeSignFlags(); } } public int PercentDecimalDigits { get { return _percentDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 0, 99)); } VerifyWritable(); _percentDecimalDigits = value; } } public string PercentDecimalSeparator { get { return _percentDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, "value"); _percentDecimalSeparator = value; } } public string PercentGroupSeparator { get { return _percentGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, "value"); _percentGroupSeparator = value; } } public string PercentSymbol { get { return _percentSymbol; } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyWritable(); _percentSymbol = value; } } public string PerMilleSymbol { get { return _perMilleSymbol; } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyWritable(); _perMilleSymbol = value; } } public string[] NativeDigits { get { return (string[])_nativeDigits.Clone(); } set { VerifyWritable(); VerifyNativeDigits(value, "value"); _nativeDigits = value; } } public DigitShapes DigitSubstitution { get { return (DigitShapes)_digitSubstitution; } set { VerifyWritable(); VerifyDigitSubstitution(value, "value"); _digitSubstitution = (int)value; } } public NumberFormatInfo() { } private static void VerifyDecimalSeparator(string decSep, string propertyName) { if (decSep == null) { throw new ArgumentNullException(propertyName); } if (decSep.Length == 0) { throw new ArgumentException(SR.Argument_EmptyDecString, propertyName); } } private static void VerifyGroupSeparator(string groupSep, string propertyName) { if (groupSep == null) { throw new ArgumentNullException(propertyName); } } private static void VerifyNativeDigits(string[] nativeDig, string propertyName) { if (nativeDig == null) { throw new ArgumentNullException(propertyName, SR.ArgumentNull_Array); } if (nativeDig.Length != 10) { throw new ArgumentException(SR.Argument_InvalidNativeDigitCount, propertyName); } for (int i = 0; i < nativeDig.Length; i++) { if (nativeDig[i] == null) { throw new ArgumentNullException(propertyName, SR.ArgumentNull_ArrayValue); } if (nativeDig[i].Length != 1) { if (nativeDig[i].Length != 2) { throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName); } if (!char.IsSurrogatePair(nativeDig[i][0], nativeDig[i][1])) { throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName); } } if (CharUnicodeInfo.GetDecimalDigitValue(nativeDig[i], 0) != i && CharUnicodeInfo.GetUnicodeCategory(nativeDig[i], 0) != UnicodeCategory.PrivateUse) { throw new ArgumentException(SR.Argument_InvalidNativeDigitValue, propertyName); } } } private static void VerifyDigitSubstitution(DigitShapes digitSub, string propertyName) { if ((uint)digitSub > 2u) { throw new ArgumentException(SR.Argument_InvalidDigitSubstitution, propertyName); } } private void InitializeInvariantAndNegativeSignFlags() { _hasInvariantNumberSigns = _positiveSign == "+" && _negativeSign == "-"; bool flag = _negativeSign.Length == 1; bool flag2 = flag; if (flag2) { bool flag3; switch (_negativeSign[0]) { case '‒': case '⁻': case '₋': case '−': case '➖': case '﹣': case '-': flag3 = true; break; default: flag3 = false; break; } flag2 = flag3; } _allowHyphenDuringParsing = flag2; } internal NumberFormatInfo(CultureData cultureData) { if (cultureData != null) { cultureData.GetNFIValues(this); InitializeInvariantAndNegativeSignFlags(); } } private void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } public static NumberFormatInfo GetInstance(IFormatProvider? formatProvider) { if (formatProvider != null) { return GetProviderNonNull(formatProvider); } return CurrentInfo; static NumberFormatInfo GetProviderNonNull(IFormatProvider provider) { if (provider is CultureInfo cultureInfo && !cultureInfo._isInherited) { return cultureInfo._numInfo ?? cultureInfo.NumberFormat; } return (provider as NumberFormatInfo) ?? (provider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo) ?? CurrentInfo; } } public object Clone() { NumberFormatInfo numberFormatInfo = (NumberFormatInfo)MemberwiseClone(); numberFormatInfo._isReadOnly = false; return numberFormatInfo; } internal static void CheckGroupSize(string propName, int[] groupSize) { for (int i = 0; i < groupSize.Length; i++) { if (groupSize[i] < 1) { if (i == groupSize.Length - 1 && groupSize[i] == 0) { break; } throw new ArgumentException(SR.Argument_InvalidGroupSize, propName); } if (groupSize[i] > 9) { throw new ArgumentException(SR.Argument_InvalidGroupSize, propName); } } } public object? GetFormat(Type? formatType) { if (!(formatType == typeof(NumberFormatInfo))) { return null; } return this; } public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) { if (nfi == null) { throw new ArgumentNullException("nfi"); } if (nfi.IsReadOnly) { return nfi; } NumberFormatInfo numberFormatInfo = (NumberFormatInfo)nfi.MemberwiseClone(); numberFormatInfo._isReadOnly = true; return numberFormatInfo; } internal static void ValidateParseStyleInteger(NumberStyles style) { if (((uint)style & 0xFFFFFE00u) != 0 && ((uint)style & 0xFFFFFDFCu) != 0) { ThrowInvalid(style); } static void ThrowInvalid(NumberStyles value) { if (((uint)value & 0xFFFFFC00u) != 0) { throw new ArgumentException(SR.Argument_InvalidNumberStyles, "style"); } throw new ArgumentException(SR.Arg_InvalidHexStyle); } } internal static void ValidateParseStyleFloatingPoint(NumberStyles style) { if (((uint)style & 0xFFFFFE00u) != 0) { ThrowInvalid(style); } static void ThrowInvalid(NumberStyles value) { if (((uint)value & 0xFFFFFC00u) != 0) { throw new ArgumentException(SR.Argument_InvalidNumberStyles, "style"); } throw new ArgumentException(SR.Arg_HexStyleNotSupported); } } } [Flags] public enum NumberStyles { None = 0, AllowLeadingWhite = 1, AllowTrailingWhite = 2, AllowLeadingSign = 4, AllowTrailingSign = 8, AllowParentheses = 0x10, AllowDecimalPoint = 0x20, AllowThousands = 0x40, AllowExponent = 0x80, AllowCurrencySymbol = 0x100, AllowHexSpecifier = 0x200, Integer = 7, HexNumber = 0x203, Number = 0x6F, Float = 0xA7, Currency = 0x17F, Any = 0x1FF } internal static class Ordinal { internal static int CompareStringIgnoreCase(ref char strA, int lengthA, ref char strB, int lengthB) { int num = Math.Min(lengthA, lengthB); int num2 = num; ref char reference = ref strA; ref char reference2 = ref strB; char c = '\u007f'; while (num != 0 && reference <= c && reference2 <= c) { if (reference == reference2 || ((reference | 0x20) == (reference2 | 0x20) && (uint)((reference | 0x20) - 97) <= 25u)) { num--; reference = ref Unsafe.Add(ref reference, 1); reference2 = ref Unsafe.Add(ref reference2, 1); continue; } int num3 = reference; int num4 = reference2; if ((uint)(reference - 97) <= 25u) { num3 -= 32; } if ((uint)(reference2 - 97) <= 25u) { num4 -= 32; } return num3 - num4; } if (num == 0) { return lengthA - lengthB; } num2 -= num; return CompareStringIgnoreCaseNonAscii(ref reference, lengthA - num2, ref reference2, lengthB - num2); } internal static int CompareStringIgnoreCaseNonAscii(ref char strA, int lengthA, ref char strB, int lengthB) { if (GlobalizationMode.Invariant) { return InvariantModeCasing.CompareStringIgnoreCase(ref strA, lengthA, ref strB, lengthB); } if (GlobalizationMode.UseNls) { return CompareInfo.NlsCompareStringOrdinalIgnoreCase(ref strA, lengthA, ref strB, lengthB); } return OrdinalCasing.CompareStringIgnoreCase(ref strA, lengthA, ref strB, lengthB); } internal static bool EqualsIgnoreCase(ref char charA, ref char charB, int length) { IntPtr zero = IntPtr.Zero; while (true) { switch (length) { default: { uint num3 = Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.AddByteOffset(ref charA, zero))); uint num4 = Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.AddByteOffset(ref charB, zero))); if (Utf16Utility.AllCharsInUInt32AreAscii(num3 | num4)) { if (Utf16Utility.UInt32OrdinalIgnoreCaseAscii(num3, num4)) { goto IL_0041; } return false; } break; } case 1: { uint num = Unsafe.AddByteOffset(ref charA, zero); uint num2 = Unsafe.AddByteOffset(ref charB, zero); if ((num | num2) <= 127) { if (num == num2) { return true; } num |= 0x20u; if (num - 97 > 25) { return false; } if (num != (num2 | 0x20)) { return false; } return true; } break; } case 0: return true; } break; IL_0041: zero += 4; length -= 2; } return CompareStringIgnoreCase(ref Unsafe.AddByteOffset(ref charA, zero), length, ref Unsafe.AddByteOffset(ref charB, zero), length) == 0; } internal static int IndexOf(string source, string value, int startIndex, int count, bool ignoreCase) { if (source == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source); } if (value == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value); } if (!source.TryGetSpan(startIndex, count, out var slice)) { if ((uint)startIndex > (uint)source.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } else { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } } int num = (ignoreCase ? IndexOfOrdinalIgnoreCase(slice, value) : slice.IndexOf(value)); if (num < 0) { return num; } return num + startIndex; } internal static int IndexOfOrdinalIgnoreCase(ReadOnlySpan source, ReadOnlySpan value) { if (value.Length == 0) { return 0; } if (value.Length > source.Length) { return -1; } if (GlobalizationMode.Invariant) { return InvariantModeCasing.IndexOfIgnoreCase(source, value); } if (GlobalizationMode.UseNls) { return CompareInfo.NlsIndexOfOrdinalCore(source, value, ignoreCase: true, fromBeginning: true); } return OrdinalCasing.IndexOf(source, value); } internal static int LastIndexOfOrdinalIgnoreCase(ReadOnlySpan source, ReadOnlySpan value) { if (value.Length == 0) { return source.Length; } if (value.Length > source.Length) { return -1; } if (GlobalizationMode.Invariant) { return InvariantModeCasing.LastIndexOfIgnoreCase(source, value); } if (GlobalizationMode.UseNls) { return CompareInfo.NlsIndexOfOrdinalCore(source, value, ignoreCase: true, fromBeginning: false); } return OrdinalCasing.LastIndexOf(source, value); } internal static int ToUpperOrdinal(ReadOnlySpan source, Span destination) { if (source.Overlaps(destination)) { throw new InvalidOperationException(SR.InvalidOperation_SpanOverlappedOperation); } if (destination.Length < source.Length) { return -1; } if (GlobalizationMode.Invariant) { InvariantModeCasing.ToUpper(source, destination); return source.Length; } if (GlobalizationMode.UseNls) { TextInfo.Invariant.ChangeCaseToUpper(source, destination); return source.Length; } OrdinalCasing.ToUpperOrdinal(source, destination); return source.Length; } } internal static class OrdinalCasing { private static ushort[] s_noCasingPage = Array.Empty(); private static ushort[] s_basicLatin = new ushort[256] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 924, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 247, 216, 217, 218, 219, 220, 221, 222, 376 }; private static ushort[][] s_casingTable = InitCasingTable(); private static ReadOnlySpan s_casingTableInit => new byte[32] { 0, 0, 76, 0, 55, 224, 31, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 254, 244, 15, 255, 255, 255, 255, 254, 255, 255, 255, 255, 200 }; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static char ToUpper(char c) { int num = (int)c >> 8; if (num == 0) { return (char)s_basicLatin[(uint)c]; } ushort[] array = s_casingTable[num]; if (array == s_noCasingPage) { return c; } if (array == null) { array = InitOrdinalCasingPage(num); } return (char)array[c & 0xFF]; } internal static void ToUpperOrdinal(ReadOnlySpan source, Span destination) { for (int i = 0; i < source.Length; i++) { char c = source[i]; if (c <= 'ÿ') { destination[i] = (char)s_basicLatin[(uint)c]; continue; } if (char.IsHighSurrogate(c) && i < source.Length - 1) { char c2 = source[i + 1]; if (char.IsLowSurrogate(c2)) { SurrogateCasing.ToUpper(c, c2, out destination[i], out destination[i + 1]); i++; continue; } } destination[i] = ToUpper(c); } } internal static int CompareStringIgnoreCase(ref char strA, int lengthA, ref char strB, int lengthB) { int num = Math.Min(lengthA, lengthB); ref char reference = ref strA; ref char reference2 = ref strB; int num2 = 0; while (num2 < num) { char c = reference; char c2 = reference2; char c3 = '\0'; if (!char.IsHighSurrogate(c) || num2 >= lengthA - 1 || !char.IsLowSurrogate(c3 = Unsafe.Add(ref reference, 1))) { if (!char.IsHighSurrogate(c2) || num2 >= lengthB - 1 || !char.IsLowSurrogate(Unsafe.Add(ref reference2, 1))) { if (c2 == c) { num2++; reference = ref Unsafe.Add(ref reference, 1); reference2 = ref Unsafe.Add(ref reference2, 1); continue; } char c4 = ToUpper(c); char c5 = ToUpper(c2); if (c4 == c5) { num2++; reference = ref Unsafe.Add(ref reference, 1); reference2 = ref Unsafe.Add(ref reference2, 1); continue; } return c - c2; } return -1; } char c6 = '\0'; if (!char.IsHighSurrogate(c2) || num2 >= lengthB - 1 || !char.IsLowSurrogate(c6 = Unsafe.Add(ref reference2, 1))) { return 1; } if (c == c2 && c3 == c6) { num2 += 2; reference = ref Unsafe.Add(ref reference, 2); reference2 = ref Unsafe.Add(ref reference2, 2); continue; } uint num3 = CharUnicodeInfo.ToUpper(UnicodeUtility.GetScalarFromUtf16SurrogatePair(c, c3)); uint num4 = CharUnicodeInfo.ToUpper(UnicodeUtility.GetScalarFromUtf16SurrogatePair(c2, c6)); if (num3 == num4) { num2 += 2; reference = ref Unsafe.Add(ref reference, 2); reference2 = ref Unsafe.Add(ref reference2, 2); continue; } return (int)(num3 - num4); } return lengthA - lengthB; } internal unsafe static int IndexOf(ReadOnlySpan source, ReadOnlySpan value) { fixed (char* ptr = &MemoryMarshal.GetReference(source)) { fixed (char* ptr3 = &MemoryMarshal.GetReference(value)) { char* ptr2 = ptr + (source.Length - value.Length); char* ptr4 = ptr3 + value.Length - 1; for (char* ptr5 = ptr; ptr5 <= ptr2; ptr5++) { char* ptr6 = ptr3; char* ptr7 = ptr5; while (ptr6 <= ptr4) { if (!char.IsHighSurrogate(*ptr6) || ptr6 == ptr4) { if (*ptr6 != *ptr7 && ToUpper(*ptr6) != ToUpper(*ptr7)) { break; } ptr6++; ptr7++; } else if (char.IsHighSurrogate(*ptr7) && char.IsLowSurrogate(ptr7[1]) && char.IsLowSurrogate(ptr6[1])) { if (!SurrogateCasing.Equal(*ptr7, ptr7[1], *ptr6, ptr6[1])) { break; } ptr7 += 2; ptr6 += 2; } else { if (*ptr6 != *ptr7) { break; } ptr7++; ptr6++; } } if (ptr6 > ptr4) { return (int)(ptr5 - ptr); } } return -1; } } } internal unsafe static int LastIndexOf(ReadOnlySpan source, ReadOnlySpan value) { fixed (char* ptr3 = &MemoryMarshal.GetReference(source)) { fixed (char* ptr = &MemoryMarshal.GetReference(value)) { char* ptr2 = ptr + value.Length - 1; for (char* ptr4 = ptr3 + (source.Length - value.Length); ptr4 >= ptr3; ptr4--) { char* ptr5 = ptr; char* ptr6 = ptr4; while (ptr5 <= ptr2) { if (!char.IsHighSurrogate(*ptr5) || ptr5 == ptr2) { if (*ptr5 != *ptr6 && ToUpper(*ptr5) != ToUpper(*ptr6)) { break; } ptr5++; ptr6++; } else if (char.IsHighSurrogate(*ptr6) && char.IsLowSurrogate(ptr6[1]) && char.IsLowSurrogate(ptr5[1])) { if (!SurrogateCasing.Equal(*ptr6, ptr6[1], *ptr5, ptr5[1])) { break; } ptr6 += 2; ptr5 += 2; } else { if (*ptr5 != *ptr6) { break; } ptr6++; ptr5++; } } if (ptr5 > ptr2) { return (int)(ptr4 - ptr3); } } return -1; } } } private static ushort[][] InitCasingTable() { ushort[][] array = new ushort[s_casingTableInit.Length * 8][]; for (int i = 0; i < s_casingTableInit.Length * 8; i++) { byte b = (byte)(s_casingTableInit[i / 8] >> 7 - i % 8); if ((b & 1) == 1) { array[i] = s_noCasingPage; } } array[0] = s_basicLatin; return array; } private unsafe static ushort[] InitOrdinalCasingPage(int pageNumber) { ushort[] array = new ushort[256]; fixed (ushort* ptr = array) { char* pTarget = (char*)ptr; Interop.Globalization.InitOrdinalCasingPage(pageNumber, pTarget); } Volatile.Write(ref s_casingTable[pageNumber], array); return array; } } public class PersianCalendar : Calendar { public static readonly int PersianEra = 1; private static readonly long s_persianEpoch = new DateTime(622, 3, 22).Ticks / 864000000000L; private static readonly int[] s_daysToMonth = new int[13] { 0, 31, 62, 93, 124, 155, 186, 216, 246, 276, 306, 336, 366 }; private static readonly DateTime s_minDate = new DateTime(622, 3, 22); private static readonly DateTime s_maxDate = DateTime.MaxValue; public override DateTime MinSupportedDateTime => s_minDate; public override DateTime MaxSupportedDateTime => s_maxDate; public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.SolarCalendar; internal override CalendarId BaseCalendarID => CalendarId.GREGORIAN; internal override CalendarId ID => CalendarId.PERSIAN; public override int[] Eras => new int[1] { PersianEra }; public override int TwoDigitYearMax { get { if (_twoDigitYearMax == -1) { _twoDigitYearMax = Calendar.GetSystemTwoDigitYearSetting(ID, 1410); } return _twoDigitYearMax; } set { VerifyWritable(); if (value < 99 || value > 9378) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 99, 9378)); } _twoDigitYearMax = value; } } private static long GetAbsoluteDatePersian(int year, int month, int day) { if (year < 1 || year > 9378 || month < 1 || month > 12) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } int num = DaysInPreviousMonths(month) + day - 1; int num2 = (int)(365.242189 * (double)(year - 1)); long num3 = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(s_persianEpoch + num2 + 180); return num3 + num; } internal static void CheckTicksRange(long ticks) { if (ticks < s_minDate.Ticks || ticks > s_maxDate.Ticks) { throw new ArgumentOutOfRangeException("time", ticks, SR.Format(SR.ArgumentOutOfRange_CalendarRange, s_minDate, s_maxDate)); } } internal static void CheckEraRange(int era) { if (era != 0 && era != PersianEra) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } } internal static void CheckYearRange(int year, int era) { CheckEraRange(era); if (year < 1 || year > 9378) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 1, 9378)); } } internal static void CheckYearMonthRange(int year, int month, int era) { CheckYearRange(year, era); if (year == 9378 && month > 10) { throw new ArgumentOutOfRangeException("month", month, SR.Format(SR.ArgumentOutOfRange_Range, 1, 10)); } if (month < 1 || month > 12) { ThrowHelper.ThrowArgumentOutOfRange_Month(month); } } private static int MonthFromOrdinalDay(int ordinalDay) { int i; for (i = 0; ordinalDay > s_daysToMonth[i]; i++) { } return i; } private static int DaysInPreviousMonths(int month) { month--; return s_daysToMonth[month]; } internal int GetDatePart(long ticks, int part) { CheckTicksRange(ticks); long num = ticks / 864000000000L + 1; long num2 = CalendricalCalculationsHelper.PersianNewYearOnOrBefore(num); int num3 = (int)Math.Floor((double)(num2 - s_persianEpoch) / 365.242189 + 0.5) + 1; if (part == 0) { return num3; } int num4 = (int)(num - CalendricalCalculationsHelper.GetNumberOfDays(ToDateTime(num3, 1, 1, 0, 0, 0, 0, 1))); if (part == 1) { return num4; } int num5 = MonthFromOrdinalDay(num4); if (part == 2) { return num5; } int result = num4 - DaysInPreviousMonths(num5); if (part == 3) { return result; } throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing); } public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException("months", months, SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000)); } int datePart = GetDatePart(time.Ticks, 0); int datePart2 = GetDatePart(time.Ticks, 2); int num = GetDatePart(time.Ticks, 3); int num2 = datePart2 - 1 + months; if (num2 >= 0) { datePart2 = num2 % 12 + 1; datePart += num2 / 12; } else { datePart2 = 12 + (num2 + 1) % 12; datePart += (num2 - 11) / 12; } int daysInMonth = GetDaysInMonth(datePart, datePart2); if (num > daysInMonth) { num = daysInMonth; } long ticks = GetAbsoluteDatePersian(datePart, datePart2, num) * 864000000000L + time.Ticks % 864000000000L; Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return new DateTime(ticks); } public override DateTime AddYears(DateTime time, int years) { return AddMonths(time, years * 12); } public override int GetDayOfMonth(DateTime time) { return GetDatePart(time.Ticks, 3); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (DayOfWeek)((int)(time.Ticks / 864000000000L + 1) % 7); } public override int GetDayOfYear(DateTime time) { return GetDatePart(time.Ticks, 1); } public override int GetDaysInMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); if (month == 10 && year == 9378) { return 13; } int num = s_daysToMonth[month] - s_daysToMonth[month - 1]; if (month == 12 && !IsLeapYear(year)) { num--; } return num; } public override int GetDaysInYear(int year, int era) { CheckYearRange(year, era); if (year == 9378) { return s_daysToMonth[9] + 13; } if (!IsLeapYear(year, 0)) { return 365; } return 366; } public override int GetEra(DateTime time) { CheckTicksRange(time.Ticks); return PersianEra; } public override int GetMonth(DateTime time) { return GetDatePart(time.Ticks, 2); } public override int GetMonthsInYear(int year, int era) { CheckYearRange(year, era); if (year == 9378) { return 10; } return 12; } public override int GetYear(DateTime time) { return GetDatePart(time.Ticks, 0); } public override bool IsLeapDay(int year, int month, int day, int era) { int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException("day", day, SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month)); } if (IsLeapYear(year, era) && month == 12) { return day == 30; } return false; } public override int GetLeapMonth(int year, int era) { CheckYearRange(year, era); return 0; } public override bool IsLeapMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); return false; } public override bool IsLeapYear(int year, int era) { CheckYearRange(year, era); if (year == 9378) { return false; } return GetAbsoluteDatePersian(year + 1, 1, 1) - GetAbsoluteDatePersian(year, 1, 1) == 366; } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException("day", day, SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month)); } long absoluteDatePersian = GetAbsoluteDatePersian(year, month, day); if (absoluteDatePersian < 0) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } return new DateTime(absoluteDatePersian * 864000000000L + Calendar.TimeToTicks(hour, minute, second, millisecond)); } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", year, SR.ArgumentOutOfRange_NeedNonNegNum); } if (year < 100) { return base.ToFourDigitYear(year); } if (year > 9378) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 1, 9378)); } return year; } } public class RegionInfo { private string _name; private readonly CultureData _cultureData; internal static volatile RegionInfo s_currentRegionInfo; public static RegionInfo CurrentRegion { get { RegionInfo regionInfo = s_currentRegionInfo; if (regionInfo == null) { regionInfo = new RegionInfo(CultureData.GetCurrentRegionData()); regionInfo._name = regionInfo._cultureData.RegionName; s_currentRegionInfo = regionInfo; } return regionInfo; } } public virtual string Name => _name; public virtual string EnglishName => _cultureData.EnglishCountryName; public virtual string DisplayName => _cultureData.LocalizedCountryName; public virtual string NativeName => _cultureData.NativeCountryName; public virtual string TwoLetterISORegionName => _cultureData.TwoLetterISOCountryName; public virtual string ThreeLetterISORegionName => _cultureData.ThreeLetterISOCountryName; public virtual string ThreeLetterWindowsRegionName => ThreeLetterISORegionName; public virtual bool IsMetric => _cultureData.MeasurementSystem == 0; public virtual int GeoId => _cultureData.GeoId; public virtual string CurrencyEnglishName => _cultureData.CurrencyEnglishName; public virtual string CurrencyNativeName => _cultureData.CurrencyNativeName; public virtual string CurrencySymbol => _cultureData.CurrencySymbol; public virtual string ISOCurrencySymbol => _cultureData.ISOCurrencySymbol; public RegionInfo(string name) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_NoRegionInvariantCulture, "name"); } _cultureData = CultureData.GetCultureDataForRegion(name, useUserOverride: true) ?? throw new ArgumentException(SR.Format(SR.Argument_InvalidCultureName, name), "name"); if (_cultureData.IsNeutralCulture) { throw new ArgumentException(SR.Format(SR.Argument_InvalidNeutralRegionName, name), "name"); } _name = _cultureData.RegionName; } public RegionInfo(int culture) { switch (culture) { case 127: throw new ArgumentException(SR.Argument_NoRegionInvariantCulture); case 0: throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), "culture"); case 3072: throw new ArgumentException(SR.Format(SR.Argument_CustomCultureCannotBePassedByNumber, culture), "culture"); } _cultureData = CultureData.GetCultureData(culture, bUseUserOverride: true); _name = _cultureData.RegionName; if (_cultureData.IsNeutralCulture) { throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), "culture"); } } internal RegionInfo(CultureData cultureData) { _cultureData = cultureData; _name = _cultureData.RegionName; } public override bool Equals([NotNullWhen(true)] object? value) { if (value is RegionInfo regionInfo) { return Name.Equals(regionInfo.Name); } return false; } public override int GetHashCode() { return Name.GetHashCode(); } public override string ToString() { return Name; } } public sealed class SortKey { private readonly CompareInfo _compareInfo; private readonly CompareOptions _options; private readonly string _string; private readonly byte[] _keyData; public string OriginalString => _string; public byte[] KeyData => (byte[])_keyData.Clone(); internal SortKey(CompareInfo compareInfo, string str, CompareOptions options, byte[] keyData) { _keyData = keyData; _compareInfo = compareInfo; _options = options; _string = str; } public static int Compare(SortKey sortkey1, SortKey sortkey2) { if (sortkey1 == null) { throw new ArgumentNullException("sortkey1"); } if (sortkey2 == null) { throw new ArgumentNullException("sortkey2"); } byte[] keyData = sortkey1._keyData; byte[] keyData2 = sortkey2._keyData; return new ReadOnlySpan(keyData).SequenceCompareTo(keyData2); } public override bool Equals([NotNullWhen(true)] object? value) { if (value is SortKey sortKey) { return new ReadOnlySpan(_keyData).SequenceEqual(sortKey._keyData); } return false; } public override int GetHashCode() { return _compareInfo.GetHashCode(_string, _options); } public override string ToString() { return $"SortKey - {_compareInfo.Name}, {_options}, {_string}"; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class SortVersion : IEquatable { private readonly int m_NlsVersion; private Guid m_SortId; public int FullVersion => m_NlsVersion; public Guid SortId => m_SortId; public SortVersion(int fullVersion, Guid sortId) { m_SortId = sortId; m_NlsVersion = fullVersion; } internal SortVersion(int nlsVersion, int effectiveId, Guid customVersion) { m_NlsVersion = nlsVersion; if (customVersion == Guid.Empty) { byte h = (byte)(effectiveId >> 24); byte i = (byte)((effectiveId & 0xFF0000) >> 16); byte j = (byte)((effectiveId & 0xFF00) >> 8); byte k = (byte)((uint)effectiveId & 0xFFu); customVersion = new Guid(0, 0, 0, 0, 0, 0, 0, h, i, j, k); } m_SortId = customVersion; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is SortVersion other) { return Equals(other); } return false; } public bool Equals([NotNullWhen(true)] SortVersion? other) { if (other == null) { return false; } if (m_NlsVersion == other.m_NlsVersion) { return m_SortId == other.m_SortId; } return false; } public override int GetHashCode() { return (m_NlsVersion * 7) | m_SortId.GetHashCode(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(SortVersion? left, SortVersion? right) { if ((object)right == null) { if ((object)left != null) { return false; } return true; } return right.Equals(left); } public static bool operator !=(SortVersion? left, SortVersion? right) { return !(left == right); } } public class StringInfo { private string _str; private int[] _indexes; private int[]? Indexes { get { if (_indexes == null && String.Length > 0) { _indexes = ParseCombiningCharacters(String); } return _indexes; } } public string String { get { return _str; } [MemberNotNull("_str")] set { _str = value ?? throw new ArgumentNullException("value"); _indexes = null; } } public int LengthInTextElements { get { int[]? indexes = Indexes; if (indexes == null) { return 0; } return indexes.Length; } } public StringInfo() : this(string.Empty) { } public StringInfo(string value) { String = value; } public override bool Equals([NotNullWhen(true)] object? value) { if (value is StringInfo stringInfo) { return _str.Equals(stringInfo._str); } return false; } public override int GetHashCode() { return _str.GetHashCode(); } public string SubstringByTextElements(int startingTextElement) { int[]? indexes = Indexes; return SubstringByTextElements(startingTextElement, ((indexes != null) ? indexes.Length : 0) - startingTextElement); } public string SubstringByTextElements(int startingTextElement, int lengthInTextElements) { int[] array = Indexes ?? Array.Empty(); if ((uint)startingTextElement >= (uint)array.Length) { throw new ArgumentOutOfRangeException("startingTextElement", startingTextElement, SR.Arg_ArgumentOutOfRangeException); } if ((uint)lengthInTextElements > (uint)(array.Length - startingTextElement)) { throw new ArgumentOutOfRangeException("lengthInTextElements", lengthInTextElements, SR.Arg_ArgumentOutOfRangeException); } int num = array[startingTextElement]; Index end = ^0; if ((uint)(startingTextElement + lengthInTextElements) < (uint)array.Length) { end = array[startingTextElement + lengthInTextElements]; } return String[num..end]; } public static string GetNextTextElement(string str) { return GetNextTextElement(str, 0); } public static string GetNextTextElement(string str, int index) { int nextTextElementLength = GetNextTextElementLength(str, index); return str.Substring(index, nextTextElementLength); } public static int GetNextTextElementLength(string str) { return GetNextTextElementLength(str, 0); } public static int GetNextTextElementLength(string str, int index) { if (str == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.str); } if ((uint)index > (uint)str.Length) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return GetNextTextElementLength(str.AsSpan(index)); } public static int GetNextTextElementLength(ReadOnlySpan str) { return TextSegmentationUtility.GetLengthOfFirstUtf16ExtendedGraphemeCluster(str); } public static TextElementEnumerator GetTextElementEnumerator(string str) { return GetTextElementEnumerator(str, 0); } public static TextElementEnumerator GetTextElementEnumerator(string str, int index) { if (str == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.str); } if ((uint)index > (uint)str.Length) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } return new TextElementEnumerator(str, index); } public static int[] ParseCombiningCharacters(string str) { if (str == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.str); } Span initialSpan = stackalloc int[64]; ValueListBuilder valueListBuilder = new ValueListBuilder(initialSpan); ReadOnlySpan str2 = str; while (!str2.IsEmpty) { valueListBuilder.Append(str.Length - str2.Length); str2 = str2.Slice(GetNextTextElementLength(str2)); } int[] result = valueListBuilder.AsSpan().ToArray(); valueListBuilder.Dispose(); return result; } } internal enum StrongBidiCategory { Other = 0, StrongLeftToRight = 0x20, StrongRightToLeft = 0x40 } internal static class SurrogateCasing { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void ToUpper(char h, char l, out char hr, out char lr) { UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneScalar(CharUnicodeInfo.ToUpper(UnicodeUtility.GetScalarFromUtf16SurrogatePair(h, l)), out hr, out lr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void ToLower(char h, char l, out char hr, out char lr) { UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneScalar(CharUnicodeInfo.ToLower(UnicodeUtility.GetScalarFromUtf16SurrogatePair(h, l)), out hr, out lr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool Equal(char h1, char l1, char h2, char l2) { ToUpper(h1, l1, out var hr, out var lr); ToUpper(h2, l2, out var hr2, out var lr2); if (hr == hr2) { return lr == lr2; } return false; } } public class TaiwanCalendar : Calendar { private static readonly EraInfo[] s_taiwanEraInfo = new EraInfo[1] { new EraInfo(1, 1912, 1, 1, 1911, 1, 8088) }; private static volatile Calendar s_defaultInstance; private readonly GregorianCalendarHelper _helper; private static readonly DateTime s_calendarMinValue = new DateTime(1912, 1, 1); public override DateTime MinSupportedDateTime => s_calendarMinValue; public override DateTime MaxSupportedDateTime => DateTime.MaxValue; public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.SolarCalendar; internal override CalendarId ID => CalendarId.TAIWAN; public override int[] Eras => _helper.Eras; public override int TwoDigitYearMax { get { if (_twoDigitYearMax == -1) { _twoDigitYearMax = Calendar.GetSystemTwoDigitYearSetting(ID, 99); } return _twoDigitYearMax; } set { VerifyWritable(); if (value < 99 || value > _helper.MaxYear) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 99, _helper.MaxYear)); } _twoDigitYearMax = value; } } internal static Calendar GetDefaultInstance() { return s_defaultInstance ?? (s_defaultInstance = new TaiwanCalendar()); } public TaiwanCalendar() { try { new CultureInfo("zh-TW"); } catch (ArgumentException innerException) { throw new TypeInitializationException(GetType().ToString(), innerException); } _helper = new GregorianCalendarHelper(this, s_taiwanEraInfo); } public override DateTime AddMonths(DateTime time, int months) { return _helper.AddMonths(time, months); } public override DateTime AddYears(DateTime time, int years) { return _helper.AddYears(time, years); } public override int GetDaysInMonth(int year, int month, int era) { return _helper.GetDaysInMonth(year, month, era); } public override int GetDaysInYear(int year, int era) { return _helper.GetDaysInYear(year, era); } public override int GetDayOfMonth(DateTime time) { return _helper.GetDayOfMonth(time); } public override DayOfWeek GetDayOfWeek(DateTime time) { return _helper.GetDayOfWeek(time); } public override int GetDayOfYear(DateTime time) { return _helper.GetDayOfYear(time); } public override int GetMonthsInYear(int year, int era) { return _helper.GetMonthsInYear(year, era); } public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return _helper.GetWeekOfYear(time, rule, firstDayOfWeek); } public override int GetEra(DateTime time) { return _helper.GetEra(time); } public override int GetMonth(DateTime time) { return _helper.GetMonth(time); } public override int GetYear(DateTime time) { return _helper.GetYear(time); } public override bool IsLeapDay(int year, int month, int day, int era) { return _helper.IsLeapDay(year, month, day, era); } public override bool IsLeapYear(int year, int era) { return _helper.IsLeapYear(year, era); } public override int GetLeapMonth(int year, int era) { return _helper.GetLeapMonth(year, era); } public override bool IsLeapMonth(int year, int month, int era) { return _helper.IsLeapMonth(year, month, era); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return _helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era); } public override int ToFourDigitYear(int year) { if (year <= 0) { throw new ArgumentOutOfRangeException("year", year, SR.ArgumentOutOfRange_NeedPosNum); } if (year > _helper.MaxYear) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 1, _helper.MaxYear)); } return year; } } public class TaiwanLunisolarCalendar : EastAsianLunisolarCalendar { private static readonly EraInfo[] s_taiwanLunisolarEraInfo = new EraInfo[1] { new EraInfo(1, 1912, 1, 1, 1911, 1, 8088) }; private readonly GregorianCalendarHelper _helper; private static readonly DateTime s_minDate = new DateTime(1912, 2, 18); private static readonly DateTime s_maxDate = new DateTime(new DateTime(2051, 2, 10, 23, 59, 59, 999).Ticks + 9999); private static readonly int[,] s_yinfo = new int[139, 4] { { 0, 2, 18, 42192 }, { 0, 2, 6, 53840 }, { 5, 1, 26, 54568 }, { 0, 2, 14, 46400 }, { 0, 2, 3, 54944 }, { 2, 1, 23, 38608 }, { 0, 2, 11, 38320 }, { 7, 2, 1, 18872 }, { 0, 2, 20, 18800 }, { 0, 2, 8, 42160 }, { 5, 1, 28, 45656 }, { 0, 2, 16, 27216 }, { 0, 2, 5, 27968 }, { 4, 1, 24, 44456 }, { 0, 2, 13, 11104 }, { 0, 2, 2, 38256 }, { 2, 1, 23, 18808 }, { 0, 2, 10, 18800 }, { 6, 1, 30, 25776 }, { 0, 2, 17, 54432 }, { 0, 2, 6, 59984 }, { 5, 1, 26, 27976 }, { 0, 2, 14, 23248 }, { 0, 2, 4, 11104 }, { 3, 1, 24, 37744 }, { 0, 2, 11, 37600 }, { 7, 1, 31, 51560 }, { 0, 2, 19, 51536 }, { 0, 2, 8, 54432 }, { 6, 1, 27, 55888 }, { 0, 2, 15, 46416 }, { 0, 2, 5, 22176 }, { 4, 1, 25, 43736 }, { 0, 2, 13, 9680 }, { 0, 2, 2, 37584 }, { 2, 1, 22, 51544 }, { 0, 2, 10, 43344 }, { 7, 1, 29, 46248 }, { 0, 2, 17, 27808 }, { 0, 2, 6, 46416 }, { 5, 1, 27, 21928 }, { 0, 2, 14, 19872 }, { 0, 2, 3, 42416 }, { 3, 1, 24, 21176 }, { 0, 2, 12, 21168 }, { 8, 1, 31, 43344 }, { 0, 2, 18, 59728 }, { 0, 2, 8, 27296 }, { 6, 1, 28, 44368 }, { 0, 2, 15, 43856 }, { 0, 2, 5, 19296 }, { 4, 1, 25, 42352 }, { 0, 2, 13, 42352 }, { 0, 2, 2, 21088 }, { 3, 1, 21, 59696 }, { 0, 2, 9, 55632 }, { 7, 1, 30, 23208 }, { 0, 2, 17, 22176 }, { 0, 2, 6, 38608 }, { 5, 1, 27, 19176 }, { 0, 2, 15, 19152 }, { 0, 2, 3, 42192 }, { 4, 1, 23, 53864 }, { 0, 2, 11, 53840 }, { 8, 1, 31, 54568 }, { 0, 2, 18, 46400 }, { 0, 2, 7, 46752 }, { 6, 1, 28, 38608 }, { 0, 2, 16, 38320 }, { 0, 2, 5, 18864 }, { 4, 1, 25, 42168 }, { 0, 2, 13, 42160 }, { 10, 2, 2, 45656 }, { 0, 2, 20, 27216 }, { 0, 2, 9, 27968 }, { 6, 1, 29, 44448 }, { 0, 2, 17, 43872 }, { 0, 2, 6, 38256 }, { 5, 1, 27, 18808 }, { 0, 2, 15, 18800 }, { 0, 2, 4, 25776 }, { 3, 1, 23, 27216 }, { 0, 2, 10, 59984 }, { 8, 1, 31, 27432 }, { 0, 2, 19, 23232 }, { 0, 2, 7, 43872 }, { 5, 1, 28, 37736 }, { 0, 2, 16, 37600 }, { 0, 2, 5, 51552 }, { 4, 1, 24, 54440 }, { 0, 2, 12, 54432 }, { 0, 2, 1, 55888 }, { 2, 1, 22, 23208 }, { 0, 2, 9, 22176 }, { 7, 1, 29, 43736 }, { 0, 2, 18, 9680 }, { 0, 2, 7, 37584 }, { 5, 1, 26, 51544 }, { 0, 2, 14, 43344 }, { 0, 2, 3, 46240 }, { 4, 1, 23, 46416 }, { 0, 2, 10, 44368 }, { 9, 1, 31, 21928 }, { 0, 2, 19, 19360 }, { 0, 2, 8, 42416 }, { 6, 1, 28, 21176 }, { 0, 2, 16, 21168 }, { 0, 2, 5, 43312 }, { 4, 1, 25, 29864 }, { 0, 2, 12, 27296 }, { 0, 2, 1, 44368 }, { 2, 1, 22, 19880 }, { 0, 2, 10, 19296 }, { 6, 1, 29, 42352 }, { 0, 2, 17, 42208 }, { 0, 2, 6, 53856 }, { 5, 1, 26, 59696 }, { 0, 2, 13, 54576 }, { 0, 2, 3, 23200 }, { 3, 1, 23, 27472 }, { 0, 2, 11, 38608 }, { 11, 1, 31, 19176 }, { 0, 2, 19, 19152 }, { 0, 2, 8, 42192 }, { 6, 1, 28, 53848 }, { 0, 2, 15, 53840 }, { 0, 2, 4, 54560 }, { 5, 1, 24, 55968 }, { 0, 2, 12, 46496 }, { 0, 2, 1, 22224 }, { 2, 1, 22, 19160 }, { 0, 2, 10, 18864 }, { 7, 1, 30, 42168 }, { 0, 2, 17, 42160 }, { 0, 2, 6, 43600 }, { 5, 1, 26, 46376 }, { 0, 2, 14, 27936 }, { 0, 2, 2, 44448 }, { 3, 1, 23, 21936 } }; public override DateTime MinSupportedDateTime => s_minDate; public override DateTime MaxSupportedDateTime => s_maxDate; protected override int DaysInYearBeforeMinSupportedYear => 384; internal override int MinCalendarYear => 1912; internal override int MaxCalendarYear => 2050; internal override DateTime MinDate => s_minDate; internal override DateTime MaxDate => s_maxDate; internal override EraInfo[]? CalEraInfo => s_taiwanLunisolarEraInfo; internal override CalendarId BaseCalendarID => CalendarId.TAIWAN; internal override CalendarId ID => CalendarId.TAIWANLUNISOLAR; public override int[] Eras => _helper.Eras; internal override int GetYearInfo(int lunarYear, int index) { if (lunarYear < 1912 || lunarYear > 2050) { throw new ArgumentOutOfRangeException("year", lunarYear, SR.Format(SR.ArgumentOutOfRange_Range, 1912, 2050)); } return s_yinfo[lunarYear - 1912, index]; } internal override int GetYear(int year, DateTime time) { return _helper.GetYear(year, time); } internal override int GetGregorianYear(int year, int era) { return _helper.GetGregorianYear(year, era); } public TaiwanLunisolarCalendar() { _helper = new GregorianCalendarHelper(this, s_taiwanLunisolarEraInfo); } public override int GetEra(DateTime time) { return _helper.GetEra(time); } } public class TextElementEnumerator : System.Collections.IEnumerator { private readonly string _str; private readonly int _strStartIndex; private int _currentTextElementOffset; private int _currentTextElementLength; private string _currentTextElementSubstr; public object Current => GetTextElement(); public int ElementIndex { get { if (_currentTextElementOffset >= _str.Length) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _currentTextElementOffset - _strStartIndex; } } internal TextElementEnumerator(string str, int startIndex) { _str = str; _strStartIndex = startIndex; Reset(); } public bool MoveNext() { _currentTextElementSubstr = null; int num = (_currentTextElementOffset += _currentTextElementLength); _currentTextElementLength = 0; if (num >= _str.Length) { return false; } _currentTextElementLength = TextSegmentationUtility.GetLengthOfFirstUtf16ExtendedGraphemeCluster(_str.AsSpan(num)); return true; } public string GetTextElement() { string text = _currentTextElementSubstr; if (text == null) { if (_currentTextElementOffset >= _str.Length) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } text = (_currentTextElementSubstr = _str.Substring(_currentTextElementOffset, _currentTextElementLength)); } return text; } public void Reset() { _currentTextElementOffset = _str.Length; _currentTextElementLength = _strStartIndex - _str.Length; _currentTextElementSubstr = null; } } public sealed class TextInfo : ICloneable, IDeserializationCallback { private enum Tristate : byte { NotInitialized, False, True } [StructLayout(LayoutKind.Sequential, Size = 1)] private readonly struct ToUpperConversion { } [StructLayout(LayoutKind.Sequential, Size = 1)] private readonly struct ToLowerConversion { } private string _listSeparator; private bool _isReadOnly; private readonly string _cultureName; private readonly CultureData _cultureData; private readonly string _textInfoName; private Tristate _isAsciiCasingSameAsInvariant; internal static readonly TextInfo Invariant = new TextInfo(CultureData.Invariant, readOnly: true) { _isAsciiCasingSameAsInvariant = Tristate.True }; private Tristate _needsTurkishCasing; private IntPtr _sortHandle; public int ANSICodePage => _cultureData.ANSICodePage; public int OEMCodePage => _cultureData.OEMCodePage; public int MacCodePage => _cultureData.MacCodePage; public int EBCDICCodePage => _cultureData.EBCDICCodePage; public int LCID => CultureInfo.GetCultureInfo(_textInfoName).LCID; public string CultureName => _textInfoName; public bool IsReadOnly => _isReadOnly; public string ListSeparator { get { return _listSeparator ?? (_listSeparator = _cultureData.ListSeparator); } set { if (value == null) { throw new ArgumentNullException("value"); } VerifyWritable(); _listSeparator = value; } } private bool IsAsciiCasingSameAsInvariant { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (_isAsciiCasingSameAsInvariant == Tristate.NotInitialized) { PopulateIsAsciiCasingSameAsInvariant(); } return _isAsciiCasingSameAsInvariant == Tristate.True; } } public bool IsRightToLeft => _cultureData.IsRightToLeft; private bool IsInvariant => _cultureName.Length == 0; internal TextInfo(CultureData cultureData) { _cultureData = cultureData; _cultureName = _cultureData.CultureName; _textInfoName = _cultureData.TextInfoName; if (GlobalizationMode.UseNls) { _sortHandle = CompareInfo.NlsGetSortHandle(_textInfoName); } } private TextInfo(CultureData cultureData, bool readOnly) : this(cultureData) { SetReadOnlyState(readOnly); } void IDeserializationCallback.OnDeserialization(object sender) { throw new PlatformNotSupportedException(); } public object Clone() { object obj = MemberwiseClone(); ((TextInfo)obj).SetReadOnlyState(readOnly: false); return obj; } public static TextInfo ReadOnly(TextInfo textInfo) { if (textInfo == null) { throw new ArgumentNullException("textInfo"); } if (textInfo.IsReadOnly) { return textInfo; } TextInfo textInfo2 = (TextInfo)textInfo.MemberwiseClone(); textInfo2.SetReadOnlyState(readOnly: true); return textInfo2; } private void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } internal void SetReadOnlyState(bool readOnly) { _isReadOnly = readOnly; } public char ToLower(char c) { if (GlobalizationMode.Invariant) { return InvariantModeCasing.ToLower(c); } if (UnicodeUtility.IsAsciiCodePoint(c) && IsAsciiCasingSameAsInvariant) { return ToLowerAsciiInvariant(c); } return ChangeCase(c, toUpper: false); } internal static char ToLowerInvariant(char c) { if (GlobalizationMode.Invariant) { return InvariantModeCasing.ToLower(c); } if (UnicodeUtility.IsAsciiCodePoint(c)) { return ToLowerAsciiInvariant(c); } return Invariant.ChangeCase(c, toUpper: false); } public string ToLower(string str) { if (str == null) { throw new ArgumentNullException("str"); } if (GlobalizationMode.Invariant) { return InvariantModeCasing.ToLower(str); } return ChangeCaseCommon(str); } private unsafe char ChangeCase(char c, bool toUpper) { char result = '\0'; ChangeCaseCore(&c, 1, &result, 1, toUpper); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ChangeCaseToLower(ReadOnlySpan source, Span destination) { ChangeCaseCommon(ref MemoryMarshal.GetReference(source), ref MemoryMarshal.GetReference(destination), source.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ChangeCaseToUpper(ReadOnlySpan source, Span destination) { ChangeCaseCommon(ref MemoryMarshal.GetReference(source), ref MemoryMarshal.GetReference(destination), source.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ChangeCaseCommon(ReadOnlySpan source, Span destination) where TConversion : struct { ChangeCaseCommon(ref MemoryMarshal.GetReference(source), ref MemoryMarshal.GetReference(destination), source.Length); } private unsafe void ChangeCaseCommon(ref char source, ref char destination, int charCount) where TConversion : struct { bool flag = typeof(TConversion) == typeof(ToUpperConversion); if (charCount == 0) { return; } fixed (char* ptr = &source) { fixed (char* ptr2 = &destination) { nuint num = 0u; if (IsAsciiCasingSameAsInvariant) { if (charCount < 4) { goto IL_00e5; } nuint num2 = (uint)(charCount - 4); while (true) { uint value = Unsafe.ReadUnaligned(ptr + num); if (!Utf16Utility.AllCharsInUInt32AreAscii(value)) { break; } value = (flag ? Utf16Utility.ConvertAllAsciiCharsInUInt32ToUppercase(value) : Utf16Utility.ConvertAllAsciiCharsInUInt32ToLowercase(value)); Unsafe.WriteUnaligned(ptr2 + num, value); value = Unsafe.ReadUnaligned(ptr + num + 2); if (Utf16Utility.AllCharsInUInt32AreAscii(value)) { value = (flag ? Utf16Utility.ConvertAllAsciiCharsInUInt32ToUppercase(value) : Utf16Utility.ConvertAllAsciiCharsInUInt32ToLowercase(value)); Unsafe.WriteUnaligned(ptr2 + num + 2, value); num += 4; if (num <= num2) { continue; } goto IL_00e5; } num += 2; break; } goto IL_0171; } goto IL_0178; IL_0178: ChangeCaseCore(ptr + num, charCount, ptr2 + num, charCount, flag); return; IL_0171: charCount -= (int)num; goto IL_0178; IL_00e5: if (((uint)charCount & 2u) != 0) { uint value2 = Unsafe.ReadUnaligned(ptr + num); if (!Utf16Utility.AllCharsInUInt32AreAscii(value2)) { goto IL_0171; } value2 = (flag ? Utf16Utility.ConvertAllAsciiCharsInUInt32ToUppercase(value2) : Utf16Utility.ConvertAllAsciiCharsInUInt32ToLowercase(value2)); Unsafe.WriteUnaligned(ptr2 + num, value2); num += 2; } if (((uint)charCount & (true ? 1u : 0u)) != 0) { uint num3 = ptr[num]; if (num3 <= 127) { num3 = (flag ? Utf16Utility.ConvertAllAsciiCharsInUInt32ToUppercase(num3) : Utf16Utility.ConvertAllAsciiCharsInUInt32ToLowercase(num3)); ptr2[num] = (char)num3; return; } goto IL_0171; } } } } private unsafe string ChangeCaseCommon(string source) where TConversion : struct { bool flag = typeof(TConversion) == typeof(ToUpperConversion); if (source.Length == 0) { return string.Empty; } fixed (char* ptr = source) { nuint num = 0u; if (IsAsciiCasingSameAsInvariant) { if (source.Length < 2) { goto IL_0095; } nuint num2 = (uint)(source.Length - 2); while (true) { uint value = Unsafe.ReadUnaligned(ptr + num); if (!Utf16Utility.AllCharsInUInt32AreAscii(value)) { break; } if (!(flag ? Utf16Utility.UInt32ContainsAnyLowercaseAsciiChar(value) : Utf16Utility.UInt32ContainsAnyUppercaseAsciiChar(value))) { num += 2; if (num <= num2) { continue; } goto IL_0095; } goto IL_00d1; } } goto IL_0121; IL_00d1: string text = string.FastAllocateString(source.Length); Span destination = new Span(ref text.GetRawStringData(), text.Length); source.AsSpan(0, (int)num).CopyTo(destination); ChangeCaseCommon(source.AsSpan((int)num), destination.Slice((int)num)); return text; IL_0095: if (((uint)source.Length & (true ? 1u : 0u)) != 0) { uint num3 = ptr[num]; if (num3 > 127) { goto IL_0121; } if (flag ? (num3 - 97 <= 25) : (num3 - 65 <= 25)) { goto IL_00d1; } } return source; IL_0121: string text2 = string.FastAllocateString(source.Length); if (num != 0) { Span destination2 = new Span(ref text2.GetRawStringData(), text2.Length); source.AsSpan(0, (int)num).CopyTo(destination2); } fixed (char* ptr2 = text2) { ChangeCaseCore(ptr + num, source.Length - (int)num, ptr2 + num, text2.Length - (int)num, flag); } return text2; } } internal unsafe static string ToLowerAsciiInvariant(string s) { if (s.Length == 0) { return string.Empty; } fixed (char* ptr = s) { int i; for (i = 0; i < s.Length && (uint)(ptr[i] - 65) > 25u; i++) { } if (i >= s.Length) { return s; } string text = string.FastAllocateString(s.Length); fixed (char* ptr2 = text) { for (int j = 0; j < i; j++) { ptr2[j] = ptr[j]; } ptr2[i] = (char)(ptr[i] | 0x20u); for (i++; i < s.Length; i++) { ptr2[i] = ToLowerAsciiInvariant(ptr[i]); } } return text; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static char ToLowerAsciiInvariant(char c) { if (UnicodeUtility.IsInRangeInclusive(c, 65u, 90u)) { c = (char)(byte)(c | 0x20u); } return c; } public char ToUpper(char c) { if (GlobalizationMode.Invariant) { return InvariantModeCasing.ToUpper(c); } if (UnicodeUtility.IsAsciiCodePoint(c) && IsAsciiCasingSameAsInvariant) { return ToUpperAsciiInvariant(c); } return ChangeCase(c, toUpper: true); } internal static char ToUpperInvariant(char c) { if (GlobalizationMode.Invariant) { return InvariantModeCasing.ToUpper(c); } if (UnicodeUtility.IsAsciiCodePoint(c)) { return ToUpperAsciiInvariant(c); } return Invariant.ChangeCase(c, toUpper: true); } public string ToUpper(string str) { if (str == null) { throw new ArgumentNullException("str"); } if (GlobalizationMode.Invariant) { return InvariantModeCasing.ToUpper(str); } return ChangeCaseCommon(str); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static char ToUpperAsciiInvariant(char c) { if (UnicodeUtility.IsInRangeInclusive(c, 97u, 122u)) { c = (char)(c & 0x5Fu); } return c; } [MethodImpl(MethodImplOptions.NoInlining)] private void PopulateIsAsciiCasingSameAsInvariant() { bool flag = CultureInfo.GetCultureInfo(_textInfoName).CompareInfo.Compare("abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", CompareOptions.IgnoreCase) == 0; _isAsciiCasingSameAsInvariant = ((!flag) ? Tristate.False : Tristate.True); } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is TextInfo textInfo) { return CultureName.Equals(textInfo.CultureName); } return false; } public override int GetHashCode() { return CultureName.GetHashCode(); } public override string ToString() { return "TextInfo - " + _cultureData.CultureName; } public string ToTitleCase(string str) { if (str == null) { throw new ArgumentNullException("str"); } if (str.Length == 0) { return str; } StringBuilder result = new StringBuilder(); string text = null; bool flag = CultureName.StartsWith("nl-", StringComparison.OrdinalIgnoreCase); int num; for (num = 0; num < str.Length; num++) { UnicodeCategory unicodeCategoryInternal = CharUnicodeInfo.GetUnicodeCategoryInternal(str, num, out var charLength); if (char.CheckLetter(unicodeCategoryInternal)) { if (flag && num < str.Length - 1 && (str[num] == 'i' || str[num] == 'I') && (str[num + 1] == 'j' || str[num + 1] == 'J')) { result.Append("IJ"); num += 2; } else { num = AddTitlecaseLetter(ref result, ref str, num, charLength) + 1; } int num2 = num; bool flag2 = unicodeCategoryInternal == UnicodeCategory.LowercaseLetter; while (num < str.Length) { unicodeCategoryInternal = CharUnicodeInfo.GetUnicodeCategoryInternal(str, num, out charLength); if (IsLetterCategory(unicodeCategoryInternal)) { if (unicodeCategoryInternal == UnicodeCategory.LowercaseLetter) { flag2 = true; } num += charLength; } else if (str[num] == '\'') { num++; if (flag2) { if (text == null) { text = ToLower(str); } result.Append(text, num2, num - num2); } else { result.Append(str, num2, num - num2); } num2 = num; flag2 = true; } else { if (IsWordSeparator(unicodeCategoryInternal)) { break; } num += charLength; } } int num3 = num - num2; if (num3 > 0) { if (flag2) { if (text == null) { text = ToLower(str); } result.Append(text, num2, num3); } else { result.Append(str, num2, num3); } } if (num < str.Length) { num = AddNonLetter(ref result, ref str, num, charLength); } } else { num = AddNonLetter(ref result, ref str, num, charLength); } } return result.ToString(); } private static int AddNonLetter(ref StringBuilder result, ref string input, int inputIndex, int charLen) { if (charLen == 2) { result.Append(input[inputIndex++]); result.Append(input[inputIndex]); } else { result.Append(input[inputIndex]); } return inputIndex; } private int AddTitlecaseLetter(ref StringBuilder result, ref string input, int inputIndex, int charLen) { if (charLen == 2) { ReadOnlySpan source = input.AsSpan(inputIndex, 2); if (GlobalizationMode.Invariant) { SurrogateCasing.ToUpper(source[0], source[1], out var hr, out var lr); result.Append(hr); result.Append(lr); } else { Span span = stackalloc char[2]; ChangeCaseToUpper(source, span); result.Append(span); } inputIndex++; } else { switch (input[inputIndex]) { case 'DŽ': case 'Dž': case 'dž': result.Append('Dž'); break; case 'LJ': case 'Lj': case 'lj': result.Append('Lj'); break; case 'NJ': case 'Nj': case 'nj': result.Append('Nj'); break; case 'DZ': case 'Dz': case 'dz': result.Append('Dz'); break; default: result.Append(GlobalizationMode.Invariant ? InvariantModeCasing.ToUpper(input[inputIndex]) : ToUpper(input[inputIndex])); break; } } return inputIndex; } private unsafe void ChangeCaseCore(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper) { if (GlobalizationMode.UseNls) { NlsChangeCase(src, srcLen, dstBuffer, dstBufferCapacity, bToUpper); } else { IcuChangeCase(src, srcLen, dstBuffer, dstBufferCapacity, bToUpper); } } private static bool IsWordSeparator(UnicodeCategory category) { return (0x1FFCF800 & (1 << (int)category)) != 0; } private static bool IsLetterCategory(UnicodeCategory uc) { if (uc != 0 && uc != UnicodeCategory.LowercaseLetter && uc != UnicodeCategory.TitlecaseLetter && uc != UnicodeCategory.ModifierLetter) { return uc == UnicodeCategory.OtherLetter; } return true; } private static bool NeedsTurkishCasing(string localeName) { return CultureInfo.GetCultureInfo(localeName).CompareInfo.Compare("ı", "I", CompareOptions.IgnoreCase) == 0; } internal unsafe void IcuChangeCase(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper) { if (IsInvariant) { Interop.Globalization.ChangeCaseInvariant(src, srcLen, dstBuffer, dstBufferCapacity, bToUpper); return; } if (_needsTurkishCasing == Tristate.NotInitialized) { _needsTurkishCasing = ((!NeedsTurkishCasing(_textInfoName)) ? Tristate.False : Tristate.True); } if (_needsTurkishCasing == Tristate.True) { Interop.Globalization.ChangeCaseTurkish(src, srcLen, dstBuffer, dstBufferCapacity, bToUpper); } else { Interop.Globalization.ChangeCase(src, srcLen, dstBuffer, dstBufferCapacity, bToUpper); } } private unsafe void NlsChangeCase(char* pSource, int pSourceLen, char* pResult, int pResultLen, bool toUpper) { uint num = ((!IsInvariantLocale(_textInfoName)) ? 16777216u : 0u); if (Interop.Kernel32.LCMapStringEx((_sortHandle != IntPtr.Zero) ? null : _textInfoName, num | (toUpper ? 512u : 256u), pSource, pSourceLen, pResult, pSourceLen, null, null, _sortHandle) == 0) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } private static bool IsInvariantLocale(string localeName) { return localeName == ""; } } public class ThaiBuddhistCalendar : Calendar { private static readonly EraInfo[] s_thaiBuddhistEraInfo = new EraInfo[1] { new EraInfo(1, 1, 1, 1, -543, 544, 10542) }; public const int ThaiBuddhistEra = 1; private readonly GregorianCalendarHelper _helper; public override DateTime MinSupportedDateTime => DateTime.MinValue; public override DateTime MaxSupportedDateTime => DateTime.MaxValue; public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.SolarCalendar; internal override CalendarId ID => CalendarId.THAI; public override int[] Eras => _helper.Eras; public override int TwoDigitYearMax { get { if (_twoDigitYearMax == -1) { _twoDigitYearMax = Calendar.GetSystemTwoDigitYearSetting(ID, 2572); } return _twoDigitYearMax; } set { VerifyWritable(); if (value < 99 || value > _helper.MaxYear) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 99, _helper.MaxYear)); } _twoDigitYearMax = value; } } public ThaiBuddhistCalendar() { _helper = new GregorianCalendarHelper(this, s_thaiBuddhistEraInfo); } public override DateTime AddMonths(DateTime time, int months) { return _helper.AddMonths(time, months); } public override DateTime AddYears(DateTime time, int years) { return _helper.AddYears(time, years); } public override int GetDaysInMonth(int year, int month, int era) { return _helper.GetDaysInMonth(year, month, era); } public override int GetDaysInYear(int year, int era) { return _helper.GetDaysInYear(year, era); } public override int GetDayOfMonth(DateTime time) { return _helper.GetDayOfMonth(time); } public override DayOfWeek GetDayOfWeek(DateTime time) { return _helper.GetDayOfWeek(time); } public override int GetDayOfYear(DateTime time) { return _helper.GetDayOfYear(time); } public override int GetMonthsInYear(int year, int era) { return _helper.GetMonthsInYear(year, era); } public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return _helper.GetWeekOfYear(time, rule, firstDayOfWeek); } public override int GetEra(DateTime time) { return _helper.GetEra(time); } public override int GetMonth(DateTime time) { return _helper.GetMonth(time); } public override int GetYear(DateTime time) { return _helper.GetYear(time); } public override bool IsLeapDay(int year, int month, int day, int era) { return _helper.IsLeapDay(year, month, day, era); } public override bool IsLeapYear(int year, int era) { return _helper.IsLeapYear(year, era); } public override int GetLeapMonth(int year, int era) { return _helper.GetLeapMonth(year, era); } public override bool IsLeapMonth(int year, int month, int era) { return _helper.IsLeapMonth(year, month, era); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return _helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era); } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", year, SR.ArgumentOutOfRange_NeedNonNegNum); } return _helper.ToFourDigitYear(year, TwoDigitYearMax); } } internal static class TimeSpanFormat { private enum StandardFormat { C, G, g } internal struct FormatLiterals { internal string AppCompatLiteral; internal int dd; internal int hh; internal int mm; internal int ss; internal int ff; private string[] _literals; internal string Start => _literals[0]; internal string DayHourSep => _literals[1]; internal string HourMinuteSep => _literals[2]; internal string MinuteSecondSep => _literals[3]; internal string SecondFractionSep => _literals[4]; internal string End => _literals[5]; internal static FormatLiterals InitInvariant(bool isNegative) { FormatLiterals result = default(FormatLiterals); result._literals = new string[6]; result._literals[0] = (isNegative ? "-" : string.Empty); result._literals[1] = "."; result._literals[2] = ":"; result._literals[3] = ":"; result._literals[4] = "."; result._literals[5] = string.Empty; result.AppCompatLiteral = ":."; result.dd = 2; result.hh = 2; result.mm = 2; result.ss = 2; result.ff = 7; return result; } internal void Init(ReadOnlySpan format, bool useInvariantFieldLengths) { dd = (hh = (mm = (ss = (ff = 0)))); _literals = new string[6]; for (int i = 0; i < _literals.Length; i++) { _literals[i] = string.Empty; } StringBuilder stringBuilder = StringBuilderCache.Acquire(); bool flag = false; char c = '\''; int num = 0; for (int j = 0; j < format.Length; j++) { switch (format[j]) { case '"': case '\'': if (flag && c == format[j]) { if (num < 0 || num > 5) { return; } _literals[num] = stringBuilder.ToString(); stringBuilder.Length = 0; flag = false; } else if (!flag) { c = format[j]; flag = true; } continue; case '\\': if (!flag) { j++; continue; } break; case 'd': if (!flag) { num = 1; dd++; } continue; case 'h': if (!flag) { num = 2; hh++; } continue; case 'm': if (!flag) { num = 3; mm++; } continue; case 's': if (!flag) { num = 4; ss++; } continue; case 'F': case 'f': if (!flag) { num = 5; ff++; } continue; } stringBuilder.Append(format[j]); } AppCompatLiteral = MinuteSecondSep + SecondFractionSep; if (useInvariantFieldLengths) { dd = 2; hh = 2; mm = 2; ss = 2; ff = 7; } else { if (dd < 1 || dd > 2) { dd = 2; } if (hh < 1 || hh > 2) { hh = 2; } if (mm < 1 || mm > 2) { mm = 2; } if (ss < 1 || ss > 2) { ss = 2; } if (ff < 1 || ff > 7) { ff = 7; } } StringBuilderCache.Release(stringBuilder); } } internal static readonly FormatLiterals PositiveInvariantFormatLiterals = FormatLiterals.InitInvariant(isNegative: false); internal static readonly FormatLiterals NegativeInvariantFormatLiterals = FormatLiterals.InitInvariant(isNegative: true); internal static string Format(TimeSpan value, string format, IFormatProvider formatProvider) { if (string.IsNullOrEmpty(format)) { return FormatC(value); } if (format.Length == 1) { char c = format[0]; if (c == 'c' || (c | 0x20) == 116) { return FormatC(value); } if ((c | 0x20) == 103) { return FormatG(value, DateTimeFormatInfo.GetInstance(formatProvider), (c == 'G') ? StandardFormat.G : StandardFormat.g); } throw new FormatException(SR.Format_InvalidString); } return StringBuilderCache.GetStringAndRelease(FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider))); } internal static bool TryFormat(TimeSpan value, Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider formatProvider) { if (format.Length == 0) { return TryFormatStandard(value, StandardFormat.C, null, destination, out charsWritten); } if (format.Length == 1) { char c = format[0]; if (c == 'c' || (c | 0x20) == 116) { return TryFormatStandard(value, StandardFormat.C, null, destination, out charsWritten); } return TryFormatStandard(value, c switch { 'G' => StandardFormat.G, 'g' => StandardFormat.g, _ => throw new FormatException(SR.Format_InvalidString), }, DateTimeFormatInfo.GetInstance(formatProvider).DecimalSeparator, destination, out charsWritten); } StringBuilder stringBuilder = FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider)); if (stringBuilder.Length <= destination.Length) { stringBuilder.CopyTo(0, destination, stringBuilder.Length); charsWritten = stringBuilder.Length; StringBuilderCache.Release(stringBuilder); return true; } charsWritten = 0; StringBuilderCache.Release(stringBuilder); return false; } internal static string FormatC(TimeSpan value) { Span destination = stackalloc char[26]; TryFormatStandard(value, StandardFormat.C, null, destination, out var charsWritten); return new string(destination.Slice(0, charsWritten)); } private static string FormatG(TimeSpan value, DateTimeFormatInfo dtfi, StandardFormat format) { string decimalSeparator = dtfi.DecimalSeparator; int num = 25 + decimalSeparator.Length; Span span = ((num >= 128) ? ((Span)new char[num]) : stackalloc char[num]); Span destination = span; TryFormatStandard(value, format, decimalSeparator, destination, out var charsWritten); return new string(destination.Slice(0, charsWritten)); } private static bool TryFormatStandard(TimeSpan value, StandardFormat format, string decimalSeparator, Span destination, out int charsWritten) { int num = 8; long num2 = value.Ticks; uint valueWithoutTrailingZeros; ulong num3; if (num2 < 0) { num = 9; num2 = -num2; if (num2 < 0) { valueWithoutTrailingZeros = 4775808u; num3 = 922337203685uL; goto IL_0050; } } (ulong Quotient, ulong Remainder) tuple = Math.DivRem((ulong)num2, 10000000uL); num3 = tuple.Quotient; ulong item = tuple.Remainder; valueWithoutTrailingZeros = (uint)item; goto IL_0050; IL_0050: int num4 = 0; switch (format) { case StandardFormat.C: if (valueWithoutTrailingZeros != 0) { num4 = 7; num += num4 + 1; } break; case StandardFormat.G: num4 = 7; num += num4 + 1; break; default: if (valueWithoutTrailingZeros != 0) { num4 = 7 - FormattingHelpers.CountDecimalTrailingZeros(valueWithoutTrailingZeros, out valueWithoutTrailingZeros); num += num4 + 1; } break; } ulong num5 = 0uL; ulong num6 = 0uL; if (num3 != 0) { (num5, num6) = Math.DivRem(num3, 60uL); } ulong num7 = 0uL; ulong num8 = 0uL; if (num5 != 0) { (num7, num8) = Math.DivRem(num5, 60uL); } uint num9 = 0u; uint num10 = 0u; if (num7 != 0) { (num9, num10) = Math.DivRem((uint)num7, 24u); } int num11 = 2; if (format == StandardFormat.g && num10 < 10) { num11 = 1; num--; } int num12 = 0; if (num9 != 0) { num12 = FormattingHelpers.CountDigits(num9); num += num12 + 1; } else if (format == StandardFormat.G) { num += 2; num12 = 1; } if (destination.Length < num) { charsWritten = 0; return false; } int num13 = 0; if (value.Ticks < 0) { destination[num13++] = '-'; } if (num12 != 0) { WriteDigits(num9, destination.Slice(num13, num12)); num13 += num12; destination[num13++] = ((format == StandardFormat.C) ? '.' : ':'); } if (num11 == 2) { WriteTwoDigits(num10, destination.Slice(num13)); num13 += 2; } else { destination[num13++] = (char)(48 + num10); } destination[num13++] = ':'; WriteTwoDigits((uint)num8, destination.Slice(num13)); num13 += 2; destination[num13++] = ':'; WriteTwoDigits((uint)num6, destination.Slice(num13)); num13 += 2; if (num4 != 0) { if (format == StandardFormat.C) { destination[num13++] = '.'; } else if (decimalSeparator.Length == 1) { destination[num13++] = decimalSeparator[0]; } else { decimalSeparator.CopyTo(destination); num13 += decimalSeparator.Length; } WriteDigits(valueWithoutTrailingZeros, destination.Slice(num13, num4)); num13 += num4; } charsWritten = num; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteTwoDigits(uint value, Span buffer) { uint num = 48 + value; value /= 10; buffer[1] = (char)(num - value * 10); buffer[0] = (char)(48 + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteDigits(uint value, Span buffer) { for (int num = buffer.Length - 1; num >= 1; num--) { uint num2 = 48 + value; value /= 10; buffer[num] = (char)(num2 - value * 10); } buffer[0] = (char)(48 + value); } private static StringBuilder FormatCustomized(TimeSpan value, ReadOnlySpan format, DateTimeFormatInfo dtfi, StringBuilder result = null) { bool flag = false; if (result == null) { result = StringBuilderCache.Acquire(); flag = true; } int num = (int)(value.Ticks / 864000000000L); long num2 = value.Ticks % 864000000000L; if (value.Ticks < 0) { num = -num; num2 = -num2; } int value2 = (int)(num2 / 36000000000L % 24); int value3 = (int)(num2 / 600000000 % 60); int value4 = (int)(num2 / 10000000 % 60); int num3 = (int)(num2 % 10000000); long num4 = 0L; int num6; for (int i = 0; i < format.Length; i += num6) { char c = format[i]; switch (c) { case 'h': num6 = DateTimeFormat.ParseRepeatPattern(format, i, c); if (num6 <= 2) { DateTimeFormat.FormatDigits(result, value2, num6); continue; } break; case 'm': num6 = DateTimeFormat.ParseRepeatPattern(format, i, c); if (num6 <= 2) { DateTimeFormat.FormatDigits(result, value3, num6); continue; } break; case 's': num6 = DateTimeFormat.ParseRepeatPattern(format, i, c); if (num6 <= 2) { DateTimeFormat.FormatDigits(result, value4, num6); continue; } break; case 'f': num6 = DateTimeFormat.ParseRepeatPattern(format, i, c); if (num6 <= 7) { num4 = num3; num4 /= TimeSpanParse.Pow10(7 - num6); result.AppendSpanFormattable(num4, DateTimeFormat.fixedNumberFormats[num6 - 1], CultureInfo.InvariantCulture); continue; } break; case 'F': num6 = DateTimeFormat.ParseRepeatPattern(format, i, c); if (num6 <= 7) { num4 = num3; num4 /= TimeSpanParse.Pow10(7 - num6); int num7 = num6; while (num7 > 0 && num4 % 10 == 0L) { num4 /= 10; num7--; } if (num7 > 0) { result.AppendSpanFormattable(num4, DateTimeFormat.fixedNumberFormats[num7 - 1], CultureInfo.InvariantCulture); } continue; } break; case 'd': num6 = DateTimeFormat.ParseRepeatPattern(format, i, c); if (num6 <= 8) { DateTimeFormat.FormatDigits(result, num, num6, overrideLengthLimit: true); continue; } break; case '"': case '\'': num6 = DateTimeFormat.ParseQuoteString(format, i, result); continue; case '%': { int num5 = DateTimeFormat.ParseNextChar(format, i); if (num5 >= 0 && num5 != 37) { char reference = (char)num5; StringBuilder stringBuilder = FormatCustomized(value, MemoryMarshal.CreateReadOnlySpan(ref reference, 1), dtfi, result); num6 = 2; continue; } break; } case '\\': { int num5 = DateTimeFormat.ParseNextChar(format, i); if (num5 >= 0) { result.Append((char)num5); num6 = 2; continue; } break; } } if (flag) { StringBuilderCache.Release(result); } throw new FormatException(SR.Format_InvalidString); } return result; } } internal static class TimeSpanParse { [Flags] private enum TimeSpanStandardStyles : byte { None = 0, Invariant = 1, Localized = 2, RequireFull = 4, Any = 3 } private enum TTT : byte { None, End, Num, Sep, NumOverflow } private ref struct TimeSpanToken { internal TTT _ttt; internal int _num; internal int _zeroes; internal ReadOnlySpan _sep; public TimeSpanToken(TTT type) : this(type, 0, 0, default(ReadOnlySpan)) { } public TimeSpanToken(int number) : this(TTT.Num, number, 0, default(ReadOnlySpan)) { } public TimeSpanToken(int number, int leadingZeroes) : this(TTT.Num, number, leadingZeroes, default(ReadOnlySpan)) { } public TimeSpanToken(TTT type, int number, int leadingZeroes, ReadOnlySpan separator) { _ttt = type; _num = number; _zeroes = leadingZeroes; _sep = separator; } public bool NormalizeAndValidateFraction() { if (_num == 0) { return true; } if (_zeroes == 0 && _num > 9999999) { return false; } int num = (int)Math.Floor(Math.Log10(_num)) + 1 + _zeroes; if (num == 7) { return true; } if (num < 7) { _num *= (int)Pow10(7 - num); return true; } _num = (int)Math.Round((double)_num / (double)Pow10(num - 7), MidpointRounding.AwayFromZero); return true; } } private ref struct TimeSpanTokenizer { private readonly ReadOnlySpan _value; private int _pos; internal bool EOL => _pos >= _value.Length - 1; internal char NextChar { get { int num = ++_pos; if ((uint)num >= (uint)_value.Length) { return '\0'; } return _value[num]; } } internal TimeSpanTokenizer(ReadOnlySpan input) : this(input, 0) { } internal TimeSpanTokenizer(ReadOnlySpan input, int startPosition) { _value = input; _pos = startPosition; } internal TimeSpanToken GetNextToken() { int pos = _pos; if (pos >= _value.Length) { return new TimeSpanToken(TTT.End); } int num = _value[pos] - 48; if ((uint)num <= 9u) { int num2 = 0; if (num == 0) { num2 = 1; int num3; while (true) { if (++_pos >= _value.Length || (uint)(num3 = _value[_pos] - 48) > 9u) { return new TimeSpanToken(TTT.Num, 0, num2, default(ReadOnlySpan)); } if (num3 != 0) { break; } num2++; } num = num3; } while (++_pos < _value.Length) { int num4 = _value[_pos] - 48; if ((uint)num4 > 9u) { break; } num = num * 10 + num4; if ((num & 0xF0000000u) != 0L) { return new TimeSpanToken(TTT.NumOverflow); } } return new TimeSpanToken(TTT.Num, num, num2, default(ReadOnlySpan)); } int num5 = 1; while (++_pos < _value.Length && (uint)(_value[_pos] - 48) > 9u) { num5++; } return new TimeSpanToken(TTT.Sep, 0, 0, _value.Slice(pos, num5)); } internal void BackOne() { if (_pos > 0) { _pos--; } } } private ref struct TimeSpanRawInfo { internal TTT _lastSeenTTT; internal int _tokenCount; internal int _sepCount; internal int _numCount; private TimeSpanFormat.FormatLiterals _posLoc; private TimeSpanFormat.FormatLiterals _negLoc; private bool _posLocInit; private bool _negLocInit; private string _fullPosPattern; private string _fullNegPattern; internal TimeSpanToken _numbers0; internal TimeSpanToken _numbers1; internal TimeSpanToken _numbers2; internal TimeSpanToken _numbers3; internal TimeSpanToken _numbers4; internal ReadOnlySpan _literals0; internal ReadOnlySpan _literals1; internal ReadOnlySpan _literals2; internal ReadOnlySpan _literals3; internal ReadOnlySpan _literals4; internal ReadOnlySpan _literals5; internal TimeSpanFormat.FormatLiterals PositiveLocalized { get { if (!_posLocInit) { _posLoc = default(TimeSpanFormat.FormatLiterals); _posLoc.Init(_fullPosPattern, useInvariantFieldLengths: false); _posLocInit = true; } return _posLoc; } } internal TimeSpanFormat.FormatLiterals NegativeLocalized { get { if (!_negLocInit) { _negLoc = default(TimeSpanFormat.FormatLiterals); _negLoc.Init(_fullNegPattern, useInvariantFieldLengths: false); _negLocInit = true; } return _negLoc; } } internal bool FullAppCompatMatch(TimeSpanFormat.FormatLiterals pattern) { if (_sepCount == 5 && _numCount == 4 && _literals0.EqualsOrdinal(pattern.Start) && _literals1.EqualsOrdinal(pattern.DayHourSep) && _literals2.EqualsOrdinal(pattern.HourMinuteSep) && _literals3.EqualsOrdinal(pattern.AppCompatLiteral)) { return _literals4.EqualsOrdinal(pattern.End); } return false; } internal bool PartialAppCompatMatch(TimeSpanFormat.FormatLiterals pattern) { if (_sepCount == 4 && _numCount == 3 && _literals0.EqualsOrdinal(pattern.Start) && _literals1.EqualsOrdinal(pattern.HourMinuteSep) && _literals2.EqualsOrdinal(pattern.AppCompatLiteral)) { return _literals3.EqualsOrdinal(pattern.End); } return false; } internal bool FullMatch(TimeSpanFormat.FormatLiterals pattern) { if (_sepCount == 6 && _numCount == 5 && _literals0.EqualsOrdinal(pattern.Start) && _literals1.EqualsOrdinal(pattern.DayHourSep) && _literals2.EqualsOrdinal(pattern.HourMinuteSep) && _literals3.EqualsOrdinal(pattern.MinuteSecondSep) && _literals4.EqualsOrdinal(pattern.SecondFractionSep)) { return _literals5.EqualsOrdinal(pattern.End); } return false; } internal bool FullDMatch(TimeSpanFormat.FormatLiterals pattern) { if (_sepCount == 2 && _numCount == 1 && _literals0.EqualsOrdinal(pattern.Start)) { return _literals1.EqualsOrdinal(pattern.End); } return false; } internal bool FullHMMatch(TimeSpanFormat.FormatLiterals pattern) { if (_sepCount == 3 && _numCount == 2 && _literals0.EqualsOrdinal(pattern.Start) && _literals1.EqualsOrdinal(pattern.HourMinuteSep)) { return _literals2.EqualsOrdinal(pattern.End); } return false; } internal bool FullDHMMatch(TimeSpanFormat.FormatLiterals pattern) { if (_sepCount == 4 && _numCount == 3 && _literals0.EqualsOrdinal(pattern.Start) && _literals1.EqualsOrdinal(pattern.DayHourSep) && _literals2.EqualsOrdinal(pattern.HourMinuteSep)) { return _literals3.EqualsOrdinal(pattern.End); } return false; } internal bool FullHMSMatch(TimeSpanFormat.FormatLiterals pattern) { if (_sepCount == 4 && _numCount == 3 && _literals0.EqualsOrdinal(pattern.Start) && _literals1.EqualsOrdinal(pattern.HourMinuteSep) && _literals2.EqualsOrdinal(pattern.MinuteSecondSep)) { return _literals3.EqualsOrdinal(pattern.End); } return false; } internal bool FullDHMSMatch(TimeSpanFormat.FormatLiterals pattern) { if (_sepCount == 5 && _numCount == 4 && _literals0.EqualsOrdinal(pattern.Start) && _literals1.EqualsOrdinal(pattern.DayHourSep) && _literals2.EqualsOrdinal(pattern.HourMinuteSep) && _literals3.EqualsOrdinal(pattern.MinuteSecondSep)) { return _literals4.EqualsOrdinal(pattern.End); } return false; } internal bool FullHMSFMatch(TimeSpanFormat.FormatLiterals pattern) { if (_sepCount == 5 && _numCount == 4 && _literals0.EqualsOrdinal(pattern.Start) && _literals1.EqualsOrdinal(pattern.HourMinuteSep) && _literals2.EqualsOrdinal(pattern.MinuteSecondSep) && _literals3.EqualsOrdinal(pattern.SecondFractionSep)) { return _literals4.EqualsOrdinal(pattern.End); } return false; } internal void Init(DateTimeFormatInfo dtfi) { _lastSeenTTT = TTT.None; _tokenCount = 0; _sepCount = 0; _numCount = 0; _fullPosPattern = dtfi.FullTimeSpanPositivePattern; _fullNegPattern = dtfi.FullTimeSpanNegativePattern; _posLocInit = false; _negLocInit = false; } internal bool ProcessToken(ref TimeSpanToken tok, ref TimeSpanResult result) { switch (tok._ttt) { case TTT.Num: if ((_tokenCount == 0 && !AddSep(default(ReadOnlySpan), ref result)) || !AddNum(tok, ref result)) { return false; } break; case TTT.Sep: if (!AddSep(tok._sep, ref result)) { return false; } break; case TTT.NumOverflow: return result.SetOverflowFailure(); default: return result.SetBadTimeSpanFailure(); } _lastSeenTTT = tok._ttt; return true; } private bool AddSep(ReadOnlySpan sep, ref TimeSpanResult result) { if (_sepCount >= 6 || _tokenCount >= 11) { return result.SetBadTimeSpanFailure(); } switch (_sepCount++) { case 0: _literals0 = sep; break; case 1: _literals1 = sep; break; case 2: _literals2 = sep; break; case 3: _literals3 = sep; break; case 4: _literals4 = sep; break; default: _literals5 = sep; break; } _tokenCount++; return true; } private bool AddNum(TimeSpanToken num, ref TimeSpanResult result) { if (_numCount >= 5 || _tokenCount >= 11) { return result.SetBadTimeSpanFailure(); } switch (_numCount++) { case 0: _numbers0 = num; break; case 1: _numbers1 = num; break; case 2: _numbers2 = num; break; case 3: _numbers3 = num; break; default: _numbers4 = num; break; } _tokenCount++; return true; } } private ref struct TimeSpanResult { internal TimeSpan parsedTimeSpan; private readonly bool _throwOnFailure; private readonly ReadOnlySpan _originalTimeSpanString; internal TimeSpanResult(bool throwOnFailure, ReadOnlySpan originalTimeSpanString) { parsedTimeSpan = default(TimeSpan); _throwOnFailure = throwOnFailure; _originalTimeSpanString = originalTimeSpanString; } internal bool SetNoFormatSpecifierFailure() { if (!_throwOnFailure) { return false; } throw new FormatException(SR.Format_NoFormatSpecifier); } internal bool SetBadQuoteFailure(char failingCharacter) { if (!_throwOnFailure) { return false; } throw new FormatException(SR.Format(SR.Format_BadQuote, failingCharacter)); } internal bool SetInvalidStringFailure() { if (!_throwOnFailure) { return false; } throw new FormatException(SR.Format_InvalidString); } internal bool SetArgumentNullFailure(string argumentName) { if (!_throwOnFailure) { return false; } throw new ArgumentNullException(argumentName, SR.ArgumentNull_String); } internal bool SetOverflowFailure() { if (!_throwOnFailure) { return false; } throw new OverflowException(SR.Format(SR.Overflow_TimeSpanElementTooLarge, new string(_originalTimeSpanString))); } internal bool SetBadTimeSpanFailure() { if (!_throwOnFailure) { return false; } throw new FormatException(SR.Format(SR.Format_BadTimeSpan, new string(_originalTimeSpanString))); } internal bool SetBadFormatSpecifierFailure(char? formatSpecifierCharacter = null) { if (!_throwOnFailure) { return false; } throw new FormatException(SR.Format(SR.Format_BadFormatSpecifier, formatSpecifierCharacter)); } } private ref struct StringParser { private ReadOnlySpan _str; private char _ch; private int _pos; private int _len; internal void NextChar() { if (_pos < _len) { _pos++; } _ch = ((_pos < _len) ? _str[_pos] : '\0'); } internal char NextNonDigit() { for (int i = _pos; i < _len; i++) { char c = _str[i]; if (c < '0' || c > '9') { return c; } } return '\0'; } internal bool TryParse(ReadOnlySpan input, ref TimeSpanResult result) { result.parsedTimeSpan = default(TimeSpan); _str = input; _len = input.Length; _pos = -1; NextChar(); SkipBlanks(); bool flag = false; if (_ch == '-') { flag = true; NextChar(); } long time; if (NextNonDigit() == ':') { if (!ParseTime(out time, ref result)) { return false; } } else { if (!ParseInt(10675199, out var i, ref result)) { return false; } time = i * 864000000000L; if (_ch == '.') { NextChar(); if (!ParseTime(out var time2, ref result)) { return false; } time += time2; } } if (flag) { time = -time; if (time > 0) { return result.SetOverflowFailure(); } } else if (time < 0) { return result.SetOverflowFailure(); } SkipBlanks(); if (_pos < _len) { return result.SetBadTimeSpanFailure(); } result.parsedTimeSpan = new TimeSpan(time); return true; } internal bool ParseInt(int max, out int i, ref TimeSpanResult result) { i = 0; int pos = _pos; while (_ch >= '0' && _ch <= '9') { if ((i & 0xF0000000u) != 0L) { return result.SetOverflowFailure(); } i = i * 10 + _ch - 48; if (i < 0) { return result.SetOverflowFailure(); } NextChar(); } if (pos == _pos) { return result.SetBadTimeSpanFailure(); } if (i > max) { return result.SetOverflowFailure(); } return true; } internal bool ParseTime(out long time, ref TimeSpanResult result) { time = 0L; if (!ParseInt(23, out var i, ref result)) { return false; } time = i * 36000000000L; if (_ch != ':') { return result.SetBadTimeSpanFailure(); } NextChar(); if (!ParseInt(59, out i, ref result)) { return false; } time += (long)i * 600000000L; if (_ch == ':') { NextChar(); if (_ch != '.') { if (!ParseInt(59, out i, ref result)) { return false; } time += (long)i * 10000000L; } if (_ch == '.') { NextChar(); int num = 10000000; while (num > 1 && _ch >= '0' && _ch <= '9') { num /= 10; time += (_ch - 48) * num; NextChar(); } } } return true; } internal void SkipBlanks() { while (_ch == ' ' || _ch == '\t') { NextChar(); } } } internal static long Pow10(int pow) { return pow switch { 0 => 1L, 1 => 10L, 2 => 100L, 3 => 1000L, 4 => 10000L, 5 => 100000L, 6 => 1000000L, 7 => 10000000L, _ => (long)Math.Pow(10.0, pow), }; } private static bool TryTimeToTicks(bool positive, TimeSpanToken days, TimeSpanToken hours, TimeSpanToken minutes, TimeSpanToken seconds, TimeSpanToken fraction, out long result) { if (days._num > 10675199 || hours._num > 23 || minutes._num > 59 || seconds._num > 59 || !fraction.NormalizeAndValidateFraction()) { result = 0L; return false; } long num = ((long)days._num * 3600L * 24 + (long)hours._num * 3600L + (long)minutes._num * 60L + seconds._num) * 1000; if (num > 922337203685477L || num < -922337203685477L) { result = 0L; return false; } result = num * 10000 + fraction._num; if (positive && result < 0) { result = 0L; return false; } return true; } internal static TimeSpan Parse(ReadOnlySpan input, IFormatProvider formatProvider) { TimeSpanResult result = new TimeSpanResult(throwOnFailure: true, input); bool flag = TryParseTimeSpan(input, TimeSpanStandardStyles.Any, formatProvider, ref result); return result.parsedTimeSpan; } internal static bool TryParse(ReadOnlySpan input, IFormatProvider formatProvider, out TimeSpan result) { TimeSpanResult result2 = new TimeSpanResult(throwOnFailure: false, input); if (TryParseTimeSpan(input, TimeSpanStandardStyles.Any, formatProvider, ref result2)) { result = result2.parsedTimeSpan; return true; } result = default(TimeSpan); return false; } internal static TimeSpan ParseExact(ReadOnlySpan input, ReadOnlySpan format, IFormatProvider formatProvider, TimeSpanStyles styles) { TimeSpanResult result = new TimeSpanResult(throwOnFailure: true, input); bool flag = TryParseExactTimeSpan(input, format, formatProvider, styles, ref result); return result.parsedTimeSpan; } internal static bool TryParseExact(ReadOnlySpan input, ReadOnlySpan format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) { TimeSpanResult result2 = new TimeSpanResult(throwOnFailure: false, input); if (TryParseExactTimeSpan(input, format, formatProvider, styles, ref result2)) { result = result2.parsedTimeSpan; return true; } result = default(TimeSpan); return false; } internal static TimeSpan ParseExactMultiple(ReadOnlySpan input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles) { TimeSpanResult result = new TimeSpanResult(throwOnFailure: true, input); bool flag = TryParseExactMultipleTimeSpan(input, formats, formatProvider, styles, ref result); return result.parsedTimeSpan; } internal static bool TryParseExactMultiple(ReadOnlySpan input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) { TimeSpanResult result2 = new TimeSpanResult(throwOnFailure: false, input); if (TryParseExactMultipleTimeSpan(input, formats, formatProvider, styles, ref result2)) { result = result2.parsedTimeSpan; return true; } result = default(TimeSpan); return false; } private static bool TryParseTimeSpan(ReadOnlySpan input, TimeSpanStandardStyles style, IFormatProvider formatProvider, ref TimeSpanResult result) { input = input.Trim(); if (input.IsEmpty) { return result.SetBadTimeSpanFailure(); } TimeSpanTokenizer timeSpanTokenizer = new TimeSpanTokenizer(input); TimeSpanRawInfo raw = default(TimeSpanRawInfo); raw.Init(DateTimeFormatInfo.GetInstance(formatProvider)); TimeSpanToken tok = timeSpanTokenizer.GetNextToken(); while (tok._ttt != TTT.End) { if (!raw.ProcessToken(ref tok, ref result)) { return result.SetBadTimeSpanFailure(); } tok = timeSpanTokenizer.GetNextToken(); } if (!ProcessTerminalState(ref raw, style, ref result)) { return result.SetBadTimeSpanFailure(); } return true; } private static bool ProcessTerminalState(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result) { if (raw._lastSeenTTT == TTT.Num) { TimeSpanToken tok = default(TimeSpanToken); tok._ttt = TTT.Sep; if (!raw.ProcessToken(ref tok, ref result)) { return result.SetBadTimeSpanFailure(); } } return raw._numCount switch { 1 => ProcessTerminal_D(ref raw, style, ref result), 2 => ProcessTerminal_HM(ref raw, style, ref result), 3 => ProcessTerminal_HM_S_D(ref raw, style, ref result), 4 => ProcessTerminal_HMS_F_D(ref raw, style, ref result), 5 => ProcessTerminal_DHMSF(ref raw, style, ref result), _ => result.SetBadTimeSpanFailure(), }; } private static bool ProcessTerminal_DHMSF(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result) { if (raw._sepCount != 6) { return result.SetBadTimeSpanFailure(); } bool flag = (style & TimeSpanStandardStyles.Invariant) != 0; bool flag2 = (style & TimeSpanStandardStyles.Localized) != 0; bool flag3 = false; bool flag4 = false; if (flag) { if (raw.FullMatch(TimeSpanFormat.PositiveInvariantFormatLiterals)) { flag4 = true; flag3 = true; } if (!flag4 && raw.FullMatch(TimeSpanFormat.NegativeInvariantFormatLiterals)) { flag4 = true; flag3 = false; } } if (flag2) { if (!flag4 && raw.FullMatch(raw.PositiveLocalized)) { flag4 = true; flag3 = true; } if (!flag4 && raw.FullMatch(raw.NegativeLocalized)) { flag4 = true; flag3 = false; } } if (flag4) { if (!TryTimeToTicks(flag3, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, raw._numbers4, out var result2)) { return result.SetOverflowFailure(); } if (!flag3) { result2 = -result2; if (result2 > 0) { return result.SetOverflowFailure(); } } result.parsedTimeSpan = new TimeSpan(result2); return true; } return result.SetBadTimeSpanFailure(); } private static bool ProcessTerminal_HMS_F_D(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result) { if (raw._sepCount != 5 || (style & TimeSpanStandardStyles.RequireFull) != 0) { return result.SetBadTimeSpanFailure(); } bool flag = (style & TimeSpanStandardStyles.Invariant) != 0; bool flag2 = (style & TimeSpanStandardStyles.Localized) != 0; long result2 = 0L; bool flag3 = false; bool flag4 = false; bool flag5 = false; TimeSpanToken timeSpanToken = new TimeSpanToken(0); if (flag) { if (raw.FullHMSFMatch(TimeSpanFormat.PositiveInvariantFormatLiterals)) { flag3 = true; flag4 = TryTimeToTicks(flag3, timeSpanToken, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullDHMSMatch(TimeSpanFormat.PositiveInvariantFormatLiterals)) { flag3 = true; flag4 = TryTimeToTicks(flag3, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, timeSpanToken, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullAppCompatMatch(TimeSpanFormat.PositiveInvariantFormatLiterals)) { flag3 = true; flag4 = TryTimeToTicks(flag3, raw._numbers0, raw._numbers1, raw._numbers2, timeSpanToken, raw._numbers3, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullHMSFMatch(TimeSpanFormat.NegativeInvariantFormatLiterals)) { flag3 = false; flag4 = TryTimeToTicks(flag3, timeSpanToken, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullDHMSMatch(TimeSpanFormat.NegativeInvariantFormatLiterals)) { flag3 = false; flag4 = TryTimeToTicks(flag3, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, timeSpanToken, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullAppCompatMatch(TimeSpanFormat.NegativeInvariantFormatLiterals)) { flag3 = false; flag4 = TryTimeToTicks(flag3, raw._numbers0, raw._numbers1, raw._numbers2, timeSpanToken, raw._numbers3, out result2); flag5 = flag5 || !flag4; } } if (flag2) { if (!flag4 && raw.FullHMSFMatch(raw.PositiveLocalized)) { flag3 = true; flag4 = TryTimeToTicks(flag3, timeSpanToken, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullDHMSMatch(raw.PositiveLocalized)) { flag3 = true; flag4 = TryTimeToTicks(flag3, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, timeSpanToken, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullAppCompatMatch(raw.PositiveLocalized)) { flag3 = true; flag4 = TryTimeToTicks(flag3, raw._numbers0, raw._numbers1, raw._numbers2, timeSpanToken, raw._numbers3, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullHMSFMatch(raw.NegativeLocalized)) { flag3 = false; flag4 = TryTimeToTicks(flag3, timeSpanToken, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullDHMSMatch(raw.NegativeLocalized)) { flag3 = false; flag4 = TryTimeToTicks(flag3, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, timeSpanToken, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullAppCompatMatch(raw.NegativeLocalized)) { flag3 = false; flag4 = TryTimeToTicks(flag3, raw._numbers0, raw._numbers1, raw._numbers2, timeSpanToken, raw._numbers3, out result2); flag5 = flag5 || !flag4; } } if (flag4) { if (!flag3) { result2 = -result2; if (result2 > 0) { return result.SetOverflowFailure(); } } result.parsedTimeSpan = new TimeSpan(result2); return true; } if (!flag5) { return result.SetBadTimeSpanFailure(); } return result.SetOverflowFailure(); } private static bool ProcessTerminal_HM_S_D(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result) { if (raw._sepCount != 4 || (style & TimeSpanStandardStyles.RequireFull) != 0) { return result.SetBadTimeSpanFailure(); } bool flag = (style & TimeSpanStandardStyles.Invariant) != 0; bool flag2 = (style & TimeSpanStandardStyles.Localized) != 0; bool flag3 = false; bool flag4 = false; bool flag5 = false; TimeSpanToken timeSpanToken = new TimeSpanToken(0); long result2 = 0L; if (flag) { if (raw.FullHMSMatch(TimeSpanFormat.PositiveInvariantFormatLiterals)) { flag3 = true; flag4 = TryTimeToTicks(flag3, timeSpanToken, raw._numbers0, raw._numbers1, raw._numbers2, timeSpanToken, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullDHMMatch(TimeSpanFormat.PositiveInvariantFormatLiterals)) { flag3 = true; flag4 = TryTimeToTicks(flag3, raw._numbers0, raw._numbers1, raw._numbers2, timeSpanToken, timeSpanToken, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.PartialAppCompatMatch(TimeSpanFormat.PositiveInvariantFormatLiterals)) { flag3 = true; flag4 = TryTimeToTicks(flag3, timeSpanToken, raw._numbers0, raw._numbers1, timeSpanToken, raw._numbers2, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullHMSMatch(TimeSpanFormat.NegativeInvariantFormatLiterals)) { flag3 = false; flag4 = TryTimeToTicks(flag3, timeSpanToken, raw._numbers0, raw._numbers1, raw._numbers2, timeSpanToken, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullDHMMatch(TimeSpanFormat.NegativeInvariantFormatLiterals)) { flag3 = false; flag4 = TryTimeToTicks(flag3, raw._numbers0, raw._numbers1, raw._numbers2, timeSpanToken, timeSpanToken, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.PartialAppCompatMatch(TimeSpanFormat.NegativeInvariantFormatLiterals)) { flag3 = false; flag4 = TryTimeToTicks(flag3, timeSpanToken, raw._numbers0, raw._numbers1, timeSpanToken, raw._numbers2, out result2); flag5 = flag5 || !flag4; } } if (flag2) { if (!flag4 && raw.FullHMSMatch(raw.PositiveLocalized)) { flag3 = true; flag4 = TryTimeToTicks(flag3, timeSpanToken, raw._numbers0, raw._numbers1, raw._numbers2, timeSpanToken, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullDHMMatch(raw.PositiveLocalized)) { flag3 = true; flag4 = TryTimeToTicks(flag3, raw._numbers0, raw._numbers1, raw._numbers2, timeSpanToken, timeSpanToken, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.PartialAppCompatMatch(raw.PositiveLocalized)) { flag3 = true; flag4 = TryTimeToTicks(flag3, timeSpanToken, raw._numbers0, raw._numbers1, timeSpanToken, raw._numbers2, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullHMSMatch(raw.NegativeLocalized)) { flag3 = false; flag4 = TryTimeToTicks(flag3, timeSpanToken, raw._numbers0, raw._numbers1, raw._numbers2, timeSpanToken, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.FullDHMMatch(raw.NegativeLocalized)) { flag3 = false; flag4 = TryTimeToTicks(flag3, raw._numbers0, raw._numbers1, raw._numbers2, timeSpanToken, timeSpanToken, out result2); flag5 = flag5 || !flag4; } if (!flag4 && raw.PartialAppCompatMatch(raw.NegativeLocalized)) { flag3 = false; flag4 = TryTimeToTicks(flag3, timeSpanToken, raw._numbers0, raw._numbers1, timeSpanToken, raw._numbers2, out result2); flag5 = flag5 || !flag4; } } if (flag4) { if (!flag3) { result2 = -result2; if (result2 > 0) { return result.SetOverflowFailure(); } } result.parsedTimeSpan = new TimeSpan(result2); return true; } if (!flag5) { return result.SetBadTimeSpanFailure(); } return result.SetOverflowFailure(); } private static bool ProcessTerminal_HM(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result) { if (raw._sepCount != 3 || (style & TimeSpanStandardStyles.RequireFull) != 0) { return result.SetBadTimeSpanFailure(); } bool flag = (style & TimeSpanStandardStyles.Invariant) != 0; bool flag2 = (style & TimeSpanStandardStyles.Localized) != 0; bool flag3 = false; bool flag4 = false; if (flag) { if (raw.FullHMMatch(TimeSpanFormat.PositiveInvariantFormatLiterals)) { flag4 = true; flag3 = true; } if (!flag4 && raw.FullHMMatch(TimeSpanFormat.NegativeInvariantFormatLiterals)) { flag4 = true; flag3 = false; } } if (flag2) { if (!flag4 && raw.FullHMMatch(raw.PositiveLocalized)) { flag4 = true; flag3 = true; } if (!flag4 && raw.FullHMMatch(raw.NegativeLocalized)) { flag4 = true; flag3 = false; } } if (flag4) { TimeSpanToken timeSpanToken = new TimeSpanToken(0); if (!TryTimeToTicks(flag3, timeSpanToken, raw._numbers0, raw._numbers1, timeSpanToken, timeSpanToken, out var result2)) { return result.SetOverflowFailure(); } if (!flag3) { result2 = -result2; if (result2 > 0) { return result.SetOverflowFailure(); } } result.parsedTimeSpan = new TimeSpan(result2); return true; } return result.SetBadTimeSpanFailure(); } private static bool ProcessTerminal_D(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result) { if (raw._sepCount != 2 || (style & TimeSpanStandardStyles.RequireFull) != 0) { return result.SetBadTimeSpanFailure(); } bool flag = (style & TimeSpanStandardStyles.Invariant) != 0; bool flag2 = (style & TimeSpanStandardStyles.Localized) != 0; bool flag3 = false; bool flag4 = false; if (flag) { if (raw.FullDMatch(TimeSpanFormat.PositiveInvariantFormatLiterals)) { flag4 = true; flag3 = true; } if (!flag4 && raw.FullDMatch(TimeSpanFormat.NegativeInvariantFormatLiterals)) { flag4 = true; flag3 = false; } } if (flag2) { if (!flag4 && raw.FullDMatch(raw.PositiveLocalized)) { flag4 = true; flag3 = true; } if (!flag4 && raw.FullDMatch(raw.NegativeLocalized)) { flag4 = true; flag3 = false; } } if (flag4) { TimeSpanToken timeSpanToken = new TimeSpanToken(0); if (!TryTimeToTicks(flag3, raw._numbers0, timeSpanToken, timeSpanToken, timeSpanToken, timeSpanToken, out var result2)) { return result.SetOverflowFailure(); } if (!flag3) { result2 = -result2; if (result2 > 0) { return result.SetOverflowFailure(); } } result.parsedTimeSpan = new TimeSpan(result2); return true; } return result.SetBadTimeSpanFailure(); } private static bool TryParseExactTimeSpan(ReadOnlySpan input, ReadOnlySpan format, IFormatProvider formatProvider, TimeSpanStyles styles, ref TimeSpanResult result) { if (format.Length == 0) { return result.SetBadFormatSpecifierFailure(); } if (format.Length == 1) { switch (format[0]) { case 'T': case 'c': case 't': return TryParseTimeSpanConstant(input, ref result); case 'g': return TryParseTimeSpan(input, TimeSpanStandardStyles.Localized, formatProvider, ref result); case 'G': return TryParseTimeSpan(input, TimeSpanStandardStyles.Localized | TimeSpanStandardStyles.RequireFull, formatProvider, ref result); default: return result.SetBadFormatSpecifierFailure(format[0]); } } return TryParseByFormat(input, format, styles, ref result); } private static bool TryParseByFormat(ReadOnlySpan input, ReadOnlySpan format, TimeSpanStyles styles, ref TimeSpanResult result) { bool flag = false; bool flag2 = false; bool flag3 = false; bool flag4 = false; bool flag5 = false; int result2 = 0; int result3 = 0; int result4 = 0; int result5 = 0; int zeroes = 0; int result6 = 0; int i = 0; TimeSpanTokenizer tokenizer = new TimeSpanTokenizer(input, -1); int returnValue; for (; i < format.Length; i += returnValue) { char c = format[i]; switch (c) { case 'h': returnValue = DateTimeFormat.ParseRepeatPattern(format, i, c); if (returnValue > 2 || flag2 || !ParseExactDigits(ref tokenizer, returnValue, out result3)) { return result.SetInvalidStringFailure(); } flag2 = true; break; case 'm': returnValue = DateTimeFormat.ParseRepeatPattern(format, i, c); if (returnValue > 2 || flag3 || !ParseExactDigits(ref tokenizer, returnValue, out result4)) { return result.SetInvalidStringFailure(); } flag3 = true; break; case 's': returnValue = DateTimeFormat.ParseRepeatPattern(format, i, c); if (returnValue > 2 || flag4 || !ParseExactDigits(ref tokenizer, returnValue, out result5)) { return result.SetInvalidStringFailure(); } flag4 = true; break; case 'f': returnValue = DateTimeFormat.ParseRepeatPattern(format, i, c); if (returnValue > 7 || flag5 || !ParseExactDigits(ref tokenizer, returnValue, returnValue, out zeroes, out result6)) { return result.SetInvalidStringFailure(); } flag5 = true; break; case 'F': returnValue = DateTimeFormat.ParseRepeatPattern(format, i, c); if (returnValue > 7 || flag5) { return result.SetInvalidStringFailure(); } ParseExactDigits(ref tokenizer, returnValue, returnValue, out zeroes, out result6); flag5 = true; break; case 'd': { returnValue = DateTimeFormat.ParseRepeatPattern(format, i, c); if (returnValue > 8 || flag || !ParseExactDigits(ref tokenizer, (returnValue < 2) ? 1 : returnValue, (returnValue < 2) ? 8 : returnValue, out var _, out result2)) { return result.SetInvalidStringFailure(); } flag = true; break; } case '"': case '\'': { StringBuilder stringBuilder = StringBuilderCache.Acquire(); if (!DateTimeParse.TryParseQuoteString(format, i, stringBuilder, out returnValue)) { StringBuilderCache.Release(stringBuilder); return result.SetBadQuoteFailure(c); } if (!ParseExactLiteral(ref tokenizer, stringBuilder)) { StringBuilderCache.Release(stringBuilder); return result.SetInvalidStringFailure(); } StringBuilderCache.Release(stringBuilder); break; } case '%': { int num = DateTimeFormat.ParseNextChar(format, i); if (num >= 0 && num != 37) { returnValue = 1; break; } return result.SetInvalidStringFailure(); } case '\\': { int num = DateTimeFormat.ParseNextChar(format, i); if (num >= 0 && tokenizer.NextChar == (ushort)num) { returnValue = 2; break; } return result.SetInvalidStringFailure(); } default: return result.SetInvalidStringFailure(); } } if (!tokenizer.EOL) { return result.SetBadTimeSpanFailure(); } bool flag6 = (styles & TimeSpanStyles.AssumeNegative) == 0; if (TryTimeToTicks(flag6, new TimeSpanToken(result2), new TimeSpanToken(result3), new TimeSpanToken(result4), new TimeSpanToken(result5), new TimeSpanToken(result6, zeroes), out var result7)) { if (!flag6) { result7 = -result7; } result.parsedTimeSpan = new TimeSpan(result7); return true; } return result.SetOverflowFailure(); } private static bool ParseExactDigits(ref TimeSpanTokenizer tokenizer, int minDigitLength, out int result) { int maxDigitLength = ((minDigitLength == 1) ? 2 : minDigitLength); int zeroes; return ParseExactDigits(ref tokenizer, minDigitLength, maxDigitLength, out zeroes, out result); } private static bool ParseExactDigits(ref TimeSpanTokenizer tokenizer, int minDigitLength, int maxDigitLength, out int zeroes, out int result) { int num = 0; int num2 = 0; int i; for (i = 0; i < maxDigitLength; i++) { char nextChar = tokenizer.NextChar; if (nextChar < '0' || nextChar > '9') { tokenizer.BackOne(); break; } num = num * 10 + (nextChar - 48); if (num == 0) { num2++; } } zeroes = num2; result = num; return i >= minDigitLength; } private static bool ParseExactLiteral(ref TimeSpanTokenizer tokenizer, StringBuilder enquotedString) { for (int i = 0; i < enquotedString.Length; i++) { if (enquotedString[i] != tokenizer.NextChar) { return false; } } return true; } private static bool TryParseTimeSpanConstant(ReadOnlySpan input, ref TimeSpanResult result) { return default(StringParser).TryParse(input, ref result); } private static bool TryParseExactMultipleTimeSpan(ReadOnlySpan input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, ref TimeSpanResult result) { if (formats == null) { return result.SetArgumentNullFailure("formats"); } if (input.Length == 0) { return result.SetBadTimeSpanFailure(); } if (formats.Length == 0) { return result.SetNoFormatSpecifierFailure(); } foreach (string text in formats) { if (string.IsNullOrEmpty(text)) { return result.SetBadFormatSpecifierFailure(); } TimeSpanResult result2 = new TimeSpanResult(throwOnFailure: false, input); if (TryParseExactTimeSpan(input, text, formatProvider, styles, ref result2)) { result.parsedTimeSpan = result2.parsedTimeSpan; return true; } } return result.SetBadTimeSpanFailure(); } } [Flags] public enum TimeSpanStyles { None = 0, AssumeNegative = 1 } public class UmAlQuraCalendar : Calendar { private struct DateMapping { internal int HijriMonthsLengthFlags; internal DateTime GregorianDate; internal DateMapping(int MonthsLengthFlags, int GYear, int GMonth, int GDay) { HijriMonthsLengthFlags = MonthsLengthFlags; GregorianDate = new DateTime(GYear, GMonth, GDay); } } private static readonly DateMapping[] s_hijriYearInfo = InitDateMapping(); public const int UmAlQuraEra = 1; private static readonly DateTime s_minDate = new DateTime(1900, 4, 30); private static readonly DateTime s_maxDate = new DateTime(new DateTime(2077, 11, 16, 23, 59, 59, 999).Ticks + 9999); public override DateTime MinSupportedDateTime => s_minDate; public override DateTime MaxSupportedDateTime => s_maxDate; public override CalendarAlgorithmType AlgorithmType => CalendarAlgorithmType.LunarCalendar; internal override CalendarId BaseCalendarID => CalendarId.HIJRI; internal override CalendarId ID => CalendarId.UMALQURA; protected override int DaysInYearBeforeMinSupportedYear => 355; public override int[] Eras => new int[1] { 1 }; public override int TwoDigitYearMax { get { if (_twoDigitYearMax == -1) { _twoDigitYearMax = Calendar.GetSystemTwoDigitYearSetting(ID, 1451); } return _twoDigitYearMax; } set { if (value != 99 && (value < 1318 || value > 1500)) { throw new ArgumentOutOfRangeException("value", value, SR.Format(SR.ArgumentOutOfRange_Range, 1318, 1500)); } VerifyWritable(); _twoDigitYearMax = value; } } private static DateMapping[] InitDateMapping() { short[] array = new short[736] { 746, 1900, 4, 30, 1769, 1901, 4, 19, 3794, 1902, 4, 9, 3748, 1903, 3, 30, 3402, 1904, 3, 18, 2710, 1905, 3, 7, 1334, 1906, 2, 24, 2741, 1907, 2, 13, 3498, 1908, 2, 3, 2980, 1909, 1, 23, 2889, 1910, 1, 12, 2707, 1911, 1, 1, 1323, 1911, 12, 21, 2647, 1912, 12, 9, 1206, 1913, 11, 29, 2741, 1914, 11, 18, 1450, 1915, 11, 8, 3413, 1916, 10, 27, 3370, 1917, 10, 17, 2646, 1918, 10, 6, 1198, 1919, 9, 25, 2397, 1920, 9, 13, 748, 1921, 9, 3, 1749, 1922, 8, 23, 1706, 1923, 8, 13, 1365, 1924, 8, 1, 1195, 1925, 7, 21, 2395, 1926, 7, 10, 698, 1927, 6, 30, 1397, 1928, 6, 18, 2994, 1929, 6, 8, 1892, 1930, 5, 29, 1865, 1931, 5, 18, 1621, 1932, 5, 6, 683, 1933, 4, 25, 1371, 1934, 4, 14, 2778, 1935, 4, 4, 1748, 1936, 3, 24, 3785, 1937, 3, 13, 3474, 1938, 3, 3, 3365, 1939, 2, 20, 2637, 1940, 2, 9, 685, 1941, 1, 28, 1389, 1942, 1, 17, 2922, 1943, 1, 7, 2898, 1943, 12, 28, 2725, 1944, 12, 16, 2635, 1945, 12, 5, 1175, 1946, 11, 24, 2359, 1947, 11, 13, 694, 1948, 11, 2, 1397, 1949, 10, 22, 3434, 1950, 10, 12, 3410, 1951, 10, 2, 2710, 1952, 9, 20, 2349, 1953, 9, 9, 605, 1954, 8, 29, 1245, 1955, 8, 18, 2778, 1956, 8, 7, 1492, 1957, 7, 28, 3497, 1958, 7, 17, 3410, 1959, 7, 7, 2730, 1960, 6, 25, 1238, 1961, 6, 14, 2486, 1962, 6, 3, 884, 1963, 5, 24, 1897, 1964, 5, 12, 1874, 1965, 5, 2, 1701, 1966, 4, 21, 1355, 1967, 4, 10, 2731, 1968, 3, 29, 1370, 1969, 3, 19, 2773, 1970, 3, 8, 3538, 1971, 2, 26, 3492, 1972, 2, 16, 3401, 1973, 2, 4, 2709, 1974, 1, 24, 1325, 1975, 1, 13, 2653, 1976, 1, 2, 1370, 1976, 12, 22, 2773, 1977, 12, 11, 1706, 1978, 12, 1, 1685, 1979, 11, 20, 1323, 1980, 11, 8, 2647, 1981, 10, 28, 1198, 1982, 10, 18, 2422, 1983, 10, 7, 1388, 1984, 9, 26, 2901, 1985, 9, 15, 2730, 1986, 9, 5, 2645, 1987, 8, 25, 1197, 1988, 8, 13, 2397, 1989, 8, 2, 730, 1990, 7, 23, 1497, 1991, 7, 12, 3506, 1992, 7, 1, 2980, 1993, 6, 21, 2890, 1994, 6, 10, 2645, 1995, 5, 30, 693, 1996, 5, 18, 1397, 1997, 5, 7, 2922, 1998, 4, 27, 3026, 1999, 4, 17, 3012, 2000, 4, 6, 2953, 2001, 3, 26, 2709, 2002, 3, 15, 1325, 2003, 3, 4, 1453, 2004, 2, 21, 2922, 2005, 2, 10, 1748, 2006, 1, 31, 3529, 2007, 1, 20, 3474, 2008, 1, 10, 2726, 2008, 12, 29, 2390, 2009, 12, 18, 686, 2010, 12, 7, 1389, 2011, 11, 26, 874, 2012, 11, 15, 2901, 2013, 11, 4, 2730, 2014, 10, 25, 2381, 2015, 10, 14, 1181, 2016, 10, 2, 2397, 2017, 9, 21, 698, 2018, 9, 11, 1461, 2019, 8, 31, 1450, 2020, 8, 20, 3413, 2021, 8, 9, 2714, 2022, 7, 30, 2350, 2023, 7, 19, 622, 2024, 7, 7, 1373, 2025, 6, 26, 2778, 2026, 6, 16, 1748, 2027, 6, 6, 1701, 2028, 5, 25, 1355, 2029, 5, 14, 2711, 2030, 5, 3, 1358, 2031, 4, 23, 2734, 2032, 4, 11, 1452, 2033, 4, 1, 2985, 2034, 3, 21, 3474, 2035, 3, 11, 2853, 2036, 2, 28, 1611, 2037, 2, 16, 3243, 2038, 2, 5, 1370, 2039, 1, 26, 2901, 2040, 1, 15, 1746, 2041, 1, 4, 3749, 2041, 12, 24, 3658, 2042, 12, 14, 2709, 2043, 12, 3, 1325, 2044, 11, 21, 2733, 2045, 11, 10, 876, 2046, 10, 31, 1881, 2047, 10, 20, 1746, 2048, 10, 9, 1685, 2049, 9, 28, 1325, 2050, 9, 17, 2651, 2051, 9, 6, 1210, 2052, 8, 26, 2490, 2053, 8, 15, 948, 2054, 8, 5, 2921, 2055, 7, 25, 2898, 2056, 7, 14, 2726, 2057, 7, 3, 1206, 2058, 6, 22, 2413, 2059, 6, 11, 748, 2060, 5, 31, 1753, 2061, 5, 20, 3762, 2062, 5, 10, 3412, 2063, 4, 30, 3370, 2064, 4, 18, 2646, 2065, 4, 7, 1198, 2066, 3, 27, 2413, 2067, 3, 16, 3434, 2068, 3, 5, 2900, 2069, 2, 23, 2857, 2070, 2, 12, 2707, 2071, 2, 1, 1323, 2072, 1, 21, 2647, 2073, 1, 9, 1334, 2073, 12, 30, 2741, 2074, 12, 19, 1706, 2075, 12, 9, 3731, 2076, 11, 27, 0, 2077, 11, 17 }; DateMapping[] array2 = new DateMapping[array.Length / 4]; for (int i = 0; i < array2.Length; i++) { array2[i] = new DateMapping(array[i * 4], array[i * 4 + 1], array[i * 4 + 2], array[i * 4 + 3]); } return array2; } private static void ConvertHijriToGregorian(int HijriYear, int HijriMonth, int HijriDay, out int yg, out int mg, out int dg) { int num = HijriDay - 1; int num2 = HijriYear - 1318; DateTime gregorianDate = s_hijriYearInfo[num2].GregorianDate; int num3 = s_hijriYearInfo[num2].HijriMonthsLengthFlags; for (int i = 1; i < HijriMonth; i++) { num = num + 29 + (num3 & 1); num3 >>= 1; } gregorianDate.AddDays(num).GetDate(out yg, out mg, out dg); } private static long GetAbsoluteDateUmAlQura(int year, int month, int day) { ConvertHijriToGregorian(year, month, day, out var yg, out var mg, out var dg); return GregorianCalendar.GetAbsoluteDate(yg, mg, dg); } internal static void CheckTicksRange(long ticks) { if (ticks < s_minDate.Ticks || ticks > s_maxDate.Ticks) { throw new ArgumentOutOfRangeException("time", ticks, SR.Format(CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, s_minDate, s_maxDate)); } } internal static void CheckEraRange(int era) { if (era != 0 && era != 1) { throw new ArgumentOutOfRangeException("era", era, SR.ArgumentOutOfRange_InvalidEraValue); } } internal static void CheckYearRange(int year, int era) { CheckEraRange(era); if (year < 1318 || year > 1500) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 1318, 1500)); } } internal static void CheckYearMonthRange(int year, int month, int era) { CheckYearRange(year, era); if (month < 1 || month > 12) { ThrowHelper.ThrowArgumentOutOfRange_Month(month); } } private static void ConvertGregorianToHijri(DateTime time, out int HijriYear, out int HijriMonth, out int HijriDay) { int num = (int)((time.Ticks - s_minDate.Ticks) / 864000000000L) / 355; while (time.CompareTo(s_hijriYearInfo[++num].GregorianDate) > 0) { } if (time.CompareTo(s_hijriYearInfo[num].GregorianDate) != 0) { num--; } TimeSpan timeSpan = time.Subtract(s_hijriYearInfo[num].GregorianDate); int num2 = num + 1318; int num3 = 1; int num4 = 1; double num5 = timeSpan.TotalDays; int num6 = s_hijriYearInfo[num].HijriMonthsLengthFlags; int num7 = 29 + (num6 & 1); while (num5 >= (double)num7) { num5 -= (double)num7; num6 >>= 1; num7 = 29 + (num6 & 1); num3++; } num4 += (int)num5; HijriDay = num4; HijriMonth = num3; HijriYear = num2; } private static int GetDatePart(DateTime time, int part) { long ticks = time.Ticks; CheckTicksRange(ticks); ConvertGregorianToHijri(time, out var HijriYear, out var HijriMonth, out var HijriDay); return part switch { 0 => HijriYear, 2 => HijriMonth, 3 => HijriDay, 1 => (int)(GetAbsoluteDateUmAlQura(HijriYear, HijriMonth, HijriDay) - GetAbsoluteDateUmAlQura(HijriYear, 1, 1) + 1), _ => throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing), }; } public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException("months", months, SR.Format(SR.ArgumentOutOfRange_Range, -120000, 120000)); } int datePart = GetDatePart(time, 0); int datePart2 = GetDatePart(time, 2); int num = GetDatePart(time, 3); int num2 = datePart2 - 1 + months; if (num2 >= 0) { datePart2 = num2 % 12 + 1; datePart += num2 / 12; } else { datePart2 = 12 + (num2 + 1) % 12; datePart += (num2 - 11) / 12; } if (num > 29) { int daysInMonth = GetDaysInMonth(datePart, datePart2); if (num > daysInMonth) { num = daysInMonth; } } CheckYearRange(datePart, 1); DateTime result = new DateTime(GetAbsoluteDateUmAlQura(datePart, datePart2, num) * 864000000000L + time.Ticks % 864000000000L); Calendar.CheckAddResult(result.Ticks, MinSupportedDateTime, MaxSupportedDateTime); return result; } public override DateTime AddYears(DateTime time, int years) { return AddMonths(time, years * 12); } public override int GetDayOfMonth(DateTime time) { return GetDatePart(time, 3); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (DayOfWeek)((int)(time.Ticks / 864000000000L + 1) % 7); } public override int GetDayOfYear(DateTime time) { return GetDatePart(time, 1); } public override int GetDaysInMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); if ((s_hijriYearInfo[year - 1318].HijriMonthsLengthFlags & (1 << month - 1)) == 0) { return 29; } return 30; } internal static int RealGetDaysInYear(int year) { int num = 0; int num2 = s_hijriYearInfo[year - 1318].HijriMonthsLengthFlags; for (int i = 1; i <= 12; i++) { num = num + 29 + (num2 & 1); num2 >>= 1; } return num; } public override int GetDaysInYear(int year, int era) { CheckYearRange(year, era); return RealGetDaysInYear(year); } public override int GetEra(DateTime time) { CheckTicksRange(time.Ticks); return 1; } public override int GetMonth(DateTime time) { return GetDatePart(time, 2); } public override int GetMonthsInYear(int year, int era) { CheckYearRange(year, era); return 12; } public override int GetYear(DateTime time) { return GetDatePart(time, 0); } public override bool IsLeapDay(int year, int month, int day, int era) { if (day >= 1 && day <= 29) { CheckYearMonthRange(year, month, era); return false; } int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException("day", day, SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month)); } return false; } public override int GetLeapMonth(int year, int era) { CheckYearRange(year, era); return 0; } public override bool IsLeapMonth(int year, int month, int era) { CheckYearMonthRange(year, month, era); return false; } public override bool IsLeapYear(int year, int era) { CheckYearRange(year, era); return RealGetDaysInYear(year) == 355; } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { if (day >= 1 && day <= 29) { CheckYearMonthRange(year, month, era); } else { int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException("day", day, SR.Format(SR.ArgumentOutOfRange_Day, daysInMonth, month)); } } long absoluteDateUmAlQura = GetAbsoluteDateUmAlQura(year, month, day); if (absoluteDateUmAlQura < 0) { throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } return new DateTime(absoluteDateUmAlQura * 864000000000L + Calendar.TimeToTicks(hour, minute, second, millisecond)); } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException("year", year, SR.ArgumentOutOfRange_NeedNonNegNum); } if (year < 100) { return base.ToFourDigitYear(year); } if (year < 1318 || year > 1500) { throw new ArgumentOutOfRangeException("year", year, SR.Format(SR.ArgumentOutOfRange_Range, 1318, 1500)); } return year; } } public enum UnicodeCategory { UppercaseLetter, LowercaseLetter, TitlecaseLetter, ModifierLetter, OtherLetter, NonSpacingMark, SpacingCombiningMark, EnclosingMark, DecimalDigitNumber, LetterNumber, OtherNumber, SpaceSeparator, LineSeparator, ParagraphSeparator, Control, Format, Surrogate, PrivateUse, ConnectorPunctuation, DashPunctuation, OpenPunctuation, ClosePunctuation, InitialQuotePunctuation, FinalQuotePunctuation, OtherPunctuation, MathSymbol, CurrencySymbol, ModifierSymbol, OtherSymbol, OtherNotAssigned } } namespace System.Configuration.Assemblies { public enum AssemblyHashAlgorithm { None = 0, MD5 = 32771, SHA1 = 32772, SHA256 = 32780, SHA384 = 32781, SHA512 = 32782 } public enum AssemblyVersionCompatibility { SameMachine = 1, SameProcess, SameDomain } } namespace System.ComponentModel { [AttributeUsage(AttributeTargets.All)] public class DefaultValueAttribute : Attribute { private object _value; private static object s_convertFromInvariantString; public virtual object? Value => _value; [RequiresUnreferencedCode("Generic TypeConverters may require the generic types to be annotated. For example, NullableConverter requires the underlying type to be DynamicallyAccessedMembers All.")] public DefaultValueAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type type, string? value) { if (type == null) { return; } try { if (TryConvertFromInvariantString(type, value, out var conversionResult2)) { _value = conversionResult2; } else if (type.IsSubclassOf(typeof(Enum)) && value != null) { _value = Enum.Parse(type, value, ignoreCase: true); } else if (type == typeof(TimeSpan) && value != null) { _value = TimeSpan.Parse(value); } else { _value = Convert.ChangeType(value, type, CultureInfo.InvariantCulture); } [RequiresUnreferencedCode("Generic TypeConverters may require the generic types to be annotated. For example, NullableConverter requires the underlying type to be DynamicallyAccessedMembers All.")] static bool TryConvertFromInvariantString([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type typeToConvert, string stringValue, out object conversionResult) { conversionResult = null; if (s_convertFromInvariantString == null) { MethodInfo methodInfo = Type.GetType("System.ComponentModel.TypeDescriptor, System.ComponentModel.TypeConverter", throwOnError: false)?.GetMethod("ConvertFromInvariantString", BindingFlags.Static | BindingFlags.NonPublic); Volatile.Write(ref s_convertFromInvariantString, (methodInfo == null) ? new object() : methodInfo.CreateDelegate(typeof(Func))); } if (!(s_convertFromInvariantString is Func func)) { return false; } try { conversionResult = func(typeToConvert, stringValue); } catch { return false; } return true; } } catch { } } public DefaultValueAttribute(char value) { _value = value; } public DefaultValueAttribute(byte value) { _value = value; } public DefaultValueAttribute(short value) { _value = value; } public DefaultValueAttribute(int value) { _value = value; } public DefaultValueAttribute(long value) { _value = value; } public DefaultValueAttribute(float value) { _value = value; } public DefaultValueAttribute(double value) { _value = value; } public DefaultValueAttribute(bool value) { _value = value; } public DefaultValueAttribute(string? value) { _value = value; } public DefaultValueAttribute(object? value) { _value = value; } [CLSCompliant(false)] public DefaultValueAttribute(sbyte value) { _value = value; } [CLSCompliant(false)] public DefaultValueAttribute(ushort value) { _value = value; } [CLSCompliant(false)] public DefaultValueAttribute(uint value) { _value = value; } [CLSCompliant(false)] public DefaultValueAttribute(ulong value) { _value = value; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == this) { return true; } if (!(obj is DefaultValueAttribute defaultValueAttribute)) { return false; } if (Value == null) { return defaultValueAttribute.Value == null; } return Value.Equals(defaultValueAttribute.Value); } public override int GetHashCode() { return base.GetHashCode(); } protected void SetValue(object? value) { _value = value; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate)] public sealed class EditorBrowsableAttribute : Attribute { public EditorBrowsableState State { get; } public EditorBrowsableAttribute(EditorBrowsableState state) { State = state; } public EditorBrowsableAttribute() : this(EditorBrowsableState.Always) { } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj == this) { return true; } if (obj is EditorBrowsableAttribute editorBrowsableAttribute) { return editorBrowsableAttribute.State == State; } return false; } public override int GetHashCode() { return base.GetHashCode(); } } public enum EditorBrowsableState { Always, Never, Advanced } } namespace System.CodeDom.Compiler { [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = false)] public sealed class GeneratedCodeAttribute : Attribute { private readonly string _tool; private readonly string _version; public string? Tool => _tool; public string? Version => _version; public GeneratedCodeAttribute(string? tool, string? version) { _tool = tool; _version = version; } } public class IndentedTextWriter : TextWriter { private readonly TextWriter _writer; private readonly string _tabString; private int _indentLevel; private bool _tabsPending; public const string DefaultTabString = " "; public override Encoding Encoding => _writer.Encoding; public override string NewLine { get { return _writer.NewLine; } [param: AllowNull] set { _writer.NewLine = value; } } public int Indent { get { return _indentLevel; } set { _indentLevel = Math.Max(value, 0); } } public TextWriter InnerWriter => _writer; public IndentedTextWriter(TextWriter writer) : this(writer, " ") { } public IndentedTextWriter(TextWriter writer, string tabString) : base(CultureInfo.InvariantCulture) { if (writer == null) { throw new ArgumentNullException("writer"); } _writer = writer; _tabString = tabString; } public override void Close() { _writer.Close(); } public override ValueTask DisposeAsync() { return _writer.DisposeAsync(); } public override void Flush() { _writer.Flush(); } public override Task FlushAsync() { return _writer.FlushAsync(); } protected virtual void OutputTabs() { if (_tabsPending) { for (int i = 0; i < _indentLevel; i++) { _writer.Write(_tabString); } _tabsPending = false; } } protected virtual async Task OutputTabsAsync() { if (_tabsPending) { for (int i = 0; i < _indentLevel; i++) { await _writer.WriteAsync(_tabString).ConfigureAwait(continueOnCapturedContext: false); } _tabsPending = false; } } public override void Write(string? s) { OutputTabs(); _writer.Write(s); } public override void Write(bool value) { OutputTabs(); _writer.Write(value); } public override void Write(char value) { OutputTabs(); _writer.Write(value); } public override void Write(char[]? buffer) { OutputTabs(); _writer.Write(buffer); } public override void Write(char[] buffer, int index, int count) { OutputTabs(); _writer.Write(buffer, index, count); } public override void Write(double value) { OutputTabs(); _writer.Write(value); } public override void Write(float value) { OutputTabs(); _writer.Write(value); } public override void Write(int value) { OutputTabs(); _writer.Write(value); } public override void Write(long value) { OutputTabs(); _writer.Write(value); } public override void Write(object? value) { OutputTabs(); _writer.Write(value); } public override void Write(string format, object? arg0) { OutputTabs(); _writer.Write(format, arg0); } public override void Write(string format, object? arg0, object? arg1) { OutputTabs(); _writer.Write(format, arg0, arg1); } public override void Write(string format, params object?[] arg) { OutputTabs(); _writer.Write(format, arg); } public override async Task WriteAsync(char value) { await OutputTabsAsync().ConfigureAwait(continueOnCapturedContext: false); await _writer.WriteAsync(value).ConfigureAwait(continueOnCapturedContext: false); } public override async Task WriteAsync(char[] buffer, int index, int count) { await OutputTabsAsync().ConfigureAwait(continueOnCapturedContext: false); await _writer.WriteAsync(buffer, index, count).ConfigureAwait(continueOnCapturedContext: false); } public override async Task WriteAsync(string? value) { await OutputTabsAsync().ConfigureAwait(continueOnCapturedContext: false); await _writer.WriteAsync(value).ConfigureAwait(continueOnCapturedContext: false); } public override async Task WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default(CancellationToken)) { await OutputTabsAsync().ConfigureAwait(continueOnCapturedContext: false); await _writer.WriteAsync(buffer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public override async Task WriteAsync(StringBuilder? value, CancellationToken cancellationToken = default(CancellationToken)) { await OutputTabsAsync().ConfigureAwait(continueOnCapturedContext: false); await _writer.WriteAsync(value, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } public void WriteLineNoTabs(string? s) { _writer.WriteLine(s); } public Task WriteLineNoTabsAsync(string? s) { return _writer.WriteLineAsync(s); } public override void WriteLine(string? s) { OutputTabs(); _writer.WriteLine(s); _tabsPending = true; } public override void WriteLine() { OutputTabs(); _writer.WriteLine(); _tabsPending = true; } public override void WriteLine(bool value) { OutputTabs(); _writer.WriteLine(value); _tabsPending = true; } public override void WriteLine(char value) { OutputTabs(); _writer.WriteLine(value); _tabsPending = true; } public override void WriteLine(char[]? buffer) { OutputTabs(); _writer.WriteLine(buffer); _tabsPending = true; } public override void WriteLine(char[] buffer, int index, int count) { OutputTabs(); _writer.WriteLine(buffer, index, count); _tabsPending = true; } public override void WriteLine(double value) { OutputTabs(); _writer.WriteLine(value); _tabsPending = true; } public override void WriteLine(float value) { OutputTabs(); _writer.WriteLine(value); _tabsPending = true; } public override void WriteLine(int value) { OutputTabs(); _writer.WriteLine(value); _tabsPending = true; } public override void WriteLine(long value) { OutputTabs(); _writer.WriteLine(value); _tabsPending = true; } public override void WriteLine(object? value) { OutputTabs(); _writer.WriteLine(value); _tabsPending = true; } public override void WriteLine(string format, object? arg0) { OutputTabs(); _writer.WriteLine(format, arg0); _tabsPending = true; } public override void WriteLine(string format, object? arg0, object? arg1) { OutputTabs(); _writer.WriteLine(format, arg0, arg1); _tabsPending = true; } public override void WriteLine(string format, params object?[] arg) { OutputTabs(); _writer.WriteLine(format, arg); _tabsPending = true; } [CLSCompliant(false)] public override void WriteLine(uint value) { OutputTabs(); _writer.WriteLine(value); _tabsPending = true; } public override async Task WriteLineAsync() { await OutputTabsAsync().ConfigureAwait(continueOnCapturedContext: false); await _writer.WriteLineAsync().ConfigureAwait(continueOnCapturedContext: false); _tabsPending = true; } public override async Task WriteLineAsync(char value) { await OutputTabsAsync().ConfigureAwait(continueOnCapturedContext: false); await _writer.WriteLineAsync(value).ConfigureAwait(continueOnCapturedContext: false); _tabsPending = true; } public override async Task WriteLineAsync(char[] buffer, int index, int count) { await OutputTabsAsync().ConfigureAwait(continueOnCapturedContext: false); await _writer.WriteLineAsync(buffer, index, count).ConfigureAwait(continueOnCapturedContext: false); _tabsPending = true; } public override async Task WriteLineAsync(string? value) { await OutputTabsAsync().ConfigureAwait(continueOnCapturedContext: false); await _writer.WriteLineAsync(value).ConfigureAwait(continueOnCapturedContext: false); _tabsPending = true; } public override async Task WriteLineAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default(CancellationToken)) { await OutputTabsAsync().ConfigureAwait(continueOnCapturedContext: false); await _writer.WriteLineAsync(buffer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); _tabsPending = true; } public override async Task WriteLineAsync(StringBuilder? value, CancellationToken cancellationToken = default(CancellationToken)) { await OutputTabsAsync().ConfigureAwait(continueOnCapturedContext: false); await _writer.WriteLineAsync(value, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); _tabsPending = true; } } } namespace System.Buffers { public delegate void SpanAction(Span span, TArg arg); public delegate void ReadOnlySpanAction(ReadOnlySpan span, TArg arg); internal delegate TResult SpanFunc(Span span, T1 arg1, T2 arg2, T3 arg3); public abstract class ArrayPool { private static readonly TlsOverPerCoreLockedStacksArrayPool s_shared = new TlsOverPerCoreLockedStacksArrayPool(); public static ArrayPool Shared => s_shared; public static ArrayPool Create() { return new ConfigurableArrayPool(); } public static ArrayPool Create(int maxArrayLength, int maxArraysPerBucket) { return new ConfigurableArrayPool(maxArrayLength, maxArraysPerBucket); } public abstract T[] Rent(int minimumLength); public abstract void Return(T[] array, bool clearArray = false); } [EventSource(Guid = "0866B2B8-5CEF-5DB9-2612-0C0FFD814A44", Name = "System.Buffers.ArrayPoolEventSource")] internal sealed class ArrayPoolEventSource : EventSource { internal enum BufferAllocatedReason { Pooled, OverMaximumSize, PoolExhausted } internal enum BufferDroppedReason { Full, OverMaximumSize } private const string EventSourceSuppressMessage = "Parameters to this method are primitive and are trimmer safe"; internal static readonly ArrayPoolEventSource Log = new ArrayPoolEventSource(); internal const int NoBucketId = -1; private protected override ReadOnlySpan ProviderMetadata => new byte[38] { 38, 0, 83, 121, 115, 116, 101, 109, 46, 66, 117, 102, 102, 101, 114, 115, 46, 65, 114, 114, 97, 121, 80, 111, 111, 108, 69, 118, 101, 110, 116, 83, 111, 117, 114, 99, 101, 0 }; private ArrayPoolEventSource(int _) { } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "Parameters to this method are primitive and are trimmer safe")] [Event(1, Level = EventLevel.Verbose)] internal unsafe void BufferRented(int bufferId, int bufferSize, int poolId, int bucketId) { EventData* ptr = stackalloc EventData[4]; ptr->Size = 4; ptr->DataPointer = (IntPtr)(&bufferId); ptr->Reserved = 0; ptr[1].Size = 4; ptr[1].DataPointer = (IntPtr)(&bufferSize); ptr[1].Reserved = 0; ptr[2].Size = 4; ptr[2].DataPointer = (IntPtr)(&poolId); ptr[2].Reserved = 0; ptr[3].Size = 4; ptr[3].DataPointer = (IntPtr)(&bucketId); ptr[3].Reserved = 0; WriteEventCore(1, 4, ptr); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "Parameters to this method are primitive and are trimmer safe")] [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->Size = 4; ptr->DataPointer = (IntPtr)(&bufferId); ptr->Reserved = 0; ptr[1].Size = 4; ptr[1].DataPointer = (IntPtr)(&bufferSize); ptr[1].Reserved = 0; ptr[2].Size = 4; ptr[2].DataPointer = (IntPtr)(&poolId); ptr[2].Reserved = 0; ptr[3].Size = 4; ptr[3].DataPointer = (IntPtr)(&bucketId); ptr[3].Reserved = 0; ptr[4].Size = 4; ptr[4].DataPointer = (IntPtr)(&reason); ptr[4].Reserved = 0; WriteEventCore(2, 5, ptr); } [Event(3, Level = EventLevel.Verbose)] internal void BufferReturned(int bufferId, int bufferSize, int poolId) { WriteEvent(3, bufferId, bufferSize, poolId); } [Event(4, Level = EventLevel.Informational)] internal void BufferTrimmed(int bufferId, int bufferSize, int poolId) { WriteEvent(4, bufferId, bufferSize, poolId); } [Event(5, Level = EventLevel.Informational)] internal void BufferTrimPoll(int milliseconds, int pressure) { WriteEvent(5, milliseconds, pressure); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Parameters to this method are primitive and are trimmer safe")] [Event(6, Level = EventLevel.Informational)] internal unsafe void BufferDropped(int bufferId, int bufferSize, int poolId, int bucketId, BufferDroppedReason reason) { EventData* ptr = stackalloc EventData[5]; ptr->Size = 4; ptr->DataPointer = (IntPtr)(&bufferId); ptr->Reserved = 0; ptr[1].Size = 4; ptr[1].DataPointer = (IntPtr)(&bufferSize); ptr[1].Reserved = 0; ptr[2].Size = 4; ptr[2].DataPointer = (IntPtr)(&poolId); ptr[2].Reserved = 0; ptr[3].Size = 4; ptr[3].DataPointer = (IntPtr)(&bucketId); ptr[3].Reserved = 0; ptr[4].Size = 4; ptr[4].DataPointer = (IntPtr)(&reason); ptr[4].Reserved = 0; WriteEventCore(6, 5, ptr); } private ArrayPoolEventSource() : base(new Guid(140948152, 23791, 23993, 38, 18, 12, 15, 253, 129, 74, 68), "System.Buffers.ArrayPoolEventSource") { } } internal sealed class ConfigurableArrayPool : ArrayPool { 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]; ArrayPoolEventSource log = ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferAllocated(array.GetHashCode(), _bufferLength, _poolId, Id, ArrayPoolEventSource.BufferAllocatedReason.Pooled); } } return array; } internal void Return(T[] array) { if (array.Length != _bufferLength) { throw new ArgumentException(SR.ArgumentException_BufferNotFromPool, "array"); } bool lockTaken = false; bool flag; try { _lock.Enter(ref lockTaken); flag = _index != 0; if (flag) { _buffers[--_index] = array; } } finally { if (lockTaken) { _lock.Exit(useMemoryBarrier: false); } } if (!flag) { ArrayPoolEventSource log = ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferDropped(array.GetHashCode(), _bufferLength, _poolId, Id, ArrayPoolEventSource.BufferDroppedReason.Full); } } } } private readonly Bucket[] _buckets; private int Id => GetHashCode(); internal ConfigurableArrayPool() : this(1048576, 50) { } internal ConfigurableArrayPool(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 = Utilities.SelectBucketIndex(maxArrayLength); Bucket[] array = new Bucket[num + 1]; for (int i = 0; i < array.Length; i++) { array[i] = new Bucket(Utilities.GetMaxSizeForBucket(i), maxArraysPerBucket, id); } _buckets = array; } public override T[] Rent(int minimumLength) { if (minimumLength < 0) { throw new ArgumentOutOfRangeException("minimumLength"); } if (minimumLength == 0) { return Array.Empty(); } ArrayPoolEventSource log = ArrayPoolEventSource.Log; int num = Utilities.SelectBucketIndex(minimumLength); T[] array; 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(); log.BufferRented(hashCode, array.Length, Id, -1); log.BufferAllocated(hashCode, array.Length, Id, -1, (num >= _buckets.Length) ? ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize : 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 = Utilities.SelectBucketIndex(array.Length); bool flag = num < _buckets.Length; if (flag) { if (clearArray) { Array.Clear(array); } _buckets[num].Return(array); } ArrayPoolEventSource log = ArrayPoolEventSource.Log; if (log.IsEnabled()) { int hashCode = array.GetHashCode(); log.BufferReturned(hashCode, array.Length, Id); if (!flag) { log.BufferDropped(hashCode, array.Length, Id, -1, ArrayPoolEventSource.BufferDroppedReason.Full); } } } } public interface IMemoryOwner : IDisposable { Memory Memory { get; } } public interface IPinnable { MemoryHandle Pin(int elementIndex); void Unpin(); } public struct MemoryHandle : IDisposable { private unsafe void* _pointer; private GCHandle _handle; private IPinnable _pinnable; [CLSCompliant(false)] public unsafe void* Pointer => _pointer; [CLSCompliant(false)] public unsafe MemoryHandle(void* pointer, GCHandle handle = default(GCHandle), IPinnable? pinnable = null) { _pointer = pointer; _handle = handle; _pinnable = pinnable; } public unsafe void Dispose() { if (_handle.IsAllocated) { _handle.Free(); } if (_pinnable != null) { _pinnable.Unpin(); _pinnable = null; } _pointer = null; } } public abstract class MemoryManager : IMemoryOwner, IDisposable, IPinnable { public virtual Memory Memory => new Memory(this, GetSpan().Length); public abstract Span GetSpan(); public abstract MemoryHandle Pin(int elementIndex = 0); public abstract void Unpin(); [MethodImpl(MethodImplOptions.AggressiveInlining)] protected Memory CreateMemory(int length) { return new Memory(this, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected Memory CreateMemory(int start, int length) { return new Memory(this, start, length); } protected internal virtual bool TryGetArray(out ArraySegment segment) { segment = default(ArraySegment); return false; } void IDisposable.Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected abstract void Dispose(bool disposing); } public enum OperationStatus { Done, DestinationTooSmall, NeedMoreData, InvalidData } public readonly struct StandardFormat : IEquatable { public const byte NoPrecision = byte.MaxValue; public const byte MaxPrecision = 99; private readonly byte _format; private readonly byte _precision; public char Symbol => (char)_format; public byte Precision => _precision; public bool HasPrecision => _precision != byte.MaxValue; public bool IsDefault { get { if (_format == 0) { return _precision == 0; } return false; } } public StandardFormat(char symbol, byte precision = byte.MaxValue) { if (precision != byte.MaxValue && precision > 99) { ThrowHelper.ThrowArgumentOutOfRangeException_PrecisionTooLarge(); } if (symbol != (byte)symbol) { ThrowHelper.ThrowArgumentOutOfRangeException_SymbolDoesNotFit(); } _format = (byte)symbol; _precision = precision; } public static implicit operator StandardFormat(char symbol) { return new StandardFormat(symbol); } public static StandardFormat Parse(ReadOnlySpan format) { ParseHelper(format, out var standardFormat, throws: true); return standardFormat; } public static StandardFormat Parse(string? format) { if (format != null) { return Parse(format.AsSpan()); } return default(StandardFormat); } public static bool TryParse(ReadOnlySpan format, out StandardFormat result) { return ParseHelper(format, out result); } private static bool ParseHelper(ReadOnlySpan format, out StandardFormat standardFormat, bool throws = false) { standardFormat = default(StandardFormat); if (format.Length == 0) { return true; } char symbol = format[0]; byte precision; if (format.Length == 1) { precision = byte.MaxValue; } else { uint num = 0u; for (int i = 1; i < format.Length; i++) { uint num2 = (uint)(format[i] - 48); if (num2 > 9) { if (!throws) { return false; } throw new FormatException(SR.Format(SR.Argument_CannotParsePrecision, (byte)99)); } num = num * 10 + num2; if (num > 99) { if (!throws) { return false; } throw new FormatException(SR.Format(SR.Argument_PrecisionTooLarge, (byte)99)); } } precision = (byte)num; } standardFormat = new StandardFormat(symbol, precision); return true; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is StandardFormat other) { return Equals(other); } return false; } public override int GetHashCode() { return _format.GetHashCode() ^ _precision.GetHashCode(); } public bool Equals(StandardFormat other) { if (_format == other._format) { return _precision == other._precision; } return false; } public override string ToString() { Span destination = stackalloc char[3]; return new string(destination[..Format(destination)]); } internal int Format(Span destination) { int num = 0; char symbol = Symbol; if (symbol != 0 && destination.Length == 3) { destination[0] = symbol; num = 1; uint num2 = Precision; if (num2 != 255) { if (num2 >= 10) { uint num3; (num3, num2) = Math.DivRem(num2, 10u); destination[1] = (char)(48 + num3 % 10); num = 2; } destination[num] = (char)(48 + num2); num++; } } return num; } public static bool operator ==(StandardFormat left, StandardFormat right) { return left.Equals(right); } public static bool operator !=(StandardFormat left, StandardFormat right) { return !left.Equals(right); } } internal sealed class TlsOverPerCoreLockedStacksArrayPool : ArrayPool { private sealed class PerCoreLockedStacks { private static readonly int s_lockedStackCount = Math.Min(Environment.ProcessorCount, 64); private readonly LockedStack[] _perCoreStacks; public PerCoreLockedStacks() { LockedStack[] array = new LockedStack[s_lockedStackCount]; for (int i = 0; i < array.Length; i++) { array[i] = new LockedStack(); } _perCoreStacks = array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryPush(T[] array) { LockedStack[] perCoreStacks = _perCoreStacks; int num = (int)((uint)Thread.GetCurrentProcessorId() % (uint)s_lockedStackCount); for (int i = 0; i < perCoreStacks.Length; i++) { if (perCoreStacks[num].TryPush(array)) { return true; } if (++num == perCoreStacks.Length) { num = 0; } } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[] TryPop() { LockedStack[] perCoreStacks = _perCoreStacks; int num = (int)((uint)Thread.GetCurrentProcessorId() % (uint)s_lockedStackCount); for (int i = 0; i < perCoreStacks.Length; i++) { T[] result; if ((result = perCoreStacks[num].TryPop()) != null) { return result; } if (++num == perCoreStacks.Length) { num = 0; } } return null; } public void Trim(int currentMilliseconds, int id, Utilities.MemoryPressure pressure, int bucketSize) { LockedStack[] perCoreStacks = _perCoreStacks; for (int i = 0; i < perCoreStacks.Length; i++) { perCoreStacks[i].Trim(currentMilliseconds, id, pressure, bucketSize); } } } private sealed class LockedStack { private readonly T[][] _arrays = new T[8][]; private int _count; private int _millisecondsTimestamp; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryPush(T[] array) { bool result = false; Monitor.Enter(this); T[][] arrays = _arrays; int count = _count; if ((uint)count < (uint)arrays.Length) { if (count == 0) { _millisecondsTimestamp = 0; } arrays[count] = array; _count = count + 1; result = true; } Monitor.Exit(this); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public T[] TryPop() { T[] result = null; Monitor.Enter(this); T[][] arrays = _arrays; int num = _count - 1; if ((uint)num < (uint)arrays.Length) { result = arrays[num]; arrays[num] = null; _count = num; } Monitor.Exit(this); return result; } public void Trim(int currentMilliseconds, int id, Utilities.MemoryPressure pressure, int bucketSize) { if (_count == 0) { return; } int num = ((pressure == Utilities.MemoryPressure.High) ? 10000 : 60000); lock (this) { if (_count == 0) { return; } if (_millisecondsTimestamp == 0) { _millisecondsTimestamp = currentMilliseconds; } else { if (currentMilliseconds - _millisecondsTimestamp <= num) { return; } ArrayPoolEventSource log = ArrayPoolEventSource.Log; int num2 = 1; switch (pressure) { case Utilities.MemoryPressure.High: num2 = 8; if (bucketSize > 16384) { num2++; } if (Unsafe.SizeOf() > 16) { num2++; } if (Unsafe.SizeOf() > 32) { num2++; } break; case Utilities.MemoryPressure.Medium: num2 = 2; break; } while (_count > 0 && num2-- > 0) { T[] array = _arrays[--_count]; _arrays[_count] = null; if (log.IsEnabled()) { log.BufferTrimmed(array.GetHashCode(), array.Length, id); } } _millisecondsTimestamp = ((_count > 0) ? (_millisecondsTimestamp + num / 4) : 0); } } } } private struct ThreadLocalArray { public T[] Array; public int MillisecondsTimeStamp; public ThreadLocalArray(T[] array) { Array = array; MillisecondsTimeStamp = 0; } } [ThreadStatic] private static ThreadLocalArray[] t_tlsBuckets; private readonly ConditionalWeakTable _allTlsBuckets = new ConditionalWeakTable(); private readonly PerCoreLockedStacks[] _buckets = new PerCoreLockedStacks[27]; private int _trimCallbackCreated; private int Id => GetHashCode(); private PerCoreLockedStacks CreatePerCoreLockedStacks(int bucketIndex) { PerCoreLockedStacks perCoreLockedStacks = new PerCoreLockedStacks(); return Interlocked.CompareExchange(ref _buckets[bucketIndex], perCoreLockedStacks, null) ?? perCoreLockedStacks; } public override T[] Rent(int minimumLength) { ArrayPoolEventSource log = ArrayPoolEventSource.Log; int num = Utilities.SelectBucketIndex(minimumLength); ThreadLocalArray[] array = t_tlsBuckets; T[] array2; if (array != null && (uint)num < (uint)array.Length) { array2 = array[num].Array; if (array2 != null) { array[num].Array = null; if (log.IsEnabled()) { log.BufferRented(array2.GetHashCode(), array2.Length, Id, num); } return array2; } } PerCoreLockedStacks[] buckets = _buckets; if ((uint)num < (uint)buckets.Length) { PerCoreLockedStacks perCoreLockedStacks = buckets[num]; if (perCoreLockedStacks != null) { array2 = perCoreLockedStacks.TryPop(); if (array2 != null) { if (log.IsEnabled()) { log.BufferRented(array2.GetHashCode(), array2.Length, Id, num); } return array2; } } minimumLength = Utilities.GetMaxSizeForBucket(num); } else { if (minimumLength == 0) { return Array.Empty(); } if (minimumLength < 0) { throw new ArgumentOutOfRangeException("minimumLength"); } } array2 = GC.AllocateUninitializedArray(minimumLength); if (log.IsEnabled()) { int hashCode = array2.GetHashCode(); log.BufferRented(hashCode, array2.Length, Id, -1); log.BufferAllocated(hashCode, array2.Length, Id, -1, (num >= _buckets.Length) ? ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize : ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted); } return array2; } public override void Return(T[] array, bool clearArray = false) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } int num = Utilities.SelectBucketIndex(array.Length); ThreadLocalArray[] array2 = t_tlsBuckets ?? InitializeTlsBucketsAndTrimming(); bool flag = false; bool flag2 = true; if ((uint)num < (uint)array2.Length) { flag = true; if (clearArray) { Array.Clear(array); } if (array.Length != Utilities.GetMaxSizeForBucket(num)) { throw new ArgumentException(SR.ArgumentException_BufferNotFromPool, "array"); } ref ThreadLocalArray reference = ref array2[num]; T[] array3 = reference.Array; reference = new ThreadLocalArray(array); if (array3 != null) { PerCoreLockedStacks perCoreLockedStacks = _buckets[num] ?? CreatePerCoreLockedStacks(num); flag2 = perCoreLockedStacks.TryPush(array3); } } ArrayPoolEventSource log = ArrayPoolEventSource.Log; if (log.IsEnabled() && array.Length != 0) { log.BufferReturned(array.GetHashCode(), array.Length, Id); if (!(flag && flag2)) { log.BufferDropped(array.GetHashCode(), array.Length, Id, flag ? num : (-1), (!flag) ? ArrayPoolEventSource.BufferDroppedReason.OverMaximumSize : ArrayPoolEventSource.BufferDroppedReason.Full); } } } public bool Trim() { int tickCount = Environment.TickCount; Utilities.MemoryPressure memoryPressure = Utilities.GetMemoryPressure(); ArrayPoolEventSource log = ArrayPoolEventSource.Log; if (log.IsEnabled()) { log.BufferTrimPoll(tickCount, (int)memoryPressure); } PerCoreLockedStacks[] buckets = _buckets; for (int i = 0; i < buckets.Length; i++) { buckets[i]?.Trim(tickCount, Id, memoryPressure, Utilities.GetMaxSizeForBucket(i)); } if (memoryPressure == Utilities.MemoryPressure.High) { if (log.IsEnabled()) { foreach (KeyValuePair item in (IEnumerable>)_allTlsBuckets) { ThreadLocalArray[] key = item.Key; for (int j = 0; j < key.Length; j++) { T[] array = Interlocked.Exchange(ref key[j].Array, null); if (array != null) { log.BufferTrimmed(array.GetHashCode(), array.Length, Id); } } } } else { foreach (KeyValuePair item2 in (IEnumerable>)_allTlsBuckets) { Array.Clear(item2.Key); } } } else { uint num = ((memoryPressure != Utilities.MemoryPressure.Medium) ? 30000u : 15000u); uint num2 = num; foreach (KeyValuePair item3 in (IEnumerable>)_allTlsBuckets) { ThreadLocalArray[] key2 = item3.Key; for (int k = 0; k < key2.Length; k++) { if (key2[k].Array == null) { continue; } int millisecondsTimeStamp = key2[k].MillisecondsTimeStamp; if (millisecondsTimeStamp == 0) { key2[k].MillisecondsTimeStamp = tickCount; } else if (tickCount - millisecondsTimeStamp >= num2) { T[] array2 = Interlocked.Exchange(ref key2[k].Array, null); if (array2 != null && log.IsEnabled()) { log.BufferTrimmed(array2.GetHashCode(), array2.Length, Id); } } } } } return true; } private ThreadLocalArray[] InitializeTlsBucketsAndTrimming() { ThreadLocalArray[] array = (t_tlsBuckets = new ThreadLocalArray[27]); _allTlsBuckets.Add(array, null); if (Interlocked.Exchange(ref _trimCallbackCreated, 1) == 0) { Gen2GcCallback.Register((object s) => ((TlsOverPerCoreLockedStacksArrayPool)s).Trim(), this); } return array; } } internal static class Utilities { internal enum MemoryPressure { Low, Medium, High } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int SelectBucketIndex(int bufferSize) { return BitOperations.Log2((uint)(bufferSize - 1) | 0xFu) - 3; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetMaxSizeForBucket(int binIndex) { return 16 << binIndex; } internal static MemoryPressure GetMemoryPressure() { GCMemoryInfo gCMemoryInfo = GC.GetGCMemoryInfo(); if ((double)gCMemoryInfo.MemoryLoadBytes >= (double)gCMemoryInfo.HighMemoryLoadThresholdBytes * 0.9) { return MemoryPressure.High; } if ((double)gCMemoryInfo.MemoryLoadBytes >= (double)gCMemoryInfo.HighMemoryLoadThresholdBytes * 0.7) { return MemoryPressure.Medium; } return MemoryPressure.Low; } } } namespace System.Buffers.Text { internal static class FormattingHelpers { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int CountDigits(ulong value) { int num = 1; uint num2; if (value >= 10000000) { if (value >= 100000000000000L) { num2 = (uint)(value / 100000000000000L); num += 14; } else { num2 = (uint)(value / 10000000); num += 7; } } else { num2 = (uint)value; } if (num2 >= 10) { num = ((num2 < 100) ? (num + 1) : ((num2 < 1000) ? (num + 2) : ((num2 < 10000) ? (num + 3) : ((num2 < 100000) ? (num + 4) : ((num2 >= 1000000) ? (num + 6) : (num + 5)))))); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int CountDigits(uint value) { int num = 1; if (value >= 100000) { value /= 100000; num += 5; } if (value >= 10) { num = ((value < 100) ? (num + 1) : ((value < 1000) ? (num + 2) : ((value >= 10000) ? (num + 4) : (num + 3)))); } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int CountHexDigits(ulong value) { return (BitOperations.Log2(value) >> 2) + 1; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int CountDecimalTrailingZeros(uint value, out uint valueWithoutTrailingZeros) { int num = 0; if (value != 0) { while (true) { uint num2 = value / 10; if (value != num2 * 10) { break; } value = num2; num++; } } valueWithoutTrailingZeros = value; return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static char GetSymbolOrDefault(in StandardFormat format, char defaultSymbol) { char c = format.Symbol; if (c == '\0' && format.Precision == 0) { c = defaultSymbol; } return c; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void FillWithAsciiZeros(Span buffer) { for (int i = 0; i < buffer.Length; i++) { buffer[i] = 48; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDigits(ulong value, Span buffer) { for (int num = buffer.Length - 1; num >= 1; num--) { ulong num2 = 48 + value; value /= 10; buffer[num] = (byte)(num2 - value * 10); } buffer[0] = (byte)(48 + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDigitsWithGroupSeparator(ulong value, Span buffer) { int num = 0; for (int num2 = buffer.Length - 1; num2 >= 1; num2--) { ulong num3 = 48 + value; value /= 10; buffer[num2] = (byte)(num3 - value * 10); if (num == 2) { buffer[--num2] = 44; num = 0; } else { num++; } } buffer[0] = (byte)(48 + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDigits(uint value, Span buffer) { for (int num = buffer.Length - 1; num >= 1; num--) { uint num2 = 48 + value; value /= 10; buffer[num] = (byte)(num2 - value * 10); } buffer[0] = (byte)(48 + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteFourDecimalDigits(uint value, Span buffer, int startingIndex = 0) { uint num = 48 + value; value /= 10; buffer[startingIndex + 3] = (byte)(num - value * 10); num = 48 + value; value /= 10; buffer[startingIndex + 2] = (byte)(num - value * 10); num = 48 + value; value /= 10; buffer[startingIndex + 1] = (byte)(num - value * 10); buffer[startingIndex] = (byte)(48 + value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteTwoDecimalDigits(uint value, Span buffer, int startingIndex = 0) { uint num = 48 + value; value /= 10; buffer[startingIndex + 1] = (byte)(num - value * 10); buffer[startingIndex] = (byte)(48 + value); } public static bool TryFormatThrowFormatException(out int bytesWritten) { bytesWritten = 0; ThrowHelper.ThrowFormatException_BadFormatSpecifier(); return false; } } internal static class Utf8Constants { public static readonly TimeSpan NullUtcOffset = TimeSpan.MinValue; } public static class Utf8Formatter { [StructLayout(LayoutKind.Explicit)] private struct DecomposedGuid { [FieldOffset(0)] public Guid Guid; [FieldOffset(0)] public byte Byte00; [FieldOffset(1)] public byte Byte01; [FieldOffset(2)] public byte Byte02; [FieldOffset(3)] public byte Byte03; [FieldOffset(4)] public byte Byte04; [FieldOffset(5)] public byte Byte05; [FieldOffset(6)] public byte Byte06; [FieldOffset(7)] public byte Byte07; [FieldOffset(8)] public byte Byte08; [FieldOffset(9)] public byte Byte09; [FieldOffset(10)] public byte Byte10; [FieldOffset(11)] public byte Byte11; [FieldOffset(12)] public byte Byte12; [FieldOffset(13)] public byte Byte13; [FieldOffset(14)] public byte Byte14; [FieldOffset(15)] public byte Byte15; } private static readonly uint[] s_dayAbbreviations = new uint[7] { 7238995u, 7237453u, 6649172u, 6579543u, 7694420u, 6910534u, 7627091u }; private static readonly uint[] s_dayAbbreviationsLowercase = new uint[7] { 7239027u, 7237485u, 6649204u, 6579575u, 7694452u, 6910566u, 7627123u }; private static readonly uint[] s_monthAbbreviations = new uint[12] { 7233866u, 6448454u, 7496013u, 7499841u, 7954765u, 7238986u, 7107914u, 6780225u, 7365971u, 7627599u, 7761742u, 6513988u }; private static readonly uint[] s_monthAbbreviationsLowercase = new uint[12] { 7233898u, 6448486u, 7496045u, 7499873u, 7954797u, 7239018u, 7107946u, 6780257u, 7366003u, 7627631u, 7761774u, 6514020u }; public static bool TryFormat(bool value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { char symbolOrDefault = FormattingHelpers.GetSymbolOrDefault(in format, 'G'); if (value) { if (symbolOrDefault == 'G') { if (BinaryPrimitives.TryWriteUInt32BigEndian(destination, 1416787301u)) { goto IL_0033; } } else { if (symbolOrDefault != 'l') { goto IL_0083; } if (BinaryPrimitives.TryWriteUInt32BigEndian(destination, 1953658213u)) { goto IL_0033; } } } else if (symbolOrDefault == 'G') { if (4u < (uint)destination.Length) { BinaryPrimitives.WriteUInt32BigEndian(destination, 1180789875u); goto IL_006e; } } else { if (symbolOrDefault != 'l') { goto IL_0083; } if (4u < (uint)destination.Length) { BinaryPrimitives.WriteUInt32BigEndian(destination, 1717660787u); goto IL_006e; } } bytesWritten = 0; return false; IL_0033: bytesWritten = 4; return true; IL_0083: return FormattingHelpers.TryFormatThrowFormatException(out bytesWritten); IL_006e: destination[4] = 101; bytesWritten = 5; return true; } public static bool TryFormat(DateTimeOffset value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { TimeSpan offset = Utf8Constants.NullUtcOffset; char c = format.Symbol; if (format.IsDefault) { c = 'G'; offset = value.Offset; } return c switch { 'R' => TryFormatDateTimeR(value.UtcDateTime, destination, out bytesWritten), 'l' => TryFormatDateTimeL(value.UtcDateTime, destination, out bytesWritten), 'O' => TryFormatDateTimeO(value.DateTime, value.Offset, destination, out bytesWritten), 'G' => TryFormatDateTimeG(value.DateTime, offset, destination, out bytesWritten), _ => FormattingHelpers.TryFormatThrowFormatException(out bytesWritten), }; } public static bool TryFormat(DateTime value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return FormattingHelpers.GetSymbolOrDefault(in format, 'G') switch { 'R' => TryFormatDateTimeR(value, destination, out bytesWritten), 'l' => TryFormatDateTimeL(value, destination, out bytesWritten), 'O' => TryFormatDateTimeO(value, Utf8Constants.NullUtcOffset, destination, out bytesWritten), 'G' => TryFormatDateTimeG(value, Utf8Constants.NullUtcOffset, destination, out bytesWritten), _ => FormattingHelpers.TryFormatThrowFormatException(out bytesWritten), }; } private static bool TryFormatDateTimeG(DateTime value, TimeSpan offset, Span destination, out int bytesWritten) { int num = 19; if (offset != Utf8Constants.NullUtcOffset) { num += 7; } if (destination.Length < num) { bytesWritten = 0; return false; } bytesWritten = num; byte b = destination[18]; value.GetDate(out var year, out var month, out var day); value.GetTime(out var hour, out var minute, out var second); FormattingHelpers.WriteTwoDecimalDigits((uint)month, destination); destination[2] = 47; FormattingHelpers.WriteTwoDecimalDigits((uint)day, destination, 3); destination[5] = 47; FormattingHelpers.WriteFourDecimalDigits((uint)year, destination, 6); destination[10] = 32; FormattingHelpers.WriteTwoDecimalDigits((uint)hour, destination, 11); destination[13] = 58; FormattingHelpers.WriteTwoDecimalDigits((uint)minute, destination, 14); destination[16] = 58; FormattingHelpers.WriteTwoDecimalDigits((uint)second, destination, 17); if (offset != Utf8Constants.NullUtcOffset) { int num2 = (int)(offset.Ticks / 600000000); byte b2; if (num2 < 0) { b2 = 45; num2 = -num2; } else { b2 = 43; } int result; int value2 = Math.DivRem(num2, 60, out result); FormattingHelpers.WriteTwoDecimalDigits((uint)result, destination, 24); destination[23] = 58; FormattingHelpers.WriteTwoDecimalDigits((uint)value2, destination, 21); destination[20] = b2; destination[19] = 32; } return true; } private static bool TryFormatDateTimeL(DateTime value, Span destination, out int bytesWritten) { if (28u >= (uint)destination.Length) { bytesWritten = 0; return false; } value.GetDate(out var year, out var month, out var day); value.GetTime(out var hour, out var minute, out var second); uint num = s_dayAbbreviationsLowercase[(int)value.DayOfWeek]; destination[0] = (byte)num; num >>= 8; destination[1] = (byte)num; num >>= 8; destination[2] = (byte)num; destination[3] = 44; destination[4] = 32; FormattingHelpers.WriteTwoDecimalDigits((uint)day, destination, 5); destination[7] = 32; uint num2 = s_monthAbbreviationsLowercase[month - 1]; destination[8] = (byte)num2; num2 >>= 8; destination[9] = (byte)num2; num2 >>= 8; destination[10] = (byte)num2; destination[11] = 32; FormattingHelpers.WriteFourDecimalDigits((uint)year, destination, 12); destination[16] = 32; FormattingHelpers.WriteTwoDecimalDigits((uint)hour, destination, 17); destination[19] = 58; FormattingHelpers.WriteTwoDecimalDigits((uint)minute, destination, 20); destination[22] = 58; FormattingHelpers.WriteTwoDecimalDigits((uint)second, destination, 23); destination[25] = 32; destination[26] = 103; destination[27] = 109; destination[28] = 116; bytesWritten = 29; return true; } private static bool TryFormatDateTimeO(DateTime value, TimeSpan offset, Span destination, out int bytesWritten) { int num = 27; DateTimeKind dateTimeKind = DateTimeKind.Local; if (offset == Utf8Constants.NullUtcOffset) { dateTimeKind = value.Kind; switch (dateTimeKind) { case DateTimeKind.Local: offset = TimeZoneInfo.Local.GetUtcOffset(value); num += 6; break; case DateTimeKind.Utc: num++; break; } } else { num += 6; } if (destination.Length < num) { bytesWritten = 0; return false; } bytesWritten = num; _ = ref destination[26]; value.GetDate(out var year, out var month, out var day); value.GetTimePrecise(out var hour, out var minute, out var second, out var tick); FormattingHelpers.WriteFourDecimalDigits((uint)year, destination); destination[4] = 45; FormattingHelpers.WriteTwoDecimalDigits((uint)month, destination, 5); destination[7] = 45; FormattingHelpers.WriteTwoDecimalDigits((uint)day, destination, 8); destination[10] = 84; FormattingHelpers.WriteTwoDecimalDigits((uint)hour, destination, 11); destination[13] = 58; FormattingHelpers.WriteTwoDecimalDigits((uint)minute, destination, 14); destination[16] = 58; FormattingHelpers.WriteTwoDecimalDigits((uint)second, destination, 17); destination[19] = 46; FormattingHelpers.WriteDigits((uint)tick, destination.Slice(20, 7)); switch (dateTimeKind) { case DateTimeKind.Local: { int num2 = (int)(offset.Ticks / 600000000); byte b; if (num2 < 0) { b = 45; num2 = -num2; } else { b = 43; } int result; int value2 = Math.DivRem(num2, 60, out result); FormattingHelpers.WriteTwoDecimalDigits((uint)result, destination, 31); destination[30] = 58; FormattingHelpers.WriteTwoDecimalDigits((uint)value2, destination, 28); destination[27] = b; break; } case DateTimeKind.Utc: destination[27] = 90; break; } return true; } private static bool TryFormatDateTimeR(DateTime value, Span destination, out int bytesWritten) { if (28u >= (uint)destination.Length) { bytesWritten = 0; return false; } value.GetDate(out var year, out var month, out var day); value.GetTime(out var hour, out var minute, out var second); uint num = s_dayAbbreviations[(int)value.DayOfWeek]; destination[0] = (byte)num; num >>= 8; destination[1] = (byte)num; num >>= 8; destination[2] = (byte)num; destination[3] = 44; destination[4] = 32; FormattingHelpers.WriteTwoDecimalDigits((uint)day, destination, 5); destination[7] = 32; uint num2 = s_monthAbbreviations[month - 1]; destination[8] = (byte)num2; num2 >>= 8; destination[9] = (byte)num2; num2 >>= 8; destination[10] = (byte)num2; destination[11] = 32; FormattingHelpers.WriteFourDecimalDigits((uint)year, destination, 12); destination[16] = 32; FormattingHelpers.WriteTwoDecimalDigits((uint)hour, destination, 17); destination[19] = 58; FormattingHelpers.WriteTwoDecimalDigits((uint)minute, destination, 20); destination[22] = 58; FormattingHelpers.WriteTwoDecimalDigits((uint)second, destination, 23); destination[25] = 32; destination[26] = 71; destination[27] = 77; destination[28] = 84; bytesWritten = 29; return true; } public unsafe static bool TryFormat(decimal value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { if (format.IsDefault) { format = 'G'; } switch (format.Symbol) { case 'G': case 'g': { if (format.Precision != byte.MaxValue) { throw new NotSupportedException(SR.Argument_GWithPrecisionNotSupported); } byte* digits3 = stackalloc byte[31]; Number.NumberBuffer number3 = new Number.NumberBuffer(Number.NumberBufferKind.Decimal, digits3, 31); Number.DecimalToNumber(ref value, ref number3); if (number3.Digits[0] == 0) { number3.IsNegative = false; } return TryFormatDecimalG(ref number3, destination, out bytesWritten); } case 'F': case 'f': { byte* digits2 = stackalloc byte[31]; Number.NumberBuffer number2 = new Number.NumberBuffer(Number.NumberBufferKind.Decimal, digits2, 31); Number.DecimalToNumber(ref value, ref number2); byte b2 = (byte)((format.Precision == byte.MaxValue) ? 2 : format.Precision); Number.RoundNumber(ref number2, number2.Scale + b2, isCorrectlyRounded: false); return TryFormatDecimalF(ref number2, destination, out bytesWritten, b2); } case 'E': case 'e': { byte* digits = stackalloc byte[31]; Number.NumberBuffer number = new Number.NumberBuffer(Number.NumberBufferKind.Decimal, digits, 31); Number.DecimalToNumber(ref value, ref number); byte b = (byte)((format.Precision == byte.MaxValue) ? 6 : format.Precision); Number.RoundNumber(ref number, b + 1, isCorrectlyRounded: false); return TryFormatDecimalE(ref number, destination, out bytesWritten, b, (byte)format.Symbol); } default: return FormattingHelpers.TryFormatThrowFormatException(out bytesWritten); } } private static bool TryFormatDecimalE(ref Number.NumberBuffer number, Span destination, out int bytesWritten, byte precision, byte exponentSymbol) { int scale = number.Scale; ReadOnlySpan readOnlySpan = number.Digits; int num = (number.IsNegative ? 1 : 0) + 1 + ((precision != 0) ? (precision + 1) : 0) + 2 + 3; if (destination.Length < num) { bytesWritten = 0; return false; } int num2 = 0; int num3 = 0; if (number.IsNegative) { destination[num2++] = 45; } byte b = readOnlySpan[num3]; int num4; if (b == 0) { destination[num2++] = 48; num4 = 0; } else { destination[num2++] = b; num3++; num4 = scale - 1; } if (precision > 0) { destination[num2++] = 46; for (int i = 0; i < precision; i++) { byte b2 = readOnlySpan[num3]; if (b2 == 0) { while (i++ < precision) { destination[num2++] = 48; } break; } destination[num2++] = b2; num3++; } } destination[num2++] = exponentSymbol; if (num4 >= 0) { destination[num2++] = 43; } else { destination[num2++] = 45; num4 = -num4; } destination[num2++] = 48; destination[num2++] = (byte)(num4 / 10 + 48); destination[num2++] = (byte)(num4 % 10 + 48); bytesWritten = num; return true; } private static bool TryFormatDecimalF(ref Number.NumberBuffer number, Span destination, out int bytesWritten, byte precision) { int scale = number.Scale; ReadOnlySpan readOnlySpan = number.Digits; int num = (number.IsNegative ? 1 : 0) + ((scale <= 0) ? 1 : scale) + ((precision != 0) ? (precision + 1) : 0); if (destination.Length < num) { bytesWritten = 0; return false; } int i = 0; int num2 = 0; if (number.IsNegative) { destination[num2++] = 45; } if (scale <= 0) { destination[num2++] = 48; } else { for (; i < scale; i++) { byte b = readOnlySpan[i]; if (b == 0) { int num3 = scale - i; for (int j = 0; j < num3; j++) { destination[num2++] = 48; } break; } destination[num2++] = b; } } if (precision > 0) { destination[num2++] = 46; int k = 0; if (scale < 0) { int num4 = Math.Min(precision, -scale); for (int l = 0; l < num4; l++) { destination[num2++] = 48; } k += num4; } for (; k < precision; k++) { byte b2 = readOnlySpan[i]; if (b2 == 0) { while (k++ < precision) { destination[num2++] = 48; } break; } destination[num2++] = b2; i++; } } bytesWritten = num; return true; } private static bool TryFormatDecimalG(ref Number.NumberBuffer number, Span destination, out int bytesWritten) { int scale = number.Scale; ReadOnlySpan readOnlySpan = number.Digits; int digitsCount = number.DigitsCount; bool flag = scale < digitsCount; int num; if (flag) { num = digitsCount + 1; if (scale <= 0) { num += 1 + -scale; } } else { num = ((scale <= 0) ? 1 : scale); } if (number.IsNegative) { num++; } if (destination.Length < num) { bytesWritten = 0; return false; } int i = 0; int num2 = 0; if (number.IsNegative) { destination[num2++] = 45; } if (scale <= 0) { destination[num2++] = 48; } else { for (; i < scale; i++) { byte b = readOnlySpan[i]; if (b == 0) { int num3 = scale - i; for (int j = 0; j < num3; j++) { destination[num2++] = 48; } break; } destination[num2++] = b; } } if (flag) { destination[num2++] = 46; if (scale < 0) { int num4 = -scale; for (int k = 0; k < num4; k++) { destination[num2++] = 48; } } byte b2; while ((b2 = readOnlySpan[i++]) != 0) { destination[num2++] = b2; } } bytesWritten = num; return true; } public static bool TryFormat(double value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatFloatingPoint(value, destination, out bytesWritten, format); } public static bool TryFormat(float value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatFloatingPoint(value, destination, out bytesWritten, format); } private static bool TryFormatFloatingPoint(T value, Span destination, out int bytesWritten, StandardFormat format) where T : ISpanFormattable { Span span = default(Span); if (!format.IsDefault) { span = stackalloc char[3]; span = span[..format.Format(span)]; } Span destination2 = stackalloc char[128]; ReadOnlySpan readOnlySpan = default(Span); if (value.TryFormat(destination2, out var charsWritten, span, CultureInfo.InvariantCulture)) { readOnlySpan = destination2.Slice(0, charsWritten); } else { if (destination.Length <= 128) { bytesWritten = 0; return false; } readOnlySpan = value.ToString(new string(span), CultureInfo.InvariantCulture); } if (readOnlySpan.Length > destination.Length) { bytesWritten = 0; return false; } try { bytesWritten = Encoding.UTF8.GetBytes(readOnlySpan, destination); return true; } catch { bytesWritten = 0; return false; } } public static bool TryFormat(Guid value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { int num; switch (FormattingHelpers.GetSymbolOrDefault(in format, 'D')) { case 'D': num = -2147483612; break; case 'B': num = -2139260122; break; case 'P': num = -2144786394; break; case 'N': num = 32; break; default: return FormattingHelpers.TryFormatThrowFormatException(out bytesWritten); } if ((byte)num > destination.Length) { bytesWritten = 0; return false; } bytesWritten = (byte)num; num >>= 8; if ((byte)num != 0) { destination[0] = (byte)num; destination = destination.Slice(1); } num >>= 8; DecomposedGuid decomposedGuid = default(DecomposedGuid); decomposedGuid.Guid = value; _ = ref destination[8]; _ = BitConverter.IsLittleEndian; HexConverter.ToBytesBuffer(decomposedGuid.Byte03, destination, 0, HexConverter.Casing.Lower); HexConverter.ToBytesBuffer(decomposedGuid.Byte02, destination, 2, HexConverter.Casing.Lower); HexConverter.ToBytesBuffer(decomposedGuid.Byte01, destination, 4, HexConverter.Casing.Lower); HexConverter.ToBytesBuffer(decomposedGuid.Byte00, destination, 6, HexConverter.Casing.Lower); if (num < 0) { destination[8] = 45; destination = destination.Slice(9); } else { destination = destination.Slice(8); } _ = ref destination[4]; _ = BitConverter.IsLittleEndian; HexConverter.ToBytesBuffer(decomposedGuid.Byte05, destination, 0, HexConverter.Casing.Lower); HexConverter.ToBytesBuffer(decomposedGuid.Byte04, destination, 2, HexConverter.Casing.Lower); if (num < 0) { destination[4] = 45; destination = destination.Slice(5); } else { destination = destination.Slice(4); } _ = ref destination[4]; _ = BitConverter.IsLittleEndian; HexConverter.ToBytesBuffer(decomposedGuid.Byte07, destination, 0, HexConverter.Casing.Lower); HexConverter.ToBytesBuffer(decomposedGuid.Byte06, destination, 2, HexConverter.Casing.Lower); if (num < 0) { destination[4] = 45; destination = destination.Slice(5); } else { destination = destination.Slice(4); } _ = ref destination[4]; HexConverter.ToBytesBuffer(decomposedGuid.Byte08, destination, 0, HexConverter.Casing.Lower); HexConverter.ToBytesBuffer(decomposedGuid.Byte09, destination, 2, HexConverter.Casing.Lower); if (num < 0) { destination[4] = 45; destination = destination.Slice(5); } else { destination = destination.Slice(4); } _ = ref destination[11]; HexConverter.ToBytesBuffer(decomposedGuid.Byte10, destination, 0, HexConverter.Casing.Lower); HexConverter.ToBytesBuffer(decomposedGuid.Byte11, destination, 2, HexConverter.Casing.Lower); HexConverter.ToBytesBuffer(decomposedGuid.Byte12, destination, 4, HexConverter.Casing.Lower); HexConverter.ToBytesBuffer(decomposedGuid.Byte13, destination, 6, HexConverter.Casing.Lower); HexConverter.ToBytesBuffer(decomposedGuid.Byte14, destination, 8, HexConverter.Casing.Lower); HexConverter.ToBytesBuffer(decomposedGuid.Byte15, destination, 10, HexConverter.Casing.Lower); if ((byte)num != 0) { destination[12] = (byte)num; } return true; } public static bool TryFormat(byte value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatUInt64(value, destination, out bytesWritten, format); } [CLSCompliant(false)] public static bool TryFormat(sbyte value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatInt64(value, 255uL, destination, out bytesWritten, format); } [CLSCompliant(false)] public static bool TryFormat(ushort value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatUInt64(value, destination, out bytesWritten, format); } public static bool TryFormat(short value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatInt64(value, 65535uL, destination, out bytesWritten, format); } [CLSCompliant(false)] public static bool TryFormat(uint value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatUInt64(value, destination, out bytesWritten, format); } public static bool TryFormat(int value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatInt64(value, 4294967295uL, destination, out bytesWritten, format); } [CLSCompliant(false)] public static bool TryFormat(ulong value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatUInt64(value, destination, out bytesWritten, format); } public static bool TryFormat(long value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { return TryFormatInt64(value, ulong.MaxValue, destination, out bytesWritten, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatInt64(long value, ulong mask, Span destination, out int bytesWritten, StandardFormat format) { if (format.IsDefault) { return TryFormatInt64Default(value, destination, out bytesWritten); } switch (format.Symbol) { case 'G': case 'g': if (format.HasPrecision) { throw new NotSupportedException(SR.Argument_GWithPrecisionNotSupported); } return TryFormatInt64D(value, format.Precision, destination, out bytesWritten); case 'D': case 'd': return TryFormatInt64D(value, format.Precision, destination, out bytesWritten); case 'N': case 'n': return TryFormatInt64N(value, format.Precision, destination, out bytesWritten); case 'x': return TryFormatUInt64X((ulong)value & mask, format.Precision, useLower: true, destination, out bytesWritten); case 'X': return TryFormatUInt64X((ulong)value & mask, format.Precision, useLower: false, destination, out bytesWritten); default: return FormattingHelpers.TryFormatThrowFormatException(out bytesWritten); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatInt64D(long value, byte precision, Span destination, out int bytesWritten) { bool insertNegationSign = false; if (value < 0) { insertNegationSign = true; value = -value; } return TryFormatUInt64D((ulong)value, precision, destination, insertNegationSign, out bytesWritten); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatInt64Default(long value, Span destination, out int bytesWritten) { if ((ulong)value < 10uL) { return TryFormatUInt32SingleDigit((uint)value, destination, out bytesWritten); } if (IntPtr.Size == 8) { } if (value <= int.MaxValue && value >= int.MinValue) { return TryFormatInt32MultipleDigits((int)value, destination, out bytesWritten); } if (value <= 4294967295000000000L && value >= -4294967295000000000L) { if (value >= 0) { return TryFormatUInt64LessThanBillionMaxUInt((ulong)value, destination, out bytesWritten); } return TryFormatInt64MoreThanNegativeBillionMaxUInt(-value, destination, out bytesWritten); } if (value >= 0) { return TryFormatUInt64MoreThanBillionMaxUInt((ulong)value, destination, out bytesWritten); } return TryFormatInt64LessThanNegativeBillionMaxUInt(-value, destination, out bytesWritten); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatInt32MultipleDigits(int value, Span destination, out int bytesWritten) { if (value < 0) { value = -value; int num = FormattingHelpers.CountDigits((uint)value); if (num >= destination.Length) { bytesWritten = 0; return false; } destination[0] = 45; bytesWritten = num + 1; FormattingHelpers.WriteDigits((uint)value, destination.Slice(1, num)); return true; } return TryFormatUInt32MultipleDigits((uint)value, destination, out bytesWritten); } private static bool TryFormatInt64MoreThanNegativeBillionMaxUInt(long value, Span destination, out int bytesWritten) { uint num = (uint)(value / 1000000000); uint value2 = (uint)(value - num * 1000000000); int num2 = FormattingHelpers.CountDigits(num); int num3 = num2 + 9; if (num3 >= destination.Length) { bytesWritten = 0; return false; } destination[0] = 45; bytesWritten = num3 + 1; FormattingHelpers.WriteDigits(num, destination.Slice(1, num2)); FormattingHelpers.WriteDigits(value2, destination.Slice(num2 + 1, 9)); return true; } private static bool TryFormatInt64LessThanNegativeBillionMaxUInt(long value, Span destination, out int bytesWritten) { ulong num = (ulong)value / 1000000000uL; uint value2 = (uint)((ulong)value - num * 1000000000); uint num2 = (uint)(num / 1000000000); uint value3 = (uint)(num - num2 * 1000000000); int num3 = FormattingHelpers.CountDigits(num2); int num4 = num3 + 18; if (num4 >= destination.Length) { bytesWritten = 0; return false; } destination[0] = 45; bytesWritten = num4 + 1; FormattingHelpers.WriteDigits(num2, destination.Slice(1, num3)); FormattingHelpers.WriteDigits(value3, destination.Slice(num3 + 1, 9)); FormattingHelpers.WriteDigits(value2, destination.Slice(num3 + 1 + 9, 9)); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatInt64N(long value, byte precision, Span destination, out int bytesWritten) { bool insertNegationSign = false; if (value < 0) { insertNegationSign = true; value = -value; } return TryFormatUInt64N((ulong)value, precision, destination, insertNegationSign, out bytesWritten); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatUInt64(ulong value, Span destination, out int bytesWritten, StandardFormat format) { if (format.IsDefault) { return TryFormatUInt64Default(value, destination, out bytesWritten); } switch (format.Symbol) { case 'G': case 'g': if (format.HasPrecision) { throw new NotSupportedException(SR.Argument_GWithPrecisionNotSupported); } return TryFormatUInt64D(value, format.Precision, destination, insertNegationSign: false, out bytesWritten); case 'D': case 'd': return TryFormatUInt64D(value, format.Precision, destination, insertNegationSign: false, out bytesWritten); case 'N': case 'n': return TryFormatUInt64N(value, format.Precision, destination, insertNegationSign: false, out bytesWritten); case 'x': return TryFormatUInt64X(value, format.Precision, useLower: true, destination, out bytesWritten); case 'X': return TryFormatUInt64X(value, format.Precision, useLower: false, destination, out bytesWritten); default: return FormattingHelpers.TryFormatThrowFormatException(out bytesWritten); } } private static bool TryFormatUInt64D(ulong value, byte precision, Span destination, bool insertNegationSign, out int bytesWritten) { int num = FormattingHelpers.CountDigits(value); int num2 = ((precision != byte.MaxValue) ? precision : 0) - num; if (num2 < 0) { num2 = 0; } int num3 = num + num2; if (insertNegationSign) { num3++; } if (num3 > destination.Length) { bytesWritten = 0; return false; } bytesWritten = num3; if (insertNegationSign) { destination[0] = 45; destination = destination.Slice(1); } if (num2 > 0) { FormattingHelpers.FillWithAsciiZeros(destination.Slice(0, num2)); } FormattingHelpers.WriteDigits(value, destination.Slice(num2, num)); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatUInt64Default(ulong value, Span destination, out int bytesWritten) { if (value < 10) { return TryFormatUInt32SingleDigit((uint)value, destination, out bytesWritten); } if (IntPtr.Size == 8) { } if (value <= uint.MaxValue) { return TryFormatUInt32MultipleDigits((uint)value, destination, out bytesWritten); } if (value <= 4294967295000000000L) { return TryFormatUInt64LessThanBillionMaxUInt(value, destination, out bytesWritten); } return TryFormatUInt64MoreThanBillionMaxUInt(value, destination, out bytesWritten); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatUInt32SingleDigit(uint value, Span destination, out int bytesWritten) { if (destination.Length == 0) { bytesWritten = 0; return false; } destination[0] = (byte)(48 + value); bytesWritten = 1; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool TryFormatUInt32MultipleDigits(uint value, Span destination, out int bytesWritten) { int num = FormattingHelpers.CountDigits(value); if (num > destination.Length) { bytesWritten = 0; return false; } bytesWritten = num; FormattingHelpers.WriteDigits(value, destination.Slice(0, num)); return true; } private static bool TryFormatUInt64LessThanBillionMaxUInt(ulong value, Span destination, out int bytesWritten) { uint num = (uint)(value / 1000000000); uint value2 = (uint)(value - num * 1000000000); int num2 = FormattingHelpers.CountDigits(num); int num3 = num2 + 9; if (num3 > destination.Length) { bytesWritten = 0; return false; } bytesWritten = num3; FormattingHelpers.WriteDigits(num, destination.Slice(0, num2)); FormattingHelpers.WriteDigits(value2, destination.Slice(num2, 9)); return true; } private static bool TryFormatUInt64MoreThanBillionMaxUInt(ulong value, Span destination, out int bytesWritten) { ulong num = value / 1000000000; uint value2 = (uint)(value - num * 1000000000); uint num2 = (uint)(num / 1000000000); uint value3 = (uint)(num - num2 * 1000000000); int num3 = FormattingHelpers.CountDigits(num2); int num4 = num3 + 18; if (num4 > destination.Length) { bytesWritten = 0; return false; } bytesWritten = num4; FormattingHelpers.WriteDigits(num2, destination.Slice(0, num3)); FormattingHelpers.WriteDigits(value3, destination.Slice(num3, 9)); FormattingHelpers.WriteDigits(value2, destination.Slice(num3 + 9, 9)); return true; } private static bool TryFormatUInt64N(ulong value, byte precision, Span destination, bool insertNegationSign, out int bytesWritten) { int num = FormattingHelpers.CountDigits(value); int num2 = (num - 1) / 3; int num3 = ((precision == byte.MaxValue) ? 2 : precision); int num4 = num + num2; if (num3 > 0) { num4 += num3 + 1; } if (insertNegationSign) { num4++; } if (num4 > destination.Length) { bytesWritten = 0; return false; } bytesWritten = num4; if (insertNegationSign) { destination[0] = 45; destination = destination.Slice(1); } FormattingHelpers.WriteDigitsWithGroupSeparator(value, destination.Slice(0, num + num2)); if (num3 > 0) { destination[num + num2] = 46; FormattingHelpers.FillWithAsciiZeros(destination.Slice(num + num2 + 1, num3)); } return true; } private static bool TryFormatUInt64X(ulong value, byte precision, bool useLower, Span destination, out int bytesWritten) { int num = FormattingHelpers.CountHexDigits(value); int num2 = ((precision == byte.MaxValue) ? num : Math.Max(precision, num)); if (destination.Length < num2) { bytesWritten = 0; return false; } bytesWritten = num2; if (useLower) { while ((uint)(--num2) < (uint)destination.Length) { destination[num2] = (byte)HexConverter.ToCharLower((int)value); value >>= 4; } } else { while ((uint)(--num2) < (uint)destination.Length) { destination[num2] = (byte)HexConverter.ToCharUpper((int)value); value >>= 4; } } return true; } public static bool TryFormat(TimeSpan value, Span destination, out int bytesWritten, StandardFormat format = default(StandardFormat)) { char c = FormattingHelpers.GetSymbolOrDefault(in format, 'c'); switch (c) { case 'T': case 't': c = 'c'; break; default: return FormattingHelpers.TryFormatThrowFormatException(out bytesWritten); case 'G': case 'c': case 'g': break; } int num = 8; long ticks = value.Ticks; uint valueWithoutTrailingZeros; ulong num2; if (ticks < 0) { ticks = -ticks; if (ticks < 0) { valueWithoutTrailingZeros = 4775808u; num2 = 922337203685uL; goto IL_008d; } } (ulong Quotient, ulong Remainder) tuple = Math.DivRem((ulong)Math.Abs(value.Ticks), 10000000uL); num2 = tuple.Quotient; ulong item = tuple.Remainder; valueWithoutTrailingZeros = (uint)item; goto IL_008d; IL_008d: int num3 = 0; switch (c) { case 'c': if (valueWithoutTrailingZeros != 0) { num3 = 7; } break; case 'G': num3 = 7; break; default: if (valueWithoutTrailingZeros != 0) { num3 = 7 - FormattingHelpers.CountDecimalTrailingZeros(valueWithoutTrailingZeros, out valueWithoutTrailingZeros); } break; } if (num3 != 0) { num += num3 + 1; } ulong num4 = 0uL; ulong num5 = 0uL; if (num2 != 0) { (num4, num5) = Math.DivRem(num2, 60uL); } ulong num6 = 0uL; ulong num7 = 0uL; if (num4 != 0) { (num6, num7) = Math.DivRem(num4, 60uL); } uint num8 = 0u; uint num9 = 0u; if (num6 != 0) { (num8, num9) = Math.DivRem((uint)num6, 24u); } int num10 = 2; if (num9 < 10 && c == 'g') { num10--; num--; } int num11 = 0; if (num8 == 0) { if (c == 'G') { num += 2; num11 = 1; } } else { num11 = FormattingHelpers.CountDigits(num8); num += num11 + 1; } if (value.Ticks < 0) { num++; } if (destination.Length < num) { bytesWritten = 0; return false; } bytesWritten = num; int num12 = 0; if (value.Ticks < 0) { destination[num12++] = 45; } if (num11 > 0) { FormattingHelpers.WriteDigits(num8, destination.Slice(num12, num11)); num12 += num11; destination[num12++] = (byte)((c == 'c') ? 46 : 58); } FormattingHelpers.WriteDigits(num9, destination.Slice(num12, num10)); num12 += num10; destination[num12++] = 58; FormattingHelpers.WriteDigits((uint)num7, destination.Slice(num12, 2)); num12 += 2; destination[num12++] = 58; FormattingHelpers.WriteDigits((uint)num5, destination.Slice(num12, 2)); num12 += 2; if (num3 > 0) { destination[num12++] = 46; FormattingHelpers.WriteDigits(valueWithoutTrailingZeros, destination.Slice(num12, num3)); num12 += num3; } return true; } } internal static class ParserHelpers { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsDigit(int i) { return (uint)(i - 48) <= 9u; } public static bool TryParseThrowFormatException(out int bytesConsumed) { bytesConsumed = 0; ThrowHelper.ThrowFormatException_BadFormatSpecifier(); return false; } public static bool TryParseThrowFormatException(out T value, out int bytesConsumed) where T : struct { value = default(T); return TryParseThrowFormatException(out bytesConsumed); } [DoesNotReturn] [StackTraceHidden] public static bool TryParseThrowFormatException(ReadOnlySpan source, out T value, out int bytesConsumed) where T : struct { Unsafe.SkipInit(out value); Unsafe.SkipInit(out bytesConsumed); ThrowHelper.ThrowFormatException_BadFormatSpecifier(); return false; } } public static class Utf8Parser { [Flags] private enum ParseNumberOptions { AllowExponent = 1 } private enum ComponentParseResult : byte { NoMoreData, Colon, Period, ParseFailure } private struct TimeSpanSplitter { public uint V1; public uint V2; public uint V3; public uint V4; public uint V5; public bool IsNegative; public uint Separators; public bool TrySplitTimeSpan(ReadOnlySpan source, bool periodUsedToSeparateDay, out int bytesConsumed) { int i = 0; byte b = 0; for (; i != source.Length; i++) { b = source[i]; if (b != 32 && b != 9) { break; } } if (i == source.Length) { bytesConsumed = 0; return false; } if (b == 45) { IsNegative = true; i++; if (i == source.Length) { bytesConsumed = 0; return false; } } if (!TryParseUInt32D(source.Slice(i), out V1, out var bytesConsumed2)) { bytesConsumed = 0; return false; } i += bytesConsumed2; ComponentParseResult componentParseResult = ParseComponent(source, periodUsedToSeparateDay, ref i, out V2); switch (componentParseResult) { case ComponentParseResult.ParseFailure: bytesConsumed = 0; return false; case ComponentParseResult.NoMoreData: bytesConsumed = i; return true; default: Separators |= (uint)componentParseResult << 24; componentParseResult = ParseComponent(source, neverParseAsFraction: false, ref i, out V3); switch (componentParseResult) { case ComponentParseResult.ParseFailure: bytesConsumed = 0; return false; case ComponentParseResult.NoMoreData: bytesConsumed = i; return true; default: Separators |= (uint)componentParseResult << 16; componentParseResult = ParseComponent(source, neverParseAsFraction: false, ref i, out V4); switch (componentParseResult) { case ComponentParseResult.ParseFailure: bytesConsumed = 0; return false; case ComponentParseResult.NoMoreData: bytesConsumed = i; return true; default: Separators |= (uint)componentParseResult << 8; componentParseResult = ParseComponent(source, neverParseAsFraction: false, ref i, out V5); switch (componentParseResult) { case ComponentParseResult.ParseFailure: bytesConsumed = 0; return false; case ComponentParseResult.NoMoreData: bytesConsumed = i; return true; default: Separators |= (uint)componentParseResult; if (i != source.Length && (source[i] == 46 || source[i] == 58)) { bytesConsumed = 0; return false; } bytesConsumed = i; return true; } } } } } private static ComponentParseResult ParseComponent(ReadOnlySpan source, bool neverParseAsFraction, ref int srcIndex, out uint value) { if (srcIndex == source.Length) { value = 0u; return ComponentParseResult.NoMoreData; } byte b = source[srcIndex]; if (b == 58 || (b == 46 && neverParseAsFraction)) { srcIndex++; if (!TryParseUInt32D(source.Slice(srcIndex), out value, out var bytesConsumed)) { value = 0u; return ComponentParseResult.ParseFailure; } srcIndex += bytesConsumed; if (b != 58) { return ComponentParseResult.Period; } return ComponentParseResult.Colon; } if (b == 46) { srcIndex++; if (!TryParseTimeSpanFraction(source.Slice(srcIndex), out value, out var bytesConsumed2)) { value = 0u; return ComponentParseResult.ParseFailure; } srcIndex += bytesConsumed2; return ComponentParseResult.Period; } value = 0u; return ComponentParseResult.NoMoreData; } } private static readonly int[] s_daysToMonth365 = new int[13] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; private static readonly int[] s_daysToMonth366 = new int[13] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; public static bool TryParse(ReadOnlySpan source, out bool value, out int bytesConsumed, char standardFormat = '\0') { if (standardFormat != 0 && standardFormat != 'G' && standardFormat != 'l') { ThrowHelper.ThrowFormatException_BadFormatSpecifier(); } if (source.Length >= 4) { int num = BinaryPrimitives.ReadInt32LittleEndian(source) & -538976289; if (num == 1163219540) { bytesConsumed = 4; value = true; return true; } if (source.Length > 4 && num == 1397506374 && (source[4] & -33) == 69) { bytesConsumed = 5; value = false; return true; } } bytesConsumed = 0; value = false; return false; } public static bool TryParse(ReadOnlySpan source, out DateTime value, out int bytesConsumed, char standardFormat = '\0') { switch (standardFormat) { case 'R': { if (!TryParseDateTimeOffsetR(source, 0u, out var dateTimeOffset, out bytesConsumed)) { value = default(DateTime); return false; } value = dateTimeOffset.DateTime; return true; } case 'l': { if (!TryParseDateTimeOffsetR(source, 32u, out var dateTimeOffset2, out bytesConsumed)) { value = default(DateTime); return false; } value = dateTimeOffset2.DateTime; return true; } case 'O': { if (!TryParseDateTimeOffsetO(source, out var value2, out bytesConsumed, out var kind)) { value = default(DateTime); bytesConsumed = 0; return false; } switch (kind) { case DateTimeKind.Local: value = value2.LocalDateTime; break; case DateTimeKind.Utc: value = value2.UtcDateTime; break; default: value = value2.DateTime; break; } return true; } case '\0': case 'G': { DateTimeOffset valueAsOffset; return TryParseDateTimeG(source, out value, out valueAsOffset, out bytesConsumed); } default: return ParserHelpers.TryParseThrowFormatException(out value, out bytesConsumed); } } public static bool TryParse(ReadOnlySpan source, out DateTimeOffset value, out int bytesConsumed, char standardFormat = '\0') { DateTimeKind kind; DateTime value2; return standardFormat switch { 'R' => TryParseDateTimeOffsetR(source, 0u, out value, out bytesConsumed), 'l' => TryParseDateTimeOffsetR(source, 32u, out value, out bytesConsumed), 'O' => TryParseDateTimeOffsetO(source, out value, out bytesConsumed, out kind), '\0' => TryParseDateTimeOffsetDefault(source, out value, out bytesConsumed), 'G' => TryParseDateTimeG(source, out value2, out value, out bytesConsumed), _ => ParserHelpers.TryParseThrowFormatException(out value, out bytesConsumed), }; } private static bool TryParseDateTimeOffsetDefault(ReadOnlySpan source, out DateTimeOffset value, out int bytesConsumed) { if (source.Length < 26) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } if (!TryParseDateTimeG(source, out var value2, out var _, out var _)) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } if (source[19] != 32) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } byte b = source[20]; if (b != 43 && b != 45) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } uint num = (uint)(source[21] - 48); uint num2 = (uint)(source[22] - 48); if (num > 9 || num2 > 9) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } int offsetHours = (int)(num * 10 + num2); if (source[23] != 58) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } uint num3 = (uint)(source[24] - 48); uint num4 = (uint)(source[25] - 48); if (num3 > 9 || num4 > 9) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } int offsetMinutes = (int)(num3 * 10 + num4); if (!TryCreateDateTimeOffset(value2, b == 45, offsetHours, offsetMinutes, out value)) { bytesConsumed = 0; value = default(DateTimeOffset); return false; } bytesConsumed = 26; return true; } private static bool TryParseDateTimeG(ReadOnlySpan source, out DateTime value, out DateTimeOffset valueAsOffset, out int bytesConsumed) { if (source.Length < 19) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } uint num = (uint)(source[0] - 48); uint num2 = (uint)(source[1] - 48); if (num > 9 || num2 > 9) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } int month = (int)(num * 10 + num2); if (source[2] != 47) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } uint num3 = (uint)(source[3] - 48); uint num4 = (uint)(source[4] - 48); if (num3 > 9 || num4 > 9) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } int day = (int)(num3 * 10 + num4); if (source[5] != 47) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } uint num5 = (uint)(source[6] - 48); uint num6 = (uint)(source[7] - 48); uint num7 = (uint)(source[8] - 48); uint num8 = (uint)(source[9] - 48); if (num5 > 9 || num6 > 9 || num7 > 9 || num8 > 9) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } int year = (int)(num5 * 1000 + num6 * 100 + num7 * 10 + num8); if (source[10] != 32) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } uint num9 = (uint)(source[11] - 48); uint num10 = (uint)(source[12] - 48); if (num9 > 9 || num10 > 9) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } int hour = (int)(num9 * 10 + num10); if (source[13] != 58) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } uint num11 = (uint)(source[14] - 48); uint num12 = (uint)(source[15] - 48); if (num11 > 9 || num12 > 9) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } int minute = (int)(num11 * 10 + num12); if (source[16] != 58) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } uint num13 = (uint)(source[17] - 48); uint num14 = (uint)(source[18] - 48); if (num13 > 9 || num14 > 9) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } int second = (int)(num13 * 10 + num14); if (!TryCreateDateTimeOffsetInterpretingDataAsLocalTime(year, month, day, hour, minute, second, 0, out valueAsOffset)) { bytesConsumed = 0; value = default(DateTime); valueAsOffset = default(DateTimeOffset); return false; } bytesConsumed = 19; value = valueAsOffset.DateTime; return true; } private static bool TryCreateDateTimeOffset(DateTime dateTime, bool offsetNegative, int offsetHours, int offsetMinutes, out DateTimeOffset value) { if ((uint)offsetHours > 14u) { value = default(DateTimeOffset); return false; } if ((uint)offsetMinutes > 59u) { value = default(DateTimeOffset); return false; } if (offsetHours == 14 && offsetMinutes != 0) { value = default(DateTimeOffset); return false; } long num = ((long)offsetHours * 3600L + (long)offsetMinutes * 60L) * 10000000; if (offsetNegative) { num = -num; } try { value = new DateTimeOffset(dateTime.Ticks, new TimeSpan(num)); } catch (ArgumentOutOfRangeException) { value = default(DateTimeOffset); return false; } return true; } private static bool TryCreateDateTimeOffset(int year, int month, int day, int hour, int minute, int second, int fraction, bool offsetNegative, int offsetHours, int offsetMinutes, out DateTimeOffset value) { if (!TryCreateDateTime(year, month, day, hour, minute, second, fraction, DateTimeKind.Unspecified, out var value2)) { value = default(DateTimeOffset); return false; } if (!TryCreateDateTimeOffset(value2, offsetNegative, offsetHours, offsetMinutes, out value)) { value = default(DateTimeOffset); return false; } return true; } private static bool TryCreateDateTimeOffsetInterpretingDataAsLocalTime(int year, int month, int day, int hour, int minute, int second, int fraction, out DateTimeOffset value) { if (!TryCreateDateTime(year, month, day, hour, minute, second, fraction, DateTimeKind.Local, out var value2)) { value = default(DateTimeOffset); return false; } try { value = new DateTimeOffset(value2); } catch (ArgumentOutOfRangeException) { value = default(DateTimeOffset); return false; } return true; } private static bool TryCreateDateTime(int year, int month, int day, int hour, int minute, int second, int fraction, DateTimeKind kind, out DateTime value) { if (year == 0) { value = default(DateTime); return false; } if ((uint)(month - 1) >= 12u) { value = default(DateTime); return false; } uint num = (uint)(day - 1); if (num >= 28 && num >= DateTime.DaysInMonth(year, month)) { value = default(DateTime); return false; } if ((uint)hour > 23u) { value = default(DateTime); return false; } if ((uint)minute > 59u) { value = default(DateTime); return false; } if ((uint)second > 59u) { value = default(DateTime); return false; } int[] array = (DateTime.IsLeapYear(year) ? s_daysToMonth366 : s_daysToMonth365); int num2 = year - 1; int num3 = num2 * 365 + num2 / 4 - num2 / 100 + num2 / 400 + array[month - 1] + day - 1; long num4 = num3 * 864000000000L; int num5 = hour * 3600 + minute * 60 + second; num4 += (long)num5 * 10000000L; num4 += fraction; value = new DateTime(num4, kind); return true; } private static bool TryParseDateTimeOffsetO(ReadOnlySpan source, out DateTimeOffset value, out int bytesConsumed, out DateTimeKind kind) { if (source.Length < 27) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num = (uint)(source[0] - 48); uint num2 = (uint)(source[1] - 48); uint num3 = (uint)(source[2] - 48); uint num4 = (uint)(source[3] - 48); if (num > 9 || num2 > 9 || num3 > 9 || num4 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int year = (int)(num * 1000 + num2 * 100 + num3 * 10 + num4); if (source[4] != 45) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num5 = (uint)(source[5] - 48); uint num6 = (uint)(source[6] - 48); if (num5 > 9 || num6 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int month = (int)(num5 * 10 + num6); if (source[7] != 45) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num7 = (uint)(source[8] - 48); uint num8 = (uint)(source[9] - 48); if (num7 > 9 || num8 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int day = (int)(num7 * 10 + num8); if (source[10] != 84) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num9 = (uint)(source[11] - 48); uint num10 = (uint)(source[12] - 48); if (num9 > 9 || num10 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int hour = (int)(num9 * 10 + num10); if (source[13] != 58) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num11 = (uint)(source[14] - 48); uint num12 = (uint)(source[15] - 48); if (num11 > 9 || num12 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int minute = (int)(num11 * 10 + num12); if (source[16] != 58) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num13 = (uint)(source[17] - 48); uint num14 = (uint)(source[18] - 48); if (num13 > 9 || num14 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int second = (int)(num13 * 10 + num14); if (source[19] != 46) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num15 = (uint)(source[20] - 48); uint num16 = (uint)(source[21] - 48); uint num17 = (uint)(source[22] - 48); uint num18 = (uint)(source[23] - 48); uint num19 = (uint)(source[24] - 48); uint num20 = (uint)(source[25] - 48); uint num21 = (uint)(source[26] - 48); if (num15 > 9 || num16 > 9 || num17 > 9 || num18 > 9 || num19 > 9 || num20 > 9 || num21 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int fraction = (int)(num15 * 1000000 + num16 * 100000 + num17 * 10000 + num18 * 1000 + num19 * 100 + num20 * 10 + num21); byte b = (byte)((source.Length > 27) ? source[27] : 0); if (b != 90 && b != 43 && b != 45) { if (!TryCreateDateTimeOffsetInterpretingDataAsLocalTime(year, month, day, hour, minute, second, fraction, out value)) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } bytesConsumed = 27; kind = DateTimeKind.Unspecified; return true; } if (b == 90) { if (!TryCreateDateTimeOffset(year, month, day, hour, minute, second, fraction, offsetNegative: false, 0, 0, out value)) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } bytesConsumed = 28; kind = DateTimeKind.Utc; return true; } if (source.Length < 33) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num22 = (uint)(source[28] - 48); uint num23 = (uint)(source[29] - 48); if (num22 > 9 || num23 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int offsetHours = (int)(num22 * 10 + num23); if (source[30] != 58) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } uint num24 = (uint)(source[31] - 48); uint num25 = (uint)(source[32] - 48); if (num24 > 9 || num25 > 9) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } int offsetMinutes = (int)(num24 * 10 + num25); if (!TryCreateDateTimeOffset(year, month, day, hour, minute, second, fraction, b == 45, offsetHours, offsetMinutes, out value)) { value = default(DateTimeOffset); bytesConsumed = 0; kind = DateTimeKind.Unspecified; return false; } bytesConsumed = 33; kind = DateTimeKind.Local; return true; } private static bool TryParseDateTimeOffsetR(ReadOnlySpan source, uint caseFlipXorMask, out DateTimeOffset dateTimeOffset, out int bytesConsumed) { if (source.Length < 29) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } uint num = source[0] ^ caseFlipXorMask; uint num2 = source[1]; uint num3 = source[2]; uint num4 = source[3]; DayOfWeek dayOfWeek; switch ((num << 24) | (num2 << 16) | (num3 << 8) | num4) { case 1400204844u: dayOfWeek = DayOfWeek.Sunday; break; case 1299148332u: dayOfWeek = DayOfWeek.Monday; break; case 1416979756u: dayOfWeek = DayOfWeek.Tuesday; break; case 1466262572u: dayOfWeek = DayOfWeek.Wednesday; break; case 1416131884u: dayOfWeek = DayOfWeek.Thursday; break; case 1181903148u: dayOfWeek = DayOfWeek.Friday; break; case 1398895660u: dayOfWeek = DayOfWeek.Saturday; break; default: bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } if (source[4] != 32) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } uint num5 = (uint)(source[5] - 48); uint num6 = (uint)(source[6] - 48); if (num5 > 9 || num6 > 9) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } int day = (int)(num5 * 10 + num6); if (source[7] != 32) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } uint num7 = source[8] ^ caseFlipXorMask; uint num8 = source[9]; uint num9 = source[10]; uint num10 = source[11]; int month; switch ((num7 << 24) | (num8 << 16) | (num9 << 8) | num10) { case 1247899168u: month = 1; break; case 1181049376u: month = 2; break; case 1298231840u: month = 3; break; case 1097888288u: month = 4; break; case 1298233632u: month = 5; break; case 1249209888u: month = 6; break; case 1249209376u: month = 7; break; case 1098213152u: month = 8; break; case 1399156768u: month = 9; break; case 1331917856u: month = 10; break; case 1315927584u: month = 11; break; case 1147495200u: month = 12; break; default: bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } uint num11 = (uint)(source[12] - 48); uint num12 = (uint)(source[13] - 48); uint num13 = (uint)(source[14] - 48); uint num14 = (uint)(source[15] - 48); if (num11 > 9 || num12 > 9 || num13 > 9 || num14 > 9) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } int year = (int)(num11 * 1000 + num12 * 100 + num13 * 10 + num14); if (source[16] != 32) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } uint num15 = (uint)(source[17] - 48); uint num16 = (uint)(source[18] - 48); if (num15 > 9 || num16 > 9) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } int hour = (int)(num15 * 10 + num16); if (source[19] != 58) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } uint num17 = (uint)(source[20] - 48); uint num18 = (uint)(source[21] - 48); if (num17 > 9 || num18 > 9) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } int minute = (int)(num17 * 10 + num18); if (source[22] != 58) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } uint num19 = (uint)(source[23] - 48); uint num20 = (uint)(source[24] - 48); if (num19 > 9 || num20 > 9) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } int second = (int)(num19 * 10 + num20); uint num21 = source[25]; uint num22 = source[26] ^ caseFlipXorMask; uint num23 = source[27] ^ caseFlipXorMask; uint num24 = source[28] ^ caseFlipXorMask; uint num25 = (num21 << 24) | (num22 << 16) | (num23 << 8) | num24; if (num25 != 541543764) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } if (!TryCreateDateTimeOffset(year, month, day, hour, minute, second, 0, offsetNegative: false, 0, 0, out dateTimeOffset)) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } if (dayOfWeek != dateTimeOffset.DayOfWeek) { bytesConsumed = 0; dateTimeOffset = default(DateTimeOffset); return false; } bytesConsumed = 29; return true; } public unsafe static bool TryParse(ReadOnlySpan source, out decimal value, out int bytesConsumed, char standardFormat = '\0') { ParseNumberOptions options; switch (standardFormat) { case '\0': case 'E': case 'G': case 'e': case 'g': options = ParseNumberOptions.AllowExponent; break; case 'F': case 'f': options = (ParseNumberOptions)0; break; default: return ParserHelpers.TryParseThrowFormatException(out value, out bytesConsumed); } byte* digits = stackalloc byte[31]; Number.NumberBuffer number = new Number.NumberBuffer(Number.NumberBufferKind.Decimal, digits, 31); if (!TryParseNumber(source, ref number, out bytesConsumed, options, out var textUsedExponentNotation)) { value = default(decimal); return false; } if (!textUsedExponentNotation && (standardFormat == 'E' || standardFormat == 'e')) { value = default(decimal); bytesConsumed = 0; return false; } value = default(decimal); if (!Number.TryNumberToDecimal(ref number, ref value)) { value = default(decimal); bytesConsumed = 0; return false; } return true; } public unsafe static bool TryParse(ReadOnlySpan source, out float value, out int bytesConsumed, char standardFormat = '\0') { byte* digits = stackalloc byte[114]; Number.NumberBuffer number = new Number.NumberBuffer(Number.NumberBufferKind.FloatingPoint, digits, 114); if (TryParseNormalAsFloatingPoint(source, ref number, out bytesConsumed, standardFormat)) { value = Number.NumberToSingle(ref number); return true; } return TryParseAsSpecialFloatingPoint(source, float.PositiveInfinity, float.NegativeInfinity, float.NaN, out value, out bytesConsumed); } public unsafe static bool TryParse(ReadOnlySpan source, out double value, out int bytesConsumed, char standardFormat = '\0') { byte* digits = stackalloc byte[769]; Number.NumberBuffer number = new Number.NumberBuffer(Number.NumberBufferKind.FloatingPoint, digits, 769); if (TryParseNormalAsFloatingPoint(source, ref number, out bytesConsumed, standardFormat)) { value = Number.NumberToDouble(ref number); return true; } return TryParseAsSpecialFloatingPoint(source, double.PositiveInfinity, double.NegativeInfinity, double.NaN, out value, out bytesConsumed); } private static bool TryParseNormalAsFloatingPoint(ReadOnlySpan source, ref Number.NumberBuffer number, out int bytesConsumed, char standardFormat) { ParseNumberOptions options; switch (standardFormat) { case '\0': case 'E': case 'G': case 'e': case 'g': options = ParseNumberOptions.AllowExponent; break; case 'F': case 'f': options = (ParseNumberOptions)0; break; default: return ParserHelpers.TryParseThrowFormatException(out bytesConsumed); } if (!TryParseNumber(source, ref number, out bytesConsumed, options, out var textUsedExponentNotation)) { return false; } if (!textUsedExponentNotation && (standardFormat == 'E' || standardFormat == 'e')) { bytesConsumed = 0; return false; } return true; } private static bool TryParseAsSpecialFloatingPoint(ReadOnlySpan source, T positiveInfinity, T negativeInfinity, T nan, out T value, out int bytesConsumed) where T : struct { int num = 0; int num2 = source.Length; bool flag = false; if (num2 >= 4) { byte b = source[num]; if (b != 43) { if (b != 45) { goto IL_002e; } flag = true; } num++; num2--; } goto IL_002e; IL_002e: if (num2 >= 3) { if (((source[num] ^ 0x6E) & -33) == 0 && ((source[num + 1] ^ 0x61) & -33) == 0 && ((source[num + 2] ^ 0x6E) & -33) == 0) { value = nan; bytesConsumed = 3 + num; return true; } if (num2 >= 8) { int num3 = BinaryPrimitives.ReadInt32LittleEndian(source.Slice(num)) ^ 0x69666E69; if ((num3 & -538976289) == 0) { num3 = BinaryPrimitives.ReadInt32LittleEndian(source.Slice(num + 4)) ^ 0x7974696E; if ((num3 & -538976289) == 0) { value = (flag ? negativeInfinity : positiveInfinity); bytesConsumed = 8 + num; return true; } } } } value = default(T); bytesConsumed = 0; return false; } public static bool TryParse(ReadOnlySpan source, out Guid value, out int bytesConsumed, char standardFormat = '\0') { while (true) { switch (standardFormat) { case '\0': return TryParseGuidCore(source, out value, out bytesConsumed, 0); case 'D': break; case 'B': return TryParseGuidCore(source, out value, out bytesConsumed, 32123); case 'P': return TryParseGuidCore(source, out value, out bytesConsumed, 10536); case 'N': return TryParseGuidN(source, out value, out bytesConsumed); default: return ParserHelpers.TryParseThrowFormatException(source, out value, out bytesConsumed); } standardFormat = '\0'; } } private static bool TryParseGuidN(ReadOnlySpan text, out Guid value, out int bytesConsumed) { if (text.Length < 32) { value = default(Guid); bytesConsumed = 0; return false; } if (!TryParseUInt32X(text.Slice(0, 8), out var value2, out var bytesConsumed2) || bytesConsumed2 != 8) { value = default(Guid); bytesConsumed = 0; return false; } if (!TryParseUInt16X(text.Slice(8, 4), out var value3, out bytesConsumed2) || bytesConsumed2 != 4) { value = default(Guid); bytesConsumed = 0; return false; } if (!TryParseUInt16X(text.Slice(12, 4), out var value4, out bytesConsumed2) || bytesConsumed2 != 4) { value = default(Guid); bytesConsumed = 0; return false; } if (!TryParseUInt16X(text.Slice(16, 4), out var value5, out bytesConsumed2) || bytesConsumed2 != 4) { value = default(Guid); bytesConsumed = 0; return false; } if (!TryParseUInt64X(text.Slice(20), out var value6, out bytesConsumed2) || bytesConsumed2 != 12) { value = default(Guid); bytesConsumed = 0; return false; } bytesConsumed = 32; value = new Guid((int)value2, (short)value3, (short)value4, (byte)(value5 >> 8), (byte)value5, (byte)(value6 >> 40), (byte)(value6 >> 32), (byte)(value6 >> 24), (byte)(value6 >> 16), (byte)(value6 >> 8), (byte)value6); return true; } private static bool TryParseGuidCore(ReadOnlySpan source, out Guid value, out int bytesConsumed, int ends) { int num = 36 + ((ends != 0) ? 2 : 0); if (source.Length < num) { value = default(Guid); bytesConsumed = 0; return false; } if (ends != 0) { if (source[0] != (byte)ends) { value = default(Guid); bytesConsumed = 0; return false; } source = source.Slice(1); ends >>= 8; } if (!TryParseUInt32X(source, out var value2, out var bytesConsumed2)) { value = default(Guid); bytesConsumed = 0; return false; } if (bytesConsumed2 != 8) { value = default(Guid); bytesConsumed = 0; return false; } if (source[bytesConsumed2] != 45) { value = default(Guid); bytesConsumed = 0; return false; } source = source.Slice(9); if (!TryParseUInt16X(source, out var value3, out bytesConsumed2)) { value = default(Guid); bytesConsumed = 0; return false; } if (bytesConsumed2 != 4) { value = default(Guid); bytesConsumed = 0; return false; } if (source[bytesConsumed2] != 45) { value = default(Guid); bytesConsumed = 0; return false; } source = source.Slice(5); if (!TryParseUInt16X(source, out var value4, out bytesConsumed2)) { value = default(Guid); bytesConsumed = 0; return false; } if (bytesConsumed2 != 4) { value = default(Guid); bytesConsumed = 0; return false; } if (source[bytesConsumed2] != 45) { value = default(Guid); bytesConsumed = 0; return false; } source = source.Slice(5); if (!TryParseUInt16X(source, out var value5, out bytesConsumed2)) { value = default(Guid); bytesConsumed = 0; return false; } if (bytesConsumed2 != 4) { value = default(Guid); bytesConsumed = 0; return false; } if (source[bytesConsumed2] != 45) { value = default(Guid); bytesConsumed = 0; return false; } source = source.Slice(5); if (!TryParseUInt64X(source, out var value6, out bytesConsumed2)) { value = default(Guid); bytesConsumed = 0; return false; } if (bytesConsumed2 != 12) { value = default(Guid); bytesConsumed = 0; return false; } if (ends != 0 && source[bytesConsumed2] != (byte)ends) { value = default(Guid); bytesConsumed = 0; return false; } bytesConsumed = num; value = new Guid((int)value2, (short)value3, (short)value4, (byte)(value5 >> 8), (byte)value5, (byte)(value6 >> 40), (byte)(value6 >> 32), (byte)(value6 >> 24), (byte)(value6 >> 16), (byte)(value6 >> 8), (byte)value6); return true; } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan source, out sbyte value, out int bytesConsumed, char standardFormat = '\0') { while (standardFormat != 0) { switch (standardFormat | 0x20) { case 100: case 103: break; case 110: return TryParseSByteN(source, out value, out bytesConsumed); case 120: Unsafe.SkipInit(out value); return TryParseByteX(source, out Unsafe.As(ref value), out bytesConsumed); default: return ParserHelpers.TryParseThrowFormatException(source, out value, out bytesConsumed); } standardFormat = '\0'; } return TryParseSByteD(source, out value, out bytesConsumed); } public static bool TryParse(ReadOnlySpan source, out short value, out int bytesConsumed, char standardFormat = '\0') { while (standardFormat != 0) { switch (standardFormat | 0x20) { case 100: case 103: break; case 110: return TryParseInt16N(source, out value, out bytesConsumed); case 120: Unsafe.SkipInit(out value); return TryParseUInt16X(source, out Unsafe.As(ref value), out bytesConsumed); default: return ParserHelpers.TryParseThrowFormatException(source, out value, out bytesConsumed); } standardFormat = '\0'; } return TryParseInt16D(source, out value, out bytesConsumed); } public static bool TryParse(ReadOnlySpan source, out int value, out int bytesConsumed, char standardFormat = '\0') { while (standardFormat != 0) { switch (standardFormat | 0x20) { case 100: case 103: break; case 110: return TryParseInt32N(source, out value, out bytesConsumed); case 120: Unsafe.SkipInit(out value); return TryParseUInt32X(source, out Unsafe.As(ref value), out bytesConsumed); default: return ParserHelpers.TryParseThrowFormatException(source, out value, out bytesConsumed); } standardFormat = '\0'; } return TryParseInt32D(source, out value, out bytesConsumed); } public static bool TryParse(ReadOnlySpan source, out long value, out int bytesConsumed, char standardFormat = '\0') { while (standardFormat != 0) { switch (standardFormat | 0x20) { case 100: case 103: break; case 110: return TryParseInt64N(source, out value, out bytesConsumed); case 120: Unsafe.SkipInit(out value); return TryParseUInt64X(source, out Unsafe.As(ref value), out bytesConsumed); default: return ParserHelpers.TryParseThrowFormatException(source, out value, out bytesConsumed); } standardFormat = '\0'; } return TryParseInt64D(source, out value, out bytesConsumed); } private static bool TryParseSByteD(ReadOnlySpan source, out sbyte value, out int bytesConsumed) { int num; int num2; int num4; int num3; if (source.Length >= 1) { num = 1; num2 = 0; num3 = source[num2]; if (num3 == 45) { num = -1; num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0123; } num3 = source[num2]; } else if (num3 == 43) { num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0123; } num3 = source[num2]; } num4 = 0; if (ParserHelpers.IsDigit(num3)) { if (num3 != 48) { goto IL_009c; } while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 48) { continue; } goto IL_0091; } goto IL_012b; } } goto IL_0123; IL_0123: bytesConsumed = 0; value = 0; return false; IL_0091: if (ParserHelpers.IsDigit(num3)) { goto IL_009c; } goto IL_012b; IL_012b: bytesConsumed = num2; value = (sbyte)(num4 * num); return true; IL_009c: num4 = num3 - 48; num2++; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; num4 = num4 * 10 + num3 - 48; if ((uint)num4 > 127L + (long)((-1 * num + 1) / 2) || ((uint)num2 < (uint)source.Length && ParserHelpers.IsDigit(source[num2]))) { goto IL_0123; } } } } } goto IL_012b; } private static bool TryParseInt16D(ReadOnlySpan source, out short value, out int bytesConsumed) { int num; int num2; int num4; int num3; if (source.Length >= 1) { num = 1; num2 = 0; num3 = source[num2]; if (num3 == 45) { num = -1; num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0186; } num3 = source[num2]; } else if (num3 == 43) { num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0186; } num3 = source[num2]; } num4 = 0; if (ParserHelpers.IsDigit(num3)) { if (num3 != 48) { goto IL_009c; } while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 48) { continue; } goto IL_0091; } goto IL_018e; } } goto IL_0186; IL_0186: bytesConsumed = 0; value = 0; return false; IL_0091: if (ParserHelpers.IsDigit(num3)) { goto IL_009c; } goto IL_018e; IL_018e: bytesConsumed = num2; value = (short)(num4 * num); return true; IL_009c: num4 = num3 - 48; num2++; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; num4 = num4 * 10 + num3 - 48; if ((uint)num4 > 32767L + (long)((-1 * num + 1) / 2) || ((uint)num2 < (uint)source.Length && ParserHelpers.IsDigit(source[num2]))) { goto IL_0186; } } } } } } } } } goto IL_018e; } private static bool TryParseInt32D(ReadOnlySpan source, out int value, out int bytesConsumed) { int num; int num2; int num4; int num3; if (source.Length >= 1) { num = 1; num2 = 0; num3 = source[num2]; if (num3 == 45) { num = -1; num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0281; } num3 = source[num2]; } else if (num3 == 43) { num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0281; } num3 = source[num2]; } num4 = 0; if (ParserHelpers.IsDigit(num3)) { if (num3 != 48) { goto IL_009c; } while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 48) { continue; } goto IL_0091; } goto IL_0289; } } goto IL_0281; IL_0281: bytesConsumed = 0; value = 0; return false; IL_0091: if (ParserHelpers.IsDigit(num3)) { goto IL_009c; } goto IL_0289; IL_0289: bytesConsumed = num2; value = num4 * num; return true; IL_009c: num4 = num3 - 48; num2++; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; num4 = 10 * num4 + num3 - 48; if ((uint)num2 < (uint)source.Length) { num3 = source[num2]; if (ParserHelpers.IsDigit(num3)) { num2++; if (num4 <= 214748364) { num4 = num4 * 10 + num3 - 48; if ((uint)num4 <= 2147483647L + (long)((-1 * num + 1) / 2) && ((uint)num2 >= (uint)source.Length || !ParserHelpers.IsDigit(source[num2]))) { goto IL_0289; } } goto IL_0281; } } } } } } } } } } } } } } } } } } goto IL_0289; } private static bool TryParseInt64D(ReadOnlySpan source, out long value, out int bytesConsumed) { long num = 0L; int num2 = 0; while ((uint)num2 < (uint)source.Length) { nuint num3 = (uint)(source[num2] - 48); if ((uint)num3 > 9) { if (num2 != 0) { break; } num2++; if ((int)num3 == -3) { num--; } else if ((int)num3 != -5) { break; } continue; } ulong num4 = num3; int num5 = 19 + num2; num2++; if (source.Length < num5) { for (; (uint)num2 < (uint)source.Length; num2++) { nuint num6 = (uint)(source[num2] - 48); if ((uint)num6 > 9) { break; } num4 = num4 * 10 + num6; } } else { while ((uint)num2 < (uint)source.Length) { nuint num7 = (uint)(source[num2] - 48); if ((uint)num7 > 9) { break; } num2++; if (num4 < 922337203685477580L) { num4 = num4 * 10 + num7; continue; } if (num4 != 922337203685477580L || (int)num7 + (int)num > 7) { goto end_IL_0005; } num4 = 9223372036854775800uL + (ulong)num7; } } bytesConsumed = num2; value = (long)(num4 ^ (ulong)num) - num; return true; continue; end_IL_0005: break; } bytesConsumed = 0; value = 0L; return false; } private static bool TryParseSByteN(ReadOnlySpan source, out sbyte value, out int bytesConsumed) { int num; int num2; int num4; int num3; if (source.Length >= 1) { num = 1; num2 = 0; num3 = source[num2]; if (num3 == 45) { num = -1; num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_00f9; } num3 = source[num2]; } else if (num3 == 43) { num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_00f9; } num3 = source[num2]; } if (num3 != 46) { if (ParserHelpers.IsDigit(num3)) { num4 = num3 - 48; while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 44) { continue; } if (num3 == 46) { goto IL_00d4; } if (!ParserHelpers.IsDigit(num3)) { break; } num4 = num4 * 10 + num3 - 48; if (num4 <= 127 + (-1 * num + 1) / 2) { continue; } goto IL_00f9; } goto IL_0101; } } else { num4 = 0; num2++; if ((uint)num2 < (uint)source.Length && source[num2] == 48) { goto IL_00d4; } } } goto IL_00f9; IL_00f9: bytesConsumed = 0; value = 0; return false; IL_0101: bytesConsumed = num2; value = (sbyte)(num4 * num); return true; IL_00d4: while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 48) { continue; } goto IL_00f1; } goto IL_0101; IL_00f1: if (ParserHelpers.IsDigit(num3)) { goto IL_00f9; } goto IL_0101; } private static bool TryParseInt16N(ReadOnlySpan source, out short value, out int bytesConsumed) { int num; int num2; int num4; int num3; if (source.Length >= 1) { num = 1; num2 = 0; num3 = source[num2]; if (num3 == 45) { num = -1; num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_00ff; } num3 = source[num2]; } else if (num3 == 43) { num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_00ff; } num3 = source[num2]; } if (num3 != 46) { if (ParserHelpers.IsDigit(num3)) { num4 = num3 - 48; while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 44) { continue; } if (num3 == 46) { goto IL_00da; } if (!ParserHelpers.IsDigit(num3)) { break; } num4 = num4 * 10 + num3 - 48; if (num4 <= 32767 + (-1 * num + 1) / 2) { continue; } goto IL_00ff; } goto IL_0107; } } else { num4 = 0; num2++; if ((uint)num2 < (uint)source.Length && source[num2] == 48) { goto IL_00da; } } } goto IL_00ff; IL_00ff: bytesConsumed = 0; value = 0; return false; IL_0107: bytesConsumed = num2; value = (short)(num4 * num); return true; IL_00da: while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 48) { continue; } goto IL_00f7; } goto IL_0107; IL_00f7: if (ParserHelpers.IsDigit(num3)) { goto IL_00ff; } goto IL_0107; } private static bool TryParseInt32N(ReadOnlySpan source, out int value, out int bytesConsumed) { int num; int num2; int num4; int num3; if (source.Length >= 1) { num = 1; num2 = 0; num3 = source[num2]; if (num3 == 45) { num = -1; num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_010a; } num3 = source[num2]; } else if (num3 == 43) { num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_010a; } num3 = source[num2]; } if (num3 != 46) { if (ParserHelpers.IsDigit(num3)) { num4 = num3 - 48; while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 44) { continue; } if (num3 == 46) { goto IL_00e5; } if (!ParserHelpers.IsDigit(num3)) { break; } if ((uint)num4 <= 214748364u) { num4 = num4 * 10 + num3 - 48; if ((uint)num4 <= 2147483647L + (long)((-1 * num + 1) / 2)) { continue; } } goto IL_010a; } goto IL_0112; } } else { num4 = 0; num2++; if ((uint)num2 < (uint)source.Length && source[num2] == 48) { goto IL_00e5; } } } goto IL_010a; IL_010a: bytesConsumed = 0; value = 0; return false; IL_0112: bytesConsumed = num2; value = num4 * num; return true; IL_00e5: while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 48) { continue; } goto IL_0102; } goto IL_0112; IL_0102: if (ParserHelpers.IsDigit(num3)) { goto IL_010a; } goto IL_0112; } private static bool TryParseInt64N(ReadOnlySpan source, out long value, out int bytesConsumed) { int num; int num2; long num4; int num3; if (source.Length >= 1) { num = 1; num2 = 0; num3 = source[num2]; if (num3 == 45) { num = -1; num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0115; } num3 = source[num2]; } else if (num3 == 43) { num2++; if ((uint)num2 >= (uint)source.Length) { goto IL_0115; } num3 = source[num2]; } if (num3 != 46) { if (ParserHelpers.IsDigit(num3)) { num4 = num3 - 48; while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 44) { continue; } if (num3 == 46) { goto IL_00f0; } if (!ParserHelpers.IsDigit(num3)) { break; } if ((ulong)num4 <= 922337203685477580uL) { num4 = num4 * 10 + num3 - 48; if ((ulong)num4 <= (ulong)(long.MaxValue + (-1 * num + 1) / 2)) { continue; } } goto IL_0115; } goto IL_011e; } } else { num4 = 0L; num2++; if ((uint)num2 < (uint)source.Length && source[num2] == 48) { goto IL_00f0; } } } goto IL_0115; IL_0115: bytesConsumed = 0; value = 0L; return false; IL_011e: bytesConsumed = num2; value = num4 * num; return true; IL_00f0: while (true) { num2++; if ((uint)num2 >= (uint)source.Length) { break; } num3 = source[num2]; if (num3 == 48) { continue; } goto IL_010d; } goto IL_011e; IL_010d: if (ParserHelpers.IsDigit(num3)) { goto IL_0115; } goto IL_011e; } public static bool TryParse(ReadOnlySpan source, out byte value, out int bytesConsumed, char standardFormat = '\0') { while (standardFormat != 0) { switch (standardFormat | 0x20) { case 100: case 103: break; case 110: return TryParseByteN(source, out value, out bytesConsumed); case 120: return TryParseByteX(source, out value, out bytesConsumed); default: return ParserHelpers.TryParseThrowFormatException(source, out value, out bytesConsumed); } standardFormat = '\0'; } return TryParseByteD(source, out value, out bytesConsumed); } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan source, out ushort value, out int bytesConsumed, char standardFormat = '\0') { while (standardFormat != 0) { switch (standardFormat | 0x20) { case 100: case 103: break; case 110: return TryParseUInt16N(source, out value, out bytesConsumed); case 120: return TryParseUInt16X(source, out value, out bytesConsumed); default: return ParserHelpers.TryParseThrowFormatException(source, out value, out bytesConsumed); } standardFormat = '\0'; } return TryParseUInt16D(source, out value, out bytesConsumed); } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan source, out uint value, out int bytesConsumed, char standardFormat = '\0') { while (standardFormat != 0) { switch (standardFormat | 0x20) { case 100: case 103: break; case 110: return TryParseUInt32N(source, out value, out bytesConsumed); case 120: return TryParseUInt32X(source, out value, out bytesConsumed); default: return ParserHelpers.TryParseThrowFormatException(source, out value, out bytesConsumed); } standardFormat = '\0'; } return TryParseUInt32D(source, out value, out bytesConsumed); } [CLSCompliant(false)] public static bool TryParse(ReadOnlySpan source, out ulong value, out int bytesConsumed, char standardFormat = '\0') { while (standardFormat != 0) { switch (standardFormat | 0x20) { case 100: case 103: break; case 110: return TryParseUInt64N(source, out value, out bytesConsumed); case 120: return TryParseUInt64X(source, out value, out bytesConsumed); default: return ParserHelpers.TryParseThrowFormatException(source, out value, out bytesConsumed); } standardFormat = '\0'; } return TryParseUInt64D(source, out value, out bytesConsumed); } private static bool TryParseByteD(ReadOnlySpan source, out byte value, out int bytesConsumed) { int num; int num3; int num2; if (source.Length >= 1) { num = 0; num2 = source[num]; num3 = 0; if (ParserHelpers.IsDigit(num2)) { if (num2 != 48) { goto IL_0056; } while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 48) { continue; } goto IL_004b; } goto IL_00dd; } } goto IL_00d5; IL_004b: if (ParserHelpers.IsDigit(num2)) { goto IL_0056; } goto IL_00dd; IL_0056: num3 = num2 - 48; num++; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; num3 = num3 * 10 + num2 - 48; if ((uint)num3 > 255u || ((uint)num < (uint)source.Length && ParserHelpers.IsDigit(source[num]))) { goto IL_00d5; } } } } } goto IL_00dd; IL_00dd: bytesConsumed = num; value = (byte)num3; return true; IL_00d5: bytesConsumed = 0; value = 0; return false; } private static bool TryParseUInt16D(ReadOnlySpan source, out ushort value, out int bytesConsumed) { int num; int num3; int num2; if (source.Length >= 1) { num = 0; num2 = source[num]; num3 = 0; if (ParserHelpers.IsDigit(num2)) { if (num2 != 48) { goto IL_0056; } while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 48) { continue; } goto IL_004b; } goto IL_013d; } } goto IL_0135; IL_004b: if (ParserHelpers.IsDigit(num2)) { goto IL_0056; } goto IL_013d; IL_0056: num3 = num2 - 48; num++; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; num3 = num3 * 10 + num2 - 48; if ((uint)num3 > 65535u || ((uint)num < (uint)source.Length && ParserHelpers.IsDigit(source[num]))) { goto IL_0135; } } } } } } } } } goto IL_013d; IL_013d: bytesConsumed = num; value = (ushort)num3; return true; IL_0135: bytesConsumed = 0; value = 0; return false; } private static bool TryParseUInt32D(ReadOnlySpan source, out uint value, out int bytesConsumed) { int num; int num3; int num2; if (source.Length >= 1) { num = 0; num2 = source[num]; num3 = 0; if (ParserHelpers.IsDigit(num2)) { if (num2 != 48) { goto IL_0056; } while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 48) { continue; } goto IL_004b; } goto IL_023d; } } goto IL_0235; IL_004b: if (ParserHelpers.IsDigit(num2)) { goto IL_0056; } goto IL_023d; IL_0056: num3 = num2 - 48; num++; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; num3 = 10 * num3 + num2 - 48; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (ParserHelpers.IsDigit(num2)) { num++; if ((uint)num3 <= 429496729u && (num3 != 429496729 || num2 <= 53)) { num3 = num3 * 10 + num2 - 48; if ((uint)num >= (uint)source.Length || !ParserHelpers.IsDigit(source[num])) { goto IL_023d; } } goto IL_0235; } } } } } } } } } } } } } } } } } } goto IL_023d; IL_023d: bytesConsumed = num; value = (uint)num3; return true; IL_0235: bytesConsumed = 0; value = 0u; return false; } private static bool TryParseUInt64D(ReadOnlySpan source, out ulong value, out int bytesConsumed) { if (!source.IsEmpty) { nuint num = (uint)(source[0] - 48); if ((uint)num <= 9) { ulong num2 = num; int i = 1; if (source.Length < 20) { for (; (uint)i < (uint)source.Length; i++) { nuint num3 = (uint)(source[i] - 48); if ((uint)num3 > 9) { break; } num2 = num2 * 10 + num3; } } else { while ((uint)i < (uint)source.Length) { nuint num4 = (uint)(source[i] - 48); if ((uint)num4 > 9) { break; } i++; if (num2 < 1844674407370955161L) { num2 = num2 * 10 + num4; continue; } if (num2 == 1844674407370955161L && (uint)num4 <= 5) { num2 = 18446744073709551610uL + (ulong)num4; continue; } goto IL_00c0; } } bytesConsumed = i; value = num2; return true; } } goto IL_00c0; IL_00c0: bytesConsumed = 0; value = 0uL; return false; } private static bool TryParseByteN(ReadOnlySpan source, out byte value, out int bytesConsumed) { int num; int num3; int num2; if (source.Length >= 1) { num = 0; num2 = source[num]; if (num2 == 43) { num++; if ((uint)num >= (uint)source.Length) { goto IL_00ce; } num2 = source[num]; } if (num2 != 46) { if (ParserHelpers.IsDigit(num2)) { num3 = num2 - 48; while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 44) { continue; } if (num2 == 46) { goto IL_00a9; } if (!ParserHelpers.IsDigit(num2)) { break; } num3 = num3 * 10 + num2 - 48; if (num3 <= 255) { continue; } goto IL_00ce; } goto IL_00d6; } } else { num3 = 0; num++; if ((uint)num < (uint)source.Length && source[num] == 48) { goto IL_00a9; } } } goto IL_00ce; IL_00c6: if (ParserHelpers.IsDigit(num2)) { goto IL_00ce; } goto IL_00d6; IL_00ce: bytesConsumed = 0; value = 0; return false; IL_00d6: bytesConsumed = num; value = (byte)num3; return true; IL_00a9: while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 48) { continue; } goto IL_00c6; } goto IL_00d6; } private static bool TryParseUInt16N(ReadOnlySpan source, out ushort value, out int bytesConsumed) { int num; int num3; int num2; if (source.Length >= 1) { num = 0; num2 = source[num]; if (num2 == 43) { num++; if ((uint)num >= (uint)source.Length) { goto IL_00ce; } num2 = source[num]; } if (num2 != 46) { if (ParserHelpers.IsDigit(num2)) { num3 = num2 - 48; while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 44) { continue; } if (num2 == 46) { goto IL_00a9; } if (!ParserHelpers.IsDigit(num2)) { break; } num3 = num3 * 10 + num2 - 48; if (num3 <= 65535) { continue; } goto IL_00ce; } goto IL_00d6; } } else { num3 = 0; num++; if ((uint)num < (uint)source.Length && source[num] == 48) { goto IL_00a9; } } } goto IL_00ce; IL_00c6: if (ParserHelpers.IsDigit(num2)) { goto IL_00ce; } goto IL_00d6; IL_00ce: bytesConsumed = 0; value = 0; return false; IL_00d6: bytesConsumed = num; value = (ushort)num3; return true; IL_00a9: while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 48) { continue; } goto IL_00c6; } goto IL_00d6; } private static bool TryParseUInt32N(ReadOnlySpan source, out uint value, out int bytesConsumed) { int num; int num3; int num2; if (source.Length >= 1) { num = 0; num2 = source[num]; if (num2 == 43) { num++; if ((uint)num >= (uint)source.Length) { goto IL_00de; } num2 = source[num]; } if (num2 != 46) { if (ParserHelpers.IsDigit(num2)) { num3 = num2 - 48; while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 44) { continue; } if (num2 == 46) { goto IL_00b9; } if (!ParserHelpers.IsDigit(num2)) { break; } if ((uint)num3 <= 429496729u && (num3 != 429496729 || num2 <= 53)) { num3 = num3 * 10 + num2 - 48; continue; } goto IL_00de; } goto IL_00e6; } } else { num3 = 0; num++; if ((uint)num < (uint)source.Length && source[num] == 48) { goto IL_00b9; } } } goto IL_00de; IL_00d6: if (ParserHelpers.IsDigit(num2)) { goto IL_00de; } goto IL_00e6; IL_00de: bytesConsumed = 0; value = 0u; return false; IL_00e6: bytesConsumed = num; value = (uint)num3; return true; IL_00b9: while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 48) { continue; } goto IL_00d6; } goto IL_00e6; } private static bool TryParseUInt64N(ReadOnlySpan source, out ulong value, out int bytesConsumed) { int num; long num3; int num2; if (source.Length >= 1) { num = 0; num2 = source[num]; if (num2 == 43) { num++; if ((uint)num >= (uint)source.Length) { goto IL_00eb; } num2 = source[num]; } if (num2 != 46) { if (ParserHelpers.IsDigit(num2)) { num3 = num2 - 48; while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 44) { continue; } if (num2 == 46) { goto IL_00c6; } if (!ParserHelpers.IsDigit(num2)) { break; } if ((ulong)num3 <= 1844674407370955161uL && (num3 != 1844674407370955161L || num2 <= 53)) { num3 = num3 * 10 + num2 - 48; continue; } goto IL_00eb; } goto IL_00f4; } } else { num3 = 0L; num++; if ((uint)num < (uint)source.Length && source[num] == 48) { goto IL_00c6; } } } goto IL_00eb; IL_00e3: if (ParserHelpers.IsDigit(num2)) { goto IL_00eb; } goto IL_00f4; IL_00eb: bytesConsumed = 0; value = 0uL; return false; IL_00f4: bytesConsumed = num; value = (ulong)num3; return true; IL_00c6: while (true) { num++; if ((uint)num >= (uint)source.Length) { break; } num2 = source[num]; if (num2 == 48) { continue; } goto IL_00e3; } goto IL_00f4; } private static bool TryParseByteX(ReadOnlySpan source, out byte value, out int bytesConsumed) { if (source.Length < 1) { bytesConsumed = 0; value = 0; return false; } ReadOnlySpan charToHexLookup = HexConverter.CharToHexLookup; byte index = source[0]; byte b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = 0; value = 0; return false; } uint num = b; if (source.Length <= 2) { for (int i = 1; i < source.Length; i++) { index = source[i]; b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = i; value = (byte)num; return true; } num = (num << 4) + b; } } else { for (int j = 1; j < 2; j++) { index = source[j]; b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = j; value = (byte)num; return true; } num = (num << 4) + b; } for (int k = 2; k < source.Length; k++) { index = source[k]; b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = k; value = (byte)num; return true; } if (num > 15) { bytesConsumed = 0; value = 0; return false; } num = (num << 4) + b; } } bytesConsumed = source.Length; value = (byte)num; return true; } private static bool TryParseUInt16X(ReadOnlySpan source, out ushort value, out int bytesConsumed) { if (source.Length < 1) { bytesConsumed = 0; value = 0; return false; } ReadOnlySpan charToHexLookup = HexConverter.CharToHexLookup; byte index = source[0]; byte b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = 0; value = 0; return false; } uint num = b; if (source.Length <= 4) { for (int i = 1; i < source.Length; i++) { index = source[i]; b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = i; value = (ushort)num; return true; } num = (num << 4) + b; } } else { for (int j = 1; j < 4; j++) { index = source[j]; b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = j; value = (ushort)num; return true; } num = (num << 4) + b; } for (int k = 4; k < source.Length; k++) { index = source[k]; b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = k; value = (ushort)num; return true; } if (num > 4095) { bytesConsumed = 0; value = 0; return false; } num = (num << 4) + b; } } bytesConsumed = source.Length; value = (ushort)num; return true; } private static bool TryParseUInt32X(ReadOnlySpan source, out uint value, out int bytesConsumed) { if (source.Length < 1) { bytesConsumed = 0; value = 0u; return false; } ReadOnlySpan charToHexLookup = HexConverter.CharToHexLookup; byte index = source[0]; byte b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = 0; value = 0u; return false; } uint num = b; if (source.Length <= 8) { for (int i = 1; i < source.Length; i++) { index = source[i]; b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = i; value = num; return true; } num = (num << 4) + b; } } else { for (int j = 1; j < 8; j++) { index = source[j]; b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = j; value = num; return true; } num = (num << 4) + b; } for (int k = 8; k < source.Length; k++) { index = source[k]; b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = k; value = num; return true; } if (num > 268435455) { bytesConsumed = 0; value = 0u; return false; } num = (num << 4) + b; } } bytesConsumed = source.Length; value = num; return true; } private static bool TryParseUInt64X(ReadOnlySpan source, out ulong value, out int bytesConsumed) { if (source.Length < 1) { bytesConsumed = 0; value = 0uL; return false; } ReadOnlySpan charToHexLookup = HexConverter.CharToHexLookup; byte index = source[0]; byte b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = 0; value = 0uL; return false; } ulong num = b; if (source.Length <= 16) { for (int i = 1; i < source.Length; i++) { index = source[i]; b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = i; value = num; return true; } num = (num << 4) + b; } } else { for (int j = 1; j < 16; j++) { index = source[j]; b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = j; value = num; return true; } num = (num << 4) + b; } for (int k = 16; k < source.Length; k++) { index = source[k]; b = charToHexLookup[index]; if (b == byte.MaxValue) { bytesConsumed = k; value = num; return true; } if (num > 1152921504606846975L) { bytesConsumed = 0; value = 0uL; return false; } num = (num << 4) + b; } } bytesConsumed = source.Length; value = num; return true; } private static bool TryParseNumber(ReadOnlySpan source, ref Number.NumberBuffer number, out int bytesConsumed, ParseNumberOptions options, out bool textUsedExponentNotation) { textUsedExponentNotation = false; if (source.Length == 0) { bytesConsumed = 0; return false; } Span digits = number.Digits; int i = 0; int num = 0; byte b = source[i]; if (b != 43) { if (b != 45) { goto IL_0055; } number.IsNegative = true; } i++; if (i == source.Length) { bytesConsumed = 0; return false; } b = source[i]; goto IL_0055; IL_0055: int num2 = i; int num3 = 0; int num4 = digits.Length - 1; for (; i != source.Length; i++) { b = source[i]; if (b != 48) { break; } } if (i == source.Length) { bytesConsumed = i; return true; } int num5 = i; int num6 = 0; while (i != source.Length) { b = source[i]; int num7 = (byte)(b - 48); if (num7 > 9) { break; } i++; num3++; if (num3 >= num4) { num6 |= num7; } } number.HasNonZeroTail = num6 != 0; int num8 = i - num2; int num9 = i - num5; int num10 = Math.Min(num9, num4); source.Slice(num5, num10).CopyTo(digits); num = num10; number.Scale = num9; if (i == source.Length) { digits[num] = 0; number.DigitsCount = num; bytesConsumed = i; return true; } int num11 = 0; if (b == 46) { i++; int num12 = i; while (i != source.Length) { b = source[i]; int num13 = (byte)(b - 48); if (num13 > 9) { break; } i++; num3++; if (num3 >= num4) { num6 |= num13; } } number.HasNonZeroTail = num6 != 0; num11 = i - num12; int j = num12; if (num == 0) { for (; j < i && source[j] == 48; j++) { number.Scale--; } } int num14 = Math.Min(i - j, num4 - num); source.Slice(j, num14).CopyTo(digits.Slice(num)); num += num14; if (i == source.Length) { if (num8 == 0 && num11 == 0) { bytesConsumed = 0; return false; } digits[num] = 0; number.DigitsCount = num; bytesConsumed = i; return true; } } if (num8 == 0 && num11 == 0) { bytesConsumed = 0; return false; } if ((b & -33) != 69) { digits[num] = 0; number.DigitsCount = num; bytesConsumed = i; return true; } textUsedExponentNotation = true; i++; if ((options & ParseNumberOptions.AllowExponent) == 0) { bytesConsumed = 0; return false; } if (i == source.Length) { bytesConsumed = 0; return false; } bool flag = false; b = source[i]; if (b != 43) { if (b != 45) { goto IL_02a0; } flag = true; } i++; if (i == source.Length) { bytesConsumed = 0; return false; } b = source[i]; goto IL_02a0; IL_02a0: if ((byte)(b - 48) > 9) { bytesConsumed = 0; return false; } if (!TryParseUInt32D(source.Slice(i), out var value, out var bytesConsumed2)) { value = uint.MaxValue; for (i += 10; i != source.Length; i++) { b = source[i]; int num15 = (byte)(b - 48); if (num15 > 9) { break; } } } i += bytesConsumed2; if (flag) { if (number.Scale < int.MinValue + value) { number.Scale = int.MinValue; } else { number.Scale -= (int)value; } } else if (number.Scale > 2147483647L - (long)value) { number.Scale = int.MaxValue; } else { number.Scale += (int)value; } digits[num] = 0; number.DigitsCount = num; bytesConsumed = i; return true; } private static bool TryParseTimeSpanBigG(ReadOnlySpan source, out TimeSpan value, out int bytesConsumed) { int i = 0; byte b = 0; for (; i != source.Length; i++) { b = source[i]; if (b != 32 && b != 9) { break; } } if (i == source.Length) { value = default(TimeSpan); bytesConsumed = 0; return false; } bool isNegative = false; if (b == 45) { isNegative = true; i++; if (i == source.Length) { value = default(TimeSpan); bytesConsumed = 0; return false; } } if (!TryParseUInt32D(source.Slice(i), out var value2, out var bytesConsumed2)) { value = default(TimeSpan); bytesConsumed = 0; return false; } i += bytesConsumed2; if (i == source.Length || source[i++] != 58) { value = default(TimeSpan); bytesConsumed = 0; return false; } if (!TryParseUInt32D(source.Slice(i), out var value3, out bytesConsumed2)) { value = default(TimeSpan); bytesConsumed = 0; return false; } i += bytesConsumed2; if (i == source.Length || source[i++] != 58) { value = default(TimeSpan); bytesConsumed = 0; return false; } if (!TryParseUInt32D(source.Slice(i), out var value4, out bytesConsumed2)) { value = default(TimeSpan); bytesConsumed = 0; return false; } i += bytesConsumed2; if (i == source.Length || source[i++] != 58) { value = default(TimeSpan); bytesConsumed = 0; return false; } if (!TryParseUInt32D(source.Slice(i), out var value5, out bytesConsumed2)) { value = default(TimeSpan); bytesConsumed = 0; return false; } i += bytesConsumed2; if (i == source.Length || source[i++] != 46) { value = default(TimeSpan); bytesConsumed = 0; return false; } if (!TryParseTimeSpanFraction(source.Slice(i), out var value6, out bytesConsumed2)) { value = default(TimeSpan); bytesConsumed = 0; return false; } i += bytesConsumed2; if (!TryCreateTimeSpan(isNegative, value2, value3, value4, value5, value6, out value)) { value = default(TimeSpan); bytesConsumed = 0; return false; } if (i != source.Length && (source[i] == 46 || source[i] == 58)) { value = default(TimeSpan); bytesConsumed = 0; return false; } bytesConsumed = i; return true; } private static bool TryParseTimeSpanC(ReadOnlySpan source, out TimeSpan value, out int bytesConsumed) { TimeSpanSplitter timeSpanSplitter = default(TimeSpanSplitter); if (!timeSpanSplitter.TrySplitTimeSpan(source, periodUsedToSeparateDay: true, out bytesConsumed)) { value = default(TimeSpan); return false; } bool isNegative = timeSpanSplitter.IsNegative; bool flag; switch (timeSpanSplitter.Separators) { case 0u: flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, 0u, 0u, 0u, 0u, out value); break; case 16777216u: flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, 0u, 0u, out value); break; case 33619968u: flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, 0u, 0u, out value); break; case 16842752u: flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, 0u, out value); break; case 33620224u: flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, 0u, out value); break; case 16843264u: flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, out value); break; case 33620226u: flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, timeSpanSplitter.V5, out value); break; default: value = default(TimeSpan); flag = false; break; } if (!flag) { bytesConsumed = 0; return false; } return true; } public static bool TryParse(ReadOnlySpan source, out TimeSpan value, out int bytesConsumed, char standardFormat = '\0') { switch (standardFormat) { case '\0': case 'T': case 'c': case 't': return TryParseTimeSpanC(source, out value, out bytesConsumed); case 'G': return TryParseTimeSpanBigG(source, out value, out bytesConsumed); case 'g': return TryParseTimeSpanLittleG(source, out value, out bytesConsumed); default: return ParserHelpers.TryParseThrowFormatException(out value, out bytesConsumed); } } private static bool TryParseTimeSpanFraction(ReadOnlySpan source, out uint value, out int bytesConsumed) { int num = 0; if (num == source.Length) { value = 0u; bytesConsumed = 0; return false; } uint num2 = (uint)(source[num] - 48); if (num2 > 9) { value = 0u; bytesConsumed = 0; return false; } num++; uint num3 = num2; int num4 = 1; while (num != source.Length) { num2 = (uint)(source[num] - 48); if (num2 > 9) { break; } num++; num4++; if (num4 > 7) { value = 0u; bytesConsumed = 0; return false; } num3 = 10 * num3 + num2; } switch (num4) { case 6: num3 *= 10; break; case 5: num3 *= 100; break; case 4: num3 *= 1000; break; case 3: num3 *= 10000; break; case 2: num3 *= 100000; break; default: num3 *= 1000000; break; case 7: break; } value = num3; bytesConsumed = num; return true; } private static bool TryCreateTimeSpan(bool isNegative, uint days, uint hours, uint minutes, uint seconds, uint fraction, out TimeSpan timeSpan) { if (hours > 23 || minutes > 59 || seconds > 59) { timeSpan = default(TimeSpan); return false; } long num = ((long)days * 3600L * 24 + (long)hours * 3600L + (long)minutes * 60L + seconds) * 1000; long ticks; if (isNegative) { num = -num; if (num < -922337203685477L) { timeSpan = default(TimeSpan); return false; } long num2 = num * 10000; if (num2 < long.MinValue + fraction) { timeSpan = default(TimeSpan); return false; } ticks = num2 - fraction; } else { if (num > 922337203685477L) { timeSpan = default(TimeSpan); return false; } long num3 = num * 10000; if (num3 > long.MaxValue - (long)fraction) { timeSpan = default(TimeSpan); return false; } ticks = num3 + fraction; } timeSpan = new TimeSpan(ticks); return true; } private static bool TryParseTimeSpanLittleG(ReadOnlySpan source, out TimeSpan value, out int bytesConsumed) { TimeSpanSplitter timeSpanSplitter = default(TimeSpanSplitter); if (!timeSpanSplitter.TrySplitTimeSpan(source, periodUsedToSeparateDay: false, out bytesConsumed)) { value = default(TimeSpan); return false; } bool isNegative = timeSpanSplitter.IsNegative; bool flag; switch (timeSpanSplitter.Separators) { case 0u: flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, 0u, 0u, 0u, 0u, out value); break; case 16777216u: flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, 0u, 0u, out value); break; case 16842752u: flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, 0u, out value); break; case 16843008u: flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, 0u, out value); break; case 16843264u: flag = TryCreateTimeSpan(isNegative, 0u, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, out value); break; case 16843010u: flag = TryCreateTimeSpan(isNegative, timeSpanSplitter.V1, timeSpanSplitter.V2, timeSpanSplitter.V3, timeSpanSplitter.V4, timeSpanSplitter.V5, out value); break; default: value = default(TimeSpan); flag = false; break; } if (!flag) { bytesConsumed = 0; return false; } return true; } } } namespace System.Buffers.Binary { public static class BinaryPrimitives { [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static sbyte ReverseEndianness(sbyte value) { return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static short ReverseEndianness(short value) { return (short)ReverseEndianness((ushort)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static int ReverseEndianness(int value) { return (int)ReverseEndianness((uint)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static long ReverseEndianness(long value) { return (long)ReverseEndianness((ulong)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte ReverseEndianness(byte value) { return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] [Intrinsic] public static ushort ReverseEndianness(ushort value) { return (ushort)((value >> 8) + (value << 8)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] [Intrinsic] public static uint ReverseEndianness(uint value) { return BitOperations.RotateRight(value & 0xFF00FFu, 8) + BitOperations.RotateLeft(value & 0xFF00FF00u, 8); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] [Intrinsic] public static ulong ReverseEndianness(ulong value) { return ((ulong)ReverseEndianness((uint)value) << 32) + ReverseEndianness((uint)(value >> 32)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double ReadDoubleBigEndian(ReadOnlySpan source) { if (!BitConverter.IsLittleEndian) { } return BitConverter.Int64BitsToDouble(ReverseEndianness(MemoryMarshal.Read(source))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Half ReadHalfBigEndian(ReadOnlySpan source) { if (!BitConverter.IsLittleEndian) { } return BitConverter.Int16BitsToHalf(ReverseEndianness(MemoryMarshal.Read(source))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short ReadInt16BigEndian(ReadOnlySpan source) { short value = MemoryMarshal.Read(source); _ = BitConverter.IsLittleEndian; return ReverseEndianness(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ReadInt32BigEndian(ReadOnlySpan source) { int value = MemoryMarshal.Read(source); _ = BitConverter.IsLittleEndian; return ReverseEndianness(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long ReadInt64BigEndian(ReadOnlySpan source) { long value = MemoryMarshal.Read(source); _ = BitConverter.IsLittleEndian; return ReverseEndianness(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float ReadSingleBigEndian(ReadOnlySpan source) { if (!BitConverter.IsLittleEndian) { } return BitConverter.Int32BitsToSingle(ReverseEndianness(MemoryMarshal.Read(source))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ushort ReadUInt16BigEndian(ReadOnlySpan source) { ushort value = MemoryMarshal.Read(source); _ = BitConverter.IsLittleEndian; return ReverseEndianness(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint ReadUInt32BigEndian(ReadOnlySpan source) { uint value = MemoryMarshal.Read(source); _ = BitConverter.IsLittleEndian; return ReverseEndianness(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong ReadUInt64BigEndian(ReadOnlySpan source) { ulong value = MemoryMarshal.Read(source); _ = BitConverter.IsLittleEndian; return ReverseEndianness(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadDoubleBigEndian(ReadOnlySpan source, out double value) { _ = BitConverter.IsLittleEndian; long value2; bool result = MemoryMarshal.TryRead(source, out value2); value = BitConverter.Int64BitsToDouble(ReverseEndianness(value2)); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadHalfBigEndian(ReadOnlySpan source, out Half value) { _ = BitConverter.IsLittleEndian; short value2; bool result = MemoryMarshal.TryRead(source, out value2); value = BitConverter.Int16BitsToHalf(ReverseEndianness(value2)); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadInt16BigEndian(ReadOnlySpan source, out short value) { _ = BitConverter.IsLittleEndian; short value2; bool result = MemoryMarshal.TryRead(source, out value2); value = ReverseEndianness(value2); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadInt32BigEndian(ReadOnlySpan source, out int value) { _ = BitConverter.IsLittleEndian; int value2; bool result = MemoryMarshal.TryRead(source, out value2); value = ReverseEndianness(value2); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadInt64BigEndian(ReadOnlySpan source, out long value) { _ = BitConverter.IsLittleEndian; long value2; bool result = MemoryMarshal.TryRead(source, out value2); value = ReverseEndianness(value2); return result; } public static bool TryReadSingleBigEndian(ReadOnlySpan source, out float value) { _ = BitConverter.IsLittleEndian; int value2; bool result = MemoryMarshal.TryRead(source, out value2); value = BitConverter.Int32BitsToSingle(ReverseEndianness(value2)); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryReadUInt16BigEndian(ReadOnlySpan source, out ushort value) { _ = BitConverter.IsLittleEndian; ushort value2; bool result = MemoryMarshal.TryRead(source, out value2); value = ReverseEndianness(value2); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryReadUInt32BigEndian(ReadOnlySpan source, out uint value) { _ = BitConverter.IsLittleEndian; uint value2; bool result = MemoryMarshal.TryRead(source, out value2); value = ReverseEndianness(value2); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryReadUInt64BigEndian(ReadOnlySpan source, out ulong value) { _ = BitConverter.IsLittleEndian; ulong value2; bool result = MemoryMarshal.TryRead(source, out value2); value = ReverseEndianness(value2); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double ReadDoubleLittleEndian(ReadOnlySpan source) { _ = BitConverter.IsLittleEndian; return MemoryMarshal.Read(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Half ReadHalfLittleEndian(ReadOnlySpan source) { _ = BitConverter.IsLittleEndian; return MemoryMarshal.Read(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short ReadInt16LittleEndian(ReadOnlySpan source) { short result = MemoryMarshal.Read(source); if (!BitConverter.IsLittleEndian) { } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ReadInt32LittleEndian(ReadOnlySpan source) { int result = MemoryMarshal.Read(source); if (!BitConverter.IsLittleEndian) { } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long ReadInt64LittleEndian(ReadOnlySpan source) { long result = MemoryMarshal.Read(source); if (!BitConverter.IsLittleEndian) { } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float ReadSingleLittleEndian(ReadOnlySpan source) { _ = BitConverter.IsLittleEndian; return MemoryMarshal.Read(source); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ushort ReadUInt16LittleEndian(ReadOnlySpan source) { ushort result = MemoryMarshal.Read(source); if (!BitConverter.IsLittleEndian) { } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint ReadUInt32LittleEndian(ReadOnlySpan source) { uint result = MemoryMarshal.Read(source); if (!BitConverter.IsLittleEndian) { } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong ReadUInt64LittleEndian(ReadOnlySpan source) { ulong result = MemoryMarshal.Read(source); if (!BitConverter.IsLittleEndian) { } return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadDoubleLittleEndian(ReadOnlySpan source, out double value) { if (!BitConverter.IsLittleEndian) { } return MemoryMarshal.TryRead(source, out value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadHalfLittleEndian(ReadOnlySpan source, out Half value) { if (!BitConverter.IsLittleEndian) { } return MemoryMarshal.TryRead(source, out value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadInt16LittleEndian(ReadOnlySpan source, out short value) { _ = BitConverter.IsLittleEndian; return MemoryMarshal.TryRead(source, out value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadInt32LittleEndian(ReadOnlySpan source, out int value) { _ = BitConverter.IsLittleEndian; return MemoryMarshal.TryRead(source, out value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryReadInt64LittleEndian(ReadOnlySpan source, out long value) { _ = BitConverter.IsLittleEndian; return MemoryMarshal.TryRead(source, out value); } public static bool TryReadSingleLittleEndian(ReadOnlySpan source, out float value) { if (!BitConverter.IsLittleEndian) { } return MemoryMarshal.TryRead(source, out value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryReadUInt16LittleEndian(ReadOnlySpan source, out ushort value) { _ = BitConverter.IsLittleEndian; return MemoryMarshal.TryRead(source, out value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryReadUInt32LittleEndian(ReadOnlySpan source, out uint value) { _ = BitConverter.IsLittleEndian; return MemoryMarshal.TryRead(source, out value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryReadUInt64LittleEndian(ReadOnlySpan source, out ulong value) { _ = BitConverter.IsLittleEndian; return MemoryMarshal.TryRead(source, out value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDoubleBigEndian(Span destination, double value) { _ = BitConverter.IsLittleEndian; long value2 = ReverseEndianness(BitConverter.DoubleToInt64Bits(value)); MemoryMarshal.Write(destination, ref value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteHalfBigEndian(Span destination, Half value) { _ = BitConverter.IsLittleEndian; short value2 = ReverseEndianness(BitConverter.HalfToInt16Bits(value)); MemoryMarshal.Write(destination, ref value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteInt16BigEndian(Span destination, short value) { _ = BitConverter.IsLittleEndian; value = ReverseEndianness(value); MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteInt32BigEndian(Span destination, int value) { _ = BitConverter.IsLittleEndian; value = ReverseEndianness(value); MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteInt64BigEndian(Span destination, long value) { _ = BitConverter.IsLittleEndian; value = ReverseEndianness(value); MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteSingleBigEndian(Span destination, float value) { _ = BitConverter.IsLittleEndian; int value2 = ReverseEndianness(BitConverter.SingleToInt32Bits(value)); MemoryMarshal.Write(destination, ref value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static void WriteUInt16BigEndian(Span destination, ushort value) { _ = BitConverter.IsLittleEndian; value = ReverseEndianness(value); MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static void WriteUInt32BigEndian(Span destination, uint value) { _ = BitConverter.IsLittleEndian; value = ReverseEndianness(value); MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static void WriteUInt64BigEndian(Span destination, ulong value) { _ = BitConverter.IsLittleEndian; value = ReverseEndianness(value); MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteDoubleBigEndian(Span destination, double value) { _ = BitConverter.IsLittleEndian; long value2 = ReverseEndianness(BitConverter.DoubleToInt64Bits(value)); return MemoryMarshal.TryWrite(destination, ref value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteHalfBigEndian(Span destination, Half value) { _ = BitConverter.IsLittleEndian; short value2 = ReverseEndianness(BitConverter.HalfToInt16Bits(value)); return MemoryMarshal.TryWrite(destination, ref value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteInt16BigEndian(Span destination, short value) { _ = BitConverter.IsLittleEndian; value = ReverseEndianness(value); return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteInt32BigEndian(Span destination, int value) { _ = BitConverter.IsLittleEndian; value = ReverseEndianness(value); return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteInt64BigEndian(Span destination, long value) { _ = BitConverter.IsLittleEndian; value = ReverseEndianness(value); return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteSingleBigEndian(Span destination, float value) { _ = BitConverter.IsLittleEndian; int value2 = ReverseEndianness(BitConverter.SingleToInt32Bits(value)); return MemoryMarshal.TryWrite(destination, ref value2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryWriteUInt16BigEndian(Span destination, ushort value) { _ = BitConverter.IsLittleEndian; value = ReverseEndianness(value); return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryWriteUInt32BigEndian(Span destination, uint value) { _ = BitConverter.IsLittleEndian; value = ReverseEndianness(value); return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryWriteUInt64BigEndian(Span destination, ulong value) { _ = BitConverter.IsLittleEndian; value = ReverseEndianness(value); return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteDoubleLittleEndian(Span destination, double value) { if (!BitConverter.IsLittleEndian) { } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteHalfLittleEndian(Span destination, Half value) { if (!BitConverter.IsLittleEndian) { } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteInt16LittleEndian(Span destination, short value) { if (!BitConverter.IsLittleEndian) { } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteInt32LittleEndian(Span destination, int value) { if (!BitConverter.IsLittleEndian) { } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteInt64LittleEndian(Span destination, long value) { if (!BitConverter.IsLittleEndian) { } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteSingleLittleEndian(Span destination, float value) { if (!BitConverter.IsLittleEndian) { } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static void WriteUInt16LittleEndian(Span destination, ushort value) { if (!BitConverter.IsLittleEndian) { } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static void WriteUInt32LittleEndian(Span destination, uint value) { if (!BitConverter.IsLittleEndian) { } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static void WriteUInt64LittleEndian(Span destination, ulong value) { if (!BitConverter.IsLittleEndian) { } MemoryMarshal.Write(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteDoubleLittleEndian(Span destination, double value) { if (!BitConverter.IsLittleEndian) { } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteHalfLittleEndian(Span destination, Half value) { if (!BitConverter.IsLittleEndian) { } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteInt16LittleEndian(Span destination, short value) { if (!BitConverter.IsLittleEndian) { } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteInt32LittleEndian(Span destination, int value) { if (!BitConverter.IsLittleEndian) { } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteInt64LittleEndian(Span destination, long value) { if (!BitConverter.IsLittleEndian) { } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWriteSingleLittleEndian(Span destination, float value) { if (!BitConverter.IsLittleEndian) { } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryWriteUInt16LittleEndian(Span destination, ushort value) { if (!BitConverter.IsLittleEndian) { } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryWriteUInt32LittleEndian(Span destination, uint value) { if (!BitConverter.IsLittleEndian) { } return MemoryMarshal.TryWrite(destination, ref value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static bool TryWriteUInt64LittleEndian(Span destination, ulong value) { if (!BitConverter.IsLittleEndian) { } return MemoryMarshal.TryWrite(destination, ref value); } } } namespace System.Threading { public sealed class ThreadPoolBoundHandle : IDisposable { private readonly SafeHandle _handle; private bool _isDisposed; public SafeHandle Handle => _handle; private ThreadPoolBoundHandle(SafeHandle handle) { _handle = handle; } public static ThreadPoolBoundHandle BindHandle(SafeHandle handle) { if (handle == null) { throw new ArgumentNullException("handle"); } if (handle.IsClosed || handle.IsInvalid) { throw new ArgumentException(SR.Argument_InvalidHandle, "handle"); } return BindHandleCore(handle); } [CLSCompliant(false)] public unsafe NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback, object? state, object? pinData) { return AllocateNativeOverlapped(callback, state, pinData, flowExecutionContext: true); } [CLSCompliant(false)] public unsafe NativeOverlapped* UnsafeAllocateNativeOverlapped(IOCompletionCallback callback, object? state, object? pinData) { return AllocateNativeOverlapped(callback, state, pinData, flowExecutionContext: false); } private unsafe NativeOverlapped* AllocateNativeOverlapped(IOCompletionCallback callback, object state, object pinData, bool flowExecutionContext) { if (callback == null) { throw new ArgumentNullException("callback"); } EnsureNotDisposed(); ThreadPoolBoundHandleOverlapped threadPoolBoundHandleOverlapped = new ThreadPoolBoundHandleOverlapped(callback, state, pinData, null, flowExecutionContext); threadPoolBoundHandleOverlapped._boundHandle = this; return threadPoolBoundHandleOverlapped._nativeOverlapped; } [CLSCompliant(false)] public unsafe NativeOverlapped* AllocateNativeOverlapped(PreAllocatedOverlapped preAllocated) { if (preAllocated == null) { throw new ArgumentNullException("preAllocated"); } EnsureNotDisposed(); preAllocated.AddRef(); try { ThreadPoolBoundHandleOverlapped overlapped = preAllocated._overlapped; if (overlapped._boundHandle != null) { throw new ArgumentException(SR.Argument_PreAllocatedAlreadyAllocated, "preAllocated"); } overlapped._boundHandle = this; return overlapped._nativeOverlapped; } catch { preAllocated.Release(); throw; } } [CLSCompliant(false)] public unsafe void FreeNativeOverlapped(NativeOverlapped* overlapped) { if (overlapped == null) { throw new ArgumentNullException("overlapped"); } ThreadPoolBoundHandleOverlapped overlappedWrapper = GetOverlappedWrapper(overlapped); if (overlappedWrapper._boundHandle != this) { throw new ArgumentException(SR.Argument_NativeOverlappedWrongBoundHandle, "overlapped"); } if (overlappedWrapper._preAllocated != null) { overlappedWrapper._preAllocated.Release(); } else { Overlapped.Free(overlapped); } } [CLSCompliant(false)] public unsafe static object? GetNativeOverlappedState(NativeOverlapped* overlapped) { if (overlapped == null) { throw new ArgumentNullException("overlapped"); } ThreadPoolBoundHandleOverlapped overlappedWrapper = GetOverlappedWrapper(overlapped); return overlappedWrapper._userState; } private unsafe static ThreadPoolBoundHandleOverlapped GetOverlappedWrapper(NativeOverlapped* overlapped) { try { return (ThreadPoolBoundHandleOverlapped)Overlapped.Unpack(overlapped); } catch (NullReferenceException innerException) { throw new ArgumentException(SR.Argument_NativeOverlappedAlreadyFree, "overlapped", innerException); } } public void Dispose() { _isDisposed = true; } private void EnsureNotDisposed() { if (_isDisposed) { throw new ObjectDisposedException(GetType().ToString()); } } private static ThreadPoolBoundHandle BindHandleCore(SafeHandle handle) { try { bool flag = ThreadPool.BindHandle(handle); } catch (Exception ex) { if (ex.HResult == -2147024890) { throw new ArgumentException(SR.Argument_InvalidHandle, "handle"); } if (ex.HResult == -2147024809) { throw new ArgumentException(SR.Argument_AlreadyBoundOrSyncHandle, "handle"); } throw; } return new ThreadPoolBoundHandle(handle); } } internal sealed class ThreadPoolBoundHandleOverlapped : Overlapped { private unsafe static readonly IOCompletionCallback s_completionCallback = CompletionCallback; private readonly IOCompletionCallback _userCallback; internal readonly object _userState; internal readonly PreAllocatedOverlapped _preAllocated; internal unsafe NativeOverlapped* _nativeOverlapped; internal ThreadPoolBoundHandle _boundHandle; internal bool _completed; public unsafe ThreadPoolBoundHandleOverlapped(IOCompletionCallback callback, object state, object pinData, PreAllocatedOverlapped preAllocated, bool flowExecutionContext) { _userCallback = callback; _userState = state; _preAllocated = preAllocated; _nativeOverlapped = (flowExecutionContext ? Pack(s_completionCallback, pinData) : UnsafePack(s_completionCallback, pinData)); _nativeOverlapped->OffsetLow = 0; _nativeOverlapped->OffsetHigh = 0; } private unsafe static void CompletionCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { ThreadPoolBoundHandleOverlapped threadPoolBoundHandleOverlapped = (ThreadPoolBoundHandleOverlapped)Overlapped.Unpack(nativeOverlapped); if (threadPoolBoundHandleOverlapped._completed) { throw new InvalidOperationException(SR.InvalidOperation_NativeOverlappedReused); } threadPoolBoundHandleOverlapped._completed = true; if (threadPoolBoundHandleOverlapped._boundHandle == null) { throw new InvalidOperationException(SR.Argument_NativeOverlappedAlreadyFree); } threadPoolBoundHandleOverlapped._userCallback(errorCode, numBytes, nativeOverlapped); } } public sealed class PreAllocatedOverlapped : IDisposable, IDeferredDisposable { internal readonly ThreadPoolBoundHandleOverlapped _overlapped; private DeferredDisposableLifetime _lifetime; [CLSCompliant(false)] public PreAllocatedOverlapped(IOCompletionCallback callback, object? state, object? pinData) : this(callback, state, pinData, flowExecutionContext: true) { } [CLSCompliant(false)] public static PreAllocatedOverlapped UnsafeCreate(IOCompletionCallback callback, object? state, object? pinData) { return new PreAllocatedOverlapped(callback, state, pinData, flowExecutionContext: false); } private PreAllocatedOverlapped(IOCompletionCallback callback, object state, object pinData, bool flowExecutionContext) { if (callback == null) { throw new ArgumentNullException("callback"); } _overlapped = new ThreadPoolBoundHandleOverlapped(callback, state, pinData, this, flowExecutionContext); } internal bool AddRef() { return _lifetime.AddRef(); } internal void Release() { _lifetime.Release(this); } public void Dispose() { _lifetime.Dispose(this); GC.SuppressFinalize(this); } ~PreAllocatedOverlapped() { Dispose(); } unsafe void IDeferredDisposable.OnFinalRelease(bool disposed) { if (_overlapped != null) { if (disposed) { Overlapped.Free(_overlapped._nativeOverlapped); return; } _overlapped._boundHandle = null; _overlapped._completed = false; *_overlapped._nativeOverlapped = default(NativeOverlapped); } } internal bool IsUserObject(byte[] buffer) { return _overlapped.IsUserObject(buffer); } } public static class Interlocked { public static int Increment(ref int location) { return Add(ref location, 1); } public static long Increment(ref long location) { return Add(ref location, 1L); } public static int Decrement(ref int location) { return Add(ref location, -1); } public static long Decrement(ref long location) { return Add(ref location, -1L); } [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern int Exchange(ref int location1, int value); [MethodImpl(MethodImplOptions.InternalCall)] public static extern long Exchange(ref long location1, long value); [MethodImpl(MethodImplOptions.InternalCall)] public static extern float Exchange(ref float location1, float value); [MethodImpl(MethodImplOptions.InternalCall)] public static extern double Exchange(ref double location1, double value); [MethodImpl(MethodImplOptions.InternalCall)] [return: NotNullIfNotNull("location1")] public static extern object? Exchange([NotNullIfNotNull("value")] ref object? location1, object? value); [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NotNullIfNotNull("location1")] public static T Exchange([NotNullIfNotNull("value")] ref T location1, T value) where T : class? { return Unsafe.As(Exchange(ref Unsafe.As(ref location1), value)); } [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern int CompareExchange(ref int location1, int value, int comparand); [MethodImpl(MethodImplOptions.InternalCall)] public static extern long CompareExchange(ref long location1, long value, long comparand); [MethodImpl(MethodImplOptions.InternalCall)] public static extern float CompareExchange(ref float location1, float value, float comparand); [MethodImpl(MethodImplOptions.InternalCall)] public static extern double CompareExchange(ref double location1, double value, double comparand); [MethodImpl(MethodImplOptions.InternalCall)] [return: NotNullIfNotNull("location1")] public static extern object? CompareExchange(ref object? location1, object? value, object? comparand); [Intrinsic] [return: NotNullIfNotNull("location1")] public static T CompareExchange(ref T location1, T value, T comparand) where T : class? { return Unsafe.As(CompareExchange(ref Unsafe.As(ref location1), value, comparand)); } public static int Add(ref int location1, int value) { return ExchangeAdd(ref location1, value) + value; } public static long Add(ref long location1, long value) { return ExchangeAdd(ref location1, value) + value; } [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] private static extern int ExchangeAdd(ref int location1, int value); [MethodImpl(MethodImplOptions.InternalCall)] private static extern long ExchangeAdd(ref long location1, long value); public static long Read(ref long location) { return CompareExchange(ref location, 0L, 0L); } [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern void MemoryBarrier(); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] internal static extern void ReadMemoryBarrier(); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void _MemoryBarrierProcessWide(); public static void MemoryBarrierProcessWide() { _MemoryBarrierProcessWide(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint Increment(ref uint location) { return Add(ref location, 1u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong Increment(ref ulong location) { return Add(ref location, 1uL); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint Decrement(ref uint location) { return (uint)Add(ref Unsafe.As(ref location), -1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong Decrement(ref ulong location) { return (ulong)Add(ref Unsafe.As(ref location), -1L); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint Exchange(ref uint location1, uint value) { return (uint)Exchange(ref Unsafe.As(ref location1), (int)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong Exchange(ref ulong location1, ulong value) { return (ulong)Exchange(ref Unsafe.As(ref location1), (long)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IntPtr Exchange(ref IntPtr location1, IntPtr value) { return (IntPtr)Exchange(ref Unsafe.As(ref location1), (int)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint CompareExchange(ref uint location1, uint value, uint comparand) { return (uint)CompareExchange(ref Unsafe.As(ref location1), (int)value, (int)comparand); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong CompareExchange(ref ulong location1, ulong value, ulong comparand) { return (ulong)CompareExchange(ref Unsafe.As(ref location1), (long)value, (long)comparand); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IntPtr CompareExchange(ref IntPtr location1, IntPtr value, IntPtr comparand) { return (IntPtr)CompareExchange(ref Unsafe.As(ref location1), (int)value, (int)comparand); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint Add(ref uint location1, uint value) { return (uint)Add(ref Unsafe.As(ref location1), (int)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong Add(ref ulong location1, ulong value) { return (ulong)Add(ref Unsafe.As(ref location1), (long)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong Read(ref ulong location) { return CompareExchange(ref location, 0uL, 0uL); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static int And(ref int location1, int value) { int num = location1; int num2; while (true) { int value2 = num & value; num2 = CompareExchange(ref location1, value2, num); if (num2 == num) { break; } num = num2; } return num2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint And(ref uint location1, uint value) { return (uint)And(ref Unsafe.As(ref location1), (int)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static long And(ref long location1, long value) { long num = location1; long num2; while (true) { long value2 = num & value; num2 = CompareExchange(ref location1, value2, num); if (num2 == num) { break; } num = num2; } return num2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong And(ref ulong location1, ulong value) { return (ulong)And(ref Unsafe.As(ref location1), (long)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static int Or(ref int location1, int value) { int num = location1; int num2; while (true) { int value2 = num | value; num2 = CompareExchange(ref location1, value2, num); if (num2 == num) { break; } num = num2; } return num2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static uint Or(ref uint location1, uint value) { return (uint)Or(ref Unsafe.As(ref location1), (int)value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static long Or(ref long location1, long value) { long num = location1; long num2; while (true) { long value2 = num | value; num2 = CompareExchange(ref location1, value2, num); if (num2 == num) { break; } num = num2; } return num2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static ulong Or(ref ulong location1, ulong value) { return (ulong)Or(ref Unsafe.As(ref location1), (long)value); } } public static class Monitor { public static long LockContentionCount => GetLockContentionCount(); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void Enter(object obj); public static void Enter(object obj, ref bool lockTaken) { if (lockTaken) { ThrowLockTakenException(); } ReliableEnter(obj, ref lockTaken); } [DoesNotReturn] private static void ThrowLockTakenException() { throw new ArgumentException(SR.Argument_MustBeFalse, "lockTaken"); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ReliableEnter(object obj, ref bool lockTaken); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void Exit(object obj); public static bool TryEnter(object obj) { bool lockTaken = false; TryEnter(obj, 0, ref lockTaken); return lockTaken; } public static void TryEnter(object obj, ref bool lockTaken) { if (lockTaken) { ThrowLockTakenException(); } ReliableEnterTimeout(obj, 0, ref lockTaken); } public static bool TryEnter(object obj, int millisecondsTimeout) { bool lockTaken = false; TryEnter(obj, millisecondsTimeout, ref lockTaken); return lockTaken; } public static void TryEnter(object obj, int millisecondsTimeout, ref bool lockTaken) { if (lockTaken) { ThrowLockTakenException(); } ReliableEnterTimeout(obj, millisecondsTimeout, ref lockTaken); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ReliableEnterTimeout(object obj, int timeout, ref bool lockTaken); public static bool IsEntered(object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } return IsEnteredNative(obj); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsEnteredNative(object obj); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool ObjWait(int millisecondsTimeout, object obj); [UnsupportedOSPlatform("browser")] public static bool Wait(object obj, int millisecondsTimeout) { if (obj == null) { throw new ArgumentNullException("obj"); } if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return ObjWait(millisecondsTimeout, obj); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ObjPulse(object obj); public static void Pulse(object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } ObjPulse(obj); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ObjPulseAll(object obj); public static void PulseAll(object obj) { if (obj == null) { throw new ArgumentNullException("obj"); } ObjPulseAll(obj); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern long GetLockContentionCount(); public static bool TryEnter(object obj, TimeSpan timeout) { return TryEnter(obj, WaitHandle.ToTimeoutMilliseconds(timeout)); } public static void TryEnter(object obj, TimeSpan timeout, ref bool lockTaken) { TryEnter(obj, WaitHandle.ToTimeoutMilliseconds(timeout), ref lockTaken); } [UnsupportedOSPlatform("browser")] public static bool Wait(object obj, TimeSpan timeout) { return Wait(obj, WaitHandle.ToTimeoutMilliseconds(timeout)); } [UnsupportedOSPlatform("browser")] public static bool Wait(object obj) { return Wait(obj, -1); } [UnsupportedOSPlatform("browser")] public static bool Wait(object obj, int millisecondsTimeout, bool exitContext) { return Wait(obj, millisecondsTimeout); } [UnsupportedOSPlatform("browser")] public static bool Wait(object obj, TimeSpan timeout, bool exitContext) { return Wait(obj, WaitHandle.ToTimeoutMilliseconds(timeout)); } } internal class _IOCompletionCallback { private readonly IOCompletionCallback _ioCompletionCallback; private readonly ExecutionContext _executionContext; private uint _errorCode; private uint _numBytes; private unsafe NativeOverlapped* _pNativeOverlapped; internal static ContextCallback _ccb = IOCompletionCallback_Context; internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback, ExecutionContext executionContext) { _ioCompletionCallback = ioCompletionCallback; _executionContext = executionContext; } internal unsafe static void IOCompletionCallback_Context(object state) { _IOCompletionCallback iOCompletionCallback = (_IOCompletionCallback)state; iOCompletionCallback._ioCompletionCallback(iOCompletionCallback._errorCode, iOCompletionCallback._numBytes, iOCompletionCallback._pNativeOverlapped); } internal unsafe static void PerformIOCompletionCallback(uint errorCode, uint numBytes, NativeOverlapped* pNativeOverlapped) { do { OverlappedData overlappedFromNative = OverlappedData.GetOverlappedFromNative(pNativeOverlapped); if (overlappedFromNative._callback is IOCompletionCallback iOCompletionCallback) { iOCompletionCallback(errorCode, numBytes, pNativeOverlapped); } else { _IOCompletionCallback iOCompletionCallback2 = (_IOCompletionCallback)overlappedFromNative._callback; iOCompletionCallback2._errorCode = errorCode; iOCompletionCallback2._numBytes = numBytes; iOCompletionCallback2._pNativeOverlapped = pNativeOverlapped; ExecutionContext.RunInternal(iOCompletionCallback2._executionContext, _ccb, iOCompletionCallback2); } OverlappedData.CheckVMForIOPacket(out pNativeOverlapped, out errorCode, out numBytes); } while (pNativeOverlapped != null); } } internal sealed class OverlappedData { internal IAsyncResult _asyncResult; internal object _callback; internal readonly Overlapped _overlapped; private object _userObject; private unsafe readonly NativeOverlapped* _pNativeOverlapped; private IntPtr _eventHandle; private int _offsetLow; private int _offsetHigh; internal unsafe ref int OffsetLow { get { if (_pNativeOverlapped == null) { return ref _offsetLow; } return ref _pNativeOverlapped->OffsetLow; } } internal unsafe ref int OffsetHigh { get { if (_pNativeOverlapped == null) { return ref _offsetHigh; } return ref _pNativeOverlapped->OffsetHigh; } } internal unsafe ref IntPtr EventHandle { get { if (_pNativeOverlapped == null) { return ref _eventHandle; } return ref _pNativeOverlapped->EventHandle; } } internal OverlappedData(Overlapped overlapped) { _overlapped = overlapped; } internal unsafe NativeOverlapped* Pack(IOCompletionCallback iocb, object userData) { if (_pNativeOverlapped != null) { throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack); } if (iocb != null) { ExecutionContext executionContext = ExecutionContext.Capture(); _callback = ((executionContext != null && !executionContext.IsDefault) ? ((object)new _IOCompletionCallback(iocb, executionContext)) : ((object)iocb)); } else { _callback = null; } _userObject = userData; return AllocateNativeOverlapped(); } internal unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb, object userData) { if (_pNativeOverlapped != null) { throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack); } _userObject = userData; _callback = iocb; return AllocateNativeOverlapped(); } internal bool IsUserObject(byte[] buffer) { return _userObject == buffer; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe extern NativeOverlapped* AllocateNativeOverlapped(); [MethodImpl(MethodImplOptions.InternalCall)] internal unsafe static extern void FreeNativeOverlapped(NativeOverlapped* nativeOverlappedPtr); [MethodImpl(MethodImplOptions.InternalCall)] internal unsafe static extern OverlappedData GetOverlappedFromNative(NativeOverlapped* nativeOverlappedPtr); [MethodImpl(MethodImplOptions.InternalCall)] internal unsafe static extern void CheckVMForIOPacket(out NativeOverlapped* pNativeOverlapped, out uint errorCode, out uint numBytes); } public class Overlapped { private OverlappedData _overlappedData; public IAsyncResult? AsyncResult { get { return _overlappedData._asyncResult; } set { _overlappedData._asyncResult = value; } } public int OffsetLow { get { return _overlappedData.OffsetLow; } set { _overlappedData.OffsetLow = value; } } public int OffsetHigh { get { return _overlappedData.OffsetHigh; } set { _overlappedData.OffsetHigh = value; } } [Obsolete("Overlapped.EventHandle is not 64-bit compatible and has been deprecated. Use EventHandleIntPtr instead.")] public int EventHandle { get { return EventHandleIntPtr.ToInt32(); } set { EventHandleIntPtr = new IntPtr(value); } } public IntPtr EventHandleIntPtr { get { return _overlappedData.EventHandle; } set { _overlappedData.EventHandle = value; } } public Overlapped() { _overlappedData = new OverlappedData(this); } public Overlapped(int offsetLo, int offsetHi, IntPtr hEvent, IAsyncResult? ar) : this() { _overlappedData.OffsetLow = offsetLo; _overlappedData.OffsetHigh = offsetHi; _overlappedData.EventHandle = hEvent; _overlappedData._asyncResult = ar; } [Obsolete("This constructor is not 64-bit compatible and has been deprecated. Use the constructor that accepts an IntPtr for the event handle instead.")] public Overlapped(int offsetLo, int offsetHi, int hEvent, IAsyncResult? ar) : this(offsetLo, offsetHi, new IntPtr(hEvent), ar) { } [Obsolete("This overload is not safe and has been deprecated. Use Pack(IOCompletionCallback?, object?) instead.")] [CLSCompliant(false)] public unsafe NativeOverlapped* Pack(IOCompletionCallback? iocb) { return Pack(iocb, null); } [CLSCompliant(false)] public unsafe NativeOverlapped* Pack(IOCompletionCallback? iocb, object? userData) { return _overlappedData.Pack(iocb, userData); } [Obsolete("This overload is not safe and has been deprecated. Use UnsafePack(IOCompletionCallback?, object?) instead.")] [CLSCompliant(false)] public unsafe NativeOverlapped* UnsafePack(IOCompletionCallback? iocb) { return UnsafePack(iocb, null); } [CLSCompliant(false)] public unsafe NativeOverlapped* UnsafePack(IOCompletionCallback? iocb, object? userData) { return _overlappedData.UnsafePack(iocb, userData); } [CLSCompliant(false)] public unsafe static Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr) { if (nativeOverlappedPtr == null) { throw new ArgumentNullException("nativeOverlappedPtr"); } return OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped; } [CLSCompliant(false)] public unsafe static void Free(NativeOverlapped* nativeOverlappedPtr) { if (nativeOverlappedPtr == null) { throw new ArgumentNullException("nativeOverlappedPtr"); } OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr)._overlapped._overlappedData = null; OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr); } internal bool IsUserObject(byte[] buffer) { return _overlappedData.IsUserObject(buffer); } } public class SynchronizationContext { private bool _requireWaitNotification; public static SynchronizationContext? Current => Thread.CurrentThread._synchronizationContext; private static int InvokeWaitMethodHelper(SynchronizationContext syncContext, IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { return syncContext.Wait(waitHandles, waitAll, millisecondsTimeout); } protected void SetWaitNotificationRequired() { _requireWaitNotification = true; } public bool IsWaitNotificationRequired() { return _requireWaitNotification; } public virtual void Send(SendOrPostCallback d, object? state) { d(state); } public virtual void Post(SendOrPostCallback d, object? state) { ThreadPool.QueueUserWorkItem(delegate((SendOrPostCallback d, object state) s) { s.d(s.state); }, (d, state), preferLocal: false); } public virtual void OperationStarted() { } public virtual void OperationCompleted() { } [CLSCompliant(false)] public virtual int Wait(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { return WaitHelper(waitHandles, waitAll, millisecondsTimeout); } [CLSCompliant(false)] protected static int WaitHelper(IntPtr[] waitHandles, bool waitAll, int millisecondsTimeout) { if (waitHandles == null) { throw new ArgumentNullException("waitHandles"); } return WaitHandle.WaitMultipleIgnoringSyncContext(waitHandles, waitAll, millisecondsTimeout); } public static void SetSynchronizationContext(SynchronizationContext? syncContext) { Thread.CurrentThread._synchronizationContext = syncContext; } public virtual SynchronizationContext CreateCopy() { return new SynchronizationContext(); } } internal readonly struct ThreadHandle { private readonly IntPtr _ptr; internal ThreadHandle(IntPtr pThread) { _ptr = pThread; } } public sealed class Thread : CriticalFinalizerObject { private sealed class StartHelper { internal int _maxStackSize; internal Delegate _start; internal object _startArg; internal CultureInfo _culture; internal CultureInfo _uiCulture; internal ExecutionContext _executionContext; internal static readonly ContextCallback s_threadStartContextCallback = Callback; internal StartHelper(Delegate start) { _start = start; } private static void Callback(object state) { ((StartHelper)state).RunWorker(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void Run() { if (_executionContext != null && !_executionContext.IsDefault) { System.Threading.ExecutionContext.RunInternal(_executionContext, s_threadStartContextCallback, this); } else { RunWorker(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void RunWorker() { InitializeCulture(); Delegate start = _start; _start = null; if (start is ThreadStart threadStart) { threadStart(); return; } ParameterizedThreadStart parameterizedThreadStart = (ParameterizedThreadStart)start; object startArg = _startArg; _startArg = null; parameterizedThreadStart(startArg); } private void InitializeCulture() { if (_culture != null) { CultureInfo.CurrentCulture = _culture; _culture = null; } if (_uiCulture != null) { CultureInfo.CurrentUICulture = _uiCulture; _uiCulture = null; } } } private static class LocalDataStore { private static Dictionary s_nameToSlotMap; public static LocalDataStoreSlot AllocateSlot() { return new LocalDataStoreSlot(new ThreadLocal()); } private static Dictionary EnsureNameToSlotMap() { Dictionary dictionary = s_nameToSlotMap; if (dictionary != null) { return dictionary; } dictionary = new Dictionary(); return Interlocked.CompareExchange(ref s_nameToSlotMap, dictionary, null) ?? dictionary; } public static LocalDataStoreSlot AllocateNamedSlot(string name) { LocalDataStoreSlot localDataStoreSlot = AllocateSlot(); Dictionary dictionary = EnsureNameToSlotMap(); lock (dictionary) { dictionary.Add(name, localDataStoreSlot); return localDataStoreSlot; } } public static LocalDataStoreSlot GetNamedSlot(string name) { Dictionary dictionary = EnsureNameToSlotMap(); lock (dictionary) { if (!dictionary.TryGetValue(name, out var value)) { value = (dictionary[name] = AllocateSlot()); } return value; } } public static void FreeNamedSlot(string name) { Dictionary dictionary = EnsureNameToSlotMap(); lock (dictionary) { dictionary.Remove(name); } } private static ThreadLocal GetThreadLocal(LocalDataStoreSlot slot) { if (slot == null) { throw new ArgumentNullException("slot"); } return slot.Data; } public static object GetData(LocalDataStoreSlot slot) { return GetThreadLocal(slot).Value; } public static void SetData(LocalDataStoreSlot slot, object value) { GetThreadLocal(slot).Value = value; } } internal ExecutionContext _executionContext; internal SynchronizationContext _synchronizationContext; private string _name; private StartHelper _startHelper; private IntPtr _DONT_USE_InternalThread; private int _priority; private int _managedThreadId; private bool _mayNeedResetForThreadPool; private static readonly bool s_isProcessorNumberReallyFast = ProcessorIdCache.ProcessorNumberSpeedCheck(); private static AsyncLocal s_asyncLocalPrincipal; [ThreadStatic] private static Thread t_currentThread; public extern int ManagedThreadId { [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] get; } public extern bool IsAlive { [MethodImpl(MethodImplOptions.InternalCall)] get; } public bool IsBackground { get { return IsBackgroundNative(); } set { SetBackgroundNative(value); if (!value) { _mayNeedResetForThreadPool = true; } } } public extern bool IsThreadPoolThread { [MethodImpl(MethodImplOptions.InternalCall)] get; [MethodImpl(MethodImplOptions.InternalCall)] internal set; } public ThreadPriority Priority { get { return (ThreadPriority)GetPriorityNative(); } set { SetPriorityNative((int)value); if (value != ThreadPriority.Normal) { _mayNeedResetForThreadPool = true; } } } public ThreadState ThreadState => (ThreadState)GetThreadStateNative(); internal static extern int OptimalMaxSpinWaitsPerSpinIteration { [MethodImpl(MethodImplOptions.InternalCall)] [CompilerGenerated] get; } [UnsupportedOSPlatformGuard("browser")] internal static bool IsThreadStartSupported => true; public CultureInfo CurrentCulture { get { RequireCurrentThread(); return CultureInfo.CurrentCulture; } set { if (this != CurrentThread) { SetCultureOnUnstartedThread(value, uiCulture: false); } else { CultureInfo.CurrentCulture = value; } } } public CultureInfo CurrentUICulture { get { RequireCurrentThread(); return CultureInfo.CurrentUICulture; } set { if (this != CurrentThread) { SetCultureOnUnstartedThread(value, uiCulture: true); } else { CultureInfo.CurrentUICulture = value; } } } public static IPrincipal? CurrentPrincipal { get { IPrincipal principal = s_asyncLocalPrincipal?.Value; if (principal == null) { principal = (CurrentPrincipal = AppDomain.CurrentDomain.GetThreadPrincipal()); } return principal; } set { if (s_asyncLocalPrincipal == null) { if (value == null) { return; } Interlocked.CompareExchange(ref s_asyncLocalPrincipal, new AsyncLocal(), null); } s_asyncLocalPrincipal.Value = value; } } public static Thread CurrentThread { [Intrinsic] get { return t_currentThread ?? InitializeCurrentThread(); } } internal static ulong CurrentOSThreadId => GetCurrentOSThreadId(); public ExecutionContext? ExecutionContext => System.Threading.ExecutionContext.Capture(); public string? Name { get { return _name; } set { lock (this) { if (_name != value) { _name = value; ThreadNameChanged(value); _mayNeedResetForThreadPool = true; } } } } [Obsolete("The ApartmentState property has been deprecated. Use GetApartmentState, SetApartmentState or TrySetApartmentState.")] public ApartmentState ApartmentState { get { return GetApartmentState(); } set { TrySetApartmentState(value); } } private Thread() { } internal ThreadHandle GetNativeHandle() { IntPtr dONT_USE_InternalThread = _DONT_USE_InternalThread; if (dONT_USE_InternalThread == IntPtr.Zero) { throw new ArgumentException(null, SR.Argument_InvalidHandle); } return new ThreadHandle(dONT_USE_InternalThread); } private unsafe void StartCore() { lock (this) { fixed (char* pThreadName = _name) { StartInternal(GetNativeHandle(), _startHelper?._maxStackSize ?? 0, _priority, pThreadName); } } } [DllImport("QCall")] private unsafe static extern void StartInternal(ThreadHandle t, int stackSize, int priority, char* pThreadName); private void StartCallback() { StartHelper startHelper = _startHelper; _startHelper = null; startHelper.Run(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr InternalGetCurrentThread(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SleepInternal(int millisecondsTimeout); [DllImport("QCall")] internal static extern void UninterruptibleSleep0(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SpinWaitInternal(int iterations); public static void SpinWait(int iterations) { SpinWaitInternal(iterations); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern Interop.BOOL YieldInternal(); public static bool Yield() { return YieldInternal() != Interop.BOOL.FALSE; } [MethodImpl(MethodImplOptions.NoInlining)] private static Thread InitializeCurrentThread() { return t_currentThread = GetCurrentThreadNative(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern Thread GetCurrentThreadNative(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void Initialize(); ~Thread() { InternalFinalize(); } [MethodImpl(MethodImplOptions.InternalCall)] private extern void InternalFinalize(); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void InformThreadNameChange(ThreadHandle t, string name, int len); [MethodImpl(MethodImplOptions.InternalCall)] private extern bool IsBackgroundNative(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetBackgroundNative(bool isBackground); [MethodImpl(MethodImplOptions.InternalCall)] private extern int GetPriorityNative(); [MethodImpl(MethodImplOptions.InternalCall)] private extern void SetPriorityNative(int priority); [DllImport("QCall")] private static extern ulong GetCurrentOSThreadId(); [MethodImpl(MethodImplOptions.InternalCall)] private extern int GetThreadStateNative(); public ApartmentState GetApartmentState() { return (ApartmentState)GetApartmentStateNative(); } private bool SetApartmentStateUnchecked(ApartmentState state, bool throwOnError) { ApartmentState apartmentState = (ApartmentState)SetApartmentStateNative((int)state); if (state == ApartmentState.Unknown && apartmentState == ApartmentState.MTA) { return true; } if (apartmentState != state) { if (throwOnError) { string message = SR.Format(SR.Thread_ApartmentState_ChangeFailed, apartmentState); throw new InvalidOperationException(message); } return false; } return true; } [MethodImpl(MethodImplOptions.InternalCall)] internal extern int GetApartmentStateNative(); [MethodImpl(MethodImplOptions.InternalCall)] internal extern int SetApartmentStateNative(int state); [MethodImpl(MethodImplOptions.InternalCall)] public extern void DisableComObjectEagerCleanup(); [MethodImpl(MethodImplOptions.InternalCall)] public extern void Interrupt(); [MethodImpl(MethodImplOptions.InternalCall)] public extern bool Join(int millisecondsTimeout); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetCurrentProcessorNumber(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int GetCurrentProcessorId() { if (s_isProcessorNumberReallyFast) { return GetCurrentProcessorNumber(); } return ProcessorIdCache.GetCurrentProcessorId(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ResetThreadPoolThread() { if (ThreadPool.UsePortableThreadPool && _mayNeedResetForThreadPool) { ResetThreadPoolThreadSlow(); } } public Thread(ThreadStart start) { if (start == null) { throw new ArgumentNullException("start"); } _startHelper = new StartHelper(start); Initialize(); } public Thread(ThreadStart start, int maxStackSize) { if (start == null) { throw new ArgumentNullException("start"); } if (maxStackSize < 0) { throw new ArgumentOutOfRangeException("maxStackSize", SR.ArgumentOutOfRange_NeedNonNegNum); } _startHelper = new StartHelper(start) { _maxStackSize = maxStackSize }; Initialize(); } public Thread(ParameterizedThreadStart start) { if (start == null) { throw new ArgumentNullException("start"); } _startHelper = new StartHelper(start); Initialize(); } public Thread(ParameterizedThreadStart start, int maxStackSize) { if (start == null) { throw new ArgumentNullException("start"); } if (maxStackSize < 0) { throw new ArgumentOutOfRangeException("maxStackSize", SR.ArgumentOutOfRange_NeedNonNegNum); } _startHelper = new StartHelper(start) { _maxStackSize = maxStackSize }; Initialize(); } [UnsupportedOSPlatform("browser")] public void Start(object? parameter) { Start(parameter, captureContext: true); } [UnsupportedOSPlatform("browser")] public void UnsafeStart(object? parameter) { Start(parameter, captureContext: false); } private void Start(object parameter, bool captureContext) { StartHelper startHelper = _startHelper; if (startHelper != null) { if (startHelper._start is ThreadStart) { throw new InvalidOperationException(SR.InvalidOperation_ThreadWrongThreadStart); } startHelper._startArg = parameter; startHelper._executionContext = (captureContext ? System.Threading.ExecutionContext.Capture() : null); } StartCore(); } [UnsupportedOSPlatform("browser")] public void Start() { Start(captureContext: true); } [UnsupportedOSPlatform("browser")] public void UnsafeStart() { Start(captureContext: false); } private void Start(bool captureContext) { StartHelper startHelper = _startHelper; if (startHelper != null) { startHelper._startArg = null; startHelper._executionContext = (captureContext ? System.Threading.ExecutionContext.Capture() : null); } StartCore(); } private void RequireCurrentThread() { if (this != CurrentThread) { throw new InvalidOperationException(SR.Thread_Operation_RequiresCurrentThread); } } private void SetCultureOnUnstartedThread(CultureInfo value, bool uiCulture) { if (value == null) { throw new ArgumentNullException("value"); } StartHelper startHelper = _startHelper; if ((ThreadState & ThreadState.Unstarted) == 0) { throw new InvalidOperationException(SR.Thread_Operation_RequiresCurrentThread); } if (uiCulture) { startHelper._uiCulture = value; } else { startHelper._culture = value; } } private void ThreadNameChanged(string value) { InformThreadNameChange(GetNativeHandle(), value, value?.Length ?? 0); } [MethodImpl(MethodImplOptions.NoInlining)] public static void Sleep(int millisecondsTimeout) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", millisecondsTimeout, SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } SleepInternal(millisecondsTimeout); } internal void SetThreadPoolWorkerThreadName() { lock (this) { _name = ".NET ThreadPool Worker"; ThreadNameChanged(".NET ThreadPool Worker"); } } [MethodImpl(MethodImplOptions.NoInlining)] private void ResetThreadPoolThreadSlow() { _mayNeedResetForThreadPool = false; if (_name != ".NET ThreadPool Worker") { SetThreadPoolWorkerThreadName(); } if (!IsBackground) { IsBackground = true; } if (Priority != ThreadPriority.Normal) { Priority = ThreadPriority.Normal; } } [Obsolete("Thread.Abort is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0006", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public void Abort() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadAbort); } [Obsolete("Thread.Abort is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0006", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public void Abort(object? stateInfo) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadAbort); } [Obsolete("Thread.Abort is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0006", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public static void ResetAbort() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadAbort); } [Obsolete("Thread.Suspend has been deprecated. Use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources.")] public void Suspend() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadSuspend); } [Obsolete("Thread.Resume has been deprecated. Use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources.")] public void Resume() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ThreadSuspend); } public static void BeginCriticalRegion() { } public static void EndCriticalRegion() { } public static void BeginThreadAffinity() { } public static void EndThreadAffinity() { } public static LocalDataStoreSlot AllocateDataSlot() { return LocalDataStore.AllocateSlot(); } public static LocalDataStoreSlot AllocateNamedDataSlot(string name) { return LocalDataStore.AllocateNamedSlot(name); } public static LocalDataStoreSlot GetNamedDataSlot(string name) { return LocalDataStore.GetNamedSlot(name); } public static void FreeNamedDataSlot(string name) { LocalDataStore.FreeNamedSlot(name); } public static object? GetData(LocalDataStoreSlot slot) { return LocalDataStore.GetData(slot); } public static void SetData(LocalDataStoreSlot slot, object? data) { LocalDataStore.SetData(slot, data); } [SupportedOSPlatform("windows")] public void SetApartmentState(ApartmentState state) { SetApartmentState(state, throwOnError: true); } public bool TrySetApartmentState(ApartmentState state) { return SetApartmentState(state, throwOnError: false); } private bool SetApartmentState(ApartmentState state, bool throwOnError) { if ((uint)state > 2u) { throw new ArgumentOutOfRangeException("state", SR.ArgumentOutOfRange_Enum); } return SetApartmentStateUnchecked(state, throwOnError); } [Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId = "SYSLIB0003", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public CompressedStack GetCompressedStack() { throw new InvalidOperationException(SR.Thread_GetSetCompressedStack_NotSupported); } [Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId = "SYSLIB0003", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public void SetCompressedStack(CompressedStack stack) { throw new InvalidOperationException(SR.Thread_GetSetCompressedStack_NotSupported); } public static AppDomain GetDomain() { return AppDomain.CurrentDomain; } public static int GetDomainID() { return 1; } public override int GetHashCode() { return ManagedThreadId; } public void Join() { Join(-1); } public bool Join(TimeSpan timeout) { return Join(WaitHandle.ToTimeoutMilliseconds(timeout)); } public static void MemoryBarrier() { Interlocked.MemoryBarrier(); } public static void Sleep(TimeSpan timeout) { Sleep(WaitHandle.ToTimeoutMilliseconds(timeout)); } public static byte VolatileRead(ref byte address) { return Volatile.Read(ref address); } public static double VolatileRead(ref double address) { return Volatile.Read(ref address); } public static short VolatileRead(ref short address) { return Volatile.Read(ref address); } public static int VolatileRead(ref int address) { return Volatile.Read(ref address); } public static long VolatileRead(ref long address) { return Volatile.Read(ref address); } public static IntPtr VolatileRead(ref IntPtr address) { return Volatile.Read(ref address); } [return: NotNullIfNotNull("address")] public static object? VolatileRead([NotNullIfNotNull("address")] ref object? address) { return Volatile.Read(ref address); } [CLSCompliant(false)] public static sbyte VolatileRead(ref sbyte address) { return Volatile.Read(ref address); } public static float VolatileRead(ref float address) { return Volatile.Read(ref address); } [CLSCompliant(false)] public static ushort VolatileRead(ref ushort address) { return Volatile.Read(ref address); } [CLSCompliant(false)] public static uint VolatileRead(ref uint address) { return Volatile.Read(ref address); } [CLSCompliant(false)] public static ulong VolatileRead(ref ulong address) { return Volatile.Read(ref address); } [CLSCompliant(false)] public static UIntPtr VolatileRead(ref UIntPtr address) { return Volatile.Read(ref address); } public static void VolatileWrite(ref byte address, byte value) { Volatile.Write(ref address, value); } public static void VolatileWrite(ref double address, double value) { Volatile.Write(ref address, value); } public static void VolatileWrite(ref short address, short value) { Volatile.Write(ref address, value); } public static void VolatileWrite(ref int address, int value) { Volatile.Write(ref address, value); } public static void VolatileWrite(ref long address, long value) { Volatile.Write(ref address, value); } public static void VolatileWrite(ref IntPtr address, IntPtr value) { Volatile.Write(ref address, value); } public static void VolatileWrite([NotNullIfNotNull("value")] ref object? address, object? value) { Volatile.Write(ref address, value); } [CLSCompliant(false)] public static void VolatileWrite(ref sbyte address, sbyte value) { Volatile.Write(ref address, value); } public static void VolatileWrite(ref float address, float value) { Volatile.Write(ref address, value); } [CLSCompliant(false)] public static void VolatileWrite(ref ushort address, ushort value) { Volatile.Write(ref address, value); } [CLSCompliant(false)] public static void VolatileWrite(ref uint address, uint value) { Volatile.Write(ref address, value); } [CLSCompliant(false)] public static void VolatileWrite(ref ulong address, ulong value) { Volatile.Write(ref address, value); } [CLSCompliant(false)] public static void VolatileWrite(ref UIntPtr address, UIntPtr value) { Volatile.Write(ref address, value); } } internal static class ProcessorIdCache { [ThreadStatic] private static int t_currentProcessorIdCache; private static int s_processorIdRefreshRate; private static int RefreshCurrentProcessorId() { int num = Thread.GetCurrentProcessorNumber(); if (num < 0) { num = Environment.CurrentManagedThreadId; } t_currentProcessorIdCache = ((num << 16) & 0x7FFFFFFF) | s_processorIdRefreshRate; return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetCurrentProcessorId() { int num = t_currentProcessorIdCache--; if ((num & 0xFFFF) == 0) { return RefreshCurrentProcessorId(); } return num >> 16; } internal static bool ProcessorNumberSpeedCheck() { double num = double.MaxValue; double num2 = double.MaxValue; UninlinedThreadStatic(); if (Thread.GetCurrentProcessorNumber() < 0) { s_processorIdRefreshRate = 65535; return false; } long num3 = Stopwatch.Frequency / 1000000 + 1; for (int i = 0; i < 10; i++) { int num4 = 8; long timestamp; do { num4 *= 2; timestamp = Stopwatch.GetTimestamp(); for (int j = 0; j < num4; j++) { Thread.GetCurrentProcessorNumber(); } timestamp = Stopwatch.GetTimestamp() - timestamp; } while (timestamp < num3); num = Math.Min(num, (double)timestamp / (double)num4); num4 /= 4; do { num4 *= 2; timestamp = Stopwatch.GetTimestamp(); for (int k = 0; k < num4; k++) { UninlinedThreadStatic(); } timestamp = Stopwatch.GetTimestamp() - timestamp; } while (timestamp < num3); num2 = Math.Min(num2, (double)timestamp / (double)num4); } s_processorIdRefreshRate = Math.Min((int)(num * 5.0 / num2), 5000); return s_processorIdRefreshRate <= 5; } [MethodImpl(MethodImplOptions.NoInlining)] internal static int UninlinedThreadStatic() { return t_currentProcessorIdCache; } } internal static class _ThreadPoolWaitCallback { internal static bool PerformWaitCallback() { return ThreadPoolWorkQueue.Dispatch(); } } [UnsupportedOSPlatform("browser")] public sealed class RegisteredWaitHandle : MarshalByRefObject { private IntPtr _nativeRegisteredWaitHandle = InvalidHandleValue; private bool _releaseHandle; private static AutoResetEvent s_cachedEvent; private static readonly LowLevelLock s_callbackLock = new LowLevelLock(); private int _numRequestedCallbacks; private bool _signalAfterCallbacksComplete; private bool _unregisterCalled; private bool _unregistered; private AutoResetEvent _callbacksComplete; private AutoResetEvent _removed; internal _ThreadPoolWaitOrTimerCallback Callback { get; } internal SafeWaitHandle Handle { get; } internal int TimeoutTimeMs { get; private set; } internal int TimeoutDurationMs { get; } internal bool IsInfiniteTimeout => TimeoutDurationMs == -1; internal bool Repeating { get; } private SafeWaitHandle? UserUnregisterWaitHandle { get; set; } private IntPtr UserUnregisterWaitHandleValue { get; set; } private static IntPtr InvalidHandleValue => new IntPtr(-1); internal bool IsBlocking => UserUnregisterWaitHandleValue == InvalidHandleValue; internal PortableThreadPool.WaitThread? WaitThread { get; set; } private static bool IsValidHandle(IntPtr handle) { if (handle != InvalidHandleValue) { return handle != IntPtr.Zero; } return false; } internal void SetNativeRegisteredWaitHandle(IntPtr nativeRegisteredWaitHandle) { _nativeRegisteredWaitHandle = nativeRegisteredWaitHandle; } internal void OnBeforeRegister() { if (ThreadPool.UsePortableThreadPool) { GC.SuppressFinalize(this); } else { Handle.DangerousAddRef(ref _releaseHandle); } } public bool Unregister(WaitHandle waitObject) { if (ThreadPool.UsePortableThreadPool) { return UnregisterPortable(waitObject); } s_callbackLock.Acquire(); try { if (!IsValidHandle(_nativeRegisteredWaitHandle) || !UnregisterWaitNative(_nativeRegisteredWaitHandle, waitObject?.SafeWaitHandle)) { return false; } _nativeRegisteredWaitHandle = InvalidHandleValue; if (_releaseHandle) { Handle.DangerousRelease(); _releaseHandle = false; } } finally { s_callbackLock.Release(); } GC.SuppressFinalize(this); return true; } ~RegisteredWaitHandle() { if (ThreadPool.UsePortableThreadPool) { return; } s_callbackLock.Acquire(); try { if (IsValidHandle(_nativeRegisteredWaitHandle)) { WaitHandleCleanupNative(_nativeRegisteredWaitHandle); _nativeRegisteredWaitHandle = InvalidHandleValue; if (_releaseHandle) { Handle.DangerousRelease(); _releaseHandle = false; } } } finally { s_callbackLock.Release(); } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void WaitHandleCleanupNative(IntPtr handle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool UnregisterWaitNative(IntPtr handle, SafeHandle waitObject); internal RegisteredWaitHandle(WaitHandle waitHandle, _ThreadPoolWaitOrTimerCallback callbackHelper, int millisecondsTimeout, bool repeating) { Handle = waitHandle.SafeWaitHandle; Callback = callbackHelper; TimeoutDurationMs = millisecondsTimeout; Repeating = repeating; if (!IsInfiniteTimeout) { RestartTimeout(); } } private static AutoResetEvent RentEvent() { return Interlocked.Exchange(ref s_cachedEvent, null) ?? new AutoResetEvent(initialState: false); } private static void ReturnEvent(AutoResetEvent resetEvent) { if (Interlocked.CompareExchange(ref s_cachedEvent, resetEvent, null) != null) { resetEvent.Dispose(); } } internal void RestartTimeout() { TimeoutTimeMs = Environment.TickCount + TimeoutDurationMs; } private bool UnregisterPortable(WaitHandle waitObject) { s_callbackLock.Acquire(); bool success = false; try { if (_unregisterCalled) { return false; } UserUnregisterWaitHandle = waitObject?.SafeWaitHandle; UserUnregisterWaitHandle?.DangerousAddRef(ref success); UserUnregisterWaitHandleValue = UserUnregisterWaitHandle?.DangerousGetHandle() ?? IntPtr.Zero; if (_unregistered) { SignalUserWaitHandle(); return true; } if (IsBlocking) { _callbacksComplete = RentEvent(); } else { _removed = RentEvent(); } } catch (Exception) { if (_removed != null) { ReturnEvent(_removed); _removed = null; } else if (_callbacksComplete != null) { ReturnEvent(_callbacksComplete); _callbacksComplete = null; } UserUnregisterWaitHandleValue = IntPtr.Zero; if (success) { UserUnregisterWaitHandle?.DangerousRelease(); } UserUnregisterWaitHandle = null; throw; } finally { _unregisterCalled = true; s_callbackLock.Release(); } WaitThread.UnregisterWait(this); return true; } private void SignalUserWaitHandle() { SafeWaitHandle userUnregisterWaitHandle = UserUnregisterWaitHandle; IntPtr userUnregisterWaitHandleValue = UserUnregisterWaitHandleValue; try { if (userUnregisterWaitHandleValue != IntPtr.Zero && userUnregisterWaitHandleValue != InvalidHandleValue) { EventWaitHandle.Set(userUnregisterWaitHandle); } } finally { userUnregisterWaitHandle?.DangerousRelease(); _callbacksComplete?.Set(); _unregistered = true; } } internal void PerformCallback(bool timedOut) { _ThreadPoolWaitOrTimerCallback.PerformWaitOrTimerCallback(Callback, timedOut); CompleteCallbackRequest(); } internal void RequestCallback() { s_callbackLock.Acquire(); try { _numRequestedCallbacks++; } finally { s_callbackLock.Release(); } } internal void OnRemoveWait() { s_callbackLock.Acquire(); try { _removed?.Set(); if (_numRequestedCallbacks == 0) { SignalUserWaitHandle(); } else { _signalAfterCallbacksComplete = true; } } finally { s_callbackLock.Release(); } } private void CompleteCallbackRequest() { s_callbackLock.Acquire(); try { _numRequestedCallbacks--; if (_numRequestedCallbacks == 0 && _signalAfterCallbacksComplete) { SignalUserWaitHandle(); } } finally { s_callbackLock.Release(); } } internal void WaitForCallbacks() { _callbacksComplete.WaitOne(); ReturnEvent(_callbacksComplete); _callbacksComplete = null; } internal void WaitForRemoval() { _removed.WaitOne(); ReturnEvent(_removed); _removed = null; } } internal sealed class CompleteWaitThreadPoolWorkItem : IThreadPoolWorkItem { private RegisteredWaitHandle _registeredWaitHandle; private bool _timedOut; void IThreadPoolWorkItem.Execute() { CompleteWait(); } private void CompleteWait() { PortableThreadPool.CompleteWait(_registeredWaitHandle, _timedOut); } public CompleteWaitThreadPoolWorkItem(RegisteredWaitHandle registeredWaitHandle, bool timedOut) { _registeredWaitHandle = registeredWaitHandle; _timedOut = timedOut; } } internal sealed class UnmanagedThreadPoolWorkItem : IThreadPoolWorkItem { private readonly IntPtr _callback; private readonly IntPtr _state; public UnmanagedThreadPoolWorkItem(IntPtr callback, IntPtr state) { _callback = callback; _state = state; } void IThreadPoolWorkItem.Execute() { ExecuteUnmanagedThreadPoolWorkItem(_callback, _state); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void ExecuteUnmanagedThreadPoolWorkItem(IntPtr callback, IntPtr state); } public static class ThreadPool { internal static readonly bool UsePortableThreadPool = InitializeConfigAndDetermineUsePortableThreadPool(); private static readonly bool IsWorkerTrackingEnabledInConfig = GetEnableWorkerTracking(); internal static readonly ThreadPoolWorkQueue s_workQueue = new ThreadPoolWorkQueue(); internal static readonly Action s_invokeAsyncStateMachineBox = delegate(object state) { if (!(state is IAsyncStateMachineBox asyncStateMachineBox)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.state); } else { asyncStateMachineBox.MoveNext(); } }; internal static bool SupportsTimeSensitiveWorkItems => UsePortableThreadPool; public static int ThreadCount => (UsePortableThreadPool ? PortableThreadPool.ThreadPoolInstance.ThreadCount : 0) + GetThreadCount(); public static long CompletedWorkItemCount { get { long num = GetCompletedWorkItemCount(); if (UsePortableThreadPool) { num += PortableThreadPool.ThreadPoolInstance.CompletedWorkItemCount; } return num; } } private static long PendingUnmanagedWorkItemCount { get { if (!UsePortableThreadPool) { return GetPendingUnmanagedWorkItemCount(); } return 0L; } } internal static bool EnableWorkerTracking { get { if (IsWorkerTrackingEnabledInConfig) { return EventSource.IsSupported; } return false; } } public static long PendingWorkItemCount { get { ThreadPoolWorkQueue threadPoolWorkQueue = s_workQueue; return ThreadPoolWorkQueue.LocalCount + threadPoolWorkQueue.GlobalCount + PendingUnmanagedWorkItemCount; } } private unsafe static bool InitializeConfigAndDetermineUsePortableThreadPool() { bool result = false; int configVariableIndex = 0; while (true) { uint configValue; bool isBoolean; char* appContextConfigName; int nextConfigUInt32Value = GetNextConfigUInt32Value(configVariableIndex, out configValue, out isBoolean, out appContextConfigName); if (nextConfigUInt32Value < 0) { break; } configVariableIndex = nextConfigUInt32Value; if (appContextConfigName == null) { result = true; continue; } string text = new string(appContextConfigName); if (isBoolean) { AppContext.SetSwitch(text, configValue != 0); } else { AppContext.SetData(text, configValue); } } return result; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern int GetNextConfigUInt32Value(int configVariableIndex, out uint configValue, out bool isBoolean, out char* appContextConfigName); private static bool GetEnableWorkerTracking() { if (!UsePortableThreadPool) { return GetEnableWorkerTrackingNative(); } return AppContextConfigHelper.GetBooleanConfig("System.Threading.ThreadPool.EnableWorkerTracking", defaultValue: false); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool CanSetMinIOCompletionThreads(int ioCompletionThreads); internal static void SetMinIOCompletionThreads(int ioCompletionThreads) { bool flag = SetMinThreadsNative(1, ioCompletionThreads); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool CanSetMaxIOCompletionThreads(int ioCompletionThreads); internal static void SetMaxIOCompletionThreads(int ioCompletionThreads) { bool flag = SetMaxThreadsNative(1, ioCompletionThreads); } public static bool SetMaxThreads(int workerThreads, int completionPortThreads) { if (UsePortableThreadPool) { return PortableThreadPool.ThreadPoolInstance.SetMaxThreads(workerThreads, completionPortThreads); } if (workerThreads >= 0 && completionPortThreads >= 0) { return SetMaxThreadsNative(workerThreads, completionPortThreads); } return false; } public static void GetMaxThreads(out int workerThreads, out int completionPortThreads) { GetMaxThreadsNative(out workerThreads, out completionPortThreads); if (UsePortableThreadPool) { workerThreads = PortableThreadPool.ThreadPoolInstance.GetMaxThreads(); } } public static bool SetMinThreads(int workerThreads, int completionPortThreads) { if (UsePortableThreadPool) { return PortableThreadPool.ThreadPoolInstance.SetMinThreads(workerThreads, completionPortThreads); } if (workerThreads >= 0 && completionPortThreads >= 0) { return SetMinThreadsNative(workerThreads, completionPortThreads); } return false; } public static void GetMinThreads(out int workerThreads, out int completionPortThreads) { GetMinThreadsNative(out workerThreads, out completionPortThreads); if (UsePortableThreadPool) { workerThreads = PortableThreadPool.ThreadPoolInstance.GetMinThreads(); } } public static void GetAvailableThreads(out int workerThreads, out int completionPortThreads) { GetAvailableThreadsNative(out workerThreads, out completionPortThreads); if (UsePortableThreadPool) { workerThreads = PortableThreadPool.ThreadPoolInstance.GetAvailableThreads(); } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetThreadCount(); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern long GetCompletedWorkItemCount(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern long GetPendingUnmanagedWorkItemCount(); private static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce, bool flowExecutionContext) { if (waitObject == null) { throw new ArgumentNullException("waitObject"); } if (callBack == null) { throw new ArgumentNullException("callBack"); } RegisteredWaitHandle registeredWaitHandle = new RegisteredWaitHandle(waitObject, new _ThreadPoolWaitOrTimerCallback(callBack, state, flowExecutionContext), (int)millisecondsTimeOutInterval, !executeOnlyOnce); registeredWaitHandle.OnBeforeRegister(); if (UsePortableThreadPool) { PortableThreadPool.ThreadPoolInstance.RegisterWaitHandle(registeredWaitHandle); } else { IntPtr nativeRegisteredWaitHandle = RegisterWaitForSingleObjectNative(waitObject, registeredWaitHandle.Callback, (uint)registeredWaitHandle.TimeoutDurationMs, !registeredWaitHandle.Repeating, registeredWaitHandle); registeredWaitHandle.SetNativeRegisteredWaitHandle(nativeRegisteredWaitHandle); } return registeredWaitHandle; } internal static void UnsafeQueueWaitCompletion(CompleteWaitThreadPoolWorkItem completeWaitWorkItem) { QueueWaitCompletionNative(completeWaitWorkItem); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void QueueWaitCompletionNative(CompleteWaitThreadPoolWorkItem completeWaitWorkItem); internal static void RequestWorkerThread() { if (UsePortableThreadPool) { PortableThreadPool.ThreadPoolInstance.RequestWorker(); } else { RequestWorkerThreadNative(); } } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern Interop.BOOL RequestWorkerThreadNative(); private static void EnsureGateThreadRunning() { PortableThreadPool.EnsureGateThreadRunning(); } internal static bool PerformRuntimeSpecificGateActivities(int cpuUtilization) { return PerformRuntimeSpecificGateActivitiesNative(cpuUtilization) != Interop.BOOL.FALSE; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern Interop.BOOL PerformRuntimeSpecificGateActivitiesNative(int cpuUtilization); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern bool PostQueuedCompletionStatus(NativeOverlapped* overlapped); [CLSCompliant(false)] [SupportedOSPlatform("windows")] public unsafe static bool UnsafeQueueNativeOverlapped(NativeOverlapped* overlapped) { return PostQueuedCompletionStatus(overlapped); } private static void UnsafeQueueUnmanagedWorkItem(IntPtr callback, IntPtr state) { UnsafeQueueTimeSensitiveWorkItemInternal(new UnmanagedThreadPoolWorkItem(callback, state)); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool SetMinThreadsNative(int workerThreads, int completionPortThreads); [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool SetMaxThreadsNative(int workerThreads, int completionPortThreads); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetMinThreadsNative(out int workerThreads, out int completionPortThreads); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetMaxThreadsNative(out int workerThreads, out int completionPortThreads); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetAvailableThreadsNative(out int workerThreads, out int completionPortThreads); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool NotifyWorkItemComplete(object threadLocalCompletionCountObject, int currentTimeMs) { if (UsePortableThreadPool) { return PortableThreadPool.ThreadPoolInstance.NotifyWorkItemComplete(threadLocalCompletionCountObject, currentTimeMs); } return NotifyWorkItemCompleteNative(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool NotifyWorkItemCompleteNative(); internal static void ReportThreadStatus(bool isWorking) { if (UsePortableThreadPool) { PortableThreadPool.ThreadPoolInstance.ReportThreadStatus(isWorking); } else { ReportThreadStatusNative(isWorking); } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ReportThreadStatusNative(bool isWorking); internal static void NotifyWorkItemProgress() { if (UsePortableThreadPool) { PortableThreadPool.ThreadPoolInstance.NotifyWorkItemProgress(); } else { NotifyWorkItemProgressNative(); } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void NotifyWorkItemProgressNative(); internal static bool NotifyThreadBlocked() { if (UsePortableThreadPool) { return PortableThreadPool.ThreadPoolInstance.NotifyThreadBlocked(); } return false; } internal static void NotifyThreadUnblocked() { PortableThreadPool.ThreadPoolInstance.NotifyThreadUnblocked(); } internal static object GetOrCreateThreadLocalCompletionCountObject() { if (!UsePortableThreadPool) { return null; } return PortableThreadPool.ThreadPoolInstance.GetOrCreateThreadLocalCompletionCountObject(); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool GetEnableWorkerTrackingNative(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr RegisterWaitForSingleObjectNative(WaitHandle waitHandle, object state, uint timeOutInterval, bool executeOnlyOnce, RegisteredWaitHandle registeredWaitHandle); [Obsolete("ThreadPool.BindHandle(IntPtr) has been deprecated. Use ThreadPool.BindHandle(SafeHandle) instead.")] [SupportedOSPlatform("windows")] public static bool BindHandle(IntPtr osHandle) { return BindIOCompletionCallbackNative(osHandle); } [SupportedOSPlatform("windows")] public static bool BindHandle(SafeHandle osHandle) { if (osHandle == null) { throw new ArgumentNullException("osHandle"); } bool flag = false; bool success = false; try { osHandle.DangerousAddRef(ref success); return BindIOCompletionCallbackNative(osHandle.DangerousGetHandle()); } finally { if (success) { osHandle.DangerousRelease(); } } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool BindIOCompletionCallbackNative(IntPtr fileHandle); [CLSCompliant(false)] [UnsupportedOSPlatform("browser")] public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, uint millisecondsTimeOutInterval, bool executeOnlyOnce) { if (millisecondsTimeOutInterval > int.MaxValue && millisecondsTimeOutInterval != uint.MaxValue) { throw new ArgumentOutOfRangeException("millisecondsTimeOutInterval", SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); } return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, flowExecutionContext: true); } [CLSCompliant(false)] [UnsupportedOSPlatform("browser")] public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, uint millisecondsTimeOutInterval, bool executeOnlyOnce) { if (millisecondsTimeOutInterval > int.MaxValue && millisecondsTimeOutInterval != uint.MaxValue) { throw new ArgumentOutOfRangeException("millisecondsTimeOutInterval", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, flowExecutionContext: false); } [UnsupportedOSPlatform("browser")] public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, int millisecondsTimeOutInterval, bool executeOnlyOnce) { if (millisecondsTimeOutInterval < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeOutInterval", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, flowExecutionContext: true); } [UnsupportedOSPlatform("browser")] public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, int millisecondsTimeOutInterval, bool executeOnlyOnce) { if (millisecondsTimeOutInterval < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeOutInterval", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, flowExecutionContext: false); } [UnsupportedOSPlatform("browser")] public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, long millisecondsTimeOutInterval, bool executeOnlyOnce) { if (millisecondsTimeOutInterval < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeOutInterval", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (millisecondsTimeOutInterval > int.MaxValue) { throw new ArgumentOutOfRangeException("millisecondsTimeOutInterval", SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); } return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, flowExecutionContext: true); } [UnsupportedOSPlatform("browser")] public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, long millisecondsTimeOutInterval, bool executeOnlyOnce) { if (millisecondsTimeOutInterval < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeOutInterval", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (millisecondsTimeOutInterval > int.MaxValue) { throw new ArgumentOutOfRangeException("millisecondsTimeOutInterval", SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); } return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, flowExecutionContext: false); } [UnsupportedOSPlatform("browser")] public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, TimeSpan timeout, bool executeOnlyOnce) { long num = (long)timeout.TotalMilliseconds; if (num < -1) { throw new ArgumentOutOfRangeException("timeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout", SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); } return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)num, executeOnlyOnce, flowExecutionContext: true); } [UnsupportedOSPlatform("browser")] public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, TimeSpan timeout, bool executeOnlyOnce) { long num = (long)timeout.TotalMilliseconds; if (num < -1) { throw new ArgumentOutOfRangeException("timeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout", SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); } return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)num, executeOnlyOnce, flowExecutionContext: false); } public static bool QueueUserWorkItem(WaitCallback callBack) { return QueueUserWorkItem(callBack, null); } public static bool QueueUserWorkItem(WaitCallback callBack, object? state) { if (callBack == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } ExecutionContext executionContext = ExecutionContext.Capture(); object callback = ((executionContext == null || executionContext.IsDefault) ? ((QueueUserWorkItemCallbackBase)new QueueUserWorkItemCallbackDefaultContext(callBack, state)) : ((QueueUserWorkItemCallbackBase)new QueueUserWorkItemCallback(callBack, state, executionContext))); s_workQueue.Enqueue(callback, forceGlobal: true); return true; } public static bool QueueUserWorkItem(Action callBack, TState state, bool preferLocal) { if (callBack == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } ExecutionContext executionContext = ExecutionContext.Capture(); object callback = ((executionContext == null || executionContext.IsDefault) ? ((QueueUserWorkItemCallbackBase)new QueueUserWorkItemCallbackDefaultContext(callBack, state)) : ((QueueUserWorkItemCallbackBase)new QueueUserWorkItemCallback(callBack, state, executionContext))); s_workQueue.Enqueue(callback, !preferLocal); return true; } public static bool UnsafeQueueUserWorkItem(Action callBack, TState state, bool preferLocal) { if (callBack == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } if ((object)callBack == s_invokeAsyncStateMachineBox) { if (!(state is IAsyncStateMachineBox)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.state); } UnsafeQueueUserWorkItemInternal(state, preferLocal); return true; } s_workQueue.Enqueue(new QueueUserWorkItemCallbackDefaultContext(callBack, state), !preferLocal); return true; } public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, object? state) { if (callBack == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } object callback = new QueueUserWorkItemCallbackDefaultContext(callBack, state); s_workQueue.Enqueue(callback, forceGlobal: true); return true; } public static bool UnsafeQueueUserWorkItem(IThreadPoolWorkItem callBack, bool preferLocal) { if (callBack == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } if (callBack is Task) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.callBack); } UnsafeQueueUserWorkItemInternal(callBack, preferLocal); return true; } internal static void UnsafeQueueUserWorkItemInternal(object callBack, bool preferLocal) { s_workQueue.Enqueue(callBack, !preferLocal); } internal static void UnsafeQueueTimeSensitiveWorkItemInternal(IThreadPoolWorkItem timeSensitiveWorkItem) { s_workQueue.EnqueueTimeSensitiveWorkItem(timeSensitiveWorkItem); } internal static bool TryPopCustomWorkItem(object workItem) { return ThreadPoolWorkQueue.LocalFindAndPop(workItem); } internal static IEnumerable GetQueuedWorkItems() { if (SupportsTimeSensitiveWorkItems) { foreach (IThreadPoolWorkItem item in s_workQueue.timeSensitiveWorkQueue) { yield return item; } } foreach (object workItem in s_workQueue.workItems) { yield return workItem; } ThreadPoolWorkQueue.WorkStealingQueue[] queues = ThreadPoolWorkQueue.WorkStealingQueueList.Queues; foreach (ThreadPoolWorkQueue.WorkStealingQueue workStealingQueue in queues) { if (workStealingQueue == null || workStealingQueue.m_array == null) { continue; } object[] items = workStealingQueue.m_array; foreach (object obj in items) { if (obj != null) { yield return obj; } } } } internal static IEnumerable GetLocallyQueuedWorkItems() { ThreadPoolWorkQueue.WorkStealingQueue workStealingQueue = ThreadPoolWorkQueueThreadLocals.threadLocals?.workStealingQueue; if (workStealingQueue == null || workStealingQueue.m_array == null) { yield break; } object[] items = workStealingQueue.m_array; foreach (object obj in items) { if (obj != null) { yield return obj; } } } internal static IEnumerable GetGloballyQueuedWorkItems() { if (SupportsTimeSensitiveWorkItems) { foreach (IThreadPoolWorkItem item in s_workQueue.timeSensitiveWorkQueue) { yield return item; } } foreach (object workItem in s_workQueue.workItems) { yield return workItem; } } private static object[] ToObjectArray(IEnumerable workitems) { int num = 0; foreach (object workitem in workitems) { num++; } object[] array = new object[num]; num = 0; foreach (object workitem2 in workitems) { if (num < array.Length) { array[num] = workitem2; } num++; } return array; } internal static object[] GetQueuedWorkItemsForDebugger() { return ToObjectArray(GetQueuedWorkItems()); } internal static object[] GetGloballyQueuedWorkItemsForDebugger() { return ToObjectArray(GetGloballyQueuedWorkItems()); } internal static object[] GetLocallyQueuedWorkItemsForDebugger() { return ToObjectArray(GetLocallyQueuedWorkItems()); } } [DebuggerDisplay("Count = {CountForDebugger}")] [DebuggerTypeProxy(typeof(TimerQueueDebuggerTypeProxy))] internal sealed class TimerQueue { private sealed class AppDomainTimerSafeHandle : SafeHandleZeroOrMinusOneIsInvalid { public AppDomainTimerSafeHandle() : base(ownsHandle: true) { } protected override bool ReleaseHandle() { return DeleteAppDomainTimer(handle); } } private sealed class TimerQueueDebuggerTypeProxy { private readonly TimerQueue _queue; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public TimerQueueTimer[] Items => new List(_queue.GetTimersForDebugger()).ToArray(); public TimerQueueDebuggerTypeProxy(TimerQueue queue) { _queue = queue ?? throw new ArgumentNullException("queue"); } } private readonly int _id; private AppDomainTimerSafeHandle m_appDomainTimer; internal static readonly (long TickCount, DateTime Time) s_tickCountToTimeMap = (TickCount64, DateTime.UtcNow); private bool _isTimerScheduled; private long _currentTimerStartTicks; private uint _currentTimerDuration; private TimerQueueTimer _shortTimers; private TimerQueueTimer _longTimers; private long _currentAbsoluteThreshold = TickCount64 + 333; public static TimerQueue[] Instances { get; } = CreateTimerQueues(); private int CountForDebugger { get { int num = 0; foreach (TimerQueueTimer item in GetTimersForDebugger()) { num++; } return num; } } public long ActiveCount { get; private set; } private static long TickCount64 { get { if (Environment.IsWindows8OrAbove) { ulong UnbiasedTime; bool flag = Interop.Kernel32.QueryUnbiasedInterruptTime(out UnbiasedTime); return (long)(UnbiasedTime / 10000); } return Environment.TickCount64; } } private TimerQueue(int id) { _id = id; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool SetTimer(uint actualDuration) { if (m_appDomainTimer == null || m_appDomainTimer.IsInvalid) { m_appDomainTimer = CreateAppDomainTimer(actualDuration, _id); return !m_appDomainTimer.IsInvalid; } return ChangeAppDomainTimer(m_appDomainTimer, actualDuration); } internal static void AppDomainTimerCallback(int id) { Instances[id].FireNextTimers(); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern AppDomainTimerSafeHandle CreateAppDomainTimer(uint dueTime, int id); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern bool ChangeAppDomainTimer(AppDomainTimerSafeHandle handle, uint dueTime); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern bool DeleteAppDomainTimer(IntPtr handle); private static TimerQueue[] CreateTimerQueues() { TimerQueue[] array = new TimerQueue[Environment.ProcessorCount]; for (int i = 0; i < array.Length; i++) { array[i] = new TimerQueue(i); } return array; } internal IEnumerable GetTimersForDebugger() { for (TimerQueueTimer timer2 = _shortTimers; timer2 != null; timer2 = timer2._next) { yield return timer2; } for (TimerQueueTimer timer2 = _longTimers; timer2 != null; timer2 = timer2._next) { yield return timer2; } } private bool EnsureTimerFiresBy(uint requestedDuration) { uint num = Math.Min(requestedDuration, 268435455u); if (_isTimerScheduled) { long num2 = TickCount64 - _currentTimerStartTicks; if (num2 >= _currentTimerDuration) { return true; } uint num3 = _currentTimerDuration - (uint)(int)num2; if (num >= num3) { return true; } } if (SetTimer(num)) { _isTimerScheduled = true; _currentTimerStartTicks = TickCount64; _currentTimerDuration = num; return true; } return false; } private void FireNextTimers() { TimerQueueTimer timerQueueTimer = null; lock (this) { _isTimerScheduled = false; bool flag = false; uint num = uint.MaxValue; long tickCount = TickCount64; TimerQueueTimer timerQueueTimer2 = _shortTimers; for (int i = 0; i < 2; i++) { while (timerQueueTimer2 != null) { TimerQueueTimer next = timerQueueTimer2._next; long num2 = tickCount - timerQueueTimer2._startTicks; long num3 = timerQueueTimer2._dueTime - num2; if (num3 <= 0) { timerQueueTimer2._everQueued = true; if (timerQueueTimer2._period != uint.MaxValue) { timerQueueTimer2._startTicks = tickCount; long num4 = num2 - timerQueueTimer2._dueTime; timerQueueTimer2._dueTime = ((num4 >= timerQueueTimer2._period) ? 1u : (timerQueueTimer2._period - (uint)(int)num4)); if (timerQueueTimer2._dueTime < num) { flag = true; num = timerQueueTimer2._dueTime; } bool flag2 = tickCount + timerQueueTimer2._dueTime - _currentAbsoluteThreshold <= 0; if (timerQueueTimer2._short != flag2) { MoveTimerToCorrectList(timerQueueTimer2, flag2); } } else { DeleteTimer(timerQueueTimer2); } if (timerQueueTimer == null) { timerQueueTimer = timerQueueTimer2; } else { ThreadPool.UnsafeQueueUserWorkItemInternal(timerQueueTimer2, preferLocal: false); } } else { if (num3 < num) { flag = true; num = (uint)num3; } if (!timerQueueTimer2._short && num3 <= 333) { MoveTimerToCorrectList(timerQueueTimer2, shortList: true); } } timerQueueTimer2 = next; } if (i != 0) { continue; } long num5 = _currentAbsoluteThreshold - tickCount; if (num5 > 0) { if (_shortTimers == null && _longTimers != null) { num = (uint)((int)num5 + 1); flag = true; } break; } timerQueueTimer2 = _longTimers; _currentAbsoluteThreshold = tickCount + 333; } if (flag) { EnsureTimerFiresBy(num); } } timerQueueTimer?.Fire(); } public bool UpdateTimer(TimerQueueTimer timer, uint dueTime, uint period) { long tickCount = TickCount64; long num = tickCount + dueTime; bool flag = _currentAbsoluteThreshold - num >= 0; if (timer._dueTime == uint.MaxValue) { timer._short = flag; LinkTimer(timer); long activeCount = ActiveCount + 1; ActiveCount = activeCount; } else if (timer._short != flag) { UnlinkTimer(timer); timer._short = flag; LinkTimer(timer); } timer._dueTime = dueTime; timer._period = ((period == 0) ? uint.MaxValue : period); timer._startTicks = tickCount; return EnsureTimerFiresBy(dueTime); } public void MoveTimerToCorrectList(TimerQueueTimer timer, bool shortList) { UnlinkTimer(timer); timer._short = shortList; LinkTimer(timer); } private void LinkTimer(TimerQueueTimer timer) { ref TimerQueueTimer reference = ref timer._short ? ref _shortTimers : ref _longTimers; timer._next = reference; if (timer._next != null) { timer._next._prev = timer; } timer._prev = null; reference = timer; } private void UnlinkTimer(TimerQueueTimer timer) { TimerQueueTimer next = timer._next; if (next != null) { next._prev = timer._prev; } if (_shortTimers == timer) { _shortTimers = next; } else if (_longTimers == timer) { _longTimers = next; } next = timer._prev; if (next != null) { next._next = timer._next; } } public void DeleteTimer(TimerQueueTimer timer) { if (timer._dueTime != uint.MaxValue) { long activeCount = ActiveCount - 1; ActiveCount = activeCount; UnlinkTimer(timer); timer._prev = null; timer._next = null; timer._dueTime = uint.MaxValue; timer._period = uint.MaxValue; timer._startTicks = 0L; timer._short = false; } } } public abstract class WaitHandle : MarshalByRefObject, IDisposable { internal const int MaxWaitHandles = 64; protected static readonly IntPtr InvalidHandle = new IntPtr(-1); private SafeWaitHandle _waitHandle; [ThreadStatic] private static SafeWaitHandle[] t_safeWaitHandlesForRent; internal const int WaitSuccess = 0; internal const int WaitAbandoned = 128; public const int WaitTimeout = 258; [Obsolete("WaitHandleHandle has been deprecated. Use the SafeWaitHandle property instead.")] public virtual IntPtr Handle { get { if (_waitHandle != null) { return _waitHandle.DangerousGetHandle(); } return InvalidHandle; } set { if (value == InvalidHandle) { if (_waitHandle != null) { _waitHandle.SetHandleAsInvalid(); _waitHandle = null; } } else { _waitHandle = new SafeWaitHandle(value, ownsHandle: true); } } } public SafeWaitHandle SafeWaitHandle { get { return _waitHandle ?? (_waitHandle = new SafeWaitHandle(InvalidHandle, ownsHandle: false)); } [param: AllowNull] set { _waitHandle = value; } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern int WaitOneCore(IntPtr waitHandle, int millisecondsTimeout); internal unsafe static int WaitMultipleIgnoringSyncContext(Span waitHandles, bool waitAll, int millisecondsTimeout) { fixed (IntPtr* waitHandles2 = &MemoryMarshal.GetReference(waitHandles)) { return WaitMultipleIgnoringSyncContext(waitHandles2, waitHandles.Length, waitAll, millisecondsTimeout); } } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern int WaitMultipleIgnoringSyncContext(IntPtr* waitHandles, int numHandles, bool waitAll, int millisecondsTimeout); private static int SignalAndWaitCore(IntPtr waitHandleToSignal, IntPtr waitHandleToWaitOn, int millisecondsTimeout) { int num = SignalAndWaitNative(waitHandleToSignal, waitHandleToWaitOn, millisecondsTimeout); if (num == 298) { throw new InvalidOperationException(SR.Threading_WaitHandleTooManyPosts); } return num; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern int SignalAndWaitNative(IntPtr waitHandleToSignal, IntPtr waitHandleToWaitOn, int millisecondsTimeout); internal static int ToTimeoutMilliseconds(TimeSpan timeout) { long num = (long)timeout.TotalMilliseconds; if (num < -1) { throw new ArgumentOutOfRangeException("timeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout", SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); } return (int)num; } public virtual void Close() { Dispose(); } protected virtual void Dispose(bool explicitDisposing) { _waitHandle?.Close(); } public void Dispose() { Dispose(explicitDisposing: true); GC.SuppressFinalize(this); } public virtual bool WaitOne(int millisecondsTimeout) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return WaitOneNoCheck(millisecondsTimeout); } private bool WaitOneNoCheck(int millisecondsTimeout) { SafeWaitHandle safeWaitHandle = _waitHandle ?? throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); bool success = false; try { safeWaitHandle.DangerousAddRef(ref success); SynchronizationContext current = SynchronizationContext.Current; int num = ((current == null || !current.IsWaitNotificationRequired()) ? WaitOneCore(safeWaitHandle.DangerousGetHandle(), millisecondsTimeout) : current.Wait(new IntPtr[1] { safeWaitHandle.DangerousGetHandle() }, waitAll: false, millisecondsTimeout)); if (num == 128) { throw new AbandonedMutexException(); } return num != 258; } finally { if (success) { safeWaitHandle.DangerousRelease(); } } } private static SafeWaitHandle[] RentSafeWaitHandleArray(int capacity) { SafeWaitHandle[] array = t_safeWaitHandlesForRent; t_safeWaitHandlesForRent = null; int num = ((array != null) ? array.Length : 0); if (num < capacity) { array = new SafeWaitHandle[Math.Max(capacity, Math.Min(64, 2 * num))]; } return array; } private static void ReturnSafeWaitHandleArray(SafeWaitHandle[] safeWaitHandles) { t_safeWaitHandlesForRent = safeWaitHandles; } private static void ObtainSafeWaitHandles(ReadOnlySpan waitHandles, Span safeWaitHandles, Span unsafeWaitHandles) { bool success = true; SafeWaitHandle safeWaitHandle = null; try { for (int i = 0; i < waitHandles.Length; i++) { WaitHandle waitHandle = waitHandles[i]; if (waitHandle == null) { throw new ArgumentNullException("waitHandles[" + i + "]", SR.ArgumentNull_ArrayElement); } SafeWaitHandle safeWaitHandle2 = waitHandle._waitHandle ?? throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); safeWaitHandle = safeWaitHandle2; success = false; safeWaitHandle2.DangerousAddRef(ref success); safeWaitHandles[i] = safeWaitHandle2; unsafeWaitHandles[i] = safeWaitHandle2.DangerousGetHandle(); } } catch { for (int j = 0; j < waitHandles.Length; j++) { SafeWaitHandle safeWaitHandle3 = safeWaitHandles[j]; if (safeWaitHandle3 == null) { break; } safeWaitHandle3.DangerousRelease(); safeWaitHandles[j] = null; if (safeWaitHandle3 == safeWaitHandle) { safeWaitHandle = null; success = true; } } if (!success) { safeWaitHandle.DangerousRelease(); } throw; } } private static int WaitMultiple(WaitHandle[] waitHandles, bool waitAll, int millisecondsTimeout) { if (waitHandles == null) { throw new ArgumentNullException("waitHandles", SR.ArgumentNull_Waithandles); } return WaitMultiple(new ReadOnlySpan(waitHandles), waitAll, millisecondsTimeout); } private static int WaitMultiple(ReadOnlySpan waitHandles, bool waitAll, int millisecondsTimeout) { if (waitHandles.Length == 0) { throw new ArgumentException(SR.Argument_EmptyWaithandleArray, "waitHandles"); } if (waitHandles.Length > 64) { throw new NotSupportedException(SR.NotSupported_MaxWaitHandles); } if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } SynchronizationContext current = SynchronizationContext.Current; bool flag = current?.IsWaitNotificationRequired() ?? false; SafeWaitHandle[] array = RentSafeWaitHandleArray(waitHandles.Length); try { int num; if (flag) { IntPtr[] array2 = new IntPtr[waitHandles.Length]; ObtainSafeWaitHandles(waitHandles, array, array2); num = current.Wait(array2, waitAll, millisecondsTimeout); } else { Span span = stackalloc IntPtr[waitHandles.Length]; ObtainSafeWaitHandles(waitHandles, array, span); num = WaitMultipleIgnoringSyncContext(span, waitAll, millisecondsTimeout); } if (num >= 128 && num < 128 + waitHandles.Length) { if (waitAll) { throw new AbandonedMutexException(); } num -= 128; throw new AbandonedMutexException(num, waitHandles[num]); } return num; } finally { for (int i = 0; i < waitHandles.Length; i++) { SafeWaitHandle safeWaitHandle = array[i]; if (safeWaitHandle != null) { safeWaitHandle.DangerousRelease(); array[i] = null; } } ReturnSafeWaitHandleArray(array); } } private static int WaitAnyMultiple(ReadOnlySpan safeWaitHandles, int millisecondsTimeout) { SynchronizationContext current = SynchronizationContext.Current; if (current != null && current.IsWaitNotificationRequired()) { IntPtr[] array = new IntPtr[safeWaitHandles.Length]; for (int i = 0; i < safeWaitHandles.Length; i++) { array[i] = safeWaitHandles[i].DangerousGetHandle(); } return current.Wait(array, waitAll: false, millisecondsTimeout); } Span waitHandles = stackalloc IntPtr[safeWaitHandles.Length]; for (int j = 0; j < safeWaitHandles.Length; j++) { waitHandles[j] = safeWaitHandles[j].DangerousGetHandle(); } return WaitMultipleIgnoringSyncContext(waitHandles, waitAll: false, millisecondsTimeout); } private static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout) { if (toSignal == null) { throw new ArgumentNullException("toSignal"); } if (toWaitOn == null) { throw new ArgumentNullException("toWaitOn"); } if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } SafeWaitHandle waitHandle = toSignal._waitHandle; SafeWaitHandle waitHandle2 = toWaitOn._waitHandle; if (waitHandle == null || waitHandle2 == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); } bool success = false; bool success2 = false; try { waitHandle.DangerousAddRef(ref success); waitHandle2.DangerousAddRef(ref success2); int num = SignalAndWaitCore(waitHandle.DangerousGetHandle(), waitHandle2.DangerousGetHandle(), millisecondsTimeout); if (num == 128) { throw new AbandonedMutexException(); } return num != 258; } finally { if (success2) { waitHandle2.DangerousRelease(); } if (success) { waitHandle.DangerousRelease(); } } } public virtual bool WaitOne(TimeSpan timeout) { return WaitOneNoCheck(ToTimeoutMilliseconds(timeout)); } public virtual bool WaitOne() { return WaitOneNoCheck(-1); } public virtual bool WaitOne(int millisecondsTimeout, bool exitContext) { return WaitOne(millisecondsTimeout); } public virtual bool WaitOne(TimeSpan timeout, bool exitContext) { return WaitOneNoCheck(ToTimeoutMilliseconds(timeout)); } public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout) { return WaitMultiple(waitHandles, waitAll: true, millisecondsTimeout) != 258; } public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout) { return WaitMultiple(waitHandles, waitAll: true, ToTimeoutMilliseconds(timeout)) != 258; } public static bool WaitAll(WaitHandle[] waitHandles) { return WaitMultiple(waitHandles, waitAll: true, -1) != 258; } public static bool WaitAll(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { return WaitMultiple(waitHandles, waitAll: true, millisecondsTimeout) != 258; } public static bool WaitAll(WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) { return WaitMultiple(waitHandles, waitAll: true, ToTimeoutMilliseconds(timeout)) != 258; } public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout) { return WaitMultiple(waitHandles, waitAll: false, millisecondsTimeout); } internal static int WaitAny(ReadOnlySpan safeWaitHandles, int millisecondsTimeout) { return WaitAnyMultiple(safeWaitHandles, millisecondsTimeout); } public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout) { return WaitMultiple(waitHandles, waitAll: false, ToTimeoutMilliseconds(timeout)); } public static int WaitAny(WaitHandle[] waitHandles) { return WaitMultiple(waitHandles, waitAll: false, -1); } public static int WaitAny(WaitHandle[] waitHandles, int millisecondsTimeout, bool exitContext) { return WaitMultiple(waitHandles, waitAll: false, millisecondsTimeout); } public static int WaitAny(WaitHandle[] waitHandles, TimeSpan timeout, bool exitContext) { return WaitMultiple(waitHandles, waitAll: false, ToTimeoutMilliseconds(timeout)); } public static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn) { return SignalAndWait(toSignal, toWaitOn, -1); } public static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, TimeSpan timeout, bool exitContext) { return SignalAndWait(toSignal, toWaitOn, ToTimeoutMilliseconds(timeout)); } public static bool SignalAndWait(WaitHandle toSignal, WaitHandle toWaitOn, int millisecondsTimeout, bool exitContext) { return SignalAndWait(toSignal, toWaitOn, millisecondsTimeout); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class AbandonedMutexException : SystemException { private int _mutexIndex = -1; private Mutex _mutex; public Mutex? Mutex => _mutex; public int MutexIndex => _mutexIndex; public AbandonedMutexException() : base(SR.Threading_AbandonedMutexException) { base.HResult = -2146233043; } public AbandonedMutexException(string? message) : base(message) { base.HResult = -2146233043; } public AbandonedMutexException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233043; } public AbandonedMutexException(int location, WaitHandle? handle) : base(SR.Threading_AbandonedMutexException) { base.HResult = -2146233043; SetupException(location, handle); } public AbandonedMutexException(string? message, int location, WaitHandle? handle) : base(message) { base.HResult = -2146233043; SetupException(location, handle); } public AbandonedMutexException(string? message, Exception? inner, int location, WaitHandle? handle) : base(message, inner) { base.HResult = -2146233043; SetupException(location, handle); } protected AbandonedMutexException(SerializationInfo info, StreamingContext context) : base(info, context) { } private void SetupException(int location, WaitHandle handle) { _mutexIndex = location; _mutex = handle as Mutex; } } public enum ApartmentState { STA, MTA, Unknown } public sealed class AsyncLocal : IAsyncLocal { private readonly Action> m_valueChangedHandler; public T Value { [return: MaybeNull] get { object localValue = ExecutionContext.GetLocalValue(this); if (localValue != null) { return (T)localValue; } return default(T); } set { ExecutionContext.SetLocalValue(this, value, m_valueChangedHandler != null); } } public AsyncLocal() { } public AsyncLocal(Action>? valueChangedHandler) { m_valueChangedHandler = valueChangedHandler; } void IAsyncLocal.OnValueChanged(object previousValueObj, object currentValueObj, bool contextChanged) { T previousValue = ((previousValueObj == null) ? default(T) : ((T)previousValueObj)); T currentValue = ((currentValueObj == null) ? default(T) : ((T)currentValueObj)); m_valueChangedHandler(new AsyncLocalValueChangedArgs(previousValue, currentValue, contextChanged)); } } internal interface IAsyncLocal { void OnValueChanged(object previousValue, object currentValue, bool contextChanged); } public readonly struct AsyncLocalValueChangedArgs { public T? PreviousValue { get; } public T? CurrentValue { get; } public bool ThreadContextChanged { get; } internal AsyncLocalValueChangedArgs(T previousValue, T currentValue, bool contextChanged) { PreviousValue = previousValue; CurrentValue = currentValue; ThreadContextChanged = contextChanged; } } internal interface IAsyncLocalValueMap { bool TryGetValue(IAsyncLocal key, out object value); IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent); } internal static class AsyncLocalValueMap { private sealed class EmptyAsyncLocalValueMap : IAsyncLocalValueMap { public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent) { if (value == null && treatNullValueAsNonexistent) { return this; } return new OneElementAsyncLocalValueMap(key, value); } public bool TryGetValue(IAsyncLocal key, out object value) { value = null; return false; } } private sealed class OneElementAsyncLocalValueMap : IAsyncLocalValueMap { private readonly IAsyncLocal _key1; private readonly object _value1; public OneElementAsyncLocalValueMap(IAsyncLocal key, object value) { _key1 = key; _value1 = value; } public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent) { if (value != null || !treatNullValueAsNonexistent) { if (key != _key1) { return new TwoElementAsyncLocalValueMap(_key1, _value1, key, value); } return new OneElementAsyncLocalValueMap(key, value); } if (key != _key1) { return this; } return Empty; } public bool TryGetValue(IAsyncLocal key, out object value) { if (key == _key1) { value = _value1; return true; } value = null; return false; } } private sealed class TwoElementAsyncLocalValueMap : IAsyncLocalValueMap { private readonly IAsyncLocal _key1; private readonly IAsyncLocal _key2; private readonly object _value1; private readonly object _value2; public TwoElementAsyncLocalValueMap(IAsyncLocal key1, object value1, IAsyncLocal key2, object value2) { _key1 = key1; _value1 = value1; _key2 = key2; _value2 = value2; } public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent) { if (value != null || !treatNullValueAsNonexistent) { if (key != _key1) { if (key != _key2) { return new ThreeElementAsyncLocalValueMap(_key1, _value1, _key2, _value2, key, value); } return new TwoElementAsyncLocalValueMap(_key1, _value1, key, value); } return new TwoElementAsyncLocalValueMap(key, value, _key2, _value2); } if (key != _key1) { if (key != _key2) { return this; } return new OneElementAsyncLocalValueMap(_key1, _value1); } return new OneElementAsyncLocalValueMap(_key2, _value2); } public bool TryGetValue(IAsyncLocal key, out object value) { if (key == _key1) { value = _value1; return true; } if (key == _key2) { value = _value2; return true; } value = null; return false; } } private sealed class ThreeElementAsyncLocalValueMap : IAsyncLocalValueMap { private readonly IAsyncLocal _key1; private readonly IAsyncLocal _key2; private readonly IAsyncLocal _key3; private readonly object _value1; private readonly object _value2; private readonly object _value3; public ThreeElementAsyncLocalValueMap(IAsyncLocal key1, object value1, IAsyncLocal key2, object value2, IAsyncLocal key3, object value3) { _key1 = key1; _value1 = value1; _key2 = key2; _value2 = value2; _key3 = key3; _value3 = value3; } public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent) { if (value != null || !treatNullValueAsNonexistent) { if (key == _key1) { return new ThreeElementAsyncLocalValueMap(key, value, _key2, _value2, _key3, _value3); } if (key == _key2) { return new ThreeElementAsyncLocalValueMap(_key1, _value1, key, value, _key3, _value3); } if (key == _key3) { return new ThreeElementAsyncLocalValueMap(_key1, _value1, _key2, _value2, key, value); } MultiElementAsyncLocalValueMap multiElementAsyncLocalValueMap = new MultiElementAsyncLocalValueMap(4); multiElementAsyncLocalValueMap.UnsafeStore(0, _key1, _value1); multiElementAsyncLocalValueMap.UnsafeStore(1, _key2, _value2); multiElementAsyncLocalValueMap.UnsafeStore(2, _key3, _value3); multiElementAsyncLocalValueMap.UnsafeStore(3, key, value); return multiElementAsyncLocalValueMap; } if (key != _key1) { if (key != _key2) { if (key != _key3) { return this; } return new TwoElementAsyncLocalValueMap(_key1, _value1, _key2, _value2); } return new TwoElementAsyncLocalValueMap(_key1, _value1, _key3, _value3); } return new TwoElementAsyncLocalValueMap(_key2, _value2, _key3, _value3); } public bool TryGetValue(IAsyncLocal key, out object value) { if (key == _key1) { value = _value1; return true; } if (key == _key2) { value = _value2; return true; } if (key == _key3) { value = _value3; return true; } value = null; return false; } } private sealed class MultiElementAsyncLocalValueMap : IAsyncLocalValueMap { private readonly KeyValuePair[] _keyValues; internal MultiElementAsyncLocalValueMap(int count) { _keyValues = new KeyValuePair[count]; } internal void UnsafeStore(int index, IAsyncLocal key, object value) { _keyValues[index] = new KeyValuePair(key, value); } public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent) { for (int i = 0; i < _keyValues.Length; i++) { if (key == _keyValues[i].Key) { if (value != null || !treatNullValueAsNonexistent) { MultiElementAsyncLocalValueMap multiElementAsyncLocalValueMap = new MultiElementAsyncLocalValueMap(_keyValues.Length); Array.Copy(_keyValues, multiElementAsyncLocalValueMap._keyValues, _keyValues.Length); multiElementAsyncLocalValueMap._keyValues[i] = new KeyValuePair(key, value); return multiElementAsyncLocalValueMap; } if (_keyValues.Length == 4) { return i switch { 2 => new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[1].Key, _keyValues[1].Value, _keyValues[3].Key, _keyValues[3].Value), 1 => new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[2].Key, _keyValues[2].Value, _keyValues[3].Key, _keyValues[3].Value), 0 => new ThreeElementAsyncLocalValueMap(_keyValues[1].Key, _keyValues[1].Value, _keyValues[2].Key, _keyValues[2].Value, _keyValues[3].Key, _keyValues[3].Value), _ => new ThreeElementAsyncLocalValueMap(_keyValues[0].Key, _keyValues[0].Value, _keyValues[1].Key, _keyValues[1].Value, _keyValues[2].Key, _keyValues[2].Value), }; } MultiElementAsyncLocalValueMap multiElementAsyncLocalValueMap2 = new MultiElementAsyncLocalValueMap(_keyValues.Length - 1); if (i != 0) { Array.Copy(_keyValues, multiElementAsyncLocalValueMap2._keyValues, i); } if (i != _keyValues.Length - 1) { Array.Copy(_keyValues, i + 1, multiElementAsyncLocalValueMap2._keyValues, i, _keyValues.Length - i - 1); } return multiElementAsyncLocalValueMap2; } } if (value == null && treatNullValueAsNonexistent) { return this; } if (_keyValues.Length < 16) { MultiElementAsyncLocalValueMap multiElementAsyncLocalValueMap3 = new MultiElementAsyncLocalValueMap(_keyValues.Length + 1); Array.Copy(_keyValues, multiElementAsyncLocalValueMap3._keyValues, _keyValues.Length); multiElementAsyncLocalValueMap3._keyValues[_keyValues.Length] = new KeyValuePair(key, value); return multiElementAsyncLocalValueMap3; } ManyElementAsyncLocalValueMap manyElementAsyncLocalValueMap = new ManyElementAsyncLocalValueMap(17); KeyValuePair[] keyValues = _keyValues; for (int j = 0; j < keyValues.Length; j++) { KeyValuePair keyValuePair = keyValues[j]; manyElementAsyncLocalValueMap[keyValuePair.Key] = keyValuePair.Value; } manyElementAsyncLocalValueMap[key] = value; return manyElementAsyncLocalValueMap; } public bool TryGetValue(IAsyncLocal key, out object value) { KeyValuePair[] keyValues = _keyValues; for (int i = 0; i < keyValues.Length; i++) { KeyValuePair keyValuePair = keyValues[i]; if (key == keyValuePair.Key) { value = keyValuePair.Value; return true; } } value = null; return false; } } private sealed class ManyElementAsyncLocalValueMap : Dictionary, IAsyncLocalValueMap { public ManyElementAsyncLocalValueMap(int capacity) : base(capacity) { } public IAsyncLocalValueMap Set(IAsyncLocal key, object value, bool treatNullValueAsNonexistent) { int count = base.Count; bool flag = ContainsKey(key); if (value != null || !treatNullValueAsNonexistent) { ManyElementAsyncLocalValueMap manyElementAsyncLocalValueMap = new ManyElementAsyncLocalValueMap(count + ((!flag) ? 1 : 0)); using (Enumerator enumerator = GetEnumerator()) { while (enumerator.MoveNext()) { KeyValuePair current = enumerator.Current; manyElementAsyncLocalValueMap[current.Key] = current.Value; } } manyElementAsyncLocalValueMap[key] = value; return manyElementAsyncLocalValueMap; } if (flag) { if (count == 17) { MultiElementAsyncLocalValueMap multiElementAsyncLocalValueMap = new MultiElementAsyncLocalValueMap(16); int num = 0; using Enumerator enumerator2 = GetEnumerator(); while (enumerator2.MoveNext()) { KeyValuePair current2 = enumerator2.Current; if (key != current2.Key) { multiElementAsyncLocalValueMap.UnsafeStore(num++, current2.Key, current2.Value); } } return multiElementAsyncLocalValueMap; } ManyElementAsyncLocalValueMap manyElementAsyncLocalValueMap2 = new ManyElementAsyncLocalValueMap(count - 1); using Enumerator enumerator3 = GetEnumerator(); while (enumerator3.MoveNext()) { KeyValuePair current3 = enumerator3.Current; if (key != current3.Key) { manyElementAsyncLocalValueMap2[current3.Key] = current3.Value; } } return manyElementAsyncLocalValueMap2; } return this; } } public static IAsyncLocalValueMap Empty { get; } = new EmptyAsyncLocalValueMap(); public static bool IsEmpty(IAsyncLocalValueMap asyncLocalValueMap) { return asyncLocalValueMap == Empty; } public static IAsyncLocalValueMap Create(IAsyncLocal key, object value, bool treatNullValueAsNonexistent) { if (value == null && treatNullValueAsNonexistent) { return Empty; } return new OneElementAsyncLocalValueMap(key, value); } } public sealed class AutoResetEvent : EventWaitHandle { public AutoResetEvent(bool initialState) : base(initialState, EventResetMode.AutoReset) { } } [DebuggerDisplay("IsCancellationRequested = {IsCancellationRequested}")] public readonly struct CancellationToken { private readonly CancellationTokenSource _source; public static CancellationToken None => default(CancellationToken); public bool IsCancellationRequested { get { if (_source != null) { return _source.IsCancellationRequested; } return false; } } public bool CanBeCanceled => _source != null; public WaitHandle WaitHandle => (_source ?? CancellationTokenSource.s_neverCanceledSource).WaitHandle; internal CancellationToken(CancellationTokenSource source) { _source = source; } public CancellationToken(bool canceled) : this(canceled ? CancellationTokenSource.s_canceledSource : null) { } public CancellationTokenRegistration Register(Action callback) { return Register(callback, useSynchronizationContext: false); } public CancellationTokenRegistration Register(Action callback, bool useSynchronizationContext) { return Register((Action)delegate(object obj) { ((Action)obj)(); }, callback ?? throw new ArgumentNullException("callback"), useSynchronizationContext, useExecutionContext: true); } public CancellationTokenRegistration Register(Action callback, object? state) { return Register(callback, state, useSynchronizationContext: false, useExecutionContext: true); } public CancellationTokenRegistration Register(Action callback, object? state) { return Register(callback, state, useSynchronizationContext: false, useExecutionContext: true); } public CancellationTokenRegistration Register(Action callback, object? state, bool useSynchronizationContext) { return Register(callback, state, useSynchronizationContext, useExecutionContext: true); } public CancellationTokenRegistration UnsafeRegister(Action callback, object? state) { return Register(callback, state, useSynchronizationContext: false, useExecutionContext: false); } public CancellationTokenRegistration UnsafeRegister(Action callback, object? state) { return Register(callback, state, useSynchronizationContext: false, useExecutionContext: false); } private CancellationTokenRegistration Register(Delegate callback, object state, bool useSynchronizationContext, bool useExecutionContext) { if ((object)callback == null) { throw new ArgumentNullException("callback"); } return _source?.Register(callback, state, useSynchronizationContext ? SynchronizationContext.Current : null, useExecutionContext ? ExecutionContext.Capture() : null) ?? default(CancellationTokenRegistration); } public bool Equals(CancellationToken other) { return _source == other._source; } public override bool Equals([NotNullWhen(true)] object? other) { if (other is CancellationToken) { return Equals((CancellationToken)other); } return false; } public override int GetHashCode() { return (_source ?? CancellationTokenSource.s_neverCanceledSource).GetHashCode(); } public static bool operator ==(CancellationToken left, CancellationToken right) { return left.Equals(right); } public static bool operator !=(CancellationToken left, CancellationToken right) { return !left.Equals(right); } public void ThrowIfCancellationRequested() { if (IsCancellationRequested) { ThrowOperationCanceledException(); } } [DoesNotReturn] private void ThrowOperationCanceledException() { throw new OperationCanceledException(SR.OperationCanceled, this); } } public readonly struct CancellationTokenRegistration : IEquatable, IDisposable, IAsyncDisposable { private readonly long _id; private readonly CancellationTokenSource.CallbackNode _node; public CancellationToken Token { get { CancellationTokenSource.CallbackNode node = _node; if (node == null) { return default(CancellationToken); } return new CancellationToken(node.Registrations.Source); } } internal CancellationTokenRegistration(long id, CancellationTokenSource.CallbackNode node) { _id = id; _node = node; } public void Dispose() { CancellationTokenSource.CallbackNode node2 = _node; if (node2 != null && !node2.Registrations.Unregister(_id, node2)) { WaitForCallbackIfNecessary(_id, node2); } static void WaitForCallbackIfNecessary(long id, CancellationTokenSource.CallbackNode node) { CancellationTokenSource source = node.Registrations.Source; if (source.IsCancellationRequested && !source.IsCancellationCompleted && node.Registrations.ThreadIDExecutingCallbacks != Environment.CurrentManagedThreadId) { node.Registrations.WaitForCallbackToComplete(id); } } } public ValueTask DisposeAsync() { CancellationTokenSource.CallbackNode node2 = _node; if (node2 == null || node2.Registrations.Unregister(_id, node2)) { return default(ValueTask); } return WaitForCallbackIfNecessaryAsync(_id, node2); static ValueTask WaitForCallbackIfNecessaryAsync(long id, CancellationTokenSource.CallbackNode node) { CancellationTokenSource source = node.Registrations.Source; if (source.IsCancellationRequested && !source.IsCancellationCompleted && node.Registrations.ThreadIDExecutingCallbacks != Environment.CurrentManagedThreadId) { return node.Registrations.WaitForCallbackToCompleteAsync(id); } return default(ValueTask); } } public bool Unregister() { CancellationTokenSource.CallbackNode node = _node; return node?.Registrations.Unregister(_id, node) ?? false; } public static bool operator ==(CancellationTokenRegistration left, CancellationTokenRegistration right) { return left.Equals(right); } public static bool operator !=(CancellationTokenRegistration left, CancellationTokenRegistration right) { return !left.Equals(right); } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is CancellationTokenRegistration other) { return Equals(other); } return false; } public bool Equals(CancellationTokenRegistration other) { if (_node == other._node) { return _id == other._id; } return false; } public override int GetHashCode() { if (_node == null) { return _id.GetHashCode(); } return _node.GetHashCode() ^ _id.GetHashCode(); } } public class CancellationTokenSource : IDisposable { private sealed class Linked1CancellationTokenSource : CancellationTokenSource { private readonly CancellationTokenRegistration _reg1; internal Linked1CancellationTokenSource(CancellationToken token1) { _reg1 = token1.UnsafeRegister(LinkedNCancellationTokenSource.s_linkedTokenCancelDelegate, this); } protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _reg1.Dispose(); base.Dispose(disposing); } } } private sealed class Linked2CancellationTokenSource : CancellationTokenSource { private readonly CancellationTokenRegistration _reg1; private readonly CancellationTokenRegistration _reg2; internal Linked2CancellationTokenSource(CancellationToken token1, CancellationToken token2) { _reg1 = token1.UnsafeRegister(LinkedNCancellationTokenSource.s_linkedTokenCancelDelegate, this); _reg2 = token2.UnsafeRegister(LinkedNCancellationTokenSource.s_linkedTokenCancelDelegate, this); } protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _reg1.Dispose(); _reg2.Dispose(); base.Dispose(disposing); } } } private sealed class LinkedNCancellationTokenSource : CancellationTokenSource { internal static readonly Action s_linkedTokenCancelDelegate = delegate(object s) { ((CancellationTokenSource)s).NotifyCancellation(throwOnFirstException: false); }; private CancellationTokenRegistration[] _linkingRegistrations; internal LinkedNCancellationTokenSource(CancellationToken[] tokens) { _linkingRegistrations = new CancellationTokenRegistration[tokens.Length]; for (int i = 0; i < tokens.Length; i++) { if (tokens[i].CanBeCanceled) { _linkingRegistrations[i] = tokens[i].UnsafeRegister(s_linkedTokenCancelDelegate, this); } } } protected override void Dispose(bool disposing) { if (!disposing || _disposed) { return; } CancellationTokenRegistration[] linkingRegistrations = _linkingRegistrations; if (linkingRegistrations != null) { _linkingRegistrations = null; for (int i = 0; i < linkingRegistrations.Length; i++) { linkingRegistrations[i].Dispose(); } } base.Dispose(disposing); } } internal sealed class Registrations { public readonly CancellationTokenSource Source; public CallbackNode Callbacks; public CallbackNode FreeNodeList; public long NextAvailableId = 1L; public long ExecutingCallbackId; public volatile int ThreadIDExecutingCallbacks = -1; private int _lock; public Registrations(CancellationTokenSource source) { Source = source; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void Recycle(CallbackNode node) { node.Id = 0L; node.Callback = null; node.CallbackState = null; node.ExecutionContext = null; node.SynchronizationContext = null; node.Prev = null; node.Next = FreeNodeList; FreeNodeList = node; } public bool Unregister(long id, CallbackNode node) { if (id == 0L) { return false; } EnterLock(); try { if (node.Id != id) { return false; } if (Callbacks == node) { Callbacks = node.Next; } else { node.Prev.Next = node.Next; } if (node.Next != null) { node.Next.Prev = node.Prev; } Recycle(node); return true; } finally { ExitLock(); } } public void UnregisterAll() { EnterLock(); try { CallbackNode callbackNode = Callbacks; Callbacks = null; while (callbackNode != null) { CallbackNode next = callbackNode.Next; Recycle(callbackNode); callbackNode = next; } } finally { ExitLock(); } } public void WaitForCallbackToComplete(long id) { SpinWait spinWait = default(SpinWait); while (Volatile.Read(ref ExecutingCallbackId) == id) { spinWait.SpinOnce(); } } public ValueTask WaitForCallbackToCompleteAsync(long id) { if (Volatile.Read(ref ExecutingCallbackId) != id) { return default(ValueTask); } return new ValueTask(Task.Factory.StartNew((Func)async delegate(object s) { TupleSlim state = (TupleSlim)s; while (Volatile.Read(ref state.Item1.ExecutingCallbackId) == state.Item2) { await Task.Yield(); } }, (object?)new TupleSlim(this, id), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap()); } public void EnterLock() { ref int @lock = ref _lock; if (Interlocked.Exchange(ref @lock, 1) != 0) { Contention(ref @lock); } [MethodImpl(MethodImplOptions.NoInlining)] static void Contention(ref int value) { SpinWait spinWait = default(SpinWait); do { spinWait.SpinOnce(); } while (Interlocked.Exchange(ref value, 1) == 1); } } public void ExitLock() { Volatile.Write(ref _lock, 0); } } internal sealed class CallbackNode { public readonly Registrations Registrations; public CallbackNode Prev; public CallbackNode Next; public long Id; public Delegate Callback; public object CallbackState; public ExecutionContext ExecutionContext; public SynchronizationContext SynchronizationContext; public CallbackNode(Registrations registrations) { Registrations = registrations; } public void ExecuteCallback() { ExecutionContext executionContext = ExecutionContext; if (executionContext == null) { Invoke(Callback, CallbackState, Registrations.Source); return; } ExecutionContext.RunInternal(executionContext, delegate(object s) { CallbackNode callbackNode = (CallbackNode)s; Invoke(callbackNode.Callback, callbackNode.CallbackState, callbackNode.Registrations.Source); }, this); } } internal static readonly CancellationTokenSource s_canceledSource = new CancellationTokenSource { _state = 2 }; internal static readonly CancellationTokenSource s_neverCanceledSource = new CancellationTokenSource(); private static readonly TimerCallback s_timerCallback = TimerCallback; private volatile int _state; private bool _disposed; private volatile TimerQueueTimer _timer; private volatile ManualResetEvent _kernelEvent; private Registrations _registrations; public bool IsCancellationRequested => _state != 0; internal bool IsCancellationCompleted => _state == 2; public CancellationToken Token { get { ThrowIfDisposed(); return new CancellationToken(this); } } internal WaitHandle WaitHandle { get { ThrowIfDisposed(); if (_kernelEvent != null) { return _kernelEvent; } ManualResetEvent manualResetEvent = new ManualResetEvent(initialState: false); if (Interlocked.CompareExchange(ref _kernelEvent, manualResetEvent, null) != null) { manualResetEvent.Dispose(); } if (IsCancellationRequested) { _kernelEvent.Set(); } return _kernelEvent; } } private static void TimerCallback(object state) { ((CancellationTokenSource)state).NotifyCancellation(throwOnFirstException: false); } public CancellationTokenSource() { } public CancellationTokenSource(TimeSpan delay) { long num = (long)delay.TotalMilliseconds; if (num < -1 || num > 4294967294u) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.delay); } InitializeWithTimer((uint)num); } public CancellationTokenSource(int millisecondsDelay) { if (millisecondsDelay < -1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsDelay); } InitializeWithTimer((uint)millisecondsDelay); } private void InitializeWithTimer(uint millisecondsDelay) { if (millisecondsDelay == 0) { _state = 2; } else { _timer = new TimerQueueTimer(s_timerCallback, this, millisecondsDelay, uint.MaxValue, flowExecutionContext: false); } } public void Cancel() { Cancel(throwOnFirstException: false); } public void Cancel(bool throwOnFirstException) { ThrowIfDisposed(); NotifyCancellation(throwOnFirstException); } public void CancelAfter(TimeSpan delay) { long num = (long)delay.TotalMilliseconds; if (num < -1 || num > 4294967294u) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.delay); } CancelAfter((uint)num); } public void CancelAfter(int millisecondsDelay) { if (millisecondsDelay < -1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsDelay); } CancelAfter((uint)millisecondsDelay); } private void CancelAfter(uint millisecondsDelay) { ThrowIfDisposed(); if (IsCancellationRequested) { return; } TimerQueueTimer timerQueueTimer = _timer; if (timerQueueTimer == null) { timerQueueTimer = new TimerQueueTimer(s_timerCallback, this, uint.MaxValue, uint.MaxValue, flowExecutionContext: false); TimerQueueTimer timerQueueTimer2 = Interlocked.CompareExchange(ref _timer, timerQueueTimer, null); if (timerQueueTimer2 != null) { timerQueueTimer.Close(); timerQueueTimer = timerQueueTimer2; } } try { timerQueueTimer.Change(millisecondsDelay, uint.MaxValue); } catch (ObjectDisposedException) { } } public bool TryReset() { ThrowIfDisposed(); if (_state == 0) { bool flag = false; try { TimerQueueTimer timer = _timer; flag = timer == null || (timer.Change(uint.MaxValue, uint.MaxValue) && !timer._everQueued); } catch (ObjectDisposedException) { } if (flag) { Volatile.Read(ref _registrations)?.UnregisterAll(); return true; } } return false; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!disposing || _disposed) { return; } TimerQueueTimer timer = _timer; if (timer != null) { _timer = null; timer.Close(); } _registrations = null; if (_kernelEvent != null) { ManualResetEvent manualResetEvent = Interlocked.Exchange(ref _kernelEvent, null); if (manualResetEvent != null && _state != 1) { manualResetEvent.Dispose(); } } _disposed = true; } private void ThrowIfDisposed() { if (_disposed) { ThrowHelper.ThrowObjectDisposedException(ExceptionResource.CancellationTokenSource_Disposed); } } internal CancellationTokenRegistration Register(Delegate callback, object stateForCallback, SynchronizationContext syncContext, ExecutionContext executionContext) { if (!IsCancellationRequested) { if (_disposed) { return default(CancellationTokenRegistration); } Registrations registrations = Volatile.Read(ref _registrations); if (registrations == null) { registrations = new Registrations(this); registrations = Interlocked.CompareExchange(ref _registrations, registrations, null) ?? registrations; } CallbackNode callbackNode = null; long id = 0L; if (registrations.FreeNodeList != null) { registrations.EnterLock(); try { callbackNode = registrations.FreeNodeList; if (callbackNode != null) { registrations.FreeNodeList = callbackNode.Next; id = (callbackNode.Id = registrations.NextAvailableId++); callbackNode.Callback = callback; callbackNode.CallbackState = stateForCallback; callbackNode.ExecutionContext = executionContext; callbackNode.SynchronizationContext = syncContext; callbackNode.Next = registrations.Callbacks; registrations.Callbacks = callbackNode; if (callbackNode.Next != null) { callbackNode.Next.Prev = callbackNode; } } } finally { registrations.ExitLock(); } } if (callbackNode == null) { callbackNode = new CallbackNode(registrations); callbackNode.Callback = callback; callbackNode.CallbackState = stateForCallback; callbackNode.ExecutionContext = executionContext; callbackNode.SynchronizationContext = syncContext; registrations.EnterLock(); try { id = (callbackNode.Id = registrations.NextAvailableId++); callbackNode.Next = registrations.Callbacks; if (callbackNode.Next != null) { callbackNode.Next.Prev = callbackNode; } registrations.Callbacks = callbackNode; } finally { registrations.ExitLock(); } } if (!IsCancellationRequested || !registrations.Unregister(id, callbackNode)) { return new CancellationTokenRegistration(id, callbackNode); } } Invoke(callback, stateForCallback, this); return default(CancellationTokenRegistration); } private void NotifyCancellation(bool throwOnFirstException) { if (!IsCancellationRequested && Interlocked.CompareExchange(ref _state, 1, 0) == 0) { TimerQueueTimer timer = _timer; if (timer != null) { _timer = null; timer.Close(); } _kernelEvent?.Set(); ExecuteCallbackHandlers(throwOnFirstException); } } private void ExecuteCallbackHandlers(bool throwOnFirstException) { Registrations registrations = Interlocked.Exchange(ref _registrations, null); if (registrations == null) { Interlocked.Exchange(ref _state, 2); return; } registrations.ThreadIDExecutingCallbacks = Environment.CurrentManagedThreadId; List list = null; try { while (true) { registrations.EnterLock(); CallbackNode callbacks; try { callbacks = registrations.Callbacks; if (callbacks == null) { break; } if (callbacks.Next != null) { callbacks.Next.Prev = null; } registrations.Callbacks = callbacks.Next; registrations.ExecutingCallbackId = callbacks.Id; callbacks.Id = 0L; goto IL_0080; } finally { registrations.ExitLock(); } IL_0080: try { if (callbacks.SynchronizationContext != null) { callbacks.SynchronizationContext.Send(delegate(object s) { CallbackNode callbackNode = (CallbackNode)s; callbackNode.Registrations.ThreadIDExecutingCallbacks = Environment.CurrentManagedThreadId; callbackNode.ExecuteCallback(); }, callbacks); registrations.ThreadIDExecutingCallbacks = Environment.CurrentManagedThreadId; } else { callbacks.ExecuteCallback(); } } catch (Exception item) when (!throwOnFirstException) { (list ?? (list = new List())).Add(item); } } } finally { _state = 2; Interlocked.Exchange(ref registrations.ExecutingCallbackId, 0L); } if (list == null) { return; } throw new AggregateException(list); } public static CancellationTokenSource CreateLinkedTokenSource(CancellationToken token1, CancellationToken token2) { if (token1.CanBeCanceled) { if (!token2.CanBeCanceled) { return new Linked1CancellationTokenSource(token1); } return new Linked2CancellationTokenSource(token1, token2); } return CreateLinkedTokenSource(token2); } public static CancellationTokenSource CreateLinkedTokenSource(CancellationToken token) { if (!token.CanBeCanceled) { return new CancellationTokenSource(); } return new Linked1CancellationTokenSource(token); } public static CancellationTokenSource CreateLinkedTokenSource(params CancellationToken[] tokens) { if (tokens == null) { throw new ArgumentNullException("tokens"); } return tokens.Length switch { 0 => throw new ArgumentException(SR.CancellationToken_CreateLinkedToken_TokensIsEmpty), 1 => CreateLinkedTokenSource(tokens[0]), 2 => CreateLinkedTokenSource(tokens[0], tokens[1]), _ => new LinkedNCancellationTokenSource(tokens), }; } private static void Invoke(Delegate d, object state, CancellationTokenSource source) { if (d is Action action) { action(state); } else { ((Action)d)(state, new CancellationToken(source)); } } } public sealed class CompressedStack : ISerializable { private CompressedStack() { } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public static CompressedStack Capture() { return GetCompressedStack(); } public CompressedStack CreateCopy() { return this; } public static CompressedStack GetCompressedStack() { return new CompressedStack(); } public static void Run(CompressedStack compressedStack, ContextCallback callback, object? state) { if (compressedStack == null) { throw new ArgumentNullException("compressedStack"); } callback(state); } } internal enum StackCrawlMark { LookForMe, LookForMyCaller, LookForMyCallersCaller, LookForThread } internal interface IDeferredDisposable { void OnFinalRelease(bool disposed); } internal struct DeferredDisposableLifetime where T : class, IDeferredDisposable { private int _count; public bool AddRef() { int num; int value; do { num = Volatile.Read(ref _count); if (num < 0) { throw new ObjectDisposedException(typeof(T).ToString()); } value = checked(num + 1); } while (Interlocked.CompareExchange(ref _count, value, num) != num); return true; } public void Release(T obj) { int num3; while (true) { int num = Volatile.Read(ref _count); if (num > 0) { int num2 = num - 1; if (Interlocked.CompareExchange(ref _count, num2, num) == num) { if (num2 == 0) { obj.OnFinalRelease(disposed: false); } return; } } else { num3 = num + 1; if (Interlocked.CompareExchange(ref _count, num3, num) == num) { break; } } } if (num3 == -1) { obj.OnFinalRelease(disposed: true); } } public void Dispose(T obj) { int num; int num2; do { num = Volatile.Read(ref _count); if (num < 0) { return; } num2 = -1 - num; } while (Interlocked.CompareExchange(ref _count, num2, num) != num); if (num2 == -1) { obj.OnFinalRelease(disposed: true); } } } public enum EventResetMode { AutoReset, ManualReset } public class EventWaitHandle : WaitHandle { public EventWaitHandle(bool initialState, EventResetMode mode) : this(initialState, mode, null, out var _) { } public EventWaitHandle(bool initialState, EventResetMode mode, string? name) : this(initialState, mode, name, out var _) { } public EventWaitHandle(bool initialState, EventResetMode mode, string? name, out bool createdNew) { if (mode != 0 && mode != EventResetMode.ManualReset) { throw new ArgumentException(SR.Argument_InvalidFlag, "mode"); } CreateEventCore(initialState, mode, name, out createdNew); } [SupportedOSPlatform("windows")] public static EventWaitHandle OpenExisting(string name) { EventWaitHandle result; return OpenExistingWorker(name, out result) switch { OpenExistingResult.NameNotFound => throw new WaitHandleCannotBeOpenedException(), OpenExistingResult.NameInvalid => throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)), OpenExistingResult.PathNotFound => throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, name)), _ => result, }; } [SupportedOSPlatform("windows")] public static bool TryOpenExisting(string name, [NotNullWhen(true)] out EventWaitHandle? result) { return OpenExistingWorker(name, out result) == OpenExistingResult.Success; } private EventWaitHandle(SafeWaitHandle handle) { base.SafeWaitHandle = handle; } private void CreateEventCore(bool initialState, EventResetMode mode, string name, out bool createdNew) { uint num = (initialState ? 2u : 0u); if (mode == EventResetMode.ManualReset) { num |= 1u; } SafeWaitHandle safeWaitHandle = Interop.Kernel32.CreateEventEx(IntPtr.Zero, name, num, 34603010u); int lastPInvokeError = Marshal.GetLastPInvokeError(); if (safeWaitHandle.IsInvalid) { safeWaitHandle.SetHandleAsInvalid(); if (!string.IsNullOrEmpty(name) && lastPInvokeError == 6) { throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); } throw Win32Marshal.GetExceptionForWin32Error(lastPInvokeError, name); } createdNew = lastPInvokeError != 183; base.SafeWaitHandle = safeWaitHandle; } private static OpenExistingResult OpenExistingWorker(string name, out EventWaitHandle result) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "name"); } result = null; SafeWaitHandle safeWaitHandle = Interop.Kernel32.OpenEvent(34603010u, inheritHandle: false, name); if (safeWaitHandle.IsInvalid) { int lastPInvokeError = Marshal.GetLastPInvokeError(); switch (lastPInvokeError) { case 2: case 123: return OpenExistingResult.NameNotFound; case 3: return OpenExistingResult.PathNotFound; case 6: return OpenExistingResult.NameInvalid; default: throw Win32Marshal.GetExceptionForWin32Error(lastPInvokeError, name); } } result = new EventWaitHandle(safeWaitHandle); return OpenExistingResult.Success; } public bool Reset() { bool flag = Interop.Kernel32.ResetEvent(base.SafeWaitHandle); if (!flag) { throw Win32Marshal.GetExceptionForLastWin32Error(); } return flag; } public bool Set() { bool flag = Interop.Kernel32.SetEvent(base.SafeWaitHandle); if (!flag) { throw Win32Marshal.GetExceptionForLastWin32Error(); } return flag; } internal static bool Set(SafeWaitHandle waitHandle) { return Interop.Kernel32.SetEvent(waitHandle); } } public delegate void ContextCallback(object? state); public sealed class ExecutionContext : IDisposable, ISerializable { internal static readonly ExecutionContext Default = new ExecutionContext(); private static volatile ExecutionContext s_defaultFlowSuppressed; private readonly IAsyncLocalValueMap m_localValues; private readonly IAsyncLocal[] m_localChangeNotifications; private readonly bool m_isFlowSuppressed; private readonly bool m_isDefault; internal bool HasChangeNotifications => m_localChangeNotifications != null; internal bool IsDefault => m_isDefault; private ExecutionContext() { m_isDefault = true; } private ExecutionContext(IAsyncLocalValueMap localValues, IAsyncLocal[] localChangeNotifications, bool isFlowSuppressed) { m_localValues = localValues; m_localChangeNotifications = localChangeNotifications; m_isFlowSuppressed = isFlowSuppressed; } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public static ExecutionContext? Capture() { ExecutionContext executionContext = Thread.CurrentThread._executionContext; if (executionContext == null) { executionContext = Default; } else if (executionContext.m_isFlowSuppressed) { executionContext = null; } return executionContext; } internal static ExecutionContext CaptureForRestore() { return Thread.CurrentThread._executionContext; } private ExecutionContext ShallowClone(bool isFlowSuppressed) { if (m_localValues == null || AsyncLocalValueMap.IsEmpty(m_localValues)) { if (!isFlowSuppressed) { return null; } return s_defaultFlowSuppressed ?? (s_defaultFlowSuppressed = new ExecutionContext(AsyncLocalValueMap.Empty, new IAsyncLocal[0], isFlowSuppressed: true)); } return new ExecutionContext(m_localValues, m_localChangeNotifications, isFlowSuppressed); } public static AsyncFlowControl SuppressFlow() { Thread currentThread = Thread.CurrentThread; ExecutionContext executionContext = currentThread._executionContext ?? Default; if (executionContext.m_isFlowSuppressed) { throw new InvalidOperationException(SR.InvalidOperation_CannotSupressFlowMultipleTimes); } executionContext = executionContext.ShallowClone(isFlowSuppressed: true); AsyncFlowControl result = default(AsyncFlowControl); currentThread._executionContext = executionContext; result.Initialize(currentThread); return result; } public static void RestoreFlow() { Thread currentThread = Thread.CurrentThread; ExecutionContext executionContext = currentThread._executionContext; if (executionContext == null || !executionContext.m_isFlowSuppressed) { throw new InvalidOperationException(SR.InvalidOperation_CannotRestoreUnsupressedFlow); } currentThread._executionContext = executionContext.ShallowClone(isFlowSuppressed: false); } public static bool IsFlowSuppressed() { return Thread.CurrentThread._executionContext?.m_isFlowSuppressed ?? false; } public static void Run(ExecutionContext executionContext, ContextCallback callback, object? state) { if (executionContext == null) { ThrowNullContext(); } RunInternal(executionContext, callback, state); } internal static void RunInternal(ExecutionContext executionContext, ContextCallback callback, object state) { Thread currentThread = Thread.CurrentThread; ExecutionContext executionContext2 = currentThread._executionContext; if (executionContext2 != null && executionContext2.m_isDefault) { executionContext2 = null; } ExecutionContext executionContext3 = executionContext2; SynchronizationContext synchronizationContext = currentThread._synchronizationContext; if (executionContext != null && executionContext.m_isDefault) { executionContext = null; } if (executionContext3 != executionContext) { RestoreChangedContextToThread(currentThread, executionContext, executionContext3); } ExceptionDispatchInfo exceptionDispatchInfo = null; try { callback(state); } catch (Exception source) { exceptionDispatchInfo = ExceptionDispatchInfo.Capture(source); } if (currentThread._synchronizationContext != synchronizationContext) { currentThread._synchronizationContext = synchronizationContext; } ExecutionContext executionContext4 = currentThread._executionContext; if (executionContext4 != executionContext3) { RestoreChangedContextToThread(currentThread, executionContext3, executionContext4); } exceptionDispatchInfo?.Throw(); } public static void Restore(ExecutionContext executionContext) { if (executionContext == null) { ThrowNullContext(); } RestoreInternal(executionContext); } internal static void RestoreInternal(ExecutionContext executionContext) { Thread currentThread = Thread.CurrentThread; ExecutionContext executionContext2 = currentThread._executionContext; if (executionContext2 != null && executionContext2.m_isDefault) { executionContext2 = null; } if (executionContext != null && executionContext.m_isDefault) { executionContext = null; } if (executionContext2 != executionContext) { RestoreChangedContextToThread(currentThread, executionContext, executionContext2); } } internal static void RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, object state) { if (executionContext != null && !executionContext.m_isDefault) { RestoreChangedContextToThread(threadPoolThread, executionContext, null); } ExceptionDispatchInfo exceptionDispatchInfo = null; try { callback(state); } catch (Exception source) { exceptionDispatchInfo = ExceptionDispatchInfo.Capture(source); } ExecutionContext executionContext2 = threadPoolThread._executionContext; threadPoolThread._synchronizationContext = null; if (executionContext2 != null) { RestoreChangedContextToThread(threadPoolThread, null, executionContext2); } exceptionDispatchInfo?.Throw(); } internal static void RunForThreadPoolUnsafe(ExecutionContext executionContext, Action callback, in TState state) { Thread.CurrentThread._executionContext = executionContext; if (executionContext.HasChangeNotifications) { OnValuesChanged(null, executionContext); } callback(state); } internal static void RestoreChangedContextToThread(Thread currentThread, ExecutionContext contextToRestore, ExecutionContext currentContext) { currentThread._executionContext = contextToRestore; if ((currentContext != null && currentContext.HasChangeNotifications) || (contextToRestore != null && contextToRestore.HasChangeNotifications)) { OnValuesChanged(currentContext, contextToRestore); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void ResetThreadPoolThread(Thread currentThread) { ExecutionContext executionContext = currentThread._executionContext; currentThread._synchronizationContext = null; currentThread._executionContext = null; if (executionContext != null && executionContext.HasChangeNotifications) { OnValuesChanged(executionContext, null); currentThread._synchronizationContext = null; currentThread._executionContext = null; } } internal static void OnValuesChanged(ExecutionContext previousExecutionCtx, ExecutionContext nextExecutionCtx) { IAsyncLocal[] array = previousExecutionCtx?.m_localChangeNotifications; IAsyncLocal[] array2 = nextExecutionCtx?.m_localChangeNotifications; try { if (array != null && array2 != null) { IAsyncLocal[] array3 = array; foreach (IAsyncLocal asyncLocal in array3) { previousExecutionCtx.m_localValues.TryGetValue(asyncLocal, out var value); nextExecutionCtx.m_localValues.TryGetValue(asyncLocal, out var value2); if (value != value2) { asyncLocal.OnValueChanged(value, value2, contextChanged: true); } } if (array2 == array) { return; } IAsyncLocal[] array4 = array2; foreach (IAsyncLocal asyncLocal2 in array4) { if (!previousExecutionCtx.m_localValues.TryGetValue(asyncLocal2, out var value3)) { nextExecutionCtx.m_localValues.TryGetValue(asyncLocal2, out var value4); if (value3 != value4) { asyncLocal2.OnValueChanged(value3, value4, contextChanged: true); } } } return; } if (array != null) { IAsyncLocal[] array5 = array; foreach (IAsyncLocal asyncLocal3 in array5) { previousExecutionCtx.m_localValues.TryGetValue(asyncLocal3, out var value5); if (value5 != null) { asyncLocal3.OnValueChanged(value5, null, contextChanged: true); } } return; } IAsyncLocal[] array6 = array2; foreach (IAsyncLocal asyncLocal4 in array6) { nextExecutionCtx.m_localValues.TryGetValue(asyncLocal4, out var value6); if (value6 != null) { asyncLocal4.OnValueChanged(null, value6, contextChanged: true); } } } catch (Exception exception) { Environment.FailFast(SR.ExecutionContext_ExceptionInAsyncLocalNotification, exception); } } [DoesNotReturn] [StackTraceHidden] private static void ThrowNullContext() { throw new InvalidOperationException(SR.InvalidOperation_NullContext); } internal static object GetLocalValue(IAsyncLocal local) { ExecutionContext executionContext = Thread.CurrentThread._executionContext; if (executionContext == null) { return null; } executionContext.m_localValues.TryGetValue(local, out var value); return value; } internal static void SetLocalValue(IAsyncLocal local, object newValue, bool needChangeNotifications) { ExecutionContext executionContext = Thread.CurrentThread._executionContext; object value = null; bool flag = false; if (executionContext != null) { flag = executionContext.m_localValues.TryGetValue(local, out value); } if (value == newValue) { return; } IAsyncLocal[] array = null; bool flag2 = false; IAsyncLocalValueMap asyncLocalValueMap; if (executionContext != null) { flag2 = executionContext.m_isFlowSuppressed; asyncLocalValueMap = executionContext.m_localValues.Set(local, newValue, !needChangeNotifications); array = executionContext.m_localChangeNotifications; } else { asyncLocalValueMap = AsyncLocalValueMap.Create(local, newValue, !needChangeNotifications); } if (needChangeNotifications && !flag) { if (array == null) { array = new IAsyncLocal[1] { local }; } else { int num = array.Length; Array.Resize(ref array, num + 1); array[num] = local; } } Thread.CurrentThread._executionContext = ((!flag2 && AsyncLocalValueMap.IsEmpty(asyncLocalValueMap)) ? null : new ExecutionContext(asyncLocalValueMap, array, flag2)); if (needChangeNotifications) { local.OnValueChanged(value, newValue, contextChanged: false); } } public ExecutionContext CreateCopy() { return this; } public void Dispose() { } } public struct AsyncFlowControl : IEquatable, IDisposable { private Thread _thread; internal void Initialize(Thread currentThread) { _thread = currentThread; } public void Undo() { if (_thread == null) { throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCMultiple); } if (Thread.CurrentThread != _thread) { throw new InvalidOperationException(SR.InvalidOperation_CannotUseAFCOtherThread); } if (!ExecutionContext.IsFlowSuppressed()) { throw new InvalidOperationException(SR.InvalidOperation_AsyncFlowCtrlCtxMismatch); } _thread = null; ExecutionContext.RestoreFlow(); } public void Dispose() { Undo(); } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is AsyncFlowControl obj2) { return Equals(obj2); } return false; } public bool Equals(AsyncFlowControl obj) { return _thread == obj._thread; } public override int GetHashCode() { return _thread?.GetHashCode() ?? 0; } public static bool operator ==(AsyncFlowControl a, AsyncFlowControl b) { return a.Equals(b); } public static bool operator !=(AsyncFlowControl a, AsyncFlowControl b) { return !(a == b); } } [CLSCompliant(false)] public unsafe delegate void IOCompletionCallback(uint errorCode, uint numBytes, NativeOverlapped* pOVERLAP); public interface IThreadPoolWorkItem { void Execute(); } public static class LazyInitializer { public static T EnsureInitialized<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] T>([NotNull] ref T? target) where T : class { return Volatile.Read(ref target) ?? EnsureInitializedCore(ref target); } private static T EnsureInitializedCore<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] T>([NotNull] ref T target) where T : class { try { Interlocked.CompareExchange(ref target, Activator.CreateInstance(), null); } catch (MissingMethodException) { throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT); } return target; } public static T EnsureInitialized([NotNull] ref T? target, Func valueFactory) where T : class { return Volatile.Read(ref target) ?? EnsureInitializedCore(ref target, valueFactory); } private static T EnsureInitializedCore([NotNull] ref T target, Func valueFactory) where T : class { T val = valueFactory(); if (val == null) { throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation); } Interlocked.CompareExchange(ref target, val, null); return target; } public static T EnsureInitialized<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] T>([AllowNull] ref T target, ref bool initialized, [NotNullIfNotNull("syncLock")] ref object? syncLock) { if (Volatile.Read(ref initialized)) { return target; } return EnsureInitializedCore(ref target, ref initialized, ref syncLock); } private static T EnsureInitializedCore<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] T>([AllowNull] ref T target, ref bool initialized, [NotNull] ref object syncLock) { lock (EnsureLockInitialized(ref syncLock)) { if (!Volatile.Read(ref initialized)) { try { target = Activator.CreateInstance(); } catch (MissingMethodException) { throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT); } Volatile.Write(ref initialized, value: true); } } return target; } public static T EnsureInitialized([AllowNull] ref T target, ref bool initialized, [NotNullIfNotNull("syncLock")] ref object? syncLock, Func valueFactory) { if (Volatile.Read(ref initialized)) { return target; } return EnsureInitializedCore(ref target, ref initialized, ref syncLock, valueFactory); } private static T EnsureInitializedCore([AllowNull] ref T target, ref bool initialized, [NotNull] ref object syncLock, Func valueFactory) { lock (EnsureLockInitialized(ref syncLock)) { if (!Volatile.Read(ref initialized)) { target = valueFactory(); Volatile.Write(ref initialized, value: true); } } return target; } public static T EnsureInitialized([NotNull] ref T? target, [NotNullIfNotNull("syncLock")] ref object? syncLock, Func valueFactory) where T : class { return Volatile.Read(ref target) ?? EnsureInitializedCore(ref target, ref syncLock, valueFactory); } private static T EnsureInitializedCore([NotNull] ref T target, [NotNull] ref object syncLock, Func valueFactory) where T : class { lock (EnsureLockInitialized(ref syncLock)) { if (Volatile.Read(ref target) == null) { Volatile.Write(ref target, valueFactory()); if (target == null) { throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation); } } } return target; } private static object EnsureLockInitialized([NotNull] ref object syncLock) { return syncLock ?? Interlocked.CompareExchange(ref syncLock, new object(), null) ?? syncLock; } } public enum LazyThreadSafetyMode { None, PublicationOnly, ExecutionAndPublication } [Serializable] [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class LockRecursionException : Exception { public LockRecursionException() { } public LockRecursionException(string? message) : base(message) { } public LockRecursionException(string? message, Exception? innerException) : base(message, innerException) { } protected LockRecursionException(SerializationInfo info, StreamingContext context) : base(info, context) { } } internal sealed class LowLevelLock : IDisposable { private int _state; private bool _isAnyWaitingThreadSignaled; private LowLevelSpinWaiter _spinWaiter; private readonly Func _spinWaitTryAcquireCallback; private LowLevelMonitor _monitor; public LowLevelLock() { _spinWaiter = default(LowLevelSpinWaiter); _spinWaitTryAcquireCallback = SpinWaitTryAcquireCallback; _monitor.Initialize(); } ~LowLevelLock() { Dispose(); } public void Dispose() { _monitor.Dispose(); GC.SuppressFinalize(this); } public bool TryAcquire() { int num = Interlocked.CompareExchange(ref _state, 1, 0); if (num == 0 || TryAcquire_NoFastPath(num)) { return true; } return false; } private bool TryAcquire_NoFastPath(int state) { if ((state & 1) == 0) { return Interlocked.CompareExchange(ref _state, state + 1, state) == state; } return false; } private bool SpinWaitTryAcquireCallback() { return TryAcquire_NoFastPath(_state); } public void Acquire() { if (!TryAcquire()) { WaitAndAcquire(); } } private void WaitAndAcquire() { if (!_spinWaiter.SpinWaitForCondition(_spinWaitTryAcquireCallback, 8, 4)) { _monitor.Acquire(); int num = Interlocked.Add(ref _state, 2); while (((uint)num & (true ? 1u : 0u)) != 0 || Interlocked.CompareExchange(ref _state, num + -1, num) != num) { _monitor.Wait(); _isAnyWaitingThreadSignaled = false; num = _state; } _monitor.Release(); } } public void Release() { if (Interlocked.Decrement(ref _state) != 0) { SignalWaiter(); } } private void SignalWaiter() { _monitor.Acquire(); if ((uint)_state >= 2u && !_isAnyWaitingThreadSignaled) { _isAnyWaitingThreadSignaled = true; _monitor.Signal_Release(); } else { _monitor.Release(); } } } internal struct LowLevelSpinWaiter { private int _spinningThreadCount; public bool SpinWaitForCondition(Func condition, int spinCount, int sleep0Threshold) { int processorCount = Environment.ProcessorCount; int num = Interlocked.Increment(ref _spinningThreadCount); try { if (num <= processorCount) { for (int i = ((processorCount <= 1) ? sleep0Threshold : 0); i < spinCount; i++) { Wait(i, sleep0Threshold, processorCount); if (condition()) { return true; } } } } finally { Interlocked.Decrement(ref _spinningThreadCount); } return false; } public static void Wait(int spinIndex, int sleep0Threshold, int processorCount) { if (processorCount > 1 && (spinIndex < sleep0Threshold || (spinIndex - sleep0Threshold) % 2 != 0)) { int num = Thread.OptimalMaxSpinWaitsPerSpinIteration; if (spinIndex <= 30 && 1 << spinIndex < num) { num = 1 << spinIndex; } Thread.SpinWait(num); } else { Thread.UninterruptibleSleep0(); } } } [StructLayout(LayoutKind.Auto)] internal struct LowLevelMonitor { internal struct Monitor { public Interop.Kernel32.CRITICAL_SECTION _criticalSection; public Interop.Kernel32.CONDITION_VARIABLE _conditionVariable; } private unsafe Monitor* _pMonitor; public void Dispose() { DisposeCore(); } public void Acquire() { AcquireCore(); } public void Release() { ReleaseCore(); } public void Wait() { WaitCore(); } public void Signal_Release() { Signal_ReleaseCore(); } public unsafe void Initialize() { _pMonitor = (Monitor*)(void*)Marshal.AllocHGlobal(sizeof(Monitor)); Interop.Kernel32.InitializeCriticalSection(&_pMonitor->_criticalSection); Interop.Kernel32.InitializeConditionVariable(&_pMonitor->_conditionVariable); } private unsafe void DisposeCore() { if (_pMonitor != null) { Interop.Kernel32.DeleteCriticalSection(&_pMonitor->_criticalSection); Marshal.FreeHGlobal((IntPtr)_pMonitor); _pMonitor = null; } } private unsafe void AcquireCore() { Interop.Kernel32.EnterCriticalSection(&_pMonitor->_criticalSection); } private unsafe void ReleaseCore() { Interop.Kernel32.LeaveCriticalSection(&_pMonitor->_criticalSection); } private void WaitCore() { WaitCore(-1); } private unsafe bool WaitCore(int timeoutMilliseconds) { return Interop.Kernel32.SleepConditionVariableCS(&_pMonitor->_conditionVariable, &_pMonitor->_criticalSection, timeoutMilliseconds); } private unsafe void Signal_ReleaseCore() { Interop.Kernel32.WakeConditionVariable(&_pMonitor->_conditionVariable); Interop.Kernel32.LeaveCriticalSection(&_pMonitor->_criticalSection); } } public sealed class ManualResetEvent : EventWaitHandle { public ManualResetEvent(bool initialState) : base(initialState, EventResetMode.ManualReset) { } } [DebuggerDisplay("Set = {IsSet}")] public class ManualResetEventSlim : IDisposable { private volatile object m_lock; private volatile ManualResetEvent m_eventObj; private volatile int m_combinedState; private static readonly Action s_cancellationTokenCallback = CancellationTokenCallback; public WaitHandle WaitHandle { get { ThrowIfDisposed(); if (m_eventObj == null) { LazyInitializeEvent(); } return m_eventObj; } } public bool IsSet { get { return ExtractStatePortion(m_combinedState, int.MinValue) != 0; } private set { UpdateStateAtomically((value ? 1 : 0) << 31, int.MinValue); } } public int SpinCount { get { return ExtractStatePortionAndShiftRight(m_combinedState, 1073217536, 19); } private set { m_combinedState = (m_combinedState & -1073217537) | (value << 19); } } private int Waiters { get { return ExtractStatePortionAndShiftRight(m_combinedState, 524287, 0); } set { if (value >= 524287) { throw new InvalidOperationException(SR.Format(SR.ManualResetEventSlim_ctor_TooManyWaiters, 524287)); } UpdateStateAtomically(value, 524287); } } public ManualResetEventSlim() : this(initialState: false) { } public ManualResetEventSlim(bool initialState) { Initialize(initialState, SpinWait.SpinCountforSpinBeforeWait); } public ManualResetEventSlim(bool initialState, int spinCount) { if (spinCount < 0) { throw new ArgumentOutOfRangeException("spinCount"); } if (spinCount > 2047) { throw new ArgumentOutOfRangeException("spinCount", SR.Format(SR.ManualResetEventSlim_ctor_SpinCountOutOfRange, 2047)); } Initialize(initialState, spinCount); } private void Initialize(bool initialState, int spinCount) { m_combinedState = (initialState ? int.MinValue : 0); SpinCount = (Environment.IsSingleProcessor ? 1 : spinCount); } private void EnsureLockObjectCreated() { if (m_lock == null) { object value = new object(); Interlocked.CompareExchange(ref m_lock, value, null); } } private void LazyInitializeEvent() { bool isSet = IsSet; ManualResetEvent manualResetEvent = new ManualResetEvent(isSet); if (Interlocked.CompareExchange(ref m_eventObj, manualResetEvent, null) != null) { manualResetEvent.Dispose(); return; } bool isSet2 = IsSet; if (isSet2 == isSet) { return; } lock (manualResetEvent) { if (m_eventObj == manualResetEvent) { manualResetEvent.Set(); } } } public void Set() { Set(duringCancellation: false); } private void Set(bool duringCancellation) { IsSet = true; if (Waiters > 0) { lock (m_lock) { Monitor.PulseAll(m_lock); } } ManualResetEvent eventObj = m_eventObj; if (eventObj == null || duringCancellation) { return; } lock (eventObj) { if (m_eventObj != null) { m_eventObj.Set(); } } } public void Reset() { ThrowIfDisposed(); if (m_eventObj != null) { m_eventObj.Reset(); } IsSet = false; } [UnsupportedOSPlatform("browser")] public void Wait() { Wait(-1, CancellationToken.None); } [UnsupportedOSPlatform("browser")] public void Wait(CancellationToken cancellationToken) { Wait(-1, cancellationToken); } [UnsupportedOSPlatform("browser")] public bool Wait(TimeSpan timeout) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout"); } return Wait((int)num, CancellationToken.None); } [UnsupportedOSPlatform("browser")] public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout"); } return Wait((int)num, cancellationToken); } [UnsupportedOSPlatform("browser")] public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, CancellationToken.None); } [UnsupportedOSPlatform("browser")] public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout"); } if (!IsSet) { if (millisecondsTimeout == 0) { return false; } uint startTime = 0u; bool flag = false; int num = millisecondsTimeout; if (millisecondsTimeout != -1) { startTime = TimeoutHelper.GetTime(); flag = true; } int spinCount = SpinCount; SpinWait spinWait = default(SpinWait); while (spinWait.Count < spinCount) { spinWait.SpinOnce(-1); if (IsSet) { return true; } if (spinWait.Count >= 100 && spinWait.Count % 10 == 0) { cancellationToken.ThrowIfCancellationRequested(); } } EnsureLockObjectCreated(); using (cancellationToken.UnsafeRegister(s_cancellationTokenCallback, this)) { lock (m_lock) { while (!IsSet) { cancellationToken.ThrowIfCancellationRequested(); if (flag) { num = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout); if (num <= 0) { return false; } } Waiters++; if (IsSet) { Waiters--; return true; } try { if (!Monitor.Wait(m_lock, num)) { return false; } } finally { Waiters--; } } } } } return true; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (((uint)m_combinedState & 0x40000000u) != 0) { return; } m_combinedState |= 1073741824; if (!disposing) { return; } ManualResetEvent eventObj = m_eventObj; if (eventObj == null) { return; } lock (eventObj) { eventObj.Dispose(); m_eventObj = null; } } private void ThrowIfDisposed() { if (((uint)m_combinedState & 0x40000000u) != 0) { throw new ObjectDisposedException(SR.ManualResetEventSlim_Disposed); } } private static void CancellationTokenCallback(object obj) { ManualResetEventSlim manualResetEventSlim = (ManualResetEventSlim)obj; lock (manualResetEventSlim.m_lock) { Monitor.PulseAll(manualResetEventSlim.m_lock); } } private void UpdateStateAtomically(int newBits, int updateBitsMask) { SpinWait spinWait = default(SpinWait); while (true) { int combinedState = m_combinedState; int value = (combinedState & ~updateBitsMask) | newBits; if (Interlocked.CompareExchange(ref m_combinedState, value, combinedState) == combinedState) { break; } spinWait.SpinOnce(-1); } } private static int ExtractStatePortionAndShiftRight(int state, int mask, int rightBitShiftCount) { return (state & mask) >>> rightBitShiftCount; } private static int ExtractStatePortion(int state, int mask) { return state & mask; } } public sealed class Mutex : WaitHandle { public Mutex(bool initiallyOwned, string? name, out bool createdNew) { CreateMutexCore(initiallyOwned, name, out createdNew); } public Mutex(bool initiallyOwned, string? name) { CreateMutexCore(initiallyOwned, name, out var _); } public Mutex(bool initiallyOwned) { CreateMutexCore(initiallyOwned, null, out var _); } public Mutex() { CreateMutexCore(initiallyOwned: false, null, out var _); } private Mutex(SafeWaitHandle handle) { base.SafeWaitHandle = handle; } public static Mutex OpenExisting(string name) { Mutex result; return OpenExistingWorker(name, out result) switch { OpenExistingResult.NameNotFound => throw new WaitHandleCannotBeOpenedException(), OpenExistingResult.NameInvalid => throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)), OpenExistingResult.PathNotFound => throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, name)), _ => result, }; } public static bool TryOpenExisting(string name, [NotNullWhen(true)] out Mutex? result) { return OpenExistingWorker(name, out result) == OpenExistingResult.Success; } private void CreateMutexCore(bool initiallyOwned, string name, out bool createdNew) { uint flags = (initiallyOwned ? 1u : 0u); SafeWaitHandle safeWaitHandle = Interop.Kernel32.CreateMutexEx(IntPtr.Zero, name, flags, 34603009u); int lastPInvokeError = Marshal.GetLastPInvokeError(); if (safeWaitHandle.IsInvalid) { safeWaitHandle.SetHandleAsInvalid(); if (lastPInvokeError == 6) { throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); } throw Win32Marshal.GetExceptionForWin32Error(lastPInvokeError, name); } createdNew = lastPInvokeError != 183; base.SafeWaitHandle = safeWaitHandle; } private static OpenExistingResult OpenExistingWorker(string name, out Mutex result) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "name"); } result = null; SafeWaitHandle safeWaitHandle = Interop.Kernel32.OpenMutex(34603009u, inheritHandle: false, name); if (safeWaitHandle.IsInvalid) { int lastPInvokeError = Marshal.GetLastPInvokeError(); if (2 == lastPInvokeError || 123 == lastPInvokeError) { return OpenExistingResult.NameNotFound; } if (3 == lastPInvokeError) { return OpenExistingResult.PathNotFound; } if (6 == lastPInvokeError) { return OpenExistingResult.NameInvalid; } throw Win32Marshal.GetExceptionForWin32Error(lastPInvokeError, name); } result = new Mutex(safeWaitHandle); return OpenExistingResult.Success; } public void ReleaseMutex() { if (!Interop.Kernel32.ReleaseMutex(base.SafeWaitHandle)) { throw new ApplicationException(SR.Arg_SynchronizationLockException); } } } public struct NativeOverlapped { public IntPtr InternalLow; public IntPtr InternalHigh; public int OffsetLow; public int OffsetHigh; public IntPtr EventHandle; } public delegate void ParameterizedThreadStart(object? obj); public enum LockRecursionPolicy { NoRecursion, SupportsRecursion } internal sealed class ReaderWriterCount { public long lockID; public int readercount; public int writercount; public int upgradecount; public ReaderWriterCount next; } public class ReaderWriterLockSlim : IDisposable { private struct TimeoutTracker { private readonly int _total; private readonly int _start; public int RemainingMilliseconds { get { if (_total == -1 || _total == 0) { return _total; } int num = Environment.TickCount - _start; if (num < 0 || num >= _total) { return 0; } return _total - num; } } public bool IsExpired => RemainingMilliseconds == 0; public TimeoutTracker(TimeSpan timeout) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout"); } _total = (int)num; if (_total != -1 && _total != 0) { _start = Environment.TickCount; } else { _start = 0; } } public TimeoutTracker(int millisecondsTimeout) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout"); } _total = millisecondsTimeout; if (_total != -1 && _total != 0) { _start = Environment.TickCount; } else { _start = 0; } } } private struct SpinLock { private int _isLocked; private int _enterDeprioritizationState; private ushort EnterForEnterAnyReadDeprioritizedCount => (ushort)((uint)_enterDeprioritizationState >> 16); private ushort EnterForEnterAnyWriteDeprioritizedCount => (ushort)_enterDeprioritizationState; private static int GetEnterDeprioritizationStateChange(EnterSpinLockReason reason) { return (reason & EnterSpinLockReason.OperationMask) switch { EnterSpinLockReason.EnterAnyRead => 0, EnterSpinLockReason.ExitAnyRead => 1, EnterSpinLockReason.EnterWrite => 65536, _ => 65537, }; } private bool IsEnterDeprioritized(EnterSpinLockReason reason) { return reason switch { EnterSpinLockReason.EnterAnyRead => EnterForEnterAnyReadDeprioritizedCount != 0, EnterSpinLockReason.EnterWrite => EnterForEnterAnyWriteDeprioritizedCount != 0, EnterSpinLockReason.UpgradeToWrite => EnterForEnterAnyWriteDeprioritizedCount > 1, _ => false, }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool TryEnter() { return Interlocked.CompareExchange(ref _isLocked, 1, 0) == 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Enter(EnterSpinLockReason reason) { if (!TryEnter()) { EnterSpin(reason); } } private void EnterSpin(EnterSpinLockReason reason) { int enterDeprioritizationStateChange = GetEnterDeprioritizationStateChange(reason); if (enterDeprioritizationStateChange != 0) { Interlocked.Add(ref _enterDeprioritizationState, enterDeprioritizationStateChange); } int processorCount = Environment.ProcessorCount; int num = 0; while (true) { if (num < 10 && processorCount > 1) { Thread.SpinWait(20 * (num + 1)); } else if (num < 15) { Thread.Sleep(0); } else { Thread.Sleep(1); } if (!IsEnterDeprioritized(reason)) { if (_isLocked == 0 && TryEnter()) { break; } } else if (num >= 20) { reason |= EnterSpinLockReason.Wait; num = -1; } num++; } if (enterDeprioritizationStateChange != 0) { Interlocked.Add(ref _enterDeprioritizationState, -enterDeprioritizationStateChange); } } public void Exit() { Volatile.Write(ref _isLocked, 0); } } [Flags] private enum WaiterStates : byte { None = 0, NoWaiters = 1, WriteWaiterSignaled = 2, UpgradeableReadWaiterSignaled = 4 } private enum EnterSpinLockReason { EnterAnyRead = 0, ExitAnyRead = 1, EnterWrite = 2, UpgradeToWrite = 3, EnterRecursiveWrite = 4, ExitAnyWrite = 5, OperationMask = 7, Wait = 8 } private enum EnterLockType { Read, UpgradeableRead, Write, UpgradeToWrite } private readonly bool _fIsReentrant; private SpinLock _spinLock; private uint _numWriteWaiters; private uint _numReadWaiters; private uint _numWriteUpgradeWaiters; private uint _numUpgradeWaiters; private WaiterStates _waiterStates; private int _upgradeLockOwnerId; private int _writeLockOwnerId; private EventWaitHandle _writeEvent; private EventWaitHandle _readEvent; private EventWaitHandle _upgradeEvent; private EventWaitHandle _waitUpgradeEvent; private static long s_nextLockID; private readonly long _lockID; [ThreadStatic] private static ReaderWriterCount t_rwc; private bool _fUpgradeThreadHoldingRead; private uint _owners; private bool _fDisposed; private bool HasNoWaiters { get { return (_waiterStates & WaiterStates.NoWaiters) != 0; } set { if (value) { _waiterStates |= WaiterStates.NoWaiters; } else { _waiterStates &= ~WaiterStates.NoWaiters; } } } public bool IsReadLockHeld { get { if (RecursiveReadCount > 0) { return true; } return false; } } public bool IsUpgradeableReadLockHeld { get { if (RecursiveUpgradeCount > 0) { return true; } return false; } } public bool IsWriteLockHeld { get { if (RecursiveWriteCount > 0) { return true; } return false; } } public LockRecursionPolicy RecursionPolicy { get { if (_fIsReentrant) { return LockRecursionPolicy.SupportsRecursion; } return LockRecursionPolicy.NoRecursion; } } public int CurrentReadCount { get { int numReaders = (int)GetNumReaders(); if (_upgradeLockOwnerId != -1) { return numReaders - 1; } return numReaders; } } public int RecursiveReadCount { get { int result = 0; ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null) { result = threadRWCount.readercount; } return result; } } public int RecursiveUpgradeCount { get { if (_fIsReentrant) { int result = 0; ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null) { result = threadRWCount.upgradecount; } return result; } if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId) { return 1; } return 0; } } public int RecursiveWriteCount { get { if (_fIsReentrant) { int result = 0; ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null) { result = threadRWCount.writercount; } return result; } if (Environment.CurrentManagedThreadId == _writeLockOwnerId) { return 1; } return 0; } } public int WaitingReadCount => (int)_numReadWaiters; public int WaitingUpgradeCount => (int)_numUpgradeWaiters; public int WaitingWriteCount => (int)_numWriteWaiters; private void InitializeThreadCounts() { _upgradeLockOwnerId = -1; _writeLockOwnerId = -1; } public ReaderWriterLockSlim() : this(LockRecursionPolicy.NoRecursion) { } public ReaderWriterLockSlim(LockRecursionPolicy recursionPolicy) { if (recursionPolicy == LockRecursionPolicy.SupportsRecursion) { _fIsReentrant = true; } InitializeThreadCounts(); _waiterStates = WaiterStates.NoWaiters; _lockID = Interlocked.Increment(ref s_nextLockID); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsRWEntryEmpty(ReaderWriterCount rwc) { if (rwc.lockID == 0L) { return true; } if (rwc.readercount == 0 && rwc.writercount == 0 && rwc.upgradecount == 0) { return true; } return false; } private bool IsRwHashEntryChanged(ReaderWriterCount lrwc) { return lrwc.lockID != _lockID; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private ReaderWriterCount GetThreadRWCount(bool dontAllocate) { ReaderWriterCount next = t_rwc; ReaderWriterCount readerWriterCount = null; while (next != null) { if (next.lockID == _lockID) { return next; } if (!dontAllocate && readerWriterCount == null && IsRWEntryEmpty(next)) { readerWriterCount = next; } next = next.next; } if (dontAllocate) { return null; } if (readerWriterCount == null) { readerWriterCount = new ReaderWriterCount(); readerWriterCount.next = t_rwc; t_rwc = readerWriterCount; } readerWriterCount.lockID = _lockID; return readerWriterCount; } public void EnterReadLock() { TryEnterReadLock(-1); } public bool TryEnterReadLock(TimeSpan timeout) { return TryEnterReadLock(new TimeoutTracker(timeout)); } public bool TryEnterReadLock(int millisecondsTimeout) { return TryEnterReadLock(new TimeoutTracker(millisecondsTimeout)); } private bool TryEnterReadLock(TimeoutTracker timeout) { return TryEnterReadLockCore(timeout); } private bool TryEnterReadLockCore(TimeoutTracker timeout) { if (_fDisposed) { throw new ObjectDisposedException(null); } int currentManagedThreadId = Environment.CurrentManagedThreadId; ReaderWriterCount threadRWCount; if (!_fIsReentrant) { if (currentManagedThreadId == _writeLockOwnerId) { throw new LockRecursionException(SR.LockRecursionException_ReadAfterWriteNotAllowed); } _spinLock.Enter(EnterSpinLockReason.EnterAnyRead); threadRWCount = GetThreadRWCount(dontAllocate: false); if (threadRWCount.readercount > 0) { _spinLock.Exit(); throw new LockRecursionException(SR.LockRecursionException_RecursiveReadNotAllowed); } if (currentManagedThreadId == _upgradeLockOwnerId) { threadRWCount.readercount++; _owners++; _spinLock.Exit(); return true; } } else { _spinLock.Enter(EnterSpinLockReason.EnterAnyRead); threadRWCount = GetThreadRWCount(dontAllocate: false); if (threadRWCount.readercount > 0) { threadRWCount.readercount++; _spinLock.Exit(); return true; } if (currentManagedThreadId == _upgradeLockOwnerId) { threadRWCount.readercount++; _owners++; _spinLock.Exit(); _fUpgradeThreadHoldingRead = true; return true; } if (currentManagedThreadId == _writeLockOwnerId) { threadRWCount.readercount++; _owners++; _spinLock.Exit(); return true; } } bool flag = true; int num = 0; while (true) { if (_owners < 268435454) { _owners++; threadRWCount.readercount++; _spinLock.Exit(); return flag; } if (timeout.IsExpired) { _spinLock.Exit(); return false; } if (num < 20 && ShouldSpinForEnterAnyRead()) { _spinLock.Exit(); num++; SpinWait(num); _spinLock.Enter(EnterSpinLockReason.EnterAnyRead); if (IsRwHashEntryChanged(threadRWCount)) { threadRWCount = GetThreadRWCount(dontAllocate: false); } } else if (_readEvent == null) { LazyCreateEvent(ref _readEvent, EnterLockType.Read); if (IsRwHashEntryChanged(threadRWCount)) { threadRWCount = GetThreadRWCount(dontAllocate: false); } } else { flag = WaitOnEvent(_readEvent, ref _numReadWaiters, timeout, EnterLockType.Read); if (!flag) { break; } if (IsRwHashEntryChanged(threadRWCount)) { threadRWCount = GetThreadRWCount(dontAllocate: false); } } } return false; } public void EnterWriteLock() { TryEnterWriteLock(-1); } public bool TryEnterWriteLock(TimeSpan timeout) { return TryEnterWriteLock(new TimeoutTracker(timeout)); } public bool TryEnterWriteLock(int millisecondsTimeout) { return TryEnterWriteLock(new TimeoutTracker(millisecondsTimeout)); } private bool TryEnterWriteLock(TimeoutTracker timeout) { return TryEnterWriteLockCore(timeout); } private bool TryEnterWriteLockCore(TimeoutTracker timeout) { if (_fDisposed) { throw new ObjectDisposedException(null); } int currentManagedThreadId = Environment.CurrentManagedThreadId; bool flag = false; ReaderWriterCount threadRWCount; if (!_fIsReentrant) { if (currentManagedThreadId == _writeLockOwnerId) { throw new LockRecursionException(SR.LockRecursionException_RecursiveWriteNotAllowed); } EnterSpinLockReason reason; if (currentManagedThreadId == _upgradeLockOwnerId) { flag = true; reason = EnterSpinLockReason.UpgradeToWrite; } else { reason = EnterSpinLockReason.EnterWrite; } _spinLock.Enter(reason); threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null && threadRWCount.readercount > 0) { _spinLock.Exit(); throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed); } } else { EnterSpinLockReason reason2 = ((currentManagedThreadId == _writeLockOwnerId) ? EnterSpinLockReason.EnterRecursiveWrite : ((currentManagedThreadId != _upgradeLockOwnerId) ? EnterSpinLockReason.EnterWrite : EnterSpinLockReason.UpgradeToWrite)); _spinLock.Enter(reason2); threadRWCount = GetThreadRWCount(dontAllocate: false); if (currentManagedThreadId == _writeLockOwnerId) { threadRWCount.writercount++; _spinLock.Exit(); return true; } if (currentManagedThreadId == _upgradeLockOwnerId) { flag = true; } else if (threadRWCount.readercount > 0) { _spinLock.Exit(); throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed); } } bool flag2 = true; int num = 0; while (true) { if (IsWriterAcquired()) { SetWriterAcquired(); break; } if (flag) { uint numReaders = GetNumReaders(); if (numReaders == 1) { SetWriterAcquired(); break; } if (numReaders == 2 && threadRWCount != null) { if (IsRwHashEntryChanged(threadRWCount)) { threadRWCount = GetThreadRWCount(dontAllocate: false); } if (threadRWCount.readercount > 0) { SetWriterAcquired(); break; } } } if (timeout.IsExpired) { _spinLock.Exit(); return false; } if (num < 20 && ShouldSpinForEnterAnyWrite(flag)) { _spinLock.Exit(); num++; SpinWait(num); _spinLock.Enter(flag ? EnterSpinLockReason.UpgradeToWrite : EnterSpinLockReason.EnterWrite); } else if (flag) { if (_waitUpgradeEvent == null) { LazyCreateEvent(ref _waitUpgradeEvent, EnterLockType.UpgradeToWrite); } else if (!WaitOnEvent(_waitUpgradeEvent, ref _numWriteUpgradeWaiters, timeout, EnterLockType.UpgradeToWrite)) { return false; } } else if (_writeEvent == null) { LazyCreateEvent(ref _writeEvent, EnterLockType.Write); } else if (!WaitOnEvent(_writeEvent, ref _numWriteWaiters, timeout, EnterLockType.Write)) { return false; } } if (_fIsReentrant) { if (IsRwHashEntryChanged(threadRWCount)) { threadRWCount = GetThreadRWCount(dontAllocate: false); } threadRWCount.writercount++; } _spinLock.Exit(); _writeLockOwnerId = currentManagedThreadId; return true; } public void EnterUpgradeableReadLock() { TryEnterUpgradeableReadLock(-1); } public bool TryEnterUpgradeableReadLock(TimeSpan timeout) { return TryEnterUpgradeableReadLock(new TimeoutTracker(timeout)); } public bool TryEnterUpgradeableReadLock(int millisecondsTimeout) { return TryEnterUpgradeableReadLock(new TimeoutTracker(millisecondsTimeout)); } private bool TryEnterUpgradeableReadLock(TimeoutTracker timeout) { return TryEnterUpgradeableReadLockCore(timeout); } private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout) { if (_fDisposed) { throw new ObjectDisposedException(null); } int currentManagedThreadId = Environment.CurrentManagedThreadId; ReaderWriterCount threadRWCount; if (!_fIsReentrant) { if (currentManagedThreadId == _upgradeLockOwnerId) { throw new LockRecursionException(SR.LockRecursionException_RecursiveUpgradeNotAllowed); } if (currentManagedThreadId == _writeLockOwnerId) { throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterWriteNotAllowed); } _spinLock.Enter(EnterSpinLockReason.EnterAnyRead); threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount != null && threadRWCount.readercount > 0) { _spinLock.Exit(); throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed); } } else { _spinLock.Enter(EnterSpinLockReason.EnterAnyRead); threadRWCount = GetThreadRWCount(dontAllocate: false); if (currentManagedThreadId == _upgradeLockOwnerId) { threadRWCount.upgradecount++; _spinLock.Exit(); return true; } if (currentManagedThreadId == _writeLockOwnerId) { _owners++; _upgradeLockOwnerId = currentManagedThreadId; threadRWCount.upgradecount++; if (threadRWCount.readercount > 0) { _fUpgradeThreadHoldingRead = true; } _spinLock.Exit(); return true; } if (threadRWCount.readercount > 0) { _spinLock.Exit(); throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed); } } bool flag = true; int num = 0; while (true) { if (_upgradeLockOwnerId == -1 && _owners < 268435454) { _owners++; _upgradeLockOwnerId = currentManagedThreadId; if (_fIsReentrant) { if (IsRwHashEntryChanged(threadRWCount)) { threadRWCount = GetThreadRWCount(dontAllocate: false); } threadRWCount.upgradecount++; } break; } if (timeout.IsExpired) { _spinLock.Exit(); return false; } if (num < 20 && ShouldSpinForEnterAnyRead()) { _spinLock.Exit(); num++; SpinWait(num); _spinLock.Enter(EnterSpinLockReason.EnterAnyRead); } else if (_upgradeEvent == null) { LazyCreateEvent(ref _upgradeEvent, EnterLockType.UpgradeableRead); } else if (!WaitOnEvent(_upgradeEvent, ref _numUpgradeWaiters, timeout, EnterLockType.UpgradeableRead)) { return false; } } _spinLock.Exit(); return true; } public void ExitReadLock() { _spinLock.Enter(EnterSpinLockReason.ExitAnyRead); ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount == null || threadRWCount.readercount < 1) { _spinLock.Exit(); throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedRead); } if (_fIsReentrant) { if (threadRWCount.readercount > 1) { threadRWCount.readercount--; _spinLock.Exit(); return; } if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId) { _fUpgradeThreadHoldingRead = false; } } _owners--; threadRWCount.readercount--; ExitAndWakeUpAppropriateWaiters(); } public void ExitWriteLock() { if (!_fIsReentrant) { if (Environment.CurrentManagedThreadId != _writeLockOwnerId) { throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite); } _spinLock.Enter(EnterSpinLockReason.ExitAnyWrite); } else { _spinLock.Enter(EnterSpinLockReason.ExitAnyWrite); ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: false); if (threadRWCount == null) { _spinLock.Exit(); throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite); } if (threadRWCount.writercount < 1) { _spinLock.Exit(); throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite); } threadRWCount.writercount--; if (threadRWCount.writercount > 0) { _spinLock.Exit(); return; } } ClearWriterAcquired(); _writeLockOwnerId = -1; ExitAndWakeUpAppropriateWaiters(); } public void ExitUpgradeableReadLock() { if (!_fIsReentrant) { if (Environment.CurrentManagedThreadId != _upgradeLockOwnerId) { throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade); } _spinLock.Enter(EnterSpinLockReason.ExitAnyRead); } else { _spinLock.Enter(EnterSpinLockReason.ExitAnyRead); ReaderWriterCount threadRWCount = GetThreadRWCount(dontAllocate: true); if (threadRWCount == null) { _spinLock.Exit(); throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade); } if (threadRWCount.upgradecount < 1) { _spinLock.Exit(); throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade); } threadRWCount.upgradecount--; if (threadRWCount.upgradecount > 0) { _spinLock.Exit(); return; } _fUpgradeThreadHoldingRead = false; } _owners--; _upgradeLockOwnerId = -1; ExitAndWakeUpAppropriateWaiters(); } private void LazyCreateEvent([NotNull] ref EventWaitHandle waitEvent, EnterLockType enterLockType) { _spinLock.Exit(); EventWaitHandle eventWaitHandle = new EventWaitHandle(initialState: false, (enterLockType == EnterLockType.Read) ? EventResetMode.ManualReset : EventResetMode.AutoReset); EnterSpinLockReason reason; switch (enterLockType) { case EnterLockType.Read: case EnterLockType.UpgradeableRead: reason = EnterSpinLockReason.Wait; break; case EnterLockType.Write: reason = (EnterSpinLockReason)10; break; default: reason = (EnterSpinLockReason)11; break; } _spinLock.Enter(reason); if (waitEvent == null) { waitEvent = eventWaitHandle; } else { eventWaitHandle.Dispose(); } } private bool WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, TimeoutTracker timeout, EnterLockType enterLockType) { WaiterStates waiterStates = WaiterStates.None; EnterSpinLockReason reason; switch (enterLockType) { case EnterLockType.UpgradeableRead: waiterStates = WaiterStates.UpgradeableReadWaiterSignaled; goto case EnterLockType.Read; case EnterLockType.Read: reason = EnterSpinLockReason.EnterAnyRead; break; case EnterLockType.Write: waiterStates = WaiterStates.WriteWaiterSignaled; reason = EnterSpinLockReason.EnterWrite; break; default: reason = EnterSpinLockReason.UpgradeToWrite; break; } if (waiterStates != 0 && (_waiterStates & waiterStates) != 0) { _waiterStates &= (WaiterStates)(byte)(~(int)waiterStates); } waitEvent.Reset(); numWaiters++; HasNoWaiters = false; if (_numWriteWaiters == 1) { SetWritersWaiting(); } if (_numWriteUpgradeWaiters == 1) { SetUpgraderWaiting(); } bool flag = false; _spinLock.Exit(); try { flag = waitEvent.WaitOne(timeout.RemainingMilliseconds); } finally { _spinLock.Enter(reason); numWaiters--; if (flag && waiterStates != 0 && (_waiterStates & waiterStates) != 0) { _waiterStates &= (WaiterStates)(byte)(~(int)waiterStates); } if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0) { HasNoWaiters = true; } if (_numWriteWaiters == 0) { ClearWritersWaiting(); } if (_numWriteUpgradeWaiters == 0) { ClearUpgraderWaiting(); } if (!flag) { if (enterLockType >= EnterLockType.Write) { ExitAndWakeUpAppropriateReadWaiters(); } else { _spinLock.Exit(); } } } return flag; } private void ExitAndWakeUpAppropriateWaiters() { if (HasNoWaiters) { _spinLock.Exit(); } else { ExitAndWakeUpAppropriateWaitersPreferringWriters(); } } private void ExitAndWakeUpAppropriateWaitersPreferringWriters() { uint numReaders = GetNumReaders(); if (_fIsReentrant && _numWriteUpgradeWaiters != 0 && _fUpgradeThreadHoldingRead && numReaders == 2) { _spinLock.Exit(); _waitUpgradeEvent.Set(); } else if (numReaders == 1 && _numWriteUpgradeWaiters != 0) { _spinLock.Exit(); _waitUpgradeEvent.Set(); } else if (numReaders == 0 && _numWriteWaiters != 0) { WaiterStates waiterStates = _waiterStates & WaiterStates.WriteWaiterSignaled; if (waiterStates == WaiterStates.None) { _waiterStates |= WaiterStates.WriteWaiterSignaled; } _spinLock.Exit(); if (waiterStates == WaiterStates.None) { _writeEvent.Set(); } } else { ExitAndWakeUpAppropriateReadWaiters(); } } private void ExitAndWakeUpAppropriateReadWaiters() { if (_numWriteWaiters != 0 || _numWriteUpgradeWaiters != 0 || HasNoWaiters) { _spinLock.Exit(); return; } bool flag = _numReadWaiters != 0; bool flag2 = _numUpgradeWaiters != 0 && _upgradeLockOwnerId == -1; if (flag2) { if ((_waiterStates & WaiterStates.UpgradeableReadWaiterSignaled) == 0) { _waiterStates |= WaiterStates.UpgradeableReadWaiterSignaled; } else { flag2 = false; } } _spinLock.Exit(); if (flag) { _readEvent.Set(); } if (flag2) { _upgradeEvent.Set(); } } private bool IsWriterAcquired() { return (_owners & 0xBFFFFFFFu) == 0; } private void SetWriterAcquired() { _owners |= 2147483648u; } private void ClearWriterAcquired() { _owners &= 2147483647u; } private void SetWritersWaiting() { _owners |= 1073741824u; } private void ClearWritersWaiting() { _owners &= 3221225471u; } private void SetUpgraderWaiting() { _owners |= 536870912u; } private void ClearUpgraderWaiting() { _owners &= 3758096383u; } private uint GetNumReaders() { return _owners & 0xFFFFFFFu; } private bool ShouldSpinForEnterAnyRead() { if (!HasNoWaiters) { if (_numWriteWaiters == 0) { return _numWriteUpgradeWaiters == 0; } return false; } return true; } private bool ShouldSpinForEnterAnyWrite(bool isUpgradeToWrite) { if (!isUpgradeToWrite) { return _numWriteUpgradeWaiters == 0; } return true; } private static void SpinWait(int spinCount) { if (spinCount < 5 && Environment.ProcessorCount > 1) { Thread.SpinWait(20 * spinCount); } else { Thread.Sleep(0); } } public void Dispose() { Dispose(disposing: true); } private void Dispose(bool disposing) { if (disposing && !_fDisposed) { if (WaitingReadCount > 0 || WaitingUpgradeCount > 0 || WaitingWriteCount > 0) { throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose); } if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld) { throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose); } if (_writeEvent != null) { _writeEvent.Dispose(); _writeEvent = null; } if (_readEvent != null) { _readEvent.Dispose(); _readEvent = null; } if (_upgradeEvent != null) { _upgradeEvent.Dispose(); _upgradeEvent = null; } if (_waitUpgradeEvent != null) { _waitUpgradeEvent.Dispose(); _waitUpgradeEvent = null; } _fDisposed = true; } } } public sealed class Semaphore : WaitHandle { public Semaphore(int initialCount, int maximumCount) : this(initialCount, maximumCount, null) { } public Semaphore(int initialCount, int maximumCount, string? name) : this(initialCount, maximumCount, name, out var _) { } public Semaphore(int initialCount, int maximumCount, string? name, out bool createdNew) { if (initialCount < 0) { throw new ArgumentOutOfRangeException("initialCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (maximumCount < 1) { throw new ArgumentOutOfRangeException("maximumCount", SR.ArgumentOutOfRange_NeedPosNum); } if (initialCount > maximumCount) { throw new ArgumentException(SR.Argument_SemaphoreInitialMaximum); } CreateSemaphoreCore(initialCount, maximumCount, name, out createdNew); } [SupportedOSPlatform("windows")] public static Semaphore OpenExisting(string name) { Semaphore result; return OpenExistingWorker(name, out result) switch { OpenExistingResult.NameNotFound => throw new WaitHandleCannotBeOpenedException(), OpenExistingResult.NameInvalid => throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)), OpenExistingResult.PathNotFound => throw new IOException(SR.Format(SR.IO_PathNotFound_Path, name)), _ => result, }; } [SupportedOSPlatform("windows")] public static bool TryOpenExisting(string name, [NotNullWhen(true)] out Semaphore? result) { return OpenExistingWorker(name, out result) == OpenExistingResult.Success; } public int Release() { return ReleaseCore(1); } public int Release(int releaseCount) { if (releaseCount < 1) { throw new ArgumentOutOfRangeException("releaseCount", SR.ArgumentOutOfRange_NeedNonNegNum); } return ReleaseCore(releaseCount); } private Semaphore(SafeWaitHandle handle) { base.SafeWaitHandle = handle; } private void CreateSemaphoreCore(int initialCount, int maximumCount, string name, out bool createdNew) { SafeWaitHandle safeWaitHandle = Interop.Kernel32.CreateSemaphoreEx(IntPtr.Zero, initialCount, maximumCount, name, 0u, 34603010u); int lastPInvokeError = Marshal.GetLastPInvokeError(); if (safeWaitHandle.IsInvalid) { if (!string.IsNullOrEmpty(name) && lastPInvokeError == 6) { throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name)); } throw Win32Marshal.GetExceptionForLastWin32Error(); } createdNew = lastPInvokeError != 183; base.SafeWaitHandle = safeWaitHandle; } private static OpenExistingResult OpenExistingWorker(string name, out Semaphore result) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "name"); } SafeWaitHandle safeWaitHandle = Interop.Kernel32.OpenSemaphore(34603010u, inheritHandle: false, name); if (safeWaitHandle.IsInvalid) { result = null; switch (Marshal.GetLastPInvokeError()) { case 2: case 123: return OpenExistingResult.NameNotFound; case 3: return OpenExistingResult.PathNotFound; case 6: return OpenExistingResult.NameInvalid; default: throw Win32Marshal.GetExceptionForLastWin32Error(); } } result = new Semaphore(safeWaitHandle); return OpenExistingResult.Success; } private int ReleaseCore(int releaseCount) { if (!Interop.Kernel32.ReleaseSemaphore(base.SafeWaitHandle, releaseCount, out var previousCount)) { throw new SemaphoreFullException(); } return previousCount; } } [Serializable] [TypeForwardedFrom("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SemaphoreFullException : SystemException { public SemaphoreFullException() : base(SR.Threading_SemaphoreFullException) { } public SemaphoreFullException(string? message) : base(message) { } public SemaphoreFullException(string? message, Exception? innerException) : base(message, innerException) { } protected SemaphoreFullException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [DebuggerDisplay("Current Count = {m_currentCount}")] public class SemaphoreSlim : IDisposable { private sealed class TaskNode : Task { internal TaskNode Prev; internal TaskNode Next; internal TaskNode() : base((object)null, TaskCreationOptions.RunContinuationsAsynchronously) { } } private readonly struct ConfiguredNoThrowAwaiter : ICriticalNotifyCompletion, INotifyCompletion { private readonly Task _task; public bool IsCompleted => _task.IsCompleted; public ConfiguredNoThrowAwaiter(Task task) { _task = task; } public ConfiguredNoThrowAwaiter GetAwaiter() { return this; } public void GetResult() { _task.MarkExceptionsAsHandled(); } public void UnsafeOnCompleted(Action continuation) { _task.ConfigureAwait(continueOnCapturedContext: false).GetAwaiter().UnsafeOnCompleted(continuation); } public void OnCompleted(Action continuation) { _task.ConfigureAwait(continueOnCapturedContext: false).GetAwaiter().OnCompleted(continuation); } } private volatile int m_currentCount; private readonly int m_maxCount; private int m_waitCount; private int m_countOfWaitersPulsedToWake; private readonly StrongBox m_lockObjAndDisposed; private volatile ManualResetEvent m_waitHandle; private TaskNode m_asyncHead; private TaskNode m_asyncTail; private static readonly Action s_cancellationTokenCanceledEventHandler = CancellationTokenCanceledEventHandler; public int CurrentCount => m_currentCount; public WaitHandle AvailableWaitHandle { get { CheckDispose(); if (m_waitHandle != null) { return m_waitHandle; } lock (m_lockObjAndDisposed) { if (m_waitHandle == null) { m_waitHandle = new ManualResetEvent(m_currentCount != 0); } } return m_waitHandle; } } public SemaphoreSlim(int initialCount) : this(initialCount, int.MaxValue) { } public SemaphoreSlim(int initialCount, int maxCount) { if (initialCount < 0 || initialCount > maxCount) { throw new ArgumentOutOfRangeException("initialCount", initialCount, SR.SemaphoreSlim_ctor_InitialCountWrong); } if (maxCount <= 0) { throw new ArgumentOutOfRangeException("maxCount", maxCount, SR.SemaphoreSlim_ctor_MaxCountWrong); } m_maxCount = maxCount; m_currentCount = initialCount; m_lockObjAndDisposed = new StrongBox(); } [UnsupportedOSPlatform("browser")] public void Wait() { Wait(-1, CancellationToken.None); } [UnsupportedOSPlatform("browser")] public void Wait(CancellationToken cancellationToken) { Wait(-1, cancellationToken); } [UnsupportedOSPlatform("browser")] public bool Wait(TimeSpan timeout) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout", timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); } return Wait((int)timeout.TotalMilliseconds, CancellationToken.None); } [UnsupportedOSPlatform("browser")] public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout", timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); } return Wait((int)timeout.TotalMilliseconds, cancellationToken); } [UnsupportedOSPlatform("browser")] public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, CancellationToken.None); } [UnsupportedOSPlatform("browser")] public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { CheckDispose(); if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", millisecondsTimeout, SR.SemaphoreSlim_Wait_TimeoutWrong); } cancellationToken.ThrowIfCancellationRequested(); if (millisecondsTimeout == 0 && m_currentCount == 0) { return false; } uint startTime = 0u; if (millisecondsTimeout != -1 && millisecondsTimeout > 0) { startTime = TimeoutHelper.GetTime(); } bool flag = false; Task task = null; bool lockTaken = false; CancellationTokenRegistration cancellationTokenRegistration = cancellationToken.UnsafeRegister(s_cancellationTokenCanceledEventHandler, this); try { if (m_currentCount == 0) { int num = SpinWait.SpinCountforSpinBeforeWait * 4; SpinWait spinWait = default(SpinWait); while (spinWait.Count < num) { spinWait.SpinOnce(-1); if (m_currentCount != 0) { break; } } } Monitor.Enter(m_lockObjAndDisposed, ref lockTaken); m_waitCount++; if (m_asyncHead != null) { task = WaitAsync(millisecondsTimeout, cancellationToken); } else { OperationCanceledException ex = null; if (m_currentCount == 0) { if (millisecondsTimeout == 0) { return false; } try { flag = WaitUntilCountOrTimeout(millisecondsTimeout, startTime, cancellationToken); } catch (OperationCanceledException ex2) { ex = ex2; } } if (m_currentCount > 0) { flag = true; m_currentCount--; } else if (ex != null) { throw ex; } if (m_waitHandle != null && m_currentCount == 0) { m_waitHandle.Reset(); } } } finally { if (lockTaken) { m_waitCount--; Monitor.Exit(m_lockObjAndDisposed); } cancellationTokenRegistration.Dispose(); } return task?.GetAwaiter().GetResult() ?? flag; } [UnsupportedOSPlatform("browser")] private bool WaitUntilCountOrTimeout(int millisecondsTimeout, uint startTime, CancellationToken cancellationToken) { int num = -1; while (m_currentCount == 0) { cancellationToken.ThrowIfCancellationRequested(); if (millisecondsTimeout != -1) { num = TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout); if (num <= 0) { return false; } } bool flag = Monitor.Wait(m_lockObjAndDisposed, num); if (m_countOfWaitersPulsedToWake != 0) { m_countOfWaitersPulsedToWake--; } if (!flag) { return false; } } return true; } public Task WaitAsync() { return WaitAsync(-1, default(CancellationToken)); } public Task WaitAsync(CancellationToken cancellationToken) { return WaitAsync(-1, cancellationToken); } public Task WaitAsync(int millisecondsTimeout) { return WaitAsync(millisecondsTimeout, default(CancellationToken)); } public Task WaitAsync(TimeSpan timeout) { return WaitAsync(timeout, default(CancellationToken)); } public Task WaitAsync(TimeSpan timeout, CancellationToken cancellationToken) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout", timeout, SR.SemaphoreSlim_Wait_TimeoutWrong); } return WaitAsync((int)timeout.TotalMilliseconds, cancellationToken); } public Task WaitAsync(int millisecondsTimeout, CancellationToken cancellationToken) { CheckDispose(); if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", millisecondsTimeout, SR.SemaphoreSlim_Wait_TimeoutWrong); } if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } lock (m_lockObjAndDisposed) { if (m_currentCount > 0) { m_currentCount--; if (m_waitHandle != null && m_currentCount == 0) { m_waitHandle.Reset(); } return Task.FromResult(result: true); } if (millisecondsTimeout == 0) { return Task.FromResult(result: false); } TaskNode taskNode = CreateAndAddAsyncWaiter(); return (millisecondsTimeout == -1 && !cancellationToken.CanBeCanceled) ? taskNode : WaitUntilCountOrTimeoutAsync(taskNode, millisecondsTimeout, cancellationToken); } } private TaskNode CreateAndAddAsyncWaiter() { TaskNode taskNode = new TaskNode(); if (m_asyncHead == null) { m_asyncHead = taskNode; m_asyncTail = taskNode; } else { m_asyncTail.Next = taskNode; taskNode.Prev = m_asyncTail; m_asyncTail = taskNode; } return taskNode; } private bool RemoveAsyncWaiter(TaskNode task) { bool result = m_asyncHead == task || task.Prev != null; if (task.Next != null) { task.Next.Prev = task.Prev; } if (task.Prev != null) { task.Prev.Next = task.Next; } if (m_asyncHead == task) { m_asyncHead = task.Next; } if (m_asyncTail == task) { m_asyncTail = task.Prev; } task.Next = (task.Prev = null); return result; } private async Task WaitUntilCountOrTimeoutAsync(TaskNode asyncWaiter, int millisecondsTimeout, CancellationToken cancellationToken) { await new ConfiguredNoThrowAwaiter(asyncWaiter.WaitAsync(TimeSpan.FromMilliseconds(millisecondsTimeout), cancellationToken)); if (cancellationToken.IsCancellationRequested) { await TaskScheduler.Default; } if (asyncWaiter.IsCompleted) { return true; } lock (m_lockObjAndDisposed) { if (RemoveAsyncWaiter(asyncWaiter)) { cancellationToken.ThrowIfCancellationRequested(); return false; } } return await asyncWaiter.ConfigureAwait(continueOnCapturedContext: false); } public int Release() { return Release(1); } public int Release(int releaseCount) { CheckDispose(); if (releaseCount < 1) { throw new ArgumentOutOfRangeException("releaseCount", releaseCount, SR.SemaphoreSlim_Release_CountWrong); } int num; lock (m_lockObjAndDisposed) { int currentCount = m_currentCount; num = currentCount; if (m_maxCount - currentCount < releaseCount) { throw new SemaphoreFullException(); } currentCount += releaseCount; int waitCount = m_waitCount; int num2 = Math.Min(currentCount, waitCount) - m_countOfWaitersPulsedToWake; if (num2 > 0) { if (num2 > releaseCount) { num2 = releaseCount; } m_countOfWaitersPulsedToWake += num2; for (int i = 0; i < num2; i++) { Monitor.Pulse(m_lockObjAndDisposed); } } if (m_asyncHead != null) { int num3 = currentCount - waitCount; while (num3 > 0 && m_asyncHead != null) { currentCount--; num3--; TaskNode asyncHead = m_asyncHead; RemoveAsyncWaiter(asyncHead); asyncHead.TrySetResult(result: true); } } m_currentCount = currentCount; if (m_waitHandle != null && num == 0 && currentCount > 0) { m_waitHandle.Set(); } } return num; } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { WaitHandle waitHandle = m_waitHandle; if (waitHandle != null) { waitHandle.Dispose(); m_waitHandle = null; } m_lockObjAndDisposed.Value = true; m_asyncHead = null; m_asyncTail = null; } } private static void CancellationTokenCanceledEventHandler(object obj) { SemaphoreSlim semaphoreSlim = (SemaphoreSlim)obj; lock (semaphoreSlim.m_lockObjAndDisposed) { Monitor.PulseAll(semaphoreSlim.m_lockObjAndDisposed); } } private void CheckDispose() { if (m_lockObjAndDisposed.Value) { throw new ObjectDisposedException(null, SR.SemaphoreSlim_Disposed); } } } public delegate void SendOrPostCallback(object? state); [DebuggerTypeProxy(typeof(SystemThreading_SpinLockDebugView))] [DebuggerDisplay("IsHeld = {IsHeld}")] public struct SpinLock { internal sealed class SystemThreading_SpinLockDebugView { private SpinLock _spinLock; public bool? IsHeldByCurrentThread { get { try { return _spinLock.IsHeldByCurrentThread; } catch (InvalidOperationException) { return null; } } } public int? OwnerThreadID { get { if (_spinLock.IsThreadOwnerTrackingEnabled) { return _spinLock._owner; } return null; } } public bool IsHeld => _spinLock.IsHeld; public SystemThreading_SpinLockDebugView(SpinLock spinLock) { _spinLock = spinLock; } } private volatile int _owner; public bool IsHeld { get { if (IsThreadOwnerTrackingEnabled) { return _owner != 0; } return (_owner & 1) != 0; } } public bool IsHeldByCurrentThread { get { if (!IsThreadOwnerTrackingEnabled) { throw new InvalidOperationException(SR.SpinLock_IsHeldByCurrentThread); } return (_owner & 0x7FFFFFFF) == Environment.CurrentManagedThreadId; } } public bool IsThreadOwnerTrackingEnabled => (_owner & int.MinValue) == 0; [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int CompareExchange(ref int location, int value, int comparand, ref bool success) { int num = Interlocked.CompareExchange(ref location, value, comparand); success = num == comparand; return num; } public SpinLock(bool enableThreadOwnerTracking) { _owner = 0; if (!enableThreadOwnerTracking) { _owner |= int.MinValue; } } public void Enter(ref bool lockTaken) { int owner = _owner; if (lockTaken || (owner & -2147483647) != int.MinValue || CompareExchange(ref _owner, owner | 1, owner, ref lockTaken) != owner) { ContinueTryEnter(-1, ref lockTaken); } } public void TryEnter(ref bool lockTaken) { int owner = _owner; if (((owner & int.MinValue) == 0) | lockTaken) { ContinueTryEnter(0, ref lockTaken); } else if (((uint)owner & (true ? 1u : 0u)) != 0) { lockTaken = false; } else { CompareExchange(ref _owner, owner | 1, owner, ref lockTaken); } } public void TryEnter(TimeSpan timeout, ref bool lockTaken) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout", timeout, SR.SpinLock_TryEnter_ArgumentOutOfRange); } TryEnter((int)timeout.TotalMilliseconds, ref lockTaken); } public void TryEnter(int millisecondsTimeout, ref bool lockTaken) { int owner = _owner; if (((millisecondsTimeout < -1) | lockTaken) || (owner & -2147483647) != int.MinValue || CompareExchange(ref _owner, owner | 1, owner, ref lockTaken) != owner) { ContinueTryEnter(millisecondsTimeout, ref lockTaken); } } private void ContinueTryEnter(int millisecondsTimeout, ref bool lockTaken) { if (lockTaken) { lockTaken = false; throw new ArgumentException(SR.SpinLock_TryReliableEnter_ArgumentException); } if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", millisecondsTimeout, SR.SpinLock_TryEnter_ArgumentOutOfRange); } uint startTime = 0u; if (millisecondsTimeout != -1 && millisecondsTimeout != 0) { startTime = TimeoutHelper.GetTime(); } if (IsThreadOwnerTrackingEnabled) { ContinueTryEnterWithThreadTracking(millisecondsTimeout, startTime, ref lockTaken); return; } int num = int.MaxValue; int owner = _owner; if ((owner & 1) == 0) { if (CompareExchange(ref _owner, owner | 1, owner, ref lockTaken) == owner || millisecondsTimeout == 0) { return; } } else { if (millisecondsTimeout == 0) { return; } if ((owner & 0x7FFFFFFE) != 2147483646) { num = (Interlocked.Add(ref _owner, 2) & 0x7FFFFFFE) >> 1; } } SpinWait spinWait = default(SpinWait); if (num > Environment.ProcessorCount) { spinWait.Count = 10; } do { spinWait.SpinOnce(40); owner = _owner; if ((owner & 1) == 0) { int value = (((owner & 0x7FFFFFFE) == 0) ? (owner | 1) : ((owner - 2) | 1)); if (CompareExchange(ref _owner, value, owner, ref lockTaken) == owner) { return; } } } while (spinWait.Count % 10 != 0 || millisecondsTimeout == -1 || TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) > 0); DecrementWaiters(); } private void DecrementWaiters() { SpinWait spinWait = default(SpinWait); while (true) { int owner = _owner; if (((uint)owner & 0x7FFFFFFEu) != 0 && Interlocked.CompareExchange(ref _owner, owner - 2, owner) != owner) { spinWait.SpinOnce(); continue; } break; } } private void ContinueTryEnterWithThreadTracking(int millisecondsTimeout, uint startTime, ref bool lockTaken) { int currentManagedThreadId = Environment.CurrentManagedThreadId; if (_owner == currentManagedThreadId) { throw new LockRecursionException(SR.SpinLock_TryEnter_LockRecursionException); } SpinWait spinWait = default(SpinWait); while (true) { spinWait.SpinOnce(); if (_owner == 0 && CompareExchange(ref _owner, currentManagedThreadId, 0, ref lockTaken) == 0) { break; } switch (millisecondsTimeout) { case -1: continue; case 0: return; } if (spinWait.NextSpinWillYield && TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0) { return; } } } public void Exit() { if ((_owner & int.MinValue) == 0) { ExitSlowPath(useMemoryBarrier: true); } else { Interlocked.Decrement(ref _owner); } } public void Exit(bool useMemoryBarrier) { int owner = _owner; if ((owner & int.MinValue) != 0 && !useMemoryBarrier) { _owner = owner & -2; } else { ExitSlowPath(useMemoryBarrier); } } private void ExitSlowPath(bool useMemoryBarrier) { bool flag = (_owner & int.MinValue) == 0; if (flag && !IsHeldByCurrentThread) { throw new SynchronizationLockException(SR.SpinLock_Exit_SynchronizationLockException); } if (useMemoryBarrier) { if (flag) { Interlocked.Exchange(ref _owner, 0); } else { Interlocked.Decrement(ref _owner); } } else if (flag) { _owner = 0; } else { int owner = _owner; _owner = owner & -2; } } } public struct SpinWait { internal static readonly int SpinCountforSpinBeforeWait = (Environment.IsSingleProcessor ? 1 : 35); private int _count; public int Count { get { return _count; } internal set { _count = value; } } public bool NextSpinWillYield { get { if (_count < 10) { return Environment.IsSingleProcessor; } return true; } } public void SpinOnce() { SpinOnceCore(20); } public void SpinOnce(int sleep1Threshold) { if (sleep1Threshold < -1) { throw new ArgumentOutOfRangeException("sleep1Threshold", sleep1Threshold, SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (sleep1Threshold >= 0 && sleep1Threshold < 10) { sleep1Threshold = 10; } SpinOnceCore(sleep1Threshold); } private void SpinOnceCore(int sleep1Threshold) { if ((_count >= 10 && ((_count >= sleep1Threshold && sleep1Threshold >= 0) || (_count - 10) % 2 == 0)) || Environment.IsSingleProcessor) { if (_count >= sleep1Threshold && sleep1Threshold >= 0) { Thread.Sleep(1); } else { int num = ((_count >= 10) ? ((_count - 10) / 2) : _count); if (num % 5 == 4) { Thread.Sleep(0); } else { Thread.Yield(); } } } else { int num2 = Thread.OptimalMaxSpinWaitsPerSpinIteration; if (_count <= 30 && 1 << _count < num2) { num2 = 1 << _count; } Thread.SpinWait(num2); } _count = ((_count == int.MaxValue) ? 10 : (_count + 1)); } public void Reset() { _count = 0; } public static void SpinUntil(Func condition) { SpinUntil(condition, -1); } public static bool SpinUntil(Func condition, TimeSpan timeout) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { throw new ArgumentOutOfRangeException("timeout", timeout, SR.SpinWait_SpinUntil_TimeoutWrong); } return SpinUntil(condition, (int)num); } public static bool SpinUntil(Func condition, int millisecondsTimeout) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("millisecondsTimeout", millisecondsTimeout, SR.SpinWait_SpinUntil_TimeoutWrong); } if (condition == null) { throw new ArgumentNullException("condition", SR.SpinWait_SpinUntil_ArgumentNull); } uint num = 0u; if (millisecondsTimeout != 0 && millisecondsTimeout != -1) { num = TimeoutHelper.GetTime(); } SpinWait spinWait = default(SpinWait); while (!condition()) { if (millisecondsTimeout == 0) { return false; } spinWait.SpinOnce(); if (millisecondsTimeout != -1 && spinWait.NextSpinWillYield && millisecondsTimeout <= TimeoutHelper.GetTime() - num) { return false; } } return true; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SynchronizationLockException : SystemException { public SynchronizationLockException() : base(SR.Arg_SynchronizationLockException) { base.HResult = -2146233064; } public SynchronizationLockException(string? message) : base(message) { base.HResult = -2146233064; } public SynchronizationLockException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233064; } protected SynchronizationLockException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class ThreadAbortException : SystemException { public object? ExceptionState => null; internal ThreadAbortException() { base.HResult = -2146233040; } private ThreadAbortException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class ThreadExceptionEventArgs : EventArgs { private readonly Exception m_exception; public Exception Exception => m_exception; public ThreadExceptionEventArgs(Exception t) { m_exception = t; } } public delegate void ThreadExceptionEventHandler(object sender, ThreadExceptionEventArgs e); internal sealed class ThreadInt64PersistentCounter { private sealed class ThreadLocalNode { private uint _count; private readonly ThreadInt64PersistentCounter _counter; public uint Count => _count; public ThreadLocalNode(ThreadInt64PersistentCounter counter) { _counter = counter; } public void Dispose() { ThreadInt64PersistentCounter counter = _counter; s_lock.Acquire(); try { counter._overflowCount += _count; counter._nodes.Remove(this); } finally { s_lock.Release(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Increment() { uint num = _count + 1; if (num != 0) { _count = num; } else { OnIncrementOverflow(); } } [MethodImpl(MethodImplOptions.NoInlining)] private void OnIncrementOverflow() { ThreadInt64PersistentCounter counter = _counter; s_lock.Acquire(); try { _count = 0u; counter._overflowCount += 4294967296L; } finally { s_lock.Release(); } } } private sealed class ThreadLocalNodeFinalizationHelper { private readonly ThreadLocalNode _node; public ThreadLocalNodeFinalizationHelper(ThreadLocalNode node) { _node = node; } ~ThreadLocalNodeFinalizationHelper() { _node.Dispose(); } } private static readonly LowLevelLock s_lock = new LowLevelLock(); [ThreadStatic] private static List t_nodeFinalizationHelpers; private long _overflowCount; private HashSet _nodes = new HashSet(); public long Count { get { s_lock.Acquire(); long num = _overflowCount; try { foreach (ThreadLocalNode node in _nodes) { num += node.Count; } } catch (OutOfMemoryException) { } finally { s_lock.Release(); } return num; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Increment(object threadLocalCountObject) { Unsafe.As(threadLocalCountObject).Increment(); } public object CreateThreadLocalCountObject() { ThreadLocalNode threadLocalNode = new ThreadLocalNode(this); List list = t_nodeFinalizationHelpers ?? (t_nodeFinalizationHelpers = new List(1)); list.Add(new ThreadLocalNodeFinalizationHelper(threadLocalNode)); s_lock.Acquire(); try { _nodes.Add(threadLocalNode); return threadLocalNode; } finally { s_lock.Release(); } } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ThreadInterruptedException : SystemException { public ThreadInterruptedException() : base(Exception.GetMessageFromNativeResources(ExceptionMessageKind.ThreadInterrupted)) { base.HResult = -2146233063; } public ThreadInterruptedException(string? message) : base(message) { base.HResult = -2146233063; } public ThreadInterruptedException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233063; } protected ThreadInterruptedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [DebuggerTypeProxy(typeof(SystemThreading_ThreadLocalDebugView<>))] [DebuggerDisplay("IsValueCreated={IsValueCreated}, Value={ValueForDebugDisplay}, Count={ValuesCountForDebugDisplay}")] public class ThreadLocal : IDisposable { private struct LinkedSlotVolatile { internal volatile LinkedSlot Value; } private sealed class LinkedSlot { internal volatile LinkedSlot _next; internal volatile LinkedSlot _previous; internal volatile LinkedSlotVolatile[] _slotArray; internal T _value; internal LinkedSlot(LinkedSlotVolatile[] slotArray) { _slotArray = slotArray; } } private sealed class IdManager { private int _nextIdToTry; private volatile int _idsThatDoNotTrackAllValues; private readonly List _ids = new List(); internal int IdsThatDoNotTrackValuesCount => _idsThatDoNotTrackAllValues; internal int GetId(bool trackAllValues) { lock (_ids) { int i; for (i = _nextIdToTry; i < _ids.Count && _ids[i] != 0; i++) { } byte b = (byte)(trackAllValues ? 1 : 2); if (i == _ids.Count) { _ids.Add(b); } else { _ids[i] = b; } if (!trackAllValues) { _idsThatDoNotTrackAllValues++; } _nextIdToTry = i + 1; return i; } } internal bool IdTracksAllValues(int id) { lock (_ids) { return _ids[id] == 1; } } internal void ReturnId(int id, bool idTracksAllValues) { lock (_ids) { if (!idTracksAllValues) { _idsThatDoNotTrackAllValues--; } _ids[id] = 0; if (id < _nextIdToTry) { _nextIdToTry = id; } } } } private sealed class FinalizationHelper { internal LinkedSlotVolatile[] SlotArray; internal FinalizationHelper(LinkedSlotVolatile[] slotArray) { SlotArray = slotArray; } ~FinalizationHelper() { LinkedSlotVolatile[] slotArray = SlotArray; int num = ThreadLocal.s_idManager.IdsThatDoNotTrackValuesCount; int i = 0; for (; i < slotArray.Length; i++) { LinkedSlot value = slotArray[i].Value; if (value == null) { continue; } if (num == 0 || ThreadLocal.s_idManager.IdTracksAllValues(i)) { value._slotArray = null; continue; } lock (ThreadLocal.s_idManager) { if (slotArray[i].Value != null) { num--; } if (value._next != null) { value._next._previous = value._previous; } value._previous._next = value._next; } } } } private Func _valueFactory; [ThreadStatic] private static LinkedSlotVolatile[] ts_slotArray; [ThreadStatic] private static FinalizationHelper ts_finalizationHelper; private int _idComplement; private volatile bool _initialized; private static readonly IdManager s_idManager = new IdManager(); private LinkedSlot _linkedSlot = new LinkedSlot(null); private bool _trackAllValues; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Value { [return: MaybeNull] get { LinkedSlotVolatile[] array = ts_slotArray; int num = ~_idComplement; LinkedSlot value; if (array != null && num >= 0 && num < array.Length && (value = array[num].Value) != null && _initialized) { return value._value; } return GetValueSlow(); } set { LinkedSlotVolatile[] array = ts_slotArray; int num = ~_idComplement; LinkedSlot value2; if (array != null && num >= 0 && num < array.Length && (value2 = array[num].Value) != null && _initialized) { value2._value = value; } else { SetValueSlow(value, array); } } } public IList Values { get { if (!_trackAllValues) { throw new InvalidOperationException(SR.ThreadLocal_ValuesNotAvailable); } List valuesAsList = GetValuesAsList(); if (valuesAsList == null) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } return valuesAsList; } } private int ValuesCountForDebugDisplay { get { int num = 0; LinkedSlot linkedSlot = _linkedSlot; for (LinkedSlot linkedSlot2 = ((linkedSlot != null) ? linkedSlot._next : null); linkedSlot2 != null; linkedSlot2 = linkedSlot2._next) { num++; } return num; } } public bool IsValueCreated { get { int num = ~_idComplement; if (num < 0) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } LinkedSlotVolatile[] array = ts_slotArray; if (array != null && num < array.Length) { return array[num].Value != null; } return false; } } internal T? ValueForDebugDisplay { get { LinkedSlotVolatile[] array = ts_slotArray; int num = ~_idComplement; LinkedSlot value; if (array == null || num >= array.Length || (value = array[num].Value) == null || !_initialized) { return default(T); } return value._value; } } internal List? ValuesForDebugDisplay => GetValuesAsList(); public ThreadLocal() { Initialize(null, trackAllValues: false); } public ThreadLocal(bool trackAllValues) { Initialize(null, trackAllValues); } public ThreadLocal(Func valueFactory) { if (valueFactory == null) { throw new ArgumentNullException("valueFactory"); } Initialize(valueFactory, trackAllValues: false); } public ThreadLocal(Func valueFactory, bool trackAllValues) { if (valueFactory == null) { throw new ArgumentNullException("valueFactory"); } Initialize(valueFactory, trackAllValues); } private void Initialize(Func valueFactory, bool trackAllValues) { _valueFactory = valueFactory; _trackAllValues = trackAllValues; _idComplement = ~s_idManager.GetId(trackAllValues); _initialized = true; } ~ThreadLocal() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { int num; lock (s_idManager) { num = ~_idComplement; _idComplement = 0; if (num < 0 || !_initialized) { return; } _initialized = false; for (LinkedSlot next = _linkedSlot._next; next != null; next = next._next) { LinkedSlotVolatile[] slotArray = next._slotArray; if (slotArray != null) { next._slotArray = null; slotArray[num].Value._value = default(T); slotArray[num].Value = null; } } } _linkedSlot = null; s_idManager.ReturnId(num, _trackAllValues); } public override string? ToString() { return Value.ToString(); } private T GetValueSlow() { int num = ~_idComplement; if (num < 0) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } Debugger.NotifyOfCrossThreadDependency(); T val; if (_valueFactory == null) { val = default(T); } else { val = _valueFactory(); if (IsValueCreated) { throw new InvalidOperationException(SR.ThreadLocal_Value_RecursiveCallsToValue); } } Value = val; return val; } private void SetValueSlow(T value, LinkedSlotVolatile[] slotArray) { int num = ~_idComplement; if (num < 0) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } if (slotArray == null) { slotArray = new LinkedSlotVolatile[GetNewTableSize(num + 1)]; ts_finalizationHelper = new FinalizationHelper(slotArray); ts_slotArray = slotArray; } if (num >= slotArray.Length) { GrowTable(ref slotArray, num + 1); ts_finalizationHelper.SlotArray = slotArray; ts_slotArray = slotArray; } if (slotArray[num].Value == null) { CreateLinkedSlot(slotArray, num, value); return; } LinkedSlot value2 = slotArray[num].Value; if (!_initialized) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } value2._value = value; } private void CreateLinkedSlot(LinkedSlotVolatile[] slotArray, int id, T value) { LinkedSlot linkedSlot = new LinkedSlot(slotArray); lock (s_idManager) { if (!_initialized) { throw new ObjectDisposedException(SR.ThreadLocal_Disposed); } LinkedSlot linkedSlot2 = (linkedSlot._next = _linkedSlot._next); linkedSlot._previous = _linkedSlot; linkedSlot._value = value; if (linkedSlot2 != null) { linkedSlot2._previous = linkedSlot; } _linkedSlot._next = linkedSlot; slotArray[id].Value = linkedSlot; } } private List GetValuesAsList() { LinkedSlot linkedSlot = _linkedSlot; int num = ~_idComplement; if (num == -1 || linkedSlot == null) { return null; } List list = new List(); for (linkedSlot = linkedSlot._next; linkedSlot != null; linkedSlot = linkedSlot._next) { list.Add(linkedSlot._value); } return list; } private static void GrowTable(ref LinkedSlotVolatile[] table, int minLength) { int newTableSize = GetNewTableSize(minLength); LinkedSlotVolatile[] array = new LinkedSlotVolatile[newTableSize]; lock (s_idManager) { for (int i = 0; i < table.Length; i++) { LinkedSlot value = table[i].Value; if (value != null && value._slotArray != null) { value._slotArray = array; array[i] = table[i]; } } } table = array; } private static int GetNewTableSize(int minSize) { if ((uint)minSize > Array.MaxLength) { return int.MaxValue; } int num = minSize; num--; num |= num >> 1; num |= num >> 2; num |= num >> 4; num |= num >> 8; num |= num >> 16; num++; if ((uint)num > Array.MaxLength) { num = Array.MaxLength; } return num; } } internal sealed class SystemThreading_ThreadLocalDebugView { private readonly ThreadLocal _tlocal; public bool IsValueCreated => _tlocal.IsValueCreated; public T Value => _tlocal.ValueForDebugDisplay; public List Values => _tlocal.ValuesForDebugDisplay; public SystemThreading_ThreadLocalDebugView(ThreadLocal tlocal) { _tlocal = tlocal; } } internal sealed class ThreadPoolWorkQueue { internal static class WorkStealingQueueList { private static volatile WorkStealingQueue[] _queues = new WorkStealingQueue[0]; public static WorkStealingQueue[] Queues => _queues; public static void Add(WorkStealingQueue queue) { WorkStealingQueue[] queues; WorkStealingQueue[] array; do { queues = _queues; array = new WorkStealingQueue[queues.Length + 1]; Array.Copy(queues, array, queues.Length); array[^1] = queue; } while (Interlocked.CompareExchange(ref _queues, array, queues) != queues); } public static void Remove(WorkStealingQueue queue) { WorkStealingQueue[] queues; WorkStealingQueue[] array; do { queues = _queues; if (queues.Length == 0) { break; } int num = Array.IndexOf(queues, queue); if (num == -1) { break; } array = new WorkStealingQueue[queues.Length - 1]; if (num == 0) { Array.Copy(queues, 1, array, 0, array.Length); continue; } if (num == queues.Length - 1) { Array.Copy(queues, array, array.Length); continue; } Array.Copy(queues, array, num); Array.Copy(queues, num + 1, array, num, array.Length - num); } while (Interlocked.CompareExchange(ref _queues, array, queues) != queues); } } internal sealed class WorkStealingQueue { internal volatile object[] m_array = new object[32]; private volatile int m_mask = 31; private volatile int m_headIndex; private volatile int m_tailIndex; private SpinLock m_foreignLock = new SpinLock(enableThreadOwnerTracking: false); public bool CanSteal => m_headIndex < m_tailIndex; public int Count { get { bool lockTaken = false; try { m_foreignLock.Enter(ref lockTaken); return Math.Max(0, m_tailIndex - m_headIndex); } finally { if (lockTaken) { m_foreignLock.Exit(useMemoryBarrier: false); } } } } public void LocalPush(object obj) { int num = m_tailIndex; if (num == int.MaxValue) { num = LocalPush_HandleTailOverflow(); } if (num < m_headIndex + m_mask) { Volatile.Write(ref m_array[num & m_mask], obj); m_tailIndex = num + 1; return; } bool lockTaken = false; try { m_foreignLock.Enter(ref lockTaken); int headIndex = m_headIndex; int num2 = m_tailIndex - m_headIndex; if (num2 >= m_mask) { object[] array = new object[m_array.Length << 1]; for (int i = 0; i < m_array.Length; i++) { array[i] = m_array[(i + headIndex) & m_mask]; } m_array = array; m_headIndex = 0; num = (m_tailIndex = num2); m_mask = (m_mask << 1) | 1; } Volatile.Write(ref m_array[num & m_mask], obj); m_tailIndex = num + 1; } finally { if (lockTaken) { m_foreignLock.Exit(useMemoryBarrier: false); } } } [MethodImpl(MethodImplOptions.NoInlining)] private int LocalPush_HandleTailOverflow() { bool lockTaken = false; try { m_foreignLock.Enter(ref lockTaken); int num = m_tailIndex; if (num == int.MaxValue) { m_headIndex &= m_mask; num = (m_tailIndex &= m_mask); } return num; } finally { if (lockTaken) { m_foreignLock.Exit(useMemoryBarrier: true); } } } public bool LocalFindAndPop(object obj) { if (m_array[(m_tailIndex - 1) & m_mask] == obj) { object obj2 = LocalPop(); return obj2 != null; } for (int num = m_tailIndex - 2; num >= m_headIndex; num--) { if (m_array[num & m_mask] == obj) { bool lockTaken = false; try { m_foreignLock.Enter(ref lockTaken); if (m_array[num & m_mask] == null) { return false; } Volatile.Write(ref m_array[num & m_mask], null); if (num == m_tailIndex) { m_tailIndex--; } else if (num == m_headIndex) { m_headIndex++; } return true; } finally { if (lockTaken) { m_foreignLock.Exit(useMemoryBarrier: false); } } } } return false; } public object LocalPop() { if (m_headIndex >= m_tailIndex) { return null; } return LocalPopCore(); } private object LocalPopCore() { int num; object obj; while (true) { int tailIndex = m_tailIndex; if (m_headIndex >= tailIndex) { return null; } tailIndex--; Interlocked.Exchange(ref m_tailIndex, tailIndex); if (m_headIndex <= tailIndex) { num = tailIndex & m_mask; obj = Volatile.Read(ref m_array[num]); if (obj != null) { break; } continue; } bool lockTaken = false; try { m_foreignLock.Enter(ref lockTaken); if (m_headIndex <= tailIndex) { int num2 = tailIndex & m_mask; object obj2 = Volatile.Read(ref m_array[num2]); if (obj2 != null) { m_array[num2] = null; return obj2; } continue; } m_tailIndex = tailIndex + 1; return null; } finally { if (lockTaken) { m_foreignLock.Exit(useMemoryBarrier: false); } } } m_array[num] = null; return obj; } public object TrySteal(ref bool missedSteal) { while (CanSteal) { bool lockTaken = false; try { m_foreignLock.TryEnter(ref lockTaken); if (lockTaken) { int headIndex = m_headIndex; Interlocked.Exchange(ref m_headIndex, headIndex + 1); if (headIndex < m_tailIndex) { int num = headIndex & m_mask; object obj = Volatile.Read(ref m_array[num]); if (obj == null) { continue; } m_array[num] = null; return obj; } m_headIndex = headIndex; } } finally { if (lockTaken) { m_foreignLock.Exit(useMemoryBarrier: false); } } missedSteal = true; break; } return null; } } private struct CacheLineSeparated { private readonly PaddingFor32 pad1; public volatile int numOutstandingThreadRequests; private readonly PaddingFor32 pad2; } internal bool loggingEnabled; private bool _dispatchTimeSensitiveWorkFirst; internal readonly ConcurrentQueue workItems = new ConcurrentQueue(); internal readonly ConcurrentQueue timeSensitiveWorkQueue = (ThreadPool.SupportsTimeSensitiveWorkItems ? new ConcurrentQueue() : null); private CacheLineSeparated _separated; public static long LocalCount { get { long num = 0L; WorkStealingQueue[] queues = WorkStealingQueueList.Queues; foreach (WorkStealingQueue workStealingQueue in queues) { num += workStealingQueue.Count; } return num; } } public long GlobalCount => (ThreadPool.SupportsTimeSensitiveWorkItems ? timeSensitiveWorkQueue.Count : 0) + workItems.Count; public ThreadPoolWorkQueue() { RefreshLoggingEnabled(); } public ThreadPoolWorkQueueThreadLocals GetOrCreateThreadLocals() { return ThreadPoolWorkQueueThreadLocals.threadLocals ?? CreateThreadLocals(); } [MethodImpl(MethodImplOptions.NoInlining)] private ThreadPoolWorkQueueThreadLocals CreateThreadLocals() { return ThreadPoolWorkQueueThreadLocals.threadLocals = new ThreadPoolWorkQueueThreadLocals(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void RefreshLoggingEnabled() { if (!FrameworkEventSource.Log.IsEnabled()) { if (loggingEnabled) { loggingEnabled = false; } } else { RefreshLoggingEnabledFull(); } } [MethodImpl(MethodImplOptions.NoInlining)] public void RefreshLoggingEnabledFull() { loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, (EventKeywords)18L); } internal void EnsureThreadRequested() { int num = _separated.numOutstandingThreadRequests; while (num < Environment.ProcessorCount) { int num2 = Interlocked.CompareExchange(ref _separated.numOutstandingThreadRequests, num + 1, num); if (num2 == num) { ThreadPool.RequestWorkerThread(); break; } num = num2; } } internal void MarkThreadRequestSatisfied() { int num = _separated.numOutstandingThreadRequests; while (num > 0) { int num2 = Interlocked.CompareExchange(ref _separated.numOutstandingThreadRequests, num - 1, num); if (num2 != num) { num = num2; continue; } break; } } public void EnqueueTimeSensitiveWorkItem(IThreadPoolWorkItem timeSensitiveWorkItem) { if (loggingEnabled && FrameworkEventSource.Log.IsEnabled()) { FrameworkEventSource.Log.ThreadPoolEnqueueWorkObject(timeSensitiveWorkItem); } timeSensitiveWorkQueue.Enqueue(timeSensitiveWorkItem); EnsureThreadRequested(); } [MethodImpl(MethodImplOptions.NoInlining)] public IThreadPoolWorkItem TryDequeueTimeSensitiveWorkItem() { IThreadPoolWorkItem result; bool flag = timeSensitiveWorkQueue.TryDequeue(out result); return result; } public void Enqueue(object callback, bool forceGlobal) { if (loggingEnabled && FrameworkEventSource.Log.IsEnabled()) { FrameworkEventSource.Log.ThreadPoolEnqueueWorkObject(callback); } ThreadPoolWorkQueueThreadLocals threadPoolWorkQueueThreadLocals = null; if (!forceGlobal) { threadPoolWorkQueueThreadLocals = ThreadPoolWorkQueueThreadLocals.threadLocals; } if (threadPoolWorkQueueThreadLocals != null) { threadPoolWorkQueueThreadLocals.workStealingQueue.LocalPush(callback); } else { workItems.Enqueue(callback); } EnsureThreadRequested(); } internal static bool LocalFindAndPop(object callback) { return ThreadPoolWorkQueueThreadLocals.threadLocals?.workStealingQueue.LocalFindAndPop(callback) ?? false; } public object Dequeue(ThreadPoolWorkQueueThreadLocals tl, ref bool missedSteal) { WorkStealingQueue workStealingQueue = tl.workStealingQueue; object result; if ((result = workStealingQueue.LocalPop()) == null && !workItems.TryDequeue(out result)) { WorkStealingQueue[] queues = WorkStealingQueueList.Queues; int num = queues.Length; int num2 = num - 1; uint num3 = tl.random.NextUInt32() % (uint)num; while (num > 0) { num3 = ((num3 < num2) ? (num3 + 1) : 0u); WorkStealingQueue workStealingQueue2 = queues[num3]; if (workStealingQueue2 != workStealingQueue && workStealingQueue2.CanSteal) { result = workStealingQueue2.TrySteal(ref missedSteal); if (result != null) { return result; } } num--; } if (ThreadPool.SupportsTimeSensitiveWorkItems) { result = TryDequeueTimeSensitiveWorkItem(); } } return result; } internal static bool Dispatch() { ThreadPoolWorkQueue s_workQueue = ThreadPool.s_workQueue; s_workQueue.MarkThreadRequestSatisfied(); s_workQueue.RefreshLoggingEnabled(); bool flag = true; try { ThreadPoolWorkQueue threadPoolWorkQueue = s_workQueue; ThreadPoolWorkQueueThreadLocals orCreateThreadLocals = threadPoolWorkQueue.GetOrCreateThreadLocals(); object threadLocalCompletionCountObject = orCreateThreadLocals.threadLocalCompletionCountObject; Thread currentThread = orCreateThreadLocals.currentThread; currentThread._executionContext = null; currentThread._synchronizationContext = null; int num = Environment.TickCount; object obj = null; if (ThreadPool.SupportsTimeSensitiveWorkItems) { bool dispatchTimeSensitiveWorkFirst = threadPoolWorkQueue._dispatchTimeSensitiveWorkFirst; threadPoolWorkQueue._dispatchTimeSensitiveWorkFirst = !dispatchTimeSensitiveWorkFirst; if (dispatchTimeSensitiveWorkFirst) { obj = threadPoolWorkQueue.TryDequeueTimeSensitiveWorkItem(); } } while (true) { if (obj == null) { bool missedSteal = false; obj = threadPoolWorkQueue.Dequeue(orCreateThreadLocals, ref missedSteal); if (obj == null) { flag = missedSteal; return true; } } if (threadPoolWorkQueue.loggingEnabled && FrameworkEventSource.Log.IsEnabled()) { FrameworkEventSource.Log.ThreadPoolDequeueWorkObject(obj); } threadPoolWorkQueue.EnsureThreadRequested(); if (ThreadPool.EnableWorkerTracking) { DispatchWorkItemWithWorkerTracking(obj, currentThread); } else { DispatchWorkItem(obj, currentThread); } obj = null; ExecutionContext.ResetThreadPoolThread(currentThread); currentThread.ResetThreadPoolThread(); int tickCount = Environment.TickCount; if (!ThreadPool.NotifyWorkItemComplete(threadLocalCompletionCountObject, tickCount)) { orCreateThreadLocals.TransferLocalWork(); return false; } if ((uint)(tickCount - num) >= 30u) { if (!ThreadPool.SupportsTimeSensitiveWorkItems) { break; } num = tickCount; threadPoolWorkQueue.RefreshLoggingEnabled(); obj = threadPoolWorkQueue.TryDequeueTimeSensitiveWorkItem(); } } return true; } finally { if (flag) { s_workQueue.EnsureThreadRequested(); } } } [MethodImpl(MethodImplOptions.NoInlining)] private static void DispatchWorkItemWithWorkerTracking(object workItem, Thread currentThread) { bool flag = false; try { ThreadPool.ReportThreadStatus(isWorking: true); flag = true; DispatchWorkItem(workItem, currentThread); } finally { if (flag) { ThreadPool.ReportThreadStatus(isWorking: false); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void DispatchWorkItem(object workItem, Thread currentThread) { if (workItem is Task task) { task.ExecuteFromThreadPool(currentThread); } else { Unsafe.As(workItem).Execute(); } } } internal sealed class ThreadPoolWorkQueueThreadLocals { [ThreadStatic] public static ThreadPoolWorkQueueThreadLocals threadLocals; public readonly ThreadPoolWorkQueue workQueue; public readonly ThreadPoolWorkQueue.WorkStealingQueue workStealingQueue; public readonly Thread currentThread; public readonly object threadLocalCompletionCountObject; public readonly Random.XoshiroImpl random = new Random.XoshiroImpl(); public ThreadPoolWorkQueueThreadLocals(ThreadPoolWorkQueue tpq) { workQueue = tpq; workStealingQueue = new ThreadPoolWorkQueue.WorkStealingQueue(); ThreadPoolWorkQueue.WorkStealingQueueList.Add(workStealingQueue); currentThread = Thread.CurrentThread; threadLocalCompletionCountObject = ThreadPool.GetOrCreateThreadLocalCompletionCountObject(); } public void TransferLocalWork() { while (true) { object obj = workStealingQueue.LocalPop(); if (obj != null) { workQueue.Enqueue(obj, forceGlobal: true); continue; } break; } } ~ThreadPoolWorkQueueThreadLocals() { if (workStealingQueue != null) { TransferLocalWork(); ThreadPoolWorkQueue.WorkStealingQueueList.Remove(workStealingQueue); } } } public delegate void WaitCallback(object? state); public delegate void WaitOrTimerCallback(object? state, bool timedOut); internal abstract class QueueUserWorkItemCallbackBase : IThreadPoolWorkItem { public virtual void Execute() { } } internal sealed class QueueUserWorkItemCallback : QueueUserWorkItemCallbackBase { private WaitCallback _callback; private readonly object _state; private readonly ExecutionContext _context; private static readonly Action s_executionContextShim = delegate(QueueUserWorkItemCallback quwi) { WaitCallback callback = quwi._callback; quwi._callback = null; callback(quwi._state); }; internal QueueUserWorkItemCallback(WaitCallback callback, object state, ExecutionContext context) { _callback = callback; _state = state; _context = context; } public override void Execute() { base.Execute(); ExecutionContext.RunForThreadPoolUnsafe(_context, s_executionContextShim, in this); } } internal sealed class QueueUserWorkItemCallback : QueueUserWorkItemCallbackBase { private Action _callback; private readonly TState _state; private readonly ExecutionContext _context; internal QueueUserWorkItemCallback(Action callback, TState state, ExecutionContext context) { _callback = callback; _state = state; _context = context; } public override void Execute() { base.Execute(); Action callback = _callback; _callback = null; ExecutionContext.RunForThreadPoolUnsafe(_context, callback, in _state); } } internal sealed class QueueUserWorkItemCallbackDefaultContext : QueueUserWorkItemCallbackBase { private WaitCallback _callback; private readonly object _state; internal QueueUserWorkItemCallbackDefaultContext(WaitCallback callback, object state) { _callback = callback; _state = state; } public override void Execute() { base.Execute(); WaitCallback callback = _callback; _callback = null; callback(_state); } } internal sealed class QueueUserWorkItemCallbackDefaultContext : QueueUserWorkItemCallbackBase { private Action _callback; private readonly TState _state; internal QueueUserWorkItemCallbackDefaultContext(Action callback, TState state) { _callback = callback; _state = state; } public override void Execute() { base.Execute(); Action callback = _callback; _callback = null; callback(_state); } } internal sealed class _ThreadPoolWaitOrTimerCallback { private readonly WaitOrTimerCallback _waitOrTimerCallback; private readonly ExecutionContext _executionContext; private readonly object _state; private static readonly ContextCallback _ccbt = WaitOrTimerCallback_Context_t; private static readonly ContextCallback _ccbf = WaitOrTimerCallback_Context_f; internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, object state, bool flowExecutionContext) { _waitOrTimerCallback = waitOrTimerCallback; _state = state; if (flowExecutionContext) { _executionContext = ExecutionContext.Capture(); } } private static void WaitOrTimerCallback_Context_t(object state) { WaitOrTimerCallback_Context(state, timedOut: true); } private static void WaitOrTimerCallback_Context_f(object state) { WaitOrTimerCallback_Context(state, timedOut: false); } private static void WaitOrTimerCallback_Context(object state, bool timedOut) { _ThreadPoolWaitOrTimerCallback threadPoolWaitOrTimerCallback = (_ThreadPoolWaitOrTimerCallback)state; threadPoolWaitOrTimerCallback._waitOrTimerCallback(threadPoolWaitOrTimerCallback._state, timedOut); } internal static void PerformWaitOrTimerCallback(_ThreadPoolWaitOrTimerCallback helper, bool timedOut) { ExecutionContext executionContext = helper._executionContext; if (executionContext == null) { WaitOrTimerCallback waitOrTimerCallback = helper._waitOrTimerCallback; waitOrTimerCallback(helper._state, timedOut); } else { ExecutionContext.Run(executionContext, timedOut ? _ccbt : _ccbf, helper); } } } public enum ThreadPriority { Lowest, BelowNormal, Normal, AboveNormal, Highest } public delegate void ThreadStart(); [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class ThreadStartException : SystemException { internal ThreadStartException() : base(SR.Arg_ThreadStartException) { base.HResult = -2146233051; } internal ThreadStartException(Exception reason) : base(SR.Arg_ThreadStartException, reason) { base.HResult = -2146233051; } private ThreadStartException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Flags] public enum ThreadState { Running = 0, StopRequested = 1, SuspendRequested = 2, Background = 4, Unstarted = 8, Stopped = 0x10, WaitSleepJoin = 0x20, Suspended = 0x40, AbortRequested = 0x80, Aborted = 0x100 } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ThreadStateException : SystemException { public ThreadStateException() : base(SR.Arg_ThreadStateException) { base.HResult = -2146233056; } public ThreadStateException(string? message) : base(message) { base.HResult = -2146233056; } public ThreadStateException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233056; } protected ThreadStateException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public static class Timeout { public static readonly TimeSpan InfiniteTimeSpan = new TimeSpan(0, 0, 0, 0, -1); public const int Infinite = -1; } internal static class TimeoutHelper { public static uint GetTime() { return (uint)Environment.TickCount; } public static int UpdateTimeOut(uint startTime, int originalWaitMillisecondsTimeout) { uint num = GetTime() - startTime; if (num > int.MaxValue) { return 0; } int num2 = originalWaitMillisecondsTimeout - (int)num; if (num2 <= 0) { return 0; } return num2; } } public sealed class PeriodicTimer : IDisposable { private sealed class State : IValueTaskSource { private PeriodicTimer _owner; private ManualResetValueTaskSourceCore _mrvtsc; private CancellationTokenRegistration _ctr; private bool _stopped; private bool _signaled; private bool _activeWait; public ValueTask WaitForNextTickAsync(PeriodicTimer owner, CancellationToken cancellationToken) { lock (this) { if (_activeWait) { ThrowHelper.ThrowInvalidOperationException(); } if (cancellationToken.IsCancellationRequested) { return ValueTask.FromCanceled(cancellationToken); } if (_signaled) { if (!_stopped) { _signaled = false; } return new ValueTask(!_stopped); } _owner = owner; _activeWait = true; _ctr = cancellationToken.UnsafeRegister(delegate(object state, CancellationToken cancellationToken) { ((State)state).Signal(stopping: false, cancellationToken); }, this); return new ValueTask(this, _mrvtsc.Version); } } public void Signal(bool stopping = false, CancellationToken cancellationToken = default(CancellationToken)) { bool flag = false; lock (this) { _stopped |= stopping; if (!_signaled) { _signaled = true; flag = _activeWait; } } if (flag) { if (cancellationToken.IsCancellationRequested) { _mrvtsc.SetException(ExceptionDispatchInfo.SetCurrentStackTrace(new OperationCanceledException(cancellationToken))); } else { _mrvtsc.SetResult(result: true); } } } bool IValueTaskSource.GetResult(short token) { _ctr.Dispose(); lock (this) { try { _mrvtsc.GetResult(token); } finally { _mrvtsc.Reset(); _ctr = default(CancellationTokenRegistration); _activeWait = false; _owner = null; if (!_stopped) { _signaled = false; } } return !_stopped; } } ValueTaskSourceStatus IValueTaskSource.GetStatus(short token) { return _mrvtsc.GetStatus(token); } void IValueTaskSource.OnCompleted(Action continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { _mrvtsc.OnCompleted(continuation, state, token, flags); } } private readonly TimerQueueTimer _timer; private readonly State _state; public PeriodicTimer(TimeSpan period) { long num = (long)period.TotalMilliseconds; if (num < 1 || num > 4294967294u) { GC.SuppressFinalize(this); throw new ArgumentOutOfRangeException("period"); } _state = new State(); _timer = new TimerQueueTimer(delegate(object s) { ((State)s).Signal(); }, _state, (uint)num, (uint)num, flowExecutionContext: false); } public ValueTask WaitForNextTickAsync(CancellationToken cancellationToken = default(CancellationToken)) { return _state.WaitForNextTickAsync(this, cancellationToken); } public void Dispose() { GC.SuppressFinalize(this); _timer.Close(); _state.Signal(stopping: true); } ~PeriodicTimer() { Dispose(); } } public delegate void TimerCallback(object? state); [DebuggerDisplay("{DisplayString,nq}")] [DebuggerTypeProxy(typeof(TimerDebuggerTypeProxy))] internal sealed class TimerQueueTimer : IThreadPoolWorkItem { internal sealed class TimerDebuggerTypeProxy { private readonly TimerQueueTimer _timer; public DateTime? EstimatedNextTimeUtc { get { if (_timer._dueTime != uint.MaxValue) { long num = _timer._startTicks - TimerQueue.s_tickCountToTimeMap.TickCount + _timer._dueTime; return TimerQueue.s_tickCountToTimeMap.Time + TimeSpan.FromMilliseconds(num); } return null; } } public TimeSpan? DueTime { get { if (_timer._dueTime != uint.MaxValue) { return TimeSpan.FromMilliseconds(_timer._dueTime); } return null; } } public TimeSpan? Period { get { if (_timer._period != uint.MaxValue) { return TimeSpan.FromMilliseconds(_timer._period); } return null; } } public TimerCallback Callback => _timer._timerCallback; public object State => _timer._state; public TimerDebuggerTypeProxy(Timer timer) { _timer = timer._timer._timer; } public TimerDebuggerTypeProxy(TimerQueueTimer timer) { _timer = timer; } } private readonly TimerQueue _associatedTimerQueue; internal TimerQueueTimer _next; internal TimerQueueTimer _prev; internal bool _short; internal long _startTicks; internal uint _dueTime; internal uint _period; private readonly TimerCallback _timerCallback; private readonly object _state; private readonly ExecutionContext _executionContext; private int _callbacksRunning; private bool _canceled; internal bool _everQueued; private object _notifyWhenNoCallbacksRunning; private static readonly ContextCallback s_callCallbackInContext = delegate(object state) { TimerQueueTimer timerQueueTimer = (TimerQueueTimer)state; timerQueueTimer._timerCallback(timerQueueTimer._state); }; internal string DisplayString { get { string text = _timerCallback.Method.DeclaringType?.FullName; if (text != null) { text += "."; } return "DueTime = " + ((_dueTime == uint.MaxValue) ? "(not set)" : ((object)TimeSpan.FromMilliseconds(_dueTime)))?.ToString() + ", Period = " + ((_period == uint.MaxValue) ? "(not set)" : ((object)TimeSpan.FromMilliseconds(_period)))?.ToString() + ", " + text + _timerCallback.Method.Name + "(" + (_state?.ToString() ?? "null") + ")"; } } internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period, bool flowExecutionContext) { _timerCallback = timerCallback; _state = state; _dueTime = uint.MaxValue; _period = uint.MaxValue; if (flowExecutionContext) { _executionContext = ExecutionContext.Capture(); } _associatedTimerQueue = TimerQueue.Instances[Thread.GetCurrentProcessorId() % TimerQueue.Instances.Length]; if (dueTime != uint.MaxValue) { Change(dueTime, period); } } internal bool Change(uint dueTime, uint period) { lock (_associatedTimerQueue) { if (_canceled) { throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic); } _period = period; if (dueTime == uint.MaxValue) { _associatedTimerQueue.DeleteTimer(this); return true; } if (FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, (EventKeywords)16L)) { FrameworkEventSource.Log.ThreadTransferSendObj(this, 1, string.Empty, multiDequeues: true, (int)dueTime, (int)period); } return _associatedTimerQueue.UpdateTimer(this, dueTime, period); } } public void Close() { lock (_associatedTimerQueue) { if (!_canceled) { _canceled = true; _associatedTimerQueue.DeleteTimer(this); } } } public bool Close(WaitHandle toSignal) { bool flag = false; bool result; lock (_associatedTimerQueue) { if (_canceled) { result = false; } else { _canceled = true; _notifyWhenNoCallbacksRunning = toSignal; _associatedTimerQueue.DeleteTimer(this); flag = _callbacksRunning == 0; result = true; } } if (flag) { SignalNoCallbacksRunning(); } return result; } public ValueTask CloseAsync() { lock (_associatedTimerQueue) { object notifyWhenNoCallbacksRunning = _notifyWhenNoCallbacksRunning; if (_canceled) { if (notifyWhenNoCallbacksRunning is WaitHandle) { InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_TimerAlreadyClosed); ex.SetCurrentStackTrace(); return ValueTask.FromException(ex); } } else { _canceled = true; _associatedTimerQueue.DeleteTimer(this); } if (_callbacksRunning == 0) { return default(ValueTask); } if (notifyWhenNoCallbacksRunning == null) { return new ValueTask((Task)(_notifyWhenNoCallbacksRunning = new Task(null, TaskCreationOptions.RunContinuationsAsynchronously, promiseStyle: true))); } return new ValueTask((Task)notifyWhenNoCallbacksRunning); } } void IThreadPoolWorkItem.Execute() { Fire(isThreadPool: true); } internal void Fire(bool isThreadPool = false) { bool flag = false; lock (_associatedTimerQueue) { flag = _canceled; if (!flag) { _callbacksRunning++; } } if (!flag) { CallCallback(isThreadPool); bool flag2; lock (_associatedTimerQueue) { _callbacksRunning--; flag2 = _canceled && _callbacksRunning == 0 && _notifyWhenNoCallbacksRunning != null; } if (flag2) { SignalNoCallbacksRunning(); } } } internal void SignalNoCallbacksRunning() { object notifyWhenNoCallbacksRunning = _notifyWhenNoCallbacksRunning; if (notifyWhenNoCallbacksRunning is WaitHandle waitHandle) { EventWaitHandle.Set(waitHandle.SafeWaitHandle); } else { ((Task)notifyWhenNoCallbacksRunning).TrySetResult(); } } internal void CallCallback(bool isThreadPool) { if (FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, (EventKeywords)16L)) { FrameworkEventSource.Log.ThreadTransferReceiveObj(this, 1, string.Empty); } ExecutionContext executionContext = _executionContext; if (executionContext == null) { _timerCallback(_state); } else if (isThreadPool) { ExecutionContext.RunFromThreadPoolDispatchLoop(Thread.CurrentThread, executionContext, s_callCallbackInContext, this); } else { ExecutionContext.RunInternal(executionContext, s_callCallbackInContext, this); } } } internal sealed class TimerHolder { internal readonly TimerQueueTimer _timer; public TimerHolder(TimerQueueTimer timer) { _timer = timer; } ~TimerHolder() { _timer.Close(); } public void Close() { _timer.Close(); GC.SuppressFinalize(this); } public bool Close(WaitHandle notifyObject) { bool result = _timer.Close(notifyObject); GC.SuppressFinalize(this); return result; } public ValueTask CloseAsync() { ValueTask result = _timer.CloseAsync(); GC.SuppressFinalize(this); return result; } } [DebuggerDisplay("{DisplayString,nq}")] [DebuggerTypeProxy(typeof(TimerQueueTimer.TimerDebuggerTypeProxy))] public sealed class Timer : MarshalByRefObject, IDisposable, IAsyncDisposable { internal TimerHolder _timer; public static long ActiveCount { get { long num = 0L; TimerQueue[] instances = TimerQueue.Instances; foreach (TimerQueue timerQueue in instances) { lock (timerQueue) { num += timerQueue.ActiveCount; } } return num; } } private string DisplayString => _timer._timer.DisplayString; private static IEnumerable AllTimers { get { List list = new List(); TimerQueue[] instances = TimerQueue.Instances; foreach (TimerQueue timerQueue in instances) { list.AddRange(timerQueue.GetTimersForDebugger()); } list.Sort((TimerQueueTimer t1, TimerQueueTimer t2) => t1._dueTime.CompareTo(t2._dueTime)); return list; } } public Timer(TimerCallback callback, object? state, int dueTime, int period) : this(callback, state, dueTime, period, flowExecutionContext: true) { } internal Timer(TimerCallback callback, object state, int dueTime, int period, bool flowExecutionContext) { if (dueTime < -1) { throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (period < -1) { throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } TimerSetup(callback, state, (uint)dueTime, (uint)period, flowExecutionContext); } public Timer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period) { long num = (long)dueTime.TotalMilliseconds; if (num < -1) { throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (num > 4294967294u) { throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_TimeoutTooLarge); } long num2 = (long)period.TotalMilliseconds; if (num2 < -1) { throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (num2 > 4294967294u) { throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_PeriodTooLarge); } TimerSetup(callback, state, (uint)num, (uint)num2); } [CLSCompliant(false)] public Timer(TimerCallback callback, object? state, uint dueTime, uint period) { TimerSetup(callback, state, dueTime, period); } public Timer(TimerCallback callback, object? state, long dueTime, long period) { if (dueTime < -1) { throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (period < -1) { throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (dueTime > 4294967294u) { throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_TimeoutTooLarge); } if (period > 4294967294u) { throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_PeriodTooLarge); } TimerSetup(callback, state, (uint)dueTime, (uint)period); } public Timer(TimerCallback callback) { TimerSetup(callback, this, uint.MaxValue, uint.MaxValue); } [MemberNotNull("_timer")] private void TimerSetup(TimerCallback callback, object state, uint dueTime, uint period, bool flowExecutionContext = true) { if (callback == null) { throw new ArgumentNullException("callback"); } _timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period, flowExecutionContext)); } public bool Change(int dueTime, int period) { if (dueTime < -1) { throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (period < -1) { throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } return _timer._timer.Change((uint)dueTime, (uint)period); } public bool Change(TimeSpan dueTime, TimeSpan period) { return Change((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds); } [CLSCompliant(false)] public bool Change(uint dueTime, uint period) { return _timer._timer.Change(dueTime, period); } public bool Change(long dueTime, long period) { if (dueTime < -1) { throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (period < -1) { throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_NeedNonNegOrNegative1); } if (dueTime > 4294967294u) { throw new ArgumentOutOfRangeException("dueTime", SR.ArgumentOutOfRange_TimeoutTooLarge); } if (period > 4294967294u) { throw new ArgumentOutOfRangeException("period", SR.ArgumentOutOfRange_PeriodTooLarge); } return _timer._timer.Change((uint)dueTime, (uint)period); } public bool Dispose(WaitHandle notifyObject) { if (notifyObject == null) { throw new ArgumentNullException("notifyObject"); } return _timer.Close(notifyObject); } public void Dispose() { _timer.Close(); } public ValueTask DisposeAsync() { return _timer.CloseAsync(); } } public static class Volatile { private struct VolatileBoolean { public volatile bool Value; } private struct VolatileByte { public volatile byte Value; } private struct VolatileInt16 { public volatile short Value; } private struct VolatileInt32 { public volatile int Value; } private struct VolatileIntPtr { public volatile IntPtr Value; } private struct VolatileSByte { public volatile sbyte Value; } private struct VolatileSingle { public volatile float Value; } private struct VolatileUInt16 { public volatile ushort Value; } private struct VolatileUInt32 { public volatile uint Value; } private struct VolatileUIntPtr { public volatile UIntPtr Value; } private struct VolatileObject { public volatile object Value; } [Intrinsic] [NonVersionable] public static bool Read(ref bool location) { return Unsafe.As(ref location).Value; } [Intrinsic] [NonVersionable] public static void Write(ref bool location, bool value) { Unsafe.As(ref location).Value = value; } [Intrinsic] [NonVersionable] public static byte Read(ref byte location) { return Unsafe.As(ref location).Value; } [Intrinsic] [NonVersionable] public static void Write(ref byte location, byte value) { Unsafe.As(ref location).Value = value; } [Intrinsic] [NonVersionable] public unsafe static double Read(ref double location) { long num = Read(ref Unsafe.As(ref location)); return *(double*)(&num); } [Intrinsic] [NonVersionable] public unsafe static void Write(ref double location, double value) { Write(ref Unsafe.As(ref location), *(long*)(&value)); } [Intrinsic] [NonVersionable] public static short Read(ref short location) { return Unsafe.As(ref location).Value; } [Intrinsic] [NonVersionable] public static void Write(ref short location, short value) { Unsafe.As(ref location).Value = value; } [Intrinsic] [NonVersionable] public static int Read(ref int location) { return Unsafe.As(ref location).Value; } [Intrinsic] [NonVersionable] public static void Write(ref int location, int value) { Unsafe.As(ref location).Value = value; } [Intrinsic] [NonVersionable] public static long Read(ref long location) { return Interlocked.CompareExchange(ref location, 0L, 0L); } [Intrinsic] [NonVersionable] public static void Write(ref long location, long value) { Interlocked.Exchange(ref location, value); } [Intrinsic] [NonVersionable] public static IntPtr Read(ref IntPtr location) { return Unsafe.As(ref location).Value; } [Intrinsic] [NonVersionable] public static void Write(ref IntPtr location, IntPtr value) { Unsafe.As(ref location).Value = value; } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public static sbyte Read(ref sbyte location) { return Unsafe.As(ref location).Value; } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public static void Write(ref sbyte location, sbyte value) { Unsafe.As(ref location).Value = value; } [Intrinsic] [NonVersionable] public static float Read(ref float location) { return Unsafe.As(ref location).Value; } [Intrinsic] [NonVersionable] public static void Write(ref float location, float value) { Unsafe.As(ref location).Value = value; } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public static ushort Read(ref ushort location) { return Unsafe.As(ref location).Value; } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public static void Write(ref ushort location, ushort value) { Unsafe.As(ref location).Value = value; } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public static uint Read(ref uint location) { return Unsafe.As(ref location).Value; } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public static void Write(ref uint location, uint value) { Unsafe.As(ref location).Value = value; } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public static ulong Read(ref ulong location) { return (ulong)Read(ref Unsafe.As(ref location)); } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public static void Write(ref ulong location, ulong value) { Write(ref Unsafe.As(ref location), (long)value); } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public static UIntPtr Read(ref UIntPtr location) { return Unsafe.As(ref location).Value; } [CLSCompliant(false)] [Intrinsic] [NonVersionable] public static void Write(ref UIntPtr location, UIntPtr value) { Unsafe.As(ref location).Value = value; } [Intrinsic] [NonVersionable] [return: NotNullIfNotNull("location")] public static T Read([NotNullIfNotNull("location")] ref T location) where T : class? { return Unsafe.As(Unsafe.As(ref location).Value); } [Intrinsic] [NonVersionable] public static void Write([NotNullIfNotNull("value")] ref T location, T value) where T : class? { Unsafe.As(ref location).Value = value; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class WaitHandleCannotBeOpenedException : ApplicationException { public WaitHandleCannotBeOpenedException() : base(SR.Threading_WaitHandleCannotBeOpenedException) { base.HResult = -2146233044; } public WaitHandleCannotBeOpenedException(string? message) : base(message) { base.HResult = -2146233044; } public WaitHandleCannotBeOpenedException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233044; } protected WaitHandleCannotBeOpenedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public static class WaitHandleExtensions { public static SafeWaitHandle GetSafeWaitHandle(this WaitHandle waitHandle) { if (waitHandle == null) { throw new ArgumentNullException("waitHandle"); } return waitHandle.SafeWaitHandle; } public static void SetSafeWaitHandle(this WaitHandle waitHandle, SafeWaitHandle? value) { if (waitHandle == null) { throw new ArgumentNullException("waitHandle"); } waitHandle.SafeWaitHandle = value; } } internal enum OpenExistingResult { Success, NameNotFound, PathNotFound, NameInvalid } internal sealed class PortableThreadPool { [StructLayout(LayoutKind.Explicit, Size = 384)] private struct CacheLineSeparated { [FieldOffset(64)] public ThreadCounts counts; [FieldOffset(128)] public int lastDequeueTime; [FieldOffset(192)] public int priorCompletionCount; [FieldOffset(196)] public int priorCompletedWorkRequestsTime; [FieldOffset(200)] public int nextCompletedWorkRequestsTime; [FieldOffset(256)] public volatile int numRequestedWorkers; [FieldOffset(260)] public int gateThreadRunningState; } private enum PendingBlockingAdjustment : byte { None, Immediately, WithDelayIfNecessary } private static class BlockingConfig { public static readonly bool IsCooperativeBlockingEnabled; public static readonly short ThreadsToAddWithoutDelay; public static readonly short ThreadsPerDelayStep; public static readonly uint DelayStepMs; public static readonly uint MaxDelayMs; static BlockingConfig() { IsCooperativeBlockingEnabled = AppContextConfigHelper.GetBooleanConfig("System.Threading.ThreadPool.Blocking.CooperativeBlocking", defaultValue: true); int int32Config = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.Blocking.ThreadsToAddWithoutDelay_ProcCountFactor", 1, allowNegative: false); int int32Config2 = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.Blocking.ThreadsPerDelayStep_ProcCountFactor", 1, allowNegative: false); DelayStepMs = (uint)AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.Blocking.DelayStepMs", 25, allowNegative: false); MaxDelayMs = (uint)AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.Blocking.MaxDelayMs", 250, allowNegative: false); int processorCount = Environment.ProcessorCount; ThreadsToAddWithoutDelay = (short)(processorCount * int32Config); if (ThreadsToAddWithoutDelay > short.MaxValue || ThreadsToAddWithoutDelay / processorCount != int32Config) { ThreadsToAddWithoutDelay = short.MaxValue; } int32Config2 = Math.Max(1, int32Config2); short num = (short)(32767 - ThreadsToAddWithoutDelay); ThreadsPerDelayStep = (short)(processorCount * int32Config2); if (ThreadsPerDelayStep > num || ThreadsPerDelayStep / processorCount != int32Config2) { ThreadsPerDelayStep = num; } MaxDelayMs = Math.Max(1u, Math.Min(MaxDelayMs, 500u)); DelayStepMs = Math.Max(1u, Math.Min(DelayStepMs, MaxDelayMs)); } } private static class GateThread { private struct DelayHelper { private int _previousGateActivitiesTimeMs; private int _previousBlockingAdjustmentDelayStartTimeMs; private uint _previousBlockingAdjustmentDelayMs; private bool _runGateActivitiesAfterNextDelay; private bool _adjustForBlockingAfterNextDelay; public bool HasBlockingAdjustmentDelay => _previousBlockingAdjustmentDelayMs != 0; public void SetGateActivitiesTime(int currentTimeMs) { _previousGateActivitiesTimeMs = currentTimeMs; } public void SetBlockingAdjustmentTimeAndDelay(int currentTimeMs, uint delayMs) { _previousBlockingAdjustmentDelayStartTimeMs = currentTimeMs; _previousBlockingAdjustmentDelayMs = delayMs; } public void ClearBlockingAdjustmentDelay() { _previousBlockingAdjustmentDelayMs = 0u; } public uint GetNextDelay(int currentTimeMs) { uint num = (uint)(currentTimeMs - _previousGateActivitiesTimeMs); uint num2 = ((num >= 500) ? 1u : (500 - num)); if (_previousBlockingAdjustmentDelayMs == 0) { _runGateActivitiesAfterNextDelay = true; _adjustForBlockingAfterNextDelay = false; return num2; } uint num3 = (uint)(currentTimeMs - _previousBlockingAdjustmentDelayStartTimeMs); uint num4 = ((num3 >= _previousBlockingAdjustmentDelayMs) ? 1u : (_previousBlockingAdjustmentDelayMs - num3)); uint num5 = Math.Min(num2, num4); _runGateActivitiesAfterNextDelay = num5 == num2; _adjustForBlockingAfterNextDelay = num5 == num4; return num5; } public bool ShouldPerformGateActivities(int currentTimeMs, bool wasSignaledToWake) { bool flag = (!wasSignaledToWake && _runGateActivitiesAfterNextDelay) || (uint)(currentTimeMs - _previousGateActivitiesTimeMs) >= 500u; if (flag) { SetGateActivitiesTime(currentTimeMs); } return flag; } public bool HasBlockingAdjustmentDelayElapsed(int currentTimeMs, bool wasSignaledToWake) { if (!wasSignaledToWake && _adjustForBlockingAfterNextDelay) { return true; } uint num = (uint)(currentTimeMs - _previousBlockingAdjustmentDelayStartTimeMs); return num >= _previousBlockingAdjustmentDelayMs; } } private static readonly AutoResetEvent RunGateThreadEvent = new AutoResetEvent(initialState: true); private static readonly AutoResetEvent DelayEvent = new AutoResetEvent(initialState: false); private static void GateThreadStart() { bool booleanConfig = AppContextConfigHelper.GetBooleanConfig("System.Threading.ThreadPool.DisableStarvationDetection", defaultValue: false); bool booleanConfig2 = AppContextConfigHelper.GetBooleanConfig("System.Threading.ThreadPool.DebugBreakOnWorkerStarvation", defaultValue: false); CpuUtilizationReader cpuUtilizationReader = default(CpuUtilizationReader); _ = cpuUtilizationReader.CurrentUtilization; PortableThreadPool threadPoolInstance = ThreadPoolInstance; LowLevelLock threadAdjustmentLock = threadPoolInstance._threadAdjustmentLock; DelayHelper delayHelper = default(DelayHelper); if (BlockingConfig.IsCooperativeBlockingEnabled) { threadPoolInstance.OnGen2GCCallback(); Gen2GcCallback.Register(threadPoolInstance.OnGen2GCCallback); } while (true) { RunGateThreadEvent.WaitOne(); int tickCount = Environment.TickCount; delayHelper.SetGateActivitiesTime(tickCount); while (true) { bool wasSignaledToWake = DelayEvent.WaitOne((int)delayHelper.GetNextDelay(tickCount)); tickCount = Environment.TickCount; PendingBlockingAdjustment pendingBlockingAdjustment = threadPoolInstance._pendingBlockingAdjustment; if (pendingBlockingAdjustment == PendingBlockingAdjustment.None) { delayHelper.ClearBlockingAdjustmentDelay(); } else { bool flag = false; if (delayHelper.HasBlockingAdjustmentDelay) { flag = delayHelper.HasBlockingAdjustmentDelayElapsed(tickCount, wasSignaledToWake); if (pendingBlockingAdjustment == PendingBlockingAdjustment.WithDelayIfNecessary && !flag) { goto IL_00ee; } } uint num = threadPoolInstance.PerformBlockingAdjustment(flag); if (num == 0) { delayHelper.ClearBlockingAdjustmentDelay(); } else { delayHelper.SetBlockingAdjustmentTimeAndDelay(tickCount, num); } } goto IL_00ee; IL_00ee: if (!delayHelper.ShouldPerformGateActivities(tickCount, wasSignaledToWake)) { continue; } if (ThreadPool.EnableWorkerTracking && NativeRuntimeEventSource.Log.IsEnabled()) { NativeRuntimeEventSource.Log.ThreadPoolWorkingThreadCount((uint)threadPoolInstance.GetAndResetHighWatermarkCountOfThreadsProcessingUserCallbacks(), 0); } bool flag2 = ThreadPool.PerformRuntimeSpecificGateActivities(threadPoolInstance._cpuUtilization = cpuUtilizationReader.CurrentUtilization); if (!booleanConfig && threadPoolInstance._pendingBlockingAdjustment == PendingBlockingAdjustment.None && threadPoolInstance._separated.numRequestedWorkers > 0 && SufficientDelaySinceLastDequeue(threadPoolInstance)) { bool flag3 = false; threadAdjustmentLock.Acquire(); try { ThreadCounts threadCounts = threadPoolInstance._separated.counts; while (threadCounts.NumProcessingWork < threadPoolInstance._maxThreads && threadCounts.NumProcessingWork >= threadCounts.NumThreadsGoal) { if (booleanConfig2) { Debugger.Break(); } ThreadCounts newCounts = threadCounts; short newThreadCount = (newCounts.NumThreadsGoal = (short)(threadCounts.NumProcessingWork + 1)); ThreadCounts threadCounts2 = threadPoolInstance._separated.counts.InterlockedCompareExchange(newCounts, threadCounts); if (threadCounts2 == threadCounts) { HillClimbing.ThreadPoolHillClimber.ForceChange(newThreadCount, HillClimbing.StateOrTransition.Starvation); flag3 = true; break; } threadCounts = threadCounts2; } } finally { threadAdjustmentLock.Release(); } if (flag3) { WorkerThread.MaybeAddWorkingWorker(threadPoolInstance); } } if (!flag2 && threadPoolInstance._separated.numRequestedWorkers <= 0 && threadPoolInstance._pendingBlockingAdjustment == PendingBlockingAdjustment.None && Interlocked.Decrement(ref threadPoolInstance._separated.gateThreadRunningState) <= GetRunningStateForNumRuns(0)) { break; } } } } public static void Wake(PortableThreadPool threadPoolInstance) { DelayEvent.Set(); EnsureRunning(threadPoolInstance); } private static bool SufficientDelaySinceLastDequeue(PortableThreadPool threadPoolInstance) { uint num = (uint)(Environment.TickCount - threadPoolInstance._separated.lastDequeueTime); uint num2 = ((threadPoolInstance._cpuUtilization >= 80) ? ((uint)(threadPoolInstance._separated.counts.NumThreadsGoal * 1000)) : 500u); return num > num2; } internal static void EnsureRunning(PortableThreadPool threadPoolInstance) { if (threadPoolInstance._separated.gateThreadRunningState != GetRunningStateForNumRuns(2)) { EnsureRunningSlow(threadPoolInstance); } } [MethodImpl(MethodImplOptions.NoInlining)] internal static void EnsureRunningSlow(PortableThreadPool threadPoolInstance) { int num = Interlocked.Exchange(ref threadPoolInstance._separated.gateThreadRunningState, GetRunningStateForNumRuns(2)); if (num == GetRunningStateForNumRuns(0)) { RunGateThreadEvent.Set(); } else if ((num & 4) == 0) { CreateGateThread(threadPoolInstance); } } private static int GetRunningStateForNumRuns(int numRuns) { return 4 | numRuns; } [MethodImpl(MethodImplOptions.NoInlining)] private static void CreateGateThread(PortableThreadPool threadPoolInstance) { bool flag = false; try { Thread thread = new Thread(GateThreadStart, 262144) { IsThreadPoolThread = true, IsBackground = true, Name = ".NET ThreadPool Gate" }; thread.UnsafeStart(); flag = true; } finally { if (!flag) { Interlocked.Exchange(ref threadPoolInstance._separated.gateThreadRunningState, 0); } } } } private sealed class HillClimbing { public enum StateOrTransition { Warmup, Initializing, RandomMove, ClimbingMove, ChangePoint, Stabilizing, Starvation, ThreadTimedOut, CooperativeBlocking } private struct LogEntry { public int tickCount; public StateOrTransition stateOrTransition; public int newControlSetting; public int lastHistoryCount; public float lastHistoryMean; } private struct Complex { public double Imaginary { get; } public double Real { get; } public Complex(double real, double imaginary) { Real = real; Imaginary = imaginary; } public static Complex operator *(double scalar, Complex complex) { return new Complex(scalar * complex.Real, scalar * complex.Imaginary); } public static Complex operator /(Complex complex, double scalar) { return new Complex(complex.Real / scalar, complex.Imaginary / scalar); } public static Complex operator -(Complex lhs, Complex rhs) { return new Complex(lhs.Real - rhs.Real, lhs.Imaginary - rhs.Imaginary); } public static Complex operator /(Complex lhs, Complex rhs) { double num = rhs.Real * rhs.Real + rhs.Imaginary * rhs.Imaginary; return new Complex((lhs.Real * rhs.Real + lhs.Imaginary * rhs.Imaginary) / num, ((0.0 - lhs.Real) * rhs.Imaginary + lhs.Imaginary * rhs.Real) / num); } public double Abs() { return Math.Sqrt(Real * Real + Imaginary * Imaginary); } } public static readonly bool IsDisabled = AppContextConfigHelper.GetBooleanConfig("System.Threading.ThreadPool.HillClimbing.Disable", defaultValue: false); public static readonly HillClimbing ThreadPoolHillClimber = new HillClimbing(); private readonly int _wavePeriod; private readonly int _samplesToMeasure; private readonly double _targetThroughputRatio; private readonly double _targetSignalToNoiseRatio; private readonly double _maxChangePerSecond; private readonly double _maxChangePerSample; private readonly int _maxThreadWaveMagnitude; private readonly int _sampleIntervalMsLow; private readonly double _threadMagnitudeMultiplier; private readonly int _sampleIntervalMsHigh; private readonly double _throughputErrorSmoothingFactor; private readonly double _gainExponent; private readonly double _maxSampleError; private double _currentControlSetting; private long _totalSamples; private int _lastThreadCount; private double _averageThroughputNoise; private double _secondsElapsedSinceLastChange; private double _completionsSinceLastChange; private int _accumulatedCompletionCount; private double _accumulatedSampleDurationSeconds; private readonly double[] _samples; private readonly double[] _threadCounts; private int _currentSampleMs; private readonly Random _randomIntervalGenerator = new Random(); private readonly LogEntry[] _log = new LogEntry[200]; private int _logStart; private int _logSize; public HillClimbing() { _wavePeriod = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.WavePeriod", 4, allowNegative: false); _maxThreadWaveMagnitude = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.MaxWaveMagnitude", 20, allowNegative: false); _threadMagnitudeMultiplier = (double)AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.WaveMagnitudeMultiplier", 100, allowNegative: false) / 100.0; _samplesToMeasure = _wavePeriod * AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.WaveHistorySize", 8, allowNegative: false); _targetThroughputRatio = (double)AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.Bias", 15, allowNegative: false) / 100.0; _targetSignalToNoiseRatio = (double)AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.TargetSignalToNoiseRatio", 300, allowNegative: false) / 100.0; _maxChangePerSecond = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.MaxChangePerSecond", 4, allowNegative: false); _maxChangePerSample = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.MaxChangePerSample", 20, allowNegative: false); int int32Config = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.SampleIntervalLow", 10, allowNegative: false); int int32Config2 = AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.SampleIntervalHigh", 200, allowNegative: false); if (int32Config <= int32Config2) { _sampleIntervalMsLow = int32Config; _sampleIntervalMsHigh = int32Config2; } else { _sampleIntervalMsLow = 10; _sampleIntervalMsHigh = 200; } _throughputErrorSmoothingFactor = (double)AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.ErrorSmoothingFactor", 1, allowNegative: false) / 100.0; _gainExponent = (double)AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.GainExponent", 200, allowNegative: false) / 100.0; _maxSampleError = (double)AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.HillClimbing.MaxSampleErrorPercent", 15, allowNegative: false) / 100.0; _samples = new double[_samplesToMeasure]; _threadCounts = new double[_samplesToMeasure]; _currentSampleMs = _randomIntervalGenerator.Next(_sampleIntervalMsLow, _sampleIntervalMsHigh + 1); } public (int newThreadCount, int newSampleMs) Update(int currentThreadCount, double sampleDurationSeconds, int numCompletions) { if (currentThreadCount != _lastThreadCount) { ForceChange(currentThreadCount, StateOrTransition.Initializing); } _secondsElapsedSinceLastChange += sampleDurationSeconds; _completionsSinceLastChange += numCompletions; sampleDurationSeconds += _accumulatedSampleDurationSeconds; numCompletions += _accumulatedCompletionCount; if (_totalSamples > 0 && ((double)currentThreadCount - 1.0) / (double)numCompletions >= _maxSampleError) { _accumulatedSampleDurationSeconds = sampleDurationSeconds; _accumulatedCompletionCount = numCompletions; return (currentThreadCount, 10); } _accumulatedSampleDurationSeconds = 0.0; _accumulatedCompletionCount = 0; double num = (double)numCompletions / sampleDurationSeconds; if (NativeRuntimeEventSource.Log.IsEnabled()) { NativeRuntimeEventSource.Log.ThreadPoolWorkerThreadAdjustmentSample(num, 0); } int num2 = (int)(_totalSamples % _samplesToMeasure); _samples[num2] = num; _threadCounts[num2] = currentThreadCount; _totalSamples++; Complex complex = default(Complex); Complex complex2 = default(Complex); double num3 = 0.0; Complex complex3 = default(Complex); double num4 = 0.0; StateOrTransition state = StateOrTransition.Warmup; int num5 = (int)Math.Min(_totalSamples - 1, _samplesToMeasure) / _wavePeriod * _wavePeriod; if (num5 > _wavePeriod) { double num6 = 0.0; double num7 = 0.0; for (int i = 0; i < num5; i++) { num6 += _samples[(_totalSamples - num5 + i) % _samplesToMeasure]; num7 += _threadCounts[(_totalSamples - num5 + i) % _samplesToMeasure]; } double num8 = num6 / (double)num5; double num9 = num7 / (double)num5; if (num8 > 0.0 && num9 > 0.0) { double period = (double)num5 / ((double)num5 / (double)_wavePeriod + 1.0); double num10 = (double)num5 / ((double)num5 / (double)_wavePeriod - 1.0); complex2 = GetWaveComponent(_samples, num5, _wavePeriod) / num8; num3 = (GetWaveComponent(_samples, num5, period) / num8).Abs(); if (num10 <= (double)num5) { num3 = Math.Max(num3, (GetWaveComponent(_samples, num5, num10) / num8).Abs()); } complex = GetWaveComponent(_threadCounts, num5, _wavePeriod) / num9; if (_averageThroughputNoise == 0.0) { _averageThroughputNoise = num3; } else { _averageThroughputNoise = _throughputErrorSmoothingFactor * num3 + (1.0 - _throughputErrorSmoothingFactor) * _averageThroughputNoise; } if (complex.Abs() > 0.0) { complex3 = (complex2 - _targetThroughputRatio * complex) / complex; state = StateOrTransition.ClimbingMove; } else { complex3 = new Complex(0.0, 0.0); state = StateOrTransition.Stabilizing; } double num11 = Math.Max(_averageThroughputNoise, num3); num4 = ((!(num11 > 0.0)) ? 1.0 : (complex.Abs() / num11 / _targetSignalToNoiseRatio)); } } double num12 = Math.Min(1.0, Math.Max(-1.0, complex3.Real)); num12 *= Math.Min(1.0, Math.Max(0.0, num4)); double num13 = _maxChangePerSecond * sampleDurationSeconds; num12 = Math.Pow(Math.Abs(num12), _gainExponent) * (double)((num12 >= 0.0) ? 1 : (-1)) * num13; num12 = Math.Min(num12, _maxChangePerSample); PortableThreadPool threadPoolInstance = ThreadPoolInstance; if (num12 > 0.0 && threadPoolInstance._cpuUtilization > 95) { num12 = 0.0; } _currentControlSetting += num12; int val = (int)(0.5 + _currentControlSetting * _averageThroughputNoise * _targetSignalToNoiseRatio * _threadMagnitudeMultiplier * 2.0); val = Math.Min(val, _maxThreadWaveMagnitude); val = Math.Max(val, 1); int maxThreads = threadPoolInstance._maxThreads; int minThreadsGoal = threadPoolInstance.MinThreadsGoal; _currentControlSetting = Math.Min(maxThreads - val, _currentControlSetting); _currentControlSetting = Math.Max(minThreadsGoal, _currentControlSetting); int val2 = (int)(_currentControlSetting + (double)(val * (_totalSamples / (_wavePeriod / 2) % 2))); val2 = Math.Min(maxThreads, val2); val2 = Math.Max(minThreadsGoal, val2); if (NativeRuntimeEventSource.Log.IsEnabled()) { NativeRuntimeEventSource.Log.ThreadPoolWorkerThreadAdjustmentStats(sampleDurationSeconds, num, complex.Real, complex2.Real, num3, _averageThroughputNoise, complex3.Real, num4, _currentControlSetting, (ushort)val, 0); } if (val2 != currentThreadCount) { ChangeThreadCount(val2, state); _secondsElapsedSinceLastChange = 0.0; _completionsSinceLastChange = 0.0; } int item = ((!(complex3.Real < 0.0) || val2 != minThreadsGoal) ? _currentSampleMs : ((int)(0.5 + (double)_currentSampleMs * (10.0 * Math.Min(0.0 - complex3.Real, 1.0))))); return (val2, item); } private void ChangeThreadCount(int newThreadCount, StateOrTransition state) { _lastThreadCount = newThreadCount; if (state != StateOrTransition.CooperativeBlocking) { _currentSampleMs = _randomIntervalGenerator.Next(_sampleIntervalMsLow, _sampleIntervalMsHigh + 1); } double throughput = ((_secondsElapsedSinceLastChange > 0.0) ? (_completionsSinceLastChange / _secondsElapsedSinceLastChange) : 0.0); LogTransition(newThreadCount, throughput, state); } private void LogTransition(int newThreadCount, double throughput, StateOrTransition stateOrTransition) { int num = (_logStart + _logSize) % 200; if (_logSize == 200) { _logStart = (_logStart + 1) % 200; _logSize--; } ref LogEntry reference = ref _log[num]; reference.tickCount = Environment.TickCount; reference.stateOrTransition = stateOrTransition; reference.newControlSetting = newThreadCount; reference.lastHistoryCount = (int)(Math.Min(_totalSamples, _samplesToMeasure) / _wavePeriod) * _wavePeriod; reference.lastHistoryMean = (float)throughput; _logSize++; if (NativeRuntimeEventSource.Log.IsEnabled()) { NativeRuntimeEventSource.Log.ThreadPoolWorkerThreadAdjustmentAdjustment(throughput, (uint)newThreadCount, (NativeRuntimeEventSource.ThreadAdjustmentReasonMap)stateOrTransition, 0); } } public void ForceChange(int newThreadCount, StateOrTransition state) { if (_lastThreadCount != newThreadCount) { _currentControlSetting += newThreadCount - _lastThreadCount; ChangeThreadCount(newThreadCount, state); } } private Complex GetWaveComponent(double[] samples, int numSamples, double period) { double num = Math.PI * 2.0 / period; double num2 = Math.Cos(num); double num3 = 2.0 * num2; double num4 = 0.0; double num5 = 0.0; double num6 = 0.0; for (int i = 0; i < numSamples; i++) { num4 = num3 * num5 - num6 + samples[(_totalSamples - numSamples + i) % _samplesToMeasure]; num6 = num5; num5 = num4; } return new Complex(num5 - num6 * num2, num6 * Math.Sin(num)) / numSamples; } } private struct ThreadCounts { private ulong _data; public short NumProcessingWork { get { return GetInt16Value(0); } set { SetInt16Value(Math.Max((short)0, value), 0); } } public short NumExistingThreads { get { return GetInt16Value(16); } set { SetInt16Value(Math.Max((short)0, value), 16); } } public short NumThreadsGoal { get { return GetInt16Value(32); } set { SetInt16Value(Math.Max((short)1, value), 32); } } private ThreadCounts(ulong data) { _data = data; } private short GetInt16Value(byte shift) { return (short)(_data >> (int)shift); } private void SetInt16Value(short value, byte shift) { _data = (_data & (ulong)(~(65535L << (int)shift))) | ((ulong)(ushort)value << (int)shift); } public ThreadCounts InterlockedSetNumThreadsGoal(short value) { ThreadCounts threadCounts = this; ThreadCounts threadCounts2; while (true) { threadCounts2 = threadCounts; threadCounts2.NumThreadsGoal = value; ThreadCounts threadCounts3 = InterlockedCompareExchange(threadCounts2, threadCounts); if (threadCounts3 == threadCounts) { break; } threadCounts = threadCounts3; } return threadCounts2; } public ThreadCounts VolatileRead() { return new ThreadCounts(Volatile.Read(ref _data)); } public ThreadCounts InterlockedCompareExchange(ThreadCounts newCounts, ThreadCounts oldCounts) { return new ThreadCounts(Interlocked.CompareExchange(ref _data, newCounts._data, oldCounts._data)); } public static bool operator ==(ThreadCounts lhs, ThreadCounts rhs) { return lhs._data == rhs._data; } public override bool Equals([NotNullWhen(true)] object obj) { if (obj is ThreadCounts threadCounts) { return _data == threadCounts._data; } return false; } public override int GetHashCode() { return (int)_data + (int)(_data >> 32); } } private sealed class WaitThreadNode { public WaitThread Thread { get; } public WaitThreadNode Next { get; set; } public WaitThreadNode(WaitThread thread) { Thread = thread; } } internal sealed class WaitThread { private readonly RegisteredWaitHandle[] _registeredWaits = new RegisteredWaitHandle[63]; private readonly SafeWaitHandle[] _waitHandles = new SafeWaitHandle[64]; private int _numUserWaits; private readonly RegisteredWaitHandle[] _pendingRemoves = new RegisteredWaitHandle[63]; private int _numPendingRemoves; private readonly AutoResetEvent _changeHandlesEvent = new AutoResetEvent(initialState: false); internal bool AnyUserWaits => _numUserWaits != 0; public WaitThread() { _waitHandles[0] = _changeHandlesEvent.SafeWaitHandle; Thread thread = new Thread(WaitThreadStart, 262144) { IsThreadPoolThread = true, IsBackground = true, Name = ".NET ThreadPool Wait" }; thread.UnsafeStart(); } private void WaitThreadStart() { while (true) { int num = ProcessRemovals(); int tickCount = Environment.TickCount; int num2 = -1; if (num == 0) { num2 = 20000; } else { for (int i = 0; i < num; i++) { RegisteredWaitHandle registeredWaitHandle = _registeredWaits[i]; if (!registeredWaitHandle.IsInfiniteTimeout) { int num3 = Math.Max(0, registeredWaitHandle.TimeoutTimeMs - tickCount); num2 = ((num2 != -1) ? Math.Min(num3, num2) : num3); if (num2 == 0) { break; } } } } int num4 = WaitHandle.WaitAny(new ReadOnlySpan(_waitHandles, 0, num + 1), num2); if (num4 >= 128 && num4 < 129 + num) { num4 += -128; } switch (num4) { case 0: break; default: { RegisteredWaitHandle registeredHandle = _registeredWaits[num4 - 1]; QueueWaitCompletion(registeredHandle, timedOut: false); break; } case 258: { if (num == 0 && ThreadPoolInstance.TryRemoveWaitThread(this)) { return; } tickCount = Environment.TickCount; for (int j = 0; j < num; j++) { RegisteredWaitHandle registeredWaitHandle2 = _registeredWaits[j]; if (!registeredWaitHandle2.IsInfiniteTimeout && tickCount - registeredWaitHandle2.TimeoutTimeMs >= 0) { QueueWaitCompletion(registeredWaitHandle2, timedOut: true); } } break; } } } } private int ProcessRemovals() { PortableThreadPool threadPoolInstance = ThreadPoolInstance; threadPoolInstance._waitThreadLock.Acquire(); try { if (_numPendingRemoves == 0 || _numUserWaits == 0) { return _numUserWaits; } int numUserWaits = _numUserWaits; int numPendingRemoves = _numPendingRemoves; for (int i = 0; i < _numPendingRemoves; i++) { RegisteredWaitHandle registeredWaitHandle = _pendingRemoves[i]; int numUserWaits2 = _numUserWaits; int j; for (j = 0; j < numUserWaits2 && registeredWaitHandle != _registeredWaits[j]; j++) { } registeredWaitHandle.OnRemoveWait(); if (j + 1 < numUserWaits2) { int num = j; int num2 = numUserWaits2; Array.Copy(_registeredWaits, num + 1, _registeredWaits, num, num2 - (num + 1)); _registeredWaits[num2 - 1] = null; num++; num2++; Array.Copy(_waitHandles, num + 1, _waitHandles, num, num2 - (num + 1)); _waitHandles[num2 - 1] = null; } else { _registeredWaits[j] = null; _waitHandles[j + 1] = null; } _numUserWaits = numUserWaits2 - 1; _pendingRemoves[i] = null; registeredWaitHandle.Handle.DangerousRelease(); } _numPendingRemoves = 0; return _numUserWaits; } finally { threadPoolInstance._waitThreadLock.Release(); } } private void QueueWaitCompletion(RegisteredWaitHandle registeredHandle, bool timedOut) { registeredHandle.RequestCallback(); if (registeredHandle.Repeating) { registeredHandle.RestartTimeout(); } else { UnregisterWait(registeredHandle, blocking: false); } ThreadPool.UnsafeQueueWaitCompletion(new CompleteWaitThreadPoolWorkItem(registeredHandle, timedOut)); } public bool RegisterWaitHandle(RegisteredWaitHandle handle) { if (_numUserWaits == 63) { return false; } bool success = false; handle.Handle.DangerousAddRef(ref success); _registeredWaits[_numUserWaits] = handle; _waitHandles[_numUserWaits + 1] = handle.Handle; _numUserWaits++; handle.WaitThread = this; _changeHandlesEvent.Set(); return true; } public void UnregisterWait(RegisteredWaitHandle handle) { UnregisterWait(handle, blocking: true); } private void UnregisterWait(RegisteredWaitHandle handle, bool blocking) { bool flag = false; PortableThreadPool threadPoolInstance = ThreadPoolInstance; threadPoolInstance._waitThreadLock.Acquire(); try { if (Array.IndexOf(_registeredWaits, handle) != -1) { if (Array.IndexOf(_pendingRemoves, handle) == -1) { _pendingRemoves[_numPendingRemoves++] = handle; _changeHandlesEvent.Set(); } flag = true; } } finally { threadPoolInstance._waitThreadLock.Release(); } if (blocking) { if (handle.IsBlocking) { handle.WaitForCallbacks(); } else if (flag) { handle.WaitForRemoval(); } } } } private static class WorkerThread { private static readonly LowLevelLifoSemaphore s_semaphore = new LowLevelLifoSemaphore(0, 32767, AppContextConfigHelper.GetInt32Config("System.Threading.ThreadPool.UnfairSemaphoreSpinLimit", 70, allowNegative: false), delegate { if (NativeRuntimeEventSource.Log.IsEnabled()) { NativeRuntimeEventSource.Log.ThreadPoolWorkerThreadWait((uint)ThreadPoolInstance._separated.counts.VolatileRead().NumExistingThreads, 0u, 0); } }); private static readonly ThreadStart s_workerThreadStart = WorkerThreadStart; private static void WorkerThreadStart() { Thread.CurrentThread.SetThreadPoolWorkerThreadName(); PortableThreadPool threadPoolInstance = ThreadPoolInstance; if (NativeRuntimeEventSource.Log.IsEnabled()) { NativeRuntimeEventSource.Log.ThreadPoolWorkerThreadStart((uint)threadPoolInstance._separated.counts.VolatileRead().NumExistingThreads, 0u, 0); } LowLevelLock threadAdjustmentLock = threadPoolInstance._threadAdjustmentLock; LowLevelLifoSemaphore lowLevelLifoSemaphore = s_semaphore; while (true) { bool spinWait = true; while (lowLevelLifoSemaphore.Wait(20000, spinWait)) { bool flag = false; while (TakeActiveRequest(threadPoolInstance)) { threadPoolInstance._separated.lastDequeueTime = Environment.TickCount; if (!ThreadPoolWorkQueue.Dispatch()) { flag = true; break; } if (threadPoolInstance._separated.numRequestedWorkers <= 0) { break; } Thread.UninterruptibleSleep0(); if (!Environment.IsSingleProcessor) { Thread.SpinWait(1); } } spinWait = !flag; if (!flag) { RemoveWorkingWorker(threadPoolInstance); } } threadAdjustmentLock.Acquire(); try { ThreadCounts threadCounts = threadPoolInstance._separated.counts; while (threadCounts.NumExistingThreads > threadCounts.NumProcessingWork) { ThreadCounts newCounts = threadCounts; short num = --newCounts.NumExistingThreads; short newThreadCount = (newCounts.NumThreadsGoal = Math.Max(threadPoolInstance.MinThreadsGoal, Math.Min(num, threadCounts.NumThreadsGoal))); ThreadCounts threadCounts2 = threadPoolInstance._separated.counts.InterlockedCompareExchange(newCounts, threadCounts); if (threadCounts2 == threadCounts) { HillClimbing.ThreadPoolHillClimber.ForceChange(newThreadCount, HillClimbing.StateOrTransition.ThreadTimedOut); if (NativeRuntimeEventSource.Log.IsEnabled()) { NativeRuntimeEventSource.Log.ThreadPoolWorkerThreadStop((uint)num, 0u, 0); } return; } threadCounts = threadCounts2; } } finally { threadAdjustmentLock.Release(); } } } private static void RemoveWorkingWorker(PortableThreadPool threadPoolInstance) { ThreadCounts threadCounts = threadPoolInstance._separated.counts; while (true) { ThreadCounts newCounts = threadCounts; newCounts.NumProcessingWork--; ThreadCounts threadCounts2 = threadPoolInstance._separated.counts.InterlockedCompareExchange(newCounts, threadCounts); if (threadCounts2 == threadCounts) { break; } threadCounts = threadCounts2; } if (threadPoolInstance._separated.numRequestedWorkers > 0) { MaybeAddWorkingWorker(threadPoolInstance); } } internal static void MaybeAddWorkingWorker(PortableThreadPool threadPoolInstance) { ThreadCounts threadCounts = threadPoolInstance._separated.counts; short numProcessingWork; short num; short numExistingThreads; short num2; while (true) { numProcessingWork = threadCounts.NumProcessingWork; if (numProcessingWork >= threadCounts.NumThreadsGoal) { return; } num = (short)(numProcessingWork + 1); numExistingThreads = threadCounts.NumExistingThreads; num2 = Math.Max(numExistingThreads, num); ThreadCounts newCounts = threadCounts; newCounts.NumProcessingWork = num; newCounts.NumExistingThreads = num2; ThreadCounts threadCounts2 = threadPoolInstance._separated.counts.InterlockedCompareExchange(newCounts, threadCounts); if (threadCounts2 == threadCounts) { break; } threadCounts = threadCounts2; } int num3 = num2 - numExistingThreads; int num4 = num - numProcessingWork; if (num4 > 0) { s_semaphore.Release(num4); } while (num3 > 0) { if (TryCreateWorkerThread()) { num3--; continue; } threadCounts = threadPoolInstance._separated.counts; while (true) { ThreadCounts newCounts2 = threadCounts; newCounts2.NumProcessingWork -= (short)num3; newCounts2.NumExistingThreads -= (short)num3; ThreadCounts threadCounts3 = threadPoolInstance._separated.counts.InterlockedCompareExchange(newCounts2, threadCounts); if (!(threadCounts3 == threadCounts)) { threadCounts = threadCounts3; continue; } break; } break; } } internal static bool ShouldStopProcessingWorkNow(PortableThreadPool threadPoolInstance) { ThreadCounts threadCounts = threadPoolInstance._separated.counts; while (true) { if (threadCounts.NumProcessingWork <= threadCounts.NumThreadsGoal) { return false; } ThreadCounts newCounts = threadCounts; newCounts.NumProcessingWork--; ThreadCounts threadCounts2 = threadPoolInstance._separated.counts.InterlockedCompareExchange(newCounts, threadCounts); if (threadCounts2 == threadCounts) { break; } threadCounts = threadCounts2; } return true; } private static bool TakeActiveRequest(PortableThreadPool threadPoolInstance) { int num = threadPoolInstance._separated.numRequestedWorkers; while (num > 0) { int num2 = Interlocked.CompareExchange(ref threadPoolInstance._separated.numRequestedWorkers, num - 1, num); if (num2 == num) { return true; } num = num2; } return false; } private static bool TryCreateWorkerThread() { try { Thread thread = new Thread(s_workerThreadStart); thread.IsThreadPoolThread = true; thread.IsBackground = true; thread.UnsafeStart(); } catch (ThreadStartException) { return false; } catch (OutOfMemoryException) { return false; } return true; } } private struct CountsOfThreadsProcessingUserCallbacks { private uint _data; public short Current => GetInt16Value(0); public short HighWatermark => GetInt16Value(16); private CountsOfThreadsProcessingUserCallbacks(uint data) { _data = data; } private short GetInt16Value(byte shift) { return (short)(_data >> (int)shift); } private void SetInt16Value(short value, byte shift) { _data = (_data & (uint)(~(65535 << (int)shift))) | (uint)((ushort)value << (int)shift); } public void IncrementCurrent() { if (Current < HighWatermark) { _data++; } else { _data += 65537u; } } public void DecrementCurrent() { _data--; } public void ResetHighWatermark() { SetInt16Value(Current, 16); } public CountsOfThreadsProcessingUserCallbacks InterlockedCompareExchange(CountsOfThreadsProcessingUserCallbacks newCounts, CountsOfThreadsProcessingUserCallbacks oldCounts) { return new CountsOfThreadsProcessingUserCallbacks(Interlocked.CompareExchange(ref _data, newCounts._data, oldCounts._data)); } public static bool operator ==(CountsOfThreadsProcessingUserCallbacks lhs, CountsOfThreadsProcessingUserCallbacks rhs) { return lhs._data == rhs._data; } public override bool Equals([NotNullWhen(true)] object obj) { if (obj is CountsOfThreadsProcessingUserCallbacks countsOfThreadsProcessingUserCallbacks) { return _data == countsOfThreadsProcessingUserCallbacks._data; } return false; } public override int GetHashCode() { return (int)_data; } } private struct CpuUtilizationReader { public long _idleTime; public long _kernelTime; public long _userTime; public int CurrentUtilization { get { if (!Interop.Kernel32.GetSystemTimes(out var idle, out var kernel, out var user)) { return 0; } long num = user - _userTime + (kernel - _kernelTime); long num2 = num - (idle - _idleTime); _kernelTime = kernel; _userTime = user; _idleTime = idle; if (num > 0 && num2 > 0) { long val = num2 * 100 / num; val = Math.Min(val, 100L); return (int)val; } return 0; } } } private static readonly short ForcedMinWorkerThreads = AppContextConfigHelper.GetInt16Config("System.Threading.ThreadPool.MinThreads", 0, allowNegative: false); private static readonly short ForcedMaxWorkerThreads = AppContextConfigHelper.GetInt16Config("System.Threading.ThreadPool.MaxThreads", 0, allowNegative: false); [ThreadStatic] private static object t_completionCountObject; public static readonly PortableThreadPool ThreadPoolInstance = new PortableThreadPool(); private int _cpuUtilization; private short _minThreads; private short _maxThreads; private long _currentSampleStartTime; private readonly ThreadInt64PersistentCounter _completionCounter = new ThreadInt64PersistentCounter(); private int _threadAdjustmentIntervalMs; private short _numBlockedThreads; private short _numThreadsAddedDueToBlocking; private PendingBlockingAdjustment _pendingBlockingAdjustment; private long _memoryUsageBytes; private long _memoryLimitBytes; private readonly LowLevelLock _threadAdjustmentLock = new LowLevelLock(); private CacheLineSeparated _separated; private WaitThreadNode _waitThreadsHead; private readonly LowLevelLock _waitThreadLock = new LowLevelLock(); private CountsOfThreadsProcessingUserCallbacks _countsOfThreadsProcessingUserCallbacks; public int ThreadCount => _separated.counts.VolatileRead().NumExistingThreads; public long CompletedWorkItemCount => _completionCounter.Count; public short MinThreadsGoal => Math.Min(_separated.counts.NumThreadsGoal, TargetThreadsGoalForBlockingAdjustment); private short TargetThreadsGoalForBlockingAdjustment { get { if (_numBlockedThreads > 0) { return (short)Math.Min((ushort)(_minThreads + _numBlockedThreads), (ushort)_maxThreads); } return _minThreads; } } private PortableThreadPool() { _minThreads = ((ForcedMinWorkerThreads > 0) ? ForcedMinWorkerThreads : ((short)Environment.ProcessorCount)); if (_minThreads > short.MaxValue) { _minThreads = short.MaxValue; } _maxThreads = (short)((ForcedMaxWorkerThreads > 0) ? ForcedMaxWorkerThreads : 1023); if (_maxThreads > short.MaxValue) { _maxThreads = short.MaxValue; } else if (_maxThreads < _minThreads) { _maxThreads = _minThreads; } _separated.counts.NumThreadsGoal = _minThreads; } public bool SetMinThreads(int workerThreads, int ioCompletionThreads) { if (workerThreads < 0 || ioCompletionThreads < 0) { return false; } bool flag = false; bool flag2 = false; _threadAdjustmentLock.Acquire(); try { if (workerThreads > _maxThreads || !ThreadPool.CanSetMinIOCompletionThreads(ioCompletionThreads)) { return false; } ThreadPool.SetMinIOCompletionThreads(ioCompletionThreads); if (ForcedMinWorkerThreads != 0) { return true; } short num = (_minThreads = (short)Math.Max(1, Math.Min(workerThreads, 32767))); if (_numBlockedThreads > 0) { if (_pendingBlockingAdjustment != PendingBlockingAdjustment.Immediately) { _pendingBlockingAdjustment = PendingBlockingAdjustment.Immediately; flag2 = true; } } else if (_separated.counts.NumThreadsGoal < num) { _separated.counts.InterlockedSetNumThreadsGoal(num); if (_separated.numRequestedWorkers > 0) { flag = true; } } } finally { _threadAdjustmentLock.Release(); } if (flag) { WorkerThread.MaybeAddWorkingWorker(this); } else if (flag2) { GateThread.Wake(this); } return true; } public int GetMinThreads() { return Volatile.Read(ref _minThreads); } public bool SetMaxThreads(int workerThreads, int ioCompletionThreads) { if (workerThreads <= 0 || ioCompletionThreads <= 0) { return false; } _threadAdjustmentLock.Acquire(); try { if (workerThreads < _minThreads || !ThreadPool.CanSetMaxIOCompletionThreads(ioCompletionThreads)) { return false; } ThreadPool.SetMaxIOCompletionThreads(ioCompletionThreads); if (ForcedMaxWorkerThreads != 0) { return true; } short num = (_maxThreads = (short)Math.Min(workerThreads, 32767)); if (_separated.counts.NumThreadsGoal > num) { _separated.counts.InterlockedSetNumThreadsGoal(num); } return true; } finally { _threadAdjustmentLock.Release(); } } public int GetMaxThreads() { return Volatile.Read(ref _maxThreads); } public int GetAvailableThreads() { ThreadCounts threadCounts = _separated.counts.VolatileRead(); int num = _maxThreads - threadCounts.NumProcessingWork; if (num < 0) { return 0; } return num; } public object GetOrCreateThreadLocalCompletionCountObject() { return t_completionCountObject ?? CreateThreadLocalCompletionCountObject(); } [MethodImpl(MethodImplOptions.NoInlining)] private object CreateThreadLocalCompletionCountObject() { return t_completionCountObject = _completionCounter.CreateThreadLocalCountObject(); } private void NotifyWorkItemProgress(object threadLocalCompletionCountObject, int currentTimeMs) { ThreadInt64PersistentCounter.Increment(threadLocalCompletionCountObject); _separated.lastDequeueTime = currentTimeMs; if (ShouldAdjustMaxWorkersActive(currentTimeMs)) { AdjustMaxWorkersActive(); } } internal void NotifyWorkItemProgress() { NotifyWorkItemProgress(GetOrCreateThreadLocalCompletionCountObject(), Environment.TickCount); } internal bool NotifyWorkItemComplete(object threadLocalCompletionCountObject, int currentTimeMs) { NotifyWorkItemProgress(threadLocalCompletionCountObject, currentTimeMs); return !WorkerThread.ShouldStopProcessingWorkNow(this); } private void AdjustMaxWorkersActive() { LowLevelLock threadAdjustmentLock = _threadAdjustmentLock; if (!threadAdjustmentLock.TryAcquire()) { return; } bool flag = false; try { ThreadCounts counts = _separated.counts; if (counts.NumProcessingWork > counts.NumThreadsGoal || _pendingBlockingAdjustment != 0) { return; } long currentSampleStartTime = _currentSampleStartTime; long timestamp = Stopwatch.GetTimestamp(); long frequency = Stopwatch.Frequency; double num = (double)(timestamp - currentSampleStartTime) / (double)frequency; if (num * 1000.0 >= (double)(_threadAdjustmentIntervalMs / 2)) { int tickCount = Environment.TickCount; int num2 = (int)_completionCounter.Count; int numCompletions = num2 - _separated.priorCompletionCount; short numThreadsGoal = counts.NumThreadsGoal; int num3; (num3, _threadAdjustmentIntervalMs) = HillClimbing.ThreadPoolHillClimber.Update(numThreadsGoal, num, numCompletions); if (numThreadsGoal != (short)num3) { _separated.counts.InterlockedSetNumThreadsGoal((short)num3); if (num3 > numThreadsGoal) { flag = true; } } _separated.priorCompletionCount = num2; _separated.nextCompletedWorkRequestsTime = tickCount + _threadAdjustmentIntervalMs; Volatile.Write(ref _separated.priorCompletedWorkRequestsTime, tickCount); _currentSampleStartTime = timestamp; } } finally { threadAdjustmentLock.Release(); } if (flag) { WorkerThread.MaybeAddWorkingWorker(this); } } private bool ShouldAdjustMaxWorkersActive(int currentTimeMs) { if (HillClimbing.IsDisabled) { return false; } int num = Volatile.Read(ref _separated.priorCompletedWorkRequestsTime); uint num2 = (uint)(_separated.nextCompletedWorkRequestsTime - num); uint num3 = (uint)(currentTimeMs - num); if (num3 < num2) { return false; } ThreadCounts counts = _separated.counts; if (counts.NumProcessingWork > counts.NumThreadsGoal) { return false; } return _pendingBlockingAdjustment == PendingBlockingAdjustment.None; } internal void RequestWorker() { Interlocked.Increment(ref _separated.numRequestedWorkers); WorkerThread.MaybeAddWorkingWorker(this); GateThread.EnsureRunning(this); } private bool OnGen2GCCallback() { GCMemoryInfo gCMemoryInfo = GC.GetGCMemoryInfo(); _memoryLimitBytes = gCMemoryInfo.HighMemoryLoadThresholdBytes; _memoryUsageBytes = Math.Min(gCMemoryInfo.MemoryLoadBytes, gCMemoryInfo.HighMemoryLoadThresholdBytes); return true; } public bool NotifyThreadBlocked() { if (!BlockingConfig.IsCooperativeBlockingEnabled || !Thread.CurrentThread.IsThreadPoolThread) { return false; } bool flag = false; _threadAdjustmentLock.Acquire(); try { _numBlockedThreads++; if (_pendingBlockingAdjustment != PendingBlockingAdjustment.WithDelayIfNecessary && _separated.counts.NumThreadsGoal < TargetThreadsGoalForBlockingAdjustment) { if (_pendingBlockingAdjustment == PendingBlockingAdjustment.None) { flag = true; } _pendingBlockingAdjustment = PendingBlockingAdjustment.WithDelayIfNecessary; } } finally { _threadAdjustmentLock.Release(); } if (flag) { GateThread.Wake(this); } return true; } public void NotifyThreadUnblocked() { bool flag = false; _threadAdjustmentLock.Acquire(); try { _numBlockedThreads--; if (_pendingBlockingAdjustment != PendingBlockingAdjustment.Immediately && _numThreadsAddedDueToBlocking > 0 && _separated.counts.NumThreadsGoal > TargetThreadsGoalForBlockingAdjustment) { flag = true; _pendingBlockingAdjustment = PendingBlockingAdjustment.Immediately; } } finally { _threadAdjustmentLock.Release(); } if (flag) { GateThread.Wake(this); } } private uint PerformBlockingAdjustment(bool previousDelayElapsed) { _threadAdjustmentLock.Acquire(); uint result; bool addWorker; try { result = PerformBlockingAdjustment(previousDelayElapsed, out addWorker); } finally { _threadAdjustmentLock.Release(); } if (addWorker) { WorkerThread.MaybeAddWorkingWorker(this); } return result; } private uint PerformBlockingAdjustment(bool previousDelayElapsed, out bool addWorker) { _pendingBlockingAdjustment = PendingBlockingAdjustment.None; addWorker = false; short targetThreadsGoalForBlockingAdjustment = TargetThreadsGoalForBlockingAdjustment; ThreadCounts counts = _separated.counts; short num = counts.NumThreadsGoal; if (num == targetThreadsGoalForBlockingAdjustment) { return 0u; } if (num > targetThreadsGoalForBlockingAdjustment) { if (_numThreadsAddedDueToBlocking <= 0) { return 0u; } short num2 = Math.Min((short)(num - targetThreadsGoalForBlockingAdjustment), _numThreadsAddedDueToBlocking); _numThreadsAddedDueToBlocking -= num2; num -= num2; _separated.counts.InterlockedSetNumThreadsGoal(num); HillClimbing.ThreadPoolHillClimber.ForceChange(num, HillClimbing.StateOrTransition.CooperativeBlocking); return 0u; } short num3 = (short)Math.Min((ushort)(_minThreads + BlockingConfig.ThreadsToAddWithoutDelay), (ushort)_maxThreads); short val = Math.Max(num3, Math.Min(counts.NumExistingThreads, _maxThreads)); short num4 = Math.Min(targetThreadsGoalForBlockingAdjustment, val); short num5; if (num < num4) { num5 = num4; } else { if (!previousDelayElapsed) { goto IL_019f; } num5 = (short)(num + 1); } if (num5 > counts.NumExistingThreads) { long memoryLimitBytes = _memoryLimitBytes; if (memoryLimitBytes > 0) { long num6 = _memoryUsageBytes + (long)counts.NumExistingThreads * 65536L; long num7 = memoryLimitBytes * 8 / 10; if (num6 >= num7) { return 0u; } long val2 = counts.NumExistingThreads + (num7 - num6) / 65536; num5 = (short)Math.Min(num5, val2); if (num5 <= num) { return 0u; } } } _numThreadsAddedDueToBlocking += (short)(num5 - num); counts = _separated.counts.InterlockedSetNumThreadsGoal(num5); HillClimbing.ThreadPoolHillClimber.ForceChange(num5, HillClimbing.StateOrTransition.CooperativeBlocking); if (counts.NumProcessingWork >= num && _separated.numRequestedWorkers > 0) { addWorker = true; } num = num5; if (num >= targetThreadsGoalForBlockingAdjustment) { return 0u; } goto IL_019f; IL_019f: _pendingBlockingAdjustment = PendingBlockingAdjustment.WithDelayIfNecessary; int num8 = 1 + (num - num3) / BlockingConfig.ThreadsPerDelayStep; return Math.Min((uint)num8 * BlockingConfig.DelayStepMs, BlockingConfig.MaxDelayMs); } internal static void EnsureGateThreadRunning() { GateThread.EnsureRunning(ThreadPoolInstance); } internal void RegisterWaitHandle(RegisteredWaitHandle handle) { if (NativeRuntimeEventSource.Log.IsEnabled()) { NativeRuntimeEventSource.Log.ThreadPoolIOEnqueue(handle); } _waitThreadLock.Acquire(); try { WaitThreadNode waitThreadNode = _waitThreadsHead; if (waitThreadNode == null) { waitThreadNode = (_waitThreadsHead = new WaitThreadNode(new WaitThread())); } WaitThreadNode waitThreadNode2; do { if (waitThreadNode.Thread.RegisterWaitHandle(handle)) { return; } waitThreadNode2 = waitThreadNode; waitThreadNode = waitThreadNode.Next; } while (waitThreadNode != null); waitThreadNode2.Next = new WaitThreadNode(new WaitThread()); waitThreadNode2.Next.Thread.RegisterWaitHandle(handle); } finally { _waitThreadLock.Release(); } } internal static void CompleteWait(RegisteredWaitHandle handle, bool timedOut) { if (NativeRuntimeEventSource.Log.IsEnabled()) { NativeRuntimeEventSource.Log.ThreadPoolIODequeue(handle); } handle.PerformCallback(timedOut); } private bool TryRemoveWaitThread(WaitThread thread) { _waitThreadLock.Acquire(); try { if (thread.AnyUserWaits) { return false; } RemoveWaitThread(thread); } finally { _waitThreadLock.Release(); } return true; } private void RemoveWaitThread(WaitThread thread) { WaitThreadNode waitThreadNode = _waitThreadsHead; if (waitThreadNode.Thread == thread) { _waitThreadsHead = waitThreadNode.Next; return; } WaitThreadNode waitThreadNode2; do { waitThreadNode2 = waitThreadNode; waitThreadNode = waitThreadNode.Next; } while (waitThreadNode != null && waitThreadNode.Thread != thread); if (waitThreadNode != null) { waitThreadNode2.Next = waitThreadNode.Next; } } public void ReportThreadStatus(bool isProcessingUserCallback) { CountsOfThreadsProcessingUserCallbacks countsOfThreadsProcessingUserCallbacks = _countsOfThreadsProcessingUserCallbacks; while (true) { CountsOfThreadsProcessingUserCallbacks newCounts = countsOfThreadsProcessingUserCallbacks; if (isProcessingUserCallback) { newCounts.IncrementCurrent(); } else { newCounts.DecrementCurrent(); } CountsOfThreadsProcessingUserCallbacks countsOfThreadsProcessingUserCallbacks2 = _countsOfThreadsProcessingUserCallbacks.InterlockedCompareExchange(newCounts, countsOfThreadsProcessingUserCallbacks); if (!(countsOfThreadsProcessingUserCallbacks2 == countsOfThreadsProcessingUserCallbacks)) { countsOfThreadsProcessingUserCallbacks = countsOfThreadsProcessingUserCallbacks2; continue; } break; } } private short GetAndResetHighWatermarkCountOfThreadsProcessingUserCallbacks() { CountsOfThreadsProcessingUserCallbacks countsOfThreadsProcessingUserCallbacks = _countsOfThreadsProcessingUserCallbacks; CountsOfThreadsProcessingUserCallbacks countsOfThreadsProcessingUserCallbacks2; while (true) { CountsOfThreadsProcessingUserCallbacks newCounts = countsOfThreadsProcessingUserCallbacks; newCounts.ResetHighWatermark(); countsOfThreadsProcessingUserCallbacks2 = _countsOfThreadsProcessingUserCallbacks.InterlockedCompareExchange(newCounts, countsOfThreadsProcessingUserCallbacks); if (countsOfThreadsProcessingUserCallbacks2 == countsOfThreadsProcessingUserCallbacks || countsOfThreadsProcessingUserCallbacks2.HighWatermark == countsOfThreadsProcessingUserCallbacks2.Current) { break; } countsOfThreadsProcessingUserCallbacks = countsOfThreadsProcessingUserCallbacks2; } return countsOfThreadsProcessingUserCallbacks2.HighWatermark; } } internal sealed class LowLevelLifoSemaphore : IDisposable { private struct Counts { private ulong _data; public uint SignalCount { get { return GetUInt32Value(0); } set { SetUInt32Value(value, 0); } } public ushort WaiterCount => GetUInt16Value(32); public byte SpinnerCount => GetByteValue(48); public byte CountOfWaitersSignaledToWake => GetByteValue(56); private Counts(ulong data) { _data = data; } private uint GetUInt32Value(byte shift) { return (uint)(_data >> (int)shift); } private void SetUInt32Value(uint value, byte shift) { _data = (_data & ~(4294967295uL << (int)shift)) | ((ulong)value << (int)shift); } private ushort GetUInt16Value(byte shift) { return (ushort)(_data >> (int)shift); } private byte GetByteValue(byte shift) { return (byte)(_data >> (int)shift); } public void AddSignalCount(uint value) { _data += value; } public void DecrementSignalCount() { _data--; } public void IncrementWaiterCount() { _data += 4294967296uL; } public void DecrementWaiterCount() { _data -= 4294967296uL; } public void InterlockedDecrementWaiterCount() { Counts counts = new Counts(Interlocked.Add(ref _data, 18446744069414584320uL)); } public void IncrementSpinnerCount() { _data += 281474976710656uL; } public void DecrementSpinnerCount() { _data -= 281474976710656uL; } public void AddUpToMaxCountOfWaitersSignaledToWake(uint value) { uint num = (uint)(255 - CountOfWaitersSignaledToWake); if (value > num) { value = num; } _data += (ulong)value << 56; } public void DecrementCountOfWaitersSignaledToWake() { _data -= 72057594037927936uL; } public Counts InterlockedCompareExchange(Counts newCounts, Counts oldCounts) { return new Counts(Interlocked.CompareExchange(ref _data, newCounts._data, oldCounts._data)); } public static bool operator ==(Counts lhs, Counts rhs) { return lhs._data == rhs._data; } public override bool Equals([NotNullWhen(true)] object obj) { if (obj is Counts counts) { return _data == counts._data; } return false; } public override int GetHashCode() { return (int)_data + (int)(_data >> 32); } } private struct CacheLineSeparatedCounts { private readonly PaddingFor32 _pad1; public Counts _counts; private readonly PaddingFor32 _pad2; } private CacheLineSeparatedCounts _separated; private readonly int _maximumSignalCount; private readonly int _spinCount; private readonly Action _onWait; private IntPtr _completionPort; public LowLevelLifoSemaphore(int initialSignalCount, int maximumSignalCount, int spinCount, Action onWait) { _separated = default(CacheLineSeparatedCounts); _separated._counts.SignalCount = (uint)initialSignalCount; _maximumSignalCount = maximumSignalCount; _spinCount = spinCount; _onWait = onWait; Create(maximumSignalCount); } public bool Wait(int timeoutMs, bool spinWait) { int num = (spinWait ? _spinCount : 0); Counts counts = _separated._counts; Counts newCounts; while (true) { newCounts = counts; if (counts.SignalCount != 0) { newCounts.DecrementSignalCount(); } else if (timeoutMs != 0) { if (num > 0 && newCounts.SpinnerCount < byte.MaxValue) { newCounts.IncrementSpinnerCount(); } else { newCounts.IncrementWaiterCount(); } } Counts counts2 = _separated._counts.InterlockedCompareExchange(newCounts, counts); if (counts2 == counts) { break; } counts = counts2; } if (counts.SignalCount != 0) { return true; } if (newCounts.WaiterCount != counts.WaiterCount) { return WaitForSignal(timeoutMs); } if (timeoutMs == 0) { return false; } int processorCount = Environment.ProcessorCount; int num2 = ((processorCount <= 1) ? 10 : 0); while (num2 < num) { LowLevelSpinWaiter.Wait(num2, 10, processorCount); num2++; counts = _separated._counts; while (counts.SignalCount != 0) { Counts newCounts2 = counts; newCounts2.DecrementSignalCount(); newCounts2.DecrementSpinnerCount(); Counts counts3 = _separated._counts.InterlockedCompareExchange(newCounts2, counts); if (counts3 == counts) { return true; } counts = counts3; } } counts = _separated._counts; while (true) { Counts newCounts3 = counts; newCounts3.DecrementSpinnerCount(); if (counts.SignalCount != 0) { newCounts3.DecrementSignalCount(); } else { newCounts3.IncrementWaiterCount(); } Counts counts4 = _separated._counts.InterlockedCompareExchange(newCounts3, counts); if (counts4 == counts) { break; } counts = counts4; } if (counts.SignalCount == 0) { return WaitForSignal(timeoutMs); } return true; } public void Release(int releaseCount) { Counts counts = _separated._counts; int num; while (true) { Counts newCounts = counts; newCounts.AddSignalCount((uint)releaseCount); num = (int)(Math.Min(newCounts.SignalCount, (uint)(counts.WaiterCount + counts.SpinnerCount)) - counts.SpinnerCount - counts.CountOfWaitersSignaledToWake); if (num > 0) { if (num > releaseCount) { num = releaseCount; } newCounts.AddUpToMaxCountOfWaitersSignaledToWake((uint)num); } Counts counts2 = _separated._counts.InterlockedCompareExchange(newCounts, counts); if (counts2 == counts) { break; } counts = counts2; } if (num > 0) { ReleaseCore(num); } } private bool WaitForSignal(int timeoutMs) { _onWait(); Counts counts; do { if (!WaitCore(timeoutMs)) { _separated._counts.InterlockedDecrementWaiterCount(); return false; } counts = _separated._counts; while (true) { Counts newCounts = counts; if (counts.SignalCount != 0) { newCounts.DecrementSignalCount(); newCounts.DecrementWaiterCount(); } if (counts.CountOfWaitersSignaledToWake != 0) { newCounts.DecrementCountOfWaitersSignaledToWake(); } Counts counts2 = _separated._counts.InterlockedCompareExchange(newCounts, counts); if (counts2 == counts) { break; } counts = counts2; } } while (counts.SignalCount == 0); return true; } private void Create(int maximumSignalCount) { _completionPort = Interop.Kernel32.CreateIoCompletionPort(new IntPtr(-1), IntPtr.Zero, UIntPtr.Zero, maximumSignalCount); if (_completionPort == IntPtr.Zero) { int lastPInvokeError = Marshal.GetLastPInvokeError(); OutOfMemoryException ex = new OutOfMemoryException(); ex.HResult = lastPInvokeError; throw ex; } } ~LowLevelLifoSemaphore() { if (_completionPort != IntPtr.Zero) { Dispose(); } } public bool WaitCore(int timeoutMs) { int lpNumberOfBytes; UIntPtr CompletionKey; IntPtr lpOverlapped; return Interop.Kernel32.GetQueuedCompletionStatus(_completionPort, out lpNumberOfBytes, out CompletionKey, out lpOverlapped, timeoutMs); } public void ReleaseCore(int count) { for (int i = 0; i < count; i++) { if (!Interop.Kernel32.PostQueuedCompletionStatus(_completionPort, 1, UIntPtr.Zero, IntPtr.Zero)) { int lastPInvokeError = Marshal.GetLastPInvokeError(); OutOfMemoryException ex = new OutOfMemoryException(); ex.HResult = lastPInvokeError; throw ex; } } } public void Dispose() { Interop.Kernel32.CloseHandle(_completionPort); _completionPort = IntPtr.Zero; GC.SuppressFinalize(this); } } } namespace System.Threading.Tasks { internal enum AsyncCausalityStatus { Started, Completed, Canceled, Error } internal enum CausalityRelation { AssignDelegate, Join, Choice, Cancel, Error } internal enum CausalitySynchronousWork { CompletionNotification, ProgressNotification, Execution } [DebuggerDisplay("Concurrent={ConcurrentTaskCountForDebugger}, Exclusive={ExclusiveTaskCountForDebugger}, Mode={ModeForDebugger}")] [DebuggerTypeProxy(typeof(DebugView))] public class ConcurrentExclusiveSchedulerPair { private sealed class CompletionState : Task { internal bool m_completionRequested; internal bool m_completionQueued; internal List m_exceptions; } private sealed class SchedulerWorkItem : IThreadPoolWorkItem { private readonly ConcurrentExclusiveSchedulerPair _pair; internal SchedulerWorkItem(ConcurrentExclusiveSchedulerPair pair) { _pair = pair; } void IThreadPoolWorkItem.Execute() { if (_pair.m_processingCount == -1) { _pair.ProcessExclusiveTasks(); } else { _pair.ProcessConcurrentTasks(); } } } [DebuggerDisplay("Count={CountForDebugger}, MaxConcurrencyLevel={m_maxConcurrencyLevel}, Id={Id}")] [DebuggerTypeProxy(typeof(DebugView))] private sealed class ConcurrentExclusiveTaskScheduler : TaskScheduler { private sealed class DebugView { private readonly ConcurrentExclusiveTaskScheduler m_taskScheduler; public int MaximumConcurrencyLevel => m_taskScheduler.m_maxConcurrencyLevel; public IEnumerable ScheduledTasks => m_taskScheduler.m_tasks; public ConcurrentExclusiveSchedulerPair SchedulerPair => m_taskScheduler.m_pair; public DebugView(ConcurrentExclusiveTaskScheduler scheduler) { m_taskScheduler = scheduler; } } private readonly ConcurrentExclusiveSchedulerPair m_pair; private readonly int m_maxConcurrencyLevel; private readonly ProcessingMode m_processingMode; internal readonly IProducerConsumerQueue m_tasks; public override int MaximumConcurrencyLevel => m_maxConcurrencyLevel; private int CountForDebugger => m_tasks.Count; internal ConcurrentExclusiveTaskScheduler(ConcurrentExclusiveSchedulerPair pair, int maxConcurrencyLevel, ProcessingMode processingMode) { m_pair = pair; m_maxConcurrencyLevel = maxConcurrencyLevel; m_processingMode = processingMode; IProducerConsumerQueue tasks; if (processingMode != ProcessingMode.ProcessingExclusiveTask) { IProducerConsumerQueue producerConsumerQueue = new MultiProducerMultiConsumerQueue(); tasks = producerConsumerQueue; } else { IProducerConsumerQueue producerConsumerQueue = new SingleProducerSingleConsumerQueue(); tasks = producerConsumerQueue; } m_tasks = tasks; } protected internal override void QueueTask(Task task) { lock (m_pair.ValueLock) { if (m_pair.CompletionRequested) { throw new InvalidOperationException(GetType().ToString()); } m_tasks.Enqueue(task); m_pair.ProcessAsyncIfNecessary(); } } internal void ExecuteTask(Task task) { TryExecuteTask(task); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (!taskWasPreviouslyQueued && m_pair.CompletionRequested) { return false; } bool flag = m_pair.m_underlyingTaskScheduler == TaskScheduler.Default; if (flag && taskWasPreviouslyQueued && !Thread.CurrentThread.IsThreadPoolThread) { return false; } if (m_pair.m_threadProcessingMode.Value == m_processingMode) { if (!flag || taskWasPreviouslyQueued) { return TryExecuteTaskInlineOnTargetScheduler(task); } return TryExecuteTask(task); } return false; } private bool TryExecuteTaskInlineOnTargetScheduler(Task task) { Task task2 = new Task(delegate(object s) { TupleSlim tupleSlim = (TupleSlim)s; return tupleSlim.Item1.TryExecuteTask(tupleSlim.Item2); }, new TupleSlim(this, task)); try { task2.RunSynchronously(m_pair.m_underlyingTaskScheduler); return task2.Result; } catch { _ = task2.Exception; throw; } finally { task2.Dispose(); } } protected override IEnumerable GetScheduledTasks() { return m_tasks; } } private sealed class DebugView { private readonly ConcurrentExclusiveSchedulerPair m_pair; public ProcessingMode Mode => m_pair.ModeForDebugger; public IEnumerable ScheduledExclusive => m_pair.m_exclusiveTaskScheduler.m_tasks; public IEnumerable ScheduledConcurrent => m_pair.m_concurrentTaskScheduler.m_tasks; public int CurrentlyExecutingTaskCount { get { if (m_pair.m_processingCount != -1) { return m_pair.m_processingCount; } return 1; } } public TaskScheduler TargetScheduler => m_pair.m_underlyingTaskScheduler; public DebugView(ConcurrentExclusiveSchedulerPair pair) { m_pair = pair; } } [Flags] private enum ProcessingMode : byte { NotCurrentlyProcessing = 0, ProcessingExclusiveTask = 1, ProcessingConcurrentTasks = 2, Completing = 4, Completed = 8 } private readonly ThreadLocal m_threadProcessingMode = new ThreadLocal(); private readonly ConcurrentExclusiveTaskScheduler m_concurrentTaskScheduler; private readonly ConcurrentExclusiveTaskScheduler m_exclusiveTaskScheduler; private readonly TaskScheduler m_underlyingTaskScheduler; private readonly int m_maxConcurrencyLevel; private readonly int m_maxItemsPerTask; private int m_processingCount; private CompletionState m_completionState; private SchedulerWorkItem m_threadPoolWorkItem; private static int DefaultMaxConcurrencyLevel => Environment.ProcessorCount; private object ValueLock => m_threadProcessingMode; public Task Completion => EnsureCompletionStateInitialized(); private bool CompletionRequested { get { if (m_completionState != null) { return Volatile.Read(ref m_completionState.m_completionRequested); } return false; } } private bool ReadyToComplete { get { if (!CompletionRequested || m_processingCount != 0) { return false; } CompletionState completionState = EnsureCompletionStateInitialized(); if (completionState.m_exceptions == null || completionState.m_exceptions.Count <= 0) { if (m_concurrentTaskScheduler.m_tasks.IsEmpty) { return m_exclusiveTaskScheduler.m_tasks.IsEmpty; } return false; } return true; } } public TaskScheduler ConcurrentScheduler => m_concurrentTaskScheduler; public TaskScheduler ExclusiveScheduler => m_exclusiveTaskScheduler; private int ConcurrentTaskCountForDebugger => m_concurrentTaskScheduler.m_tasks.Count; private int ExclusiveTaskCountForDebugger => m_exclusiveTaskScheduler.m_tasks.Count; private ProcessingMode ModeForDebugger { get { if (m_completionState != null && m_completionState.IsCompleted) { return ProcessingMode.Completed; } ProcessingMode processingMode = ProcessingMode.NotCurrentlyProcessing; if (m_processingCount == -1) { processingMode |= ProcessingMode.ProcessingExclusiveTask; } if (m_processingCount >= 1) { processingMode |= ProcessingMode.ProcessingConcurrentTasks; } if (CompletionRequested) { processingMode |= ProcessingMode.Completing; } return processingMode; } } public ConcurrentExclusiveSchedulerPair() : this(TaskScheduler.Default, DefaultMaxConcurrencyLevel, -1) { } public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler) : this(taskScheduler, DefaultMaxConcurrencyLevel, -1) { } public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel) : this(taskScheduler, maxConcurrencyLevel, -1) { } public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel, int maxItemsPerTask) { if (taskScheduler == null) { throw new ArgumentNullException("taskScheduler"); } if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) { throw new ArgumentOutOfRangeException("maxConcurrencyLevel"); } if (maxItemsPerTask == 0 || maxItemsPerTask < -1) { throw new ArgumentOutOfRangeException("maxItemsPerTask"); } m_underlyingTaskScheduler = taskScheduler; m_maxConcurrencyLevel = maxConcurrencyLevel; m_maxItemsPerTask = maxItemsPerTask; int maximumConcurrencyLevel = taskScheduler.MaximumConcurrencyLevel; if (maximumConcurrencyLevel > 0 && maximumConcurrencyLevel < m_maxConcurrencyLevel) { m_maxConcurrencyLevel = maximumConcurrencyLevel; } if (m_maxConcurrencyLevel == -1) { m_maxConcurrencyLevel = int.MaxValue; } if (m_maxItemsPerTask == -1) { m_maxItemsPerTask = int.MaxValue; } m_exclusiveTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, 1, ProcessingMode.ProcessingExclusiveTask); m_concurrentTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, m_maxConcurrencyLevel, ProcessingMode.ProcessingConcurrentTasks); } public void Complete() { lock (ValueLock) { if (!CompletionRequested) { RequestCompletion(); CleanupStateIfCompletingAndQuiesced(); } } } private CompletionState EnsureCompletionStateInitialized() { return Volatile.Read(ref m_completionState) ?? InitializeCompletionState(); CompletionState InitializeCompletionState() { Interlocked.CompareExchange(ref m_completionState, new CompletionState(), null); return m_completionState; } } private void RequestCompletion() { EnsureCompletionStateInitialized().m_completionRequested = true; } private void CleanupStateIfCompletingAndQuiesced() { if (ReadyToComplete) { CompleteTaskAsync(); } } private void CompleteTaskAsync() { CompletionState completionState = EnsureCompletionStateInitialized(); if (!completionState.m_completionQueued) { completionState.m_completionQueued = true; ThreadPool.QueueUserWorkItem(delegate(object state) { ConcurrentExclusiveSchedulerPair concurrentExclusiveSchedulerPair = (ConcurrentExclusiveSchedulerPair)state; List exceptions = concurrentExclusiveSchedulerPair.m_completionState.m_exceptions; bool flag = ((exceptions != null && exceptions.Count > 0) ? concurrentExclusiveSchedulerPair.m_completionState.TrySetException(exceptions) : concurrentExclusiveSchedulerPair.m_completionState.TrySetResult()); concurrentExclusiveSchedulerPair.m_threadProcessingMode.Dispose(); }, this); } } private void FaultWithTask(Task faultedTask) { AggregateException exception = faultedTask.Exception; CompletionState completionState = EnsureCompletionStateInitialized(); CompletionState completionState2 = completionState; if (completionState2.m_exceptions == null) { completionState2.m_exceptions = new List(exception.InnerExceptionCount); } completionState.m_exceptions.AddRange(exception.InternalInnerExceptions); RequestCompletion(); } private void ProcessAsyncIfNecessary(bool fairly = false) { if (m_processingCount < 0) { return; } bool flag = !m_exclusiveTaskScheduler.m_tasks.IsEmpty; Task task = null; if (m_processingCount == 0 && flag) { m_processingCount = -1; if (!TryQueueThreadPoolWorkItem(fairly)) { try { task = new Task(delegate(object thisPair) { ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessExclusiveTasks(); }, this, default(CancellationToken), GetCreationOptionsForTask(fairly)); task.Start(m_underlyingTaskScheduler); } catch (Exception exception) { m_processingCount = 0; FaultWithTask(task ?? Task.FromException(exception)); } } } else { int count = m_concurrentTaskScheduler.m_tasks.Count; if (count > 0 && !flag && m_processingCount < m_maxConcurrencyLevel) { for (int i = 0; i < count; i++) { if (m_processingCount >= m_maxConcurrencyLevel) { break; } m_processingCount++; if (TryQueueThreadPoolWorkItem(fairly)) { continue; } try { task = new Task(delegate(object thisPair) { ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessConcurrentTasks(); }, this, default(CancellationToken), GetCreationOptionsForTask(fairly)); task.Start(m_underlyingTaskScheduler); } catch (Exception exception2) { m_processingCount--; FaultWithTask(task ?? Task.FromException(exception2)); } } } } CleanupStateIfCompletingAndQuiesced(); } private bool TryQueueThreadPoolWorkItem(bool fairly) { if (TaskScheduler.Default == m_underlyingTaskScheduler) { IThreadPoolWorkItem callBack = m_threadPoolWorkItem ?? (m_threadPoolWorkItem = new SchedulerWorkItem(this)); ThreadPool.UnsafeQueueUserWorkItemInternal(callBack, !fairly); return true; } return false; } private void ProcessExclusiveTasks() { try { m_threadProcessingMode.Value = ProcessingMode.ProcessingExclusiveTask; for (int i = 0; i < m_maxItemsPerTask; i++) { if (!m_exclusiveTaskScheduler.m_tasks.TryDequeue(out var result)) { break; } if (!result.IsFaulted) { m_exclusiveTaskScheduler.ExecuteTask(result); } } } finally { m_threadProcessingMode.Value = ProcessingMode.NotCurrentlyProcessing; lock (ValueLock) { m_processingCount = 0; ProcessAsyncIfNecessary(fairly: true); } } } private void ProcessConcurrentTasks() { try { m_threadProcessingMode.Value = ProcessingMode.ProcessingConcurrentTasks; for (int i = 0; i < m_maxItemsPerTask; i++) { if (!m_concurrentTaskScheduler.m_tasks.TryDequeue(out var result)) { break; } if (!result.IsFaulted) { m_concurrentTaskScheduler.ExecuteTask(result); } if (!m_exclusiveTaskScheduler.m_tasks.IsEmpty) { break; } } } finally { m_threadProcessingMode.Value = ProcessingMode.NotCurrentlyProcessing; lock (ValueLock) { if (m_processingCount > 0) { m_processingCount--; } ProcessAsyncIfNecessary(fairly: true); } } } internal static TaskCreationOptions GetCreationOptionsForTask(bool isReplacementReplica = false) { TaskCreationOptions taskCreationOptions = TaskCreationOptions.DenyChildAttach; if (isReplacementReplica) { taskCreationOptions |= TaskCreationOptions.PreferFairness; } return taskCreationOptions; } } [DebuggerTypeProxy(typeof(SystemThreadingTasks_FutureDebugView<>))] [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}, Result = {DebuggerDisplayResultDescription}")] public class Task : Task { internal static class TaskWhenAnyCast { internal static readonly Func, Task> Value = (Task completed) => (Task)completed.Result; } internal static readonly Task s_defaultResultTask = TaskCache.CreateCacheableTask(default(TResult)); private static TaskFactory s_Factory; internal TResult m_result; private string DebuggerDisplayResultDescription { get { if (!base.IsCompletedSuccessfully) { return SR.TaskT_DebuggerNoResult; } TResult result = m_result; return result?.ToString() ?? ""; } } private string DebuggerDisplayMethodDescription => m_action?.Method.ToString() ?? "{null}"; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public TResult Result { get { if (!base.IsWaitNotificationEnabledOrNotRanToCompletion) { return m_result; } return GetResultCore(waitCompletionNotification: true); } } internal TResult ResultOnSuccess => m_result; public new static TaskFactory Factory => Volatile.Read(ref s_Factory) ?? Interlocked.CompareExchange(ref s_Factory, new TaskFactory(), null) ?? s_Factory; internal Task() { } internal Task(object state, TaskCreationOptions options) : base(state, options, promiseStyle: true) { } internal Task(TResult result) : base(canceled: false, TaskCreationOptions.None, default(CancellationToken)) { m_result = result; } internal Task(bool canceled, TResult result, TaskCreationOptions creationOptions, CancellationToken ct) : base(canceled, creationOptions, ct) { if (!canceled) { m_result = result; } } public Task(Func function) : this(function, (Task)null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, (TaskScheduler)null) { } public Task(Func function, CancellationToken cancellationToken) : this(function, (Task)null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, (TaskScheduler)null) { } public Task(Func function, TaskCreationOptions creationOptions) : this(function, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, InternalTaskOptions.None, (TaskScheduler)null) { } public Task(Func function, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : this(function, Task.InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, (TaskScheduler)null) { } public Task(Func function, object? state) : this((Delegate)function, state, (Task)null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, (TaskScheduler)null) { } public Task(Func function, object? state, CancellationToken cancellationToken) : this((Delegate)function, state, (Task)null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, (TaskScheduler)null) { } public Task(Func function, object? state, TaskCreationOptions creationOptions) : this((Delegate)function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, InternalTaskOptions.None, (TaskScheduler)null) { } public Task(Func function, object? state, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : this((Delegate)function, state, Task.InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, (TaskScheduler)null) { } internal Task(Func valueSelector, Task parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) : base(valueSelector, null, parent, cancellationToken, creationOptions, internalOptions, scheduler) { } internal Task(Delegate valueSelector, object state, Task parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) : base(valueSelector, state, parent, cancellationToken, creationOptions, internalOptions, scheduler) { } internal static Task StartNew(Task parent, Func function, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) { if (function == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } Task task = new Task(function, parent, cancellationToken, creationOptions, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler); task.ScheduleAndStart(needsProtection: false); return task; } internal static Task StartNew(Task parent, Func function, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) { if (function == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } Task task = new Task(function, state, parent, cancellationToken, creationOptions, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler); task.ScheduleAndStart(needsProtection: false); return task; } internal bool TrySetResult(TResult result) { bool result2 = false; if (AtomicStateUpdate(67108864, 90177536)) { m_result = result; Interlocked.Exchange(ref m_stateFlags, m_stateFlags | 0x1000000); ContingentProperties contingentProperties = m_contingentProperties; if (contingentProperties != null) { NotifyParentIfPotentiallyAttachedTask(); contingentProperties.SetCompleted(); } FinishContinuations(); result2 = true; } return result2; } internal void DangerousSetResult(TResult result) { if (m_contingentProperties?.m_parent != null) { bool flag = TrySetResult(result); return; } m_result = result; m_stateFlags |= 16777216; } internal TResult GetResultCore(bool waitCompletionNotification) { if (!base.IsCompleted) { InternalWait(-1, default(CancellationToken)); } if (waitCompletionNotification) { NotifyDebuggerOfWaitCompletionIfNecessary(); } if (!base.IsCompletedSuccessfully) { ThrowIfExceptional(includeTaskCanceledExceptions: true); } return m_result; } internal override void InnerInvoke() { if (m_action is Func func) { m_result = func(); } else if (m_action is Func func2) { m_result = func2(m_stateObject); } } public new TaskAwaiter GetAwaiter() { return new TaskAwaiter(this); } public new ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) { return new ConfiguredTaskAwaitable(this, continueOnCapturedContext); } public new Task WaitAsync(CancellationToken cancellationToken) { return WaitAsync(uint.MaxValue, cancellationToken); } public new Task WaitAsync(TimeSpan timeout) { return WaitAsync(Task.ValidateTimeout(timeout, ExceptionArgument.timeout), default(CancellationToken)); } public new Task WaitAsync(TimeSpan timeout, CancellationToken cancellationToken) { return WaitAsync(Task.ValidateTimeout(timeout, ExceptionArgument.timeout), cancellationToken); } private Task WaitAsync(uint millisecondsTimeout, CancellationToken cancellationToken) { if (base.IsCompleted || (!cancellationToken.CanBeCanceled && millisecondsTimeout == uint.MaxValue)) { return this; } if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (millisecondsTimeout == 0) { return Task.FromException(new TimeoutException()); } return new CancellationPromise(this, millisecondsTimeout, cancellationToken); } public Task ContinueWith(Action> continuationAction) { return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Action> continuationAction, CancellationToken cancellationToken) { return ContinueWith(continuationAction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); } public Task ContinueWith(Action> continuationAction, TaskScheduler scheduler) { return ContinueWith(continuationAction, scheduler, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Action> continuationAction, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), continuationOptions); } public Task ContinueWith(Action> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { return ContinueWith(continuationAction, scheduler, cancellationToken, continuationOptions); } internal Task ContinueWith(Action> continuationAction, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { if (continuationAction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationAction); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } Task.CreationOptionsFromContinuationOptions(continuationOptions, out var creationOptions, out var internalOptions); Task task = new ContinuationTaskFromResultTask(this, continuationAction, null, creationOptions, internalOptions); ContinueWithCore(task, scheduler, cancellationToken, continuationOptions); return task; } public Task ContinueWith(Action, object?> continuationAction, object? state) { return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Action, object?> continuationAction, object? state, CancellationToken cancellationToken) { return ContinueWith(continuationAction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); } public Task ContinueWith(Action, object?> continuationAction, object? state, TaskScheduler scheduler) { return ContinueWith(continuationAction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Action, object?> continuationAction, object? state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions); } public Task ContinueWith(Action, object?> continuationAction, object? state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { return ContinueWith(continuationAction, state, scheduler, cancellationToken, continuationOptions); } internal Task ContinueWith(Action, object> continuationAction, object state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { if (continuationAction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationAction); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } Task.CreationOptionsFromContinuationOptions(continuationOptions, out var creationOptions, out var internalOptions); Task task = new ContinuationTaskFromResultTask(this, continuationAction, state, creationOptions, internalOptions); ContinueWithCore(task, scheduler, cancellationToken, continuationOptions); return task; } public Task ContinueWith(Func, TNewResult> continuationFunction) { return ContinueWith(continuationFunction, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Func, TNewResult> continuationFunction, CancellationToken cancellationToken) { return ContinueWith(continuationFunction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); } public Task ContinueWith(Func, TNewResult> continuationFunction, TaskScheduler scheduler) { return ContinueWith(continuationFunction, scheduler, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Func, TNewResult> continuationFunction, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationFunction, TaskScheduler.Current, default(CancellationToken), continuationOptions); } public Task ContinueWith(Func, TNewResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { return ContinueWith(continuationFunction, scheduler, cancellationToken, continuationOptions); } internal Task ContinueWith(Func, TNewResult> continuationFunction, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } Task.CreationOptionsFromContinuationOptions(continuationOptions, out var creationOptions, out var internalOptions); Task task = new ContinuationResultTaskFromResultTask(this, continuationFunction, null, creationOptions, internalOptions); ContinueWithCore(task, scheduler, cancellationToken, continuationOptions); return task; } public Task ContinueWith(Func, object?, TNewResult> continuationFunction, object? state) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Func, object?, TNewResult> continuationFunction, object? state, CancellationToken cancellationToken) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); } public Task ContinueWith(Func, object?, TNewResult> continuationFunction, object? state, TaskScheduler scheduler) { return ContinueWith(continuationFunction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Func, object?, TNewResult> continuationFunction, object? state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions); } public Task ContinueWith(Func, object?, TNewResult> continuationFunction, object? state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { return ContinueWith(continuationFunction, state, scheduler, cancellationToken, continuationOptions); } internal Task ContinueWith(Func, object, TNewResult> continuationFunction, object state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } Task.CreationOptionsFromContinuationOptions(continuationOptions, out var creationOptions, out var internalOptions); Task task = new ContinuationResultTaskFromResultTask(this, continuationFunction, state, creationOptions, internalOptions); ContinueWithCore(task, scheduler, cancellationToken, continuationOptions); return task; } } internal sealed class SystemThreadingTasks_FutureDebugView { private readonly Task m_task; public TResult Result { get { if (m_task.Status != TaskStatus.RanToCompletion) { return default(TResult); } return m_task.Result; } } public object AsyncState => m_task.AsyncState; public TaskCreationOptions CreationOptions => m_task.CreationOptions; public Exception Exception => m_task.Exception; public int Id => m_task.Id; public bool CancellationPending { get { if (m_task.Status == TaskStatus.WaitingToRun) { return m_task.CancellationToken.IsCancellationRequested; } return false; } } public TaskStatus Status => m_task.Status; public SystemThreadingTasks_FutureDebugView(Task task) { m_task = task; } } public class TaskFactory { private sealed class FromAsyncTrimPromise : Task where TInstance : class { internal static readonly AsyncCallback s_completeFromAsyncResult = CompleteFromAsyncResult; private TInstance m_thisRef; private Func m_endMethod; internal FromAsyncTrimPromise(TInstance thisRef, Func endMethod) { m_thisRef = thisRef; m_endMethod = endMethod; } internal static void CompleteFromAsyncResult(IAsyncResult asyncResult) { if (asyncResult == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult); } FromAsyncTrimPromise fromAsyncTrimPromise = asyncResult.AsyncState as FromAsyncTrimPromise; if (fromAsyncTrimPromise == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple, ExceptionArgument.asyncResult); } TInstance thisRef = fromAsyncTrimPromise.m_thisRef; Func endMethod = fromAsyncTrimPromise.m_endMethod; fromAsyncTrimPromise.m_thisRef = null; fromAsyncTrimPromise.m_endMethod = null; if (endMethod == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple, ExceptionArgument.asyncResult); } if (!asyncResult.CompletedSynchronously) { fromAsyncTrimPromise.Complete(thisRef, endMethod, asyncResult, requiresSynchronization: true); } } internal void Complete(TInstance thisRef, Func endMethod, IAsyncResult asyncResult, bool requiresSynchronization) { try { TResult result = endMethod(thisRef, asyncResult); bool flag; if (requiresSynchronization) { flag = TrySetResult(result); return; } DangerousSetResult(result); flag = true; } catch (OperationCanceledException ex) { bool flag = TrySetCanceled(ex.CancellationToken, ex); } catch (Exception exceptionObject) { bool flag = TrySetException(exceptionObject); } } } private readonly CancellationToken m_defaultCancellationToken; private readonly TaskScheduler m_defaultScheduler; private readonly TaskCreationOptions m_defaultCreationOptions; private readonly TaskContinuationOptions m_defaultContinuationOptions; private TaskScheduler DefaultScheduler => m_defaultScheduler ?? TaskScheduler.Current; public CancellationToken CancellationToken => m_defaultCancellationToken; public TaskScheduler? Scheduler => m_defaultScheduler; public TaskCreationOptions CreationOptions => m_defaultCreationOptions; public TaskContinuationOptions ContinuationOptions => m_defaultContinuationOptions; private TaskScheduler GetDefaultScheduler(Task currTask) { if (m_defaultScheduler != null) { return m_defaultScheduler; } if (currTask != null && (currTask.CreationOptions & TaskCreationOptions.HideScheduler) == 0) { return currTask.ExecutingTaskScheduler; } return TaskScheduler.Default; } public TaskFactory() { } public TaskFactory(CancellationToken cancellationToken) { m_defaultCancellationToken = cancellationToken; } public TaskFactory(TaskScheduler? scheduler) { m_defaultScheduler = scheduler; } public TaskFactory(TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions) { TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions); TaskFactory.CheckCreationOptions(creationOptions); m_defaultCreationOptions = creationOptions; m_defaultContinuationOptions = continuationOptions; } public TaskFactory(CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions, TaskScheduler? scheduler) : this(creationOptions, continuationOptions) { m_defaultCancellationToken = cancellationToken; m_defaultScheduler = scheduler; } public Task StartNew(Func function) { Task internalCurrent = Task.InternalCurrent; return Task.StartNew(internalCurrent, function, m_defaultCancellationToken, m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(internalCurrent)); } public Task StartNew(Func function, CancellationToken cancellationToken) { Task internalCurrent = Task.InternalCurrent; return Task.StartNew(internalCurrent, function, cancellationToken, m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(internalCurrent)); } public Task StartNew(Func function, TaskCreationOptions creationOptions) { Task internalCurrent = Task.InternalCurrent; return Task.StartNew(internalCurrent, function, m_defaultCancellationToken, creationOptions, InternalTaskOptions.None, GetDefaultScheduler(internalCurrent)); } public Task StartNew(Func function, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return Task.StartNew(Task.InternalCurrentIfAttached(creationOptions), function, cancellationToken, creationOptions, InternalTaskOptions.None, scheduler); } public Task StartNew(Func function, object? state) { Task internalCurrent = Task.InternalCurrent; return Task.StartNew(internalCurrent, function, state, m_defaultCancellationToken, m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(internalCurrent)); } public Task StartNew(Func function, object? state, CancellationToken cancellationToken) { Task internalCurrent = Task.InternalCurrent; return Task.StartNew(internalCurrent, function, state, cancellationToken, m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(internalCurrent)); } public Task StartNew(Func function, object? state, TaskCreationOptions creationOptions) { Task internalCurrent = Task.InternalCurrent; return Task.StartNew(internalCurrent, function, state, m_defaultCancellationToken, creationOptions, InternalTaskOptions.None, GetDefaultScheduler(internalCurrent)); } public Task StartNew(Func function, object? state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return Task.StartNew(Task.InternalCurrentIfAttached(creationOptions), function, state, cancellationToken, creationOptions, InternalTaskOptions.None, scheduler); } private static void FromAsyncCoreLogic(IAsyncResult iar, Func endFunction, Action endAction, Task promise, bool requiresSynchronization) { Exception ex = null; OperationCanceledException ex2 = null; TResult result = default(TResult); try { if (endFunction != null) { result = endFunction(iar); } else { endAction(iar); } } catch (OperationCanceledException ex3) { ex2 = ex3; } catch (Exception ex4) { ex = ex4; } finally { if (ex2 != null) { promise.TrySetCanceled(ex2.CancellationToken, ex2); } else if (ex != null) { promise.TrySetException(ex); } else { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(promise.Id, AsyncCausalityStatus.Completed); } if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(promise); } if (requiresSynchronization) { promise.TrySetResult(result); } else { promise.DangerousSetResult(result); } } } } public Task FromAsync(IAsyncResult asyncResult, Func endMethod) { return FromAsyncImpl(asyncResult, endMethod, null, m_defaultCreationOptions, DefaultScheduler); } public Task FromAsync(IAsyncResult asyncResult, Func endMethod, TaskCreationOptions creationOptions) { return FromAsyncImpl(asyncResult, endMethod, null, creationOptions, DefaultScheduler); } public Task FromAsync(IAsyncResult asyncResult, Func endMethod, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return FromAsyncImpl(asyncResult, endMethod, null, creationOptions, scheduler); } internal static Task FromAsyncImpl(IAsyncResult asyncResult, Func endFunction, Action endAction, TaskCreationOptions creationOptions, TaskScheduler scheduler) { if (asyncResult == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult); } if (endFunction == null && endAction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } TaskFactory.CheckFromAsyncOptions(creationOptions, hasBeginMethod: false); Task promise = new Task((object)null, creationOptions); if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(promise.Id, "TaskFactory.FromAsync", 0L); } if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(promise); } Task t = new Task((Action)delegate { FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: true); }, null, null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, null); if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(t.Id, "TaskFactory.FromAsync Callback", 0L); } if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(t); } if (asyncResult.IsCompleted) { try { t.InternalRunSynchronously(scheduler, waitForCompletion: false); } catch (Exception exceptionObject) { promise.TrySetException(exceptionObject); } } else { ThreadPool.RegisterWaitForSingleObject(asyncResult.AsyncWaitHandle, delegate { try { t.InternalRunSynchronously(scheduler, waitForCompletion: false); } catch (Exception exceptionObject2) { promise.TrySetException(exceptionObject2); } }, null, -1, executeOnlyOnce: true); } return promise; } public Task FromAsync(Func beginMethod, Func endMethod, object? state) { return FromAsyncImpl(beginMethod, endMethod, null, state, m_defaultCreationOptions); } public Task FromAsync(Func beginMethod, Func endMethod, object? state, TaskCreationOptions creationOptions) { return FromAsyncImpl(beginMethod, endMethod, null, state, creationOptions); } internal static Task FromAsyncImpl(Func beginMethod, Func endFunction, Action endAction, object state, TaskCreationOptions creationOptions) { if (beginMethod == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.beginMethod); } if (endFunction == null && endAction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod); } TaskFactory.CheckFromAsyncOptions(creationOptions, hasBeginMethod: true); Task promise = new Task(state, creationOptions); if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(promise.Id, "TaskFactory.FromAsync: " + beginMethod.Method.Name, 0L); } if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(promise); } try { IAsyncResult asyncResult = beginMethod(delegate(IAsyncResult iar) { if (!iar.CompletedSynchronously) { FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true); } }, state); if (asyncResult.CompletedSynchronously) { FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); } } catch { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(promise.Id, AsyncCausalityStatus.Error); } if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(promise); } promise.TrySetResult(); throw; } return promise; } public Task FromAsync(Func beginMethod, Func endMethod, TArg1 arg1, object? state) { return FromAsyncImpl(beginMethod, endMethod, null, arg1, state, m_defaultCreationOptions); } public Task FromAsync(Func beginMethod, Func endMethod, TArg1 arg1, object? state, TaskCreationOptions creationOptions) { return FromAsyncImpl(beginMethod, endMethod, null, arg1, state, creationOptions); } internal static Task FromAsyncImpl(Func beginMethod, Func endFunction, Action endAction, TArg1 arg1, object state, TaskCreationOptions creationOptions) { if (beginMethod == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.beginMethod); } if (endFunction == null && endAction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endFunction); } TaskFactory.CheckFromAsyncOptions(creationOptions, hasBeginMethod: true); Task promise = new Task(state, creationOptions); if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(promise.Id, "TaskFactory.FromAsync: " + beginMethod.Method.Name, 0L); } if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(promise); } try { IAsyncResult asyncResult = beginMethod(arg1, delegate(IAsyncResult iar) { if (!iar.CompletedSynchronously) { FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true); } }, state); if (asyncResult.CompletedSynchronously) { FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); } } catch { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(promise.Id, AsyncCausalityStatus.Error); } if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(promise); } promise.TrySetResult(); throw; } return promise; } public Task FromAsync(Func beginMethod, Func endMethod, TArg1 arg1, TArg2 arg2, object? state) { return FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, state, m_defaultCreationOptions); } public Task FromAsync(Func beginMethod, Func endMethod, TArg1 arg1, TArg2 arg2, object? state, TaskCreationOptions creationOptions) { return FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, state, creationOptions); } internal static Task FromAsyncImpl(Func beginMethod, Func endFunction, Action endAction, TArg1 arg1, TArg2 arg2, object state, TaskCreationOptions creationOptions) { if (beginMethod == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.beginMethod); } if (endFunction == null && endAction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod); } TaskFactory.CheckFromAsyncOptions(creationOptions, hasBeginMethod: true); Task promise = new Task(state, creationOptions); if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(promise.Id, "TaskFactory.FromAsync: " + beginMethod.Method.Name, 0L); } if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(promise); } try { IAsyncResult asyncResult = beginMethod(arg1, arg2, delegate(IAsyncResult iar) { if (!iar.CompletedSynchronously) { FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true); } }, state); if (asyncResult.CompletedSynchronously) { FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); } } catch { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(promise.Id, AsyncCausalityStatus.Error); } if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(promise); } promise.TrySetResult(); throw; } return promise; } public Task FromAsync(Func beginMethod, Func endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, object? state) { return FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, arg3, state, m_defaultCreationOptions); } public Task FromAsync(Func beginMethod, Func endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, object? state, TaskCreationOptions creationOptions) { return FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, arg3, state, creationOptions); } internal static Task FromAsyncImpl(Func beginMethod, Func endFunction, Action endAction, TArg1 arg1, TArg2 arg2, TArg3 arg3, object state, TaskCreationOptions creationOptions) { if (beginMethod == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.beginMethod); } if (endFunction == null && endAction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.endMethod); } TaskFactory.CheckFromAsyncOptions(creationOptions, hasBeginMethod: true); Task promise = new Task(state, creationOptions); if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(promise.Id, "TaskFactory.FromAsync: " + beginMethod.Method.Name, 0L); } if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(promise); } try { IAsyncResult asyncResult = beginMethod(arg1, arg2, arg3, delegate(IAsyncResult iar) { if (!iar.CompletedSynchronously) { FromAsyncCoreLogic(iar, endFunction, endAction, promise, requiresSynchronization: true); } }, state); if (asyncResult.CompletedSynchronously) { FromAsyncCoreLogic(asyncResult, endFunction, endAction, promise, requiresSynchronization: false); } } catch { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(promise.Id, AsyncCausalityStatus.Error); } if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(promise); } promise.TrySetResult(); throw; } return promise; } internal static Task FromAsyncTrim(TInstance thisRef, TArgs args, Func beginMethod, Func endMethod) where TInstance : class { FromAsyncTrimPromise fromAsyncTrimPromise = new FromAsyncTrimPromise(thisRef, endMethod); IAsyncResult asyncResult = beginMethod(thisRef, args, FromAsyncTrimPromise.s_completeFromAsyncResult, fromAsyncTrimPromise); if (asyncResult.CompletedSynchronously) { fromAsyncTrimPromise.Complete(thisRef, endMethod, asyncResult, requiresSynchronization: false); } return fromAsyncTrimPromise; } private static Task CreateCanceledTask(TaskContinuationOptions continuationOptions, CancellationToken ct) { Task.CreationOptionsFromContinuationOptions(continuationOptions, out var creationOptions, out var _); return new Task(canceled: true, default(TResult), creationOptions, ct); } public Task ContinueWhenAll(Task[] tasks, Func continuationFunction) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, CancellationToken cancellationToken) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } internal static Task ContinueWhenAllImpl(Task[] tasks, Func[], TResult> continuationFunction, Action[]> continuationAction, TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler) { TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions); if (tasks == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } Task[] tasksCopy = TaskFactory.CheckMultiContinuationTasksAndCopy(tasks); if (cancellationToken.IsCancellationRequested && (continuationOptions & TaskContinuationOptions.LazyCancellation) == 0) { return CreateCanceledTask(continuationOptions, cancellationToken); } Task[]> task = TaskFactory.CommonCWAllLogic(tasksCopy); if (continuationFunction != null) { return task.ContinueWith(GenericDelegateCache.CWAllFuncDelegate, continuationFunction, scheduler, cancellationToken, continuationOptions); } return task.ContinueWith(GenericDelegateCache.CWAllActionDelegate, continuationAction, scheduler, cancellationToken, continuationOptions); } internal static Task ContinueWhenAllImpl(Task[] tasks, Func continuationFunction, Action continuationAction, TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler) { TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions); if (tasks == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } Task[] tasksCopy = TaskFactory.CheckMultiContinuationTasksAndCopy(tasks); if (cancellationToken.IsCancellationRequested && (continuationOptions & TaskContinuationOptions.LazyCancellation) == 0) { return CreateCanceledTask(continuationOptions, cancellationToken); } Task task = TaskFactory.CommonCWAllLogic(tasksCopy); if (continuationFunction != null) { return task.ContinueWith(delegate(Task completedTasks, object state) { completedTasks.NotifyDebuggerOfWaitCompletionIfNecessary(); return ((Func)state)(completedTasks.Result); }, continuationFunction, scheduler, cancellationToken, continuationOptions); } return task.ContinueWith(delegate(Task completedTasks, object state) { completedTasks.NotifyDebuggerOfWaitCompletionIfNecessary(); ((Action)state)(completedTasks.Result); return default(TResult); }, continuationAction, scheduler, cancellationToken, continuationOptions); } public Task ContinueWhenAny(Task[] tasks, Func continuationFunction) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, CancellationToken cancellationToken) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } return ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } internal static Task ContinueWhenAnyImpl(Task[] tasks, Func continuationFunction, Action continuationAction, TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler) { TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions); if (tasks == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } if (tasks.Length == 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } Task task = TaskFactory.CommonCWAnyLogic(tasks); if (cancellationToken.IsCancellationRequested && (continuationOptions & TaskContinuationOptions.LazyCancellation) == 0) { return CreateCanceledTask(continuationOptions, cancellationToken); } if (continuationFunction != null) { return task.ContinueWith((Task completedTask, object state) => ((Func)state)(completedTask.Result), continuationFunction, scheduler, cancellationToken, continuationOptions); } return task.ContinueWith(delegate(Task completedTask, object state) { ((Action)state)(completedTask.Result); return default(TResult); }, continuationAction, scheduler, cancellationToken, continuationOptions); } internal static Task ContinueWhenAnyImpl(Task[] tasks, Func, TResult> continuationFunction, Action> continuationAction, TaskContinuationOptions continuationOptions, CancellationToken cancellationToken, TaskScheduler scheduler) { TaskFactory.CheckMultiTaskContinuationOptions(continuationOptions); if (tasks == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } if (tasks.Length == 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } Task task = TaskFactory.CommonCWAnyLogic(tasks); if (cancellationToken.IsCancellationRequested && (continuationOptions & TaskContinuationOptions.LazyCancellation) == 0) { return CreateCanceledTask(continuationOptions, cancellationToken); } if (continuationFunction != null) { return task.ContinueWith(GenericDelegateCache.CWAnyFuncDelegate, continuationFunction, scheduler, cancellationToken, continuationOptions); } return task.ContinueWith(GenericDelegateCache.CWAnyActionDelegate, continuationAction, scheduler, cancellationToken, continuationOptions); } } internal static class GenericDelegateCache { internal static Func, object, TResult> CWAnyFuncDelegate = delegate(Task wrappedWinner, object state) { Func, TResult> func2 = (Func, TResult>)state; Task arg = (Task)wrappedWinner.Result; return func2(arg); }; internal static Func, object, TResult> CWAnyActionDelegate = delegate(Task wrappedWinner, object state) { Action> action2 = (Action>)state; Task obj = (Task)wrappedWinner.Result; action2(obj); return default(TResult); }; internal static Func[]>, object, TResult> CWAllFuncDelegate = delegate(Task[]> wrappedAntecedents, object state) { wrappedAntecedents.NotifyDebuggerOfWaitCompletionIfNecessary(); Func[], TResult> func = (Func[], TResult>)state; return func(wrappedAntecedents.Result); }; internal static Func[]>, object, TResult> CWAllActionDelegate = delegate(Task[]> wrappedAntecedents, object state) { wrappedAntecedents.NotifyDebuggerOfWaitCompletionIfNecessary(); Action[]> action = (Action[]>)state; action(wrappedAntecedents.Result); return default(TResult); }; } internal interface IProducerConsumerQueue : IEnumerable, System.Collections.IEnumerable { bool IsEmpty { get; } int Count { get; } void Enqueue(T item); bool TryDequeue([MaybeNullWhen(false)] out T result); } [DebuggerDisplay("Count = {Count}")] internal sealed class MultiProducerMultiConsumerQueue : ConcurrentQueue, IProducerConsumerQueue, IEnumerable, System.Collections.IEnumerable { bool IProducerConsumerQueue.IsEmpty => base.IsEmpty; int IProducerConsumerQueue.Count => base.Count; void IProducerConsumerQueue.Enqueue(T item) { Enqueue(item); } bool IProducerConsumerQueue.TryDequeue([MaybeNullWhen(false)] out T result) { return TryDequeue(out result); } } [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(SingleProducerSingleConsumerQueue<>.SingleProducerSingleConsumerQueue_DebugView))] internal sealed class SingleProducerSingleConsumerQueue : IProducerConsumerQueue, IEnumerable, System.Collections.IEnumerable { [StructLayout(LayoutKind.Sequential)] private sealed class Segment { internal Segment m_next; internal readonly T[] m_array; internal SegmentState m_state; internal Segment(int size) { m_array = new T[size]; } } private struct SegmentState { internal PaddingFor32 m_pad0; internal volatile int m_first; internal int m_lastCopy; internal PaddingFor32 m_pad1; internal int m_firstCopy; internal volatile int m_last; internal PaddingFor32 m_pad2; } private sealed class SingleProducerSingleConsumerQueue_DebugView { private readonly SingleProducerSingleConsumerQueue m_queue; public SingleProducerSingleConsumerQueue_DebugView(SingleProducerSingleConsumerQueue queue) { m_queue = queue; } } private volatile Segment m_head; private volatile Segment m_tail; public bool IsEmpty { get { Segment head = m_head; if (head.m_state.m_first != head.m_state.m_lastCopy) { return false; } if (head.m_state.m_first != head.m_state.m_last) { return false; } return head.m_next == null; } } public int Count { get { int num = 0; for (Segment segment = m_head; segment != null; segment = segment.m_next) { int num2 = segment.m_array.Length; int first; int last; do { first = segment.m_state.m_first; last = segment.m_state.m_last; } while (first != segment.m_state.m_first); num += (last - first) & (num2 - 1); } return num; } } internal SingleProducerSingleConsumerQueue() { m_head = (m_tail = new Segment(32)); } public void Enqueue(T item) { Segment segment = m_tail; T[] array = segment.m_array; int last = segment.m_state.m_last; int num = (last + 1) & (array.Length - 1); if (num != segment.m_state.m_firstCopy) { array[last] = item; segment.m_state.m_last = num; } else { EnqueueSlow(item, ref segment); } } private void EnqueueSlow(T item, ref Segment segment) { if (segment.m_state.m_firstCopy != segment.m_state.m_first) { segment.m_state.m_firstCopy = segment.m_state.m_first; Enqueue(item); return; } int num = m_tail.m_array.Length << 1; if (num > 16777216) { num = 16777216; } Segment segment2 = new Segment(num); segment2.m_array[0] = item; segment2.m_state.m_last = 1; segment2.m_state.m_lastCopy = 1; Volatile.Write(ref m_tail.m_next, segment2); m_tail = segment2; } public bool TryDequeue([MaybeNullWhen(false)] out T result) { Segment segment = m_head; T[] array = segment.m_array; int first = segment.m_state.m_first; if (first != segment.m_state.m_lastCopy) { result = array[first]; array[first] = default(T); segment.m_state.m_first = (first + 1) & (array.Length - 1); return true; } return TryDequeueSlow(ref segment, ref array, out result); } private bool TryDequeueSlow(ref Segment segment, ref T[] array, [MaybeNullWhen(false)] out T result) { if (segment.m_state.m_last != segment.m_state.m_lastCopy) { segment.m_state.m_lastCopy = segment.m_state.m_last; return TryDequeue(out result); } if (segment.m_next != null && segment.m_state.m_first == segment.m_state.m_last) { segment = segment.m_next; array = segment.m_array; m_head = segment; } int first = segment.m_state.m_first; if (first == segment.m_state.m_last) { result = default(T); return false; } result = array[first]; array[first] = default(T); segment.m_state.m_first = (first + 1) & (segment.m_array.Length - 1); segment.m_state.m_lastCopy = segment.m_state.m_last; return true; } public IEnumerator GetEnumerator() { for (Segment segment = m_head; segment != null; segment = segment.m_next) { for (int pt = segment.m_state.m_first; pt != segment.m_state.m_last; pt = (pt + 1) & (segment.m_array.Length - 1)) { yield return segment.m_array[pt]; } } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } public enum TaskStatus { Created, WaitingForActivation, WaitingToRun, Running, WaitingForChildrenToComplete, RanToCompletion, Canceled, Faulted } [DebuggerTypeProxy(typeof(SystemThreadingTasks_TaskDebugView))] [DebuggerDisplay("Id = {Id}, Status = {Status}, Method = {DebuggerDisplayMethodDescription}")] public class Task : IAsyncResult, IDisposable { [Flags] internal enum TaskStateFlags { Started = 0x10000, DelegateInvoked = 0x20000, Disposed = 0x40000, ExceptionObservedByParent = 0x80000, CancellationAcknowledged = 0x100000, Faulted = 0x200000, Canceled = 0x400000, WaitingOnChildren = 0x800000, RanToCompletion = 0x1000000, WaitingForActivation = 0x2000000, CompletionReserved = 0x4000000, WaitCompletionNotification = 0x10000000, ExecutionContextIsNull = 0x20000000, TaskScheduledWasFired = 0x40000000, CompletedMask = 0x1600000, OptionsMask = 0xFFFF } internal sealed class ContingentProperties { internal ExecutionContext m_capturedContext; internal volatile ManualResetEventSlim m_completionEvent; internal volatile TaskExceptionHolder m_exceptionsHolder; internal CancellationToken m_cancellationToken; internal StrongBox m_cancellationRegistration; internal volatile int m_internalCancellationRequested; internal volatile int m_completionCountdown = 1; internal volatile List m_exceptionalChildren; internal Task m_parent; internal void SetCompleted() { m_completionEvent?.Set(); } internal void UnregisterCancellationCallback() { if (m_cancellationRegistration != null) { try { m_cancellationRegistration.Value.Dispose(); } catch (ObjectDisposedException) { } m_cancellationRegistration = null; } } } private protected sealed class CancellationPromise : Task, ITaskCompletionAction { private readonly Task _task; private readonly CancellationTokenRegistration _registration; private readonly TimerQueueTimer _timer; bool ITaskCompletionAction.InvokeMayRunArbitraryCode => true; internal CancellationPromise(Task source, uint millisecondsDelay, CancellationToken token) { _task = source; source.AddCompletionAction(this); if (millisecondsDelay != uint.MaxValue) { _timer = new TimerQueueTimer(delegate(object state) { CancellationPromise cancellationPromise2 = (CancellationPromise)state; if (cancellationPromise2.TrySetException(new TimeoutException())) { cancellationPromise2.Cleanup(); } }, this, millisecondsDelay, uint.MaxValue, flowExecutionContext: false); } _registration = token.UnsafeRegister(delegate(object state, CancellationToken cancellationToken) { CancellationPromise cancellationPromise = (CancellationPromise)state; if (cancellationPromise.TrySetCanceled(cancellationToken)) { cancellationPromise.Cleanup(); } }, this); if (base.IsCompleted) { Cleanup(); } } void ITaskCompletionAction.Invoke(Task completingTask) { if (completingTask.Status switch { TaskStatus.Canceled => TrySetCanceled(completingTask.CancellationToken, completingTask.GetCancellationExceptionDispatchInfo()), TaskStatus.Faulted => TrySetException(completingTask.GetExceptionDispatchInfos()), _ => (completingTask is Task task) ? TrySetResult(task.Result) : TrySetResult(), }) { Cleanup(); } } private void Cleanup() { _registration.Dispose(); _timer?.Close(); _task.RemoveContinuation(this); } } private sealed class SetOnInvokeMres : ManualResetEventSlim, ITaskCompletionAction { public bool InvokeMayRunArbitraryCode => false; internal SetOnInvokeMres() : base(initialState: false, 0) { } public void Invoke(Task completingTask) { Set(); } } private sealed class SetOnCountdownMres : ManualResetEventSlim, ITaskCompletionAction { private int _count; public bool InvokeMayRunArbitraryCode => false; internal SetOnCountdownMres(int count) { _count = count; } public void Invoke(Task completingTask) { if (Interlocked.Decrement(ref _count) == 0) { Set(); } } } private class DelayPromise : Task { private static readonly TimerCallback s_timerCallback = TimerCallback; private readonly TimerQueueTimer _timer; internal DelayPromise(uint millisecondsDelay) { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(base.Id, "Task.Delay", 0L); } if (s_asyncDebuggingEnabled) { AddToActiveTasks(this); } if (millisecondsDelay != uint.MaxValue) { _timer = new TimerQueueTimer(s_timerCallback, this, millisecondsDelay, uint.MaxValue, flowExecutionContext: false); if (base.IsCompleted) { _timer.Close(); } } } private static void TimerCallback(object state) { ((DelayPromise)state).CompleteTimedOut(); } private void CompleteTimedOut() { if (TrySetResult()) { Cleanup(); if (s_asyncDebuggingEnabled) { RemoveFromActiveTasks(this); } if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(base.Id, AsyncCausalityStatus.Completed); } } } protected virtual void Cleanup() { _timer?.Close(); } } private sealed class DelayPromiseWithCancellation : DelayPromise { private readonly CancellationTokenRegistration _registration; internal DelayPromiseWithCancellation(uint millisecondsDelay, CancellationToken token) : base(millisecondsDelay) { _registration = token.UnsafeRegister(delegate(object state, CancellationToken cancellationToken) { DelayPromiseWithCancellation delayPromiseWithCancellation = (DelayPromiseWithCancellation)state; if (delayPromiseWithCancellation.TrySetCanceled(cancellationToken)) { delayPromiseWithCancellation.Cleanup(); } }, this); if (base.IsCompleted) { _registration.Dispose(); } } protected override void Cleanup() { _registration.Dispose(); base.Cleanup(); } } private sealed class WhenAllPromise : Task, ITaskCompletionAction { private readonly Task[] m_tasks; private int m_count; public bool InvokeMayRunArbitraryCode => true; private protected override bool ShouldNotifyDebuggerOfWaitCompletion { get { if (base.ShouldNotifyDebuggerOfWaitCompletion) { return AnyTaskRequiresNotifyDebuggerOfWaitCompletion(m_tasks); } return false; } } internal WhenAllPromise(Task[] tasks) { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(base.Id, "Task.WhenAll", 0L); } if (s_asyncDebuggingEnabled) { AddToActiveTasks(this); } m_tasks = tasks; m_count = tasks.Length; foreach (Task task in tasks) { if (task.IsCompleted) { Invoke(task); } else { task.AddCompletionAction(this); } } } public void Invoke(Task completedTask) { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationRelation(base.Id, CausalityRelation.Join); } if (Interlocked.Decrement(ref m_count) != 0) { return; } List list = null; Task task = null; for (int i = 0; i < m_tasks.Length; i++) { Task task2 = m_tasks[i]; if (task2.IsFaulted) { if (list == null) { list = new List(); } list.AddRange(task2.GetExceptionDispatchInfos()); } else if (task2.IsCanceled && task == null) { task = task2; } if (task2.IsWaitNotificationEnabled) { SetNotificationForWaitCompletion(enabled: true); } else { m_tasks[i] = null; } } if (list != null) { TrySetException(list); return; } if (task != null) { TrySetCanceled(task.CancellationToken, task.GetCancellationExceptionDispatchInfo()); return; } if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(base.Id, AsyncCausalityStatus.Completed); } if (s_asyncDebuggingEnabled) { RemoveFromActiveTasks(this); } TrySetResult(); } } private sealed class WhenAllPromise : Task, ITaskCompletionAction { private readonly Task[] m_tasks; private int m_count; public bool InvokeMayRunArbitraryCode => true; private protected override bool ShouldNotifyDebuggerOfWaitCompletion { get { if (base.ShouldNotifyDebuggerOfWaitCompletion) { Task[] tasks = m_tasks; return AnyTaskRequiresNotifyDebuggerOfWaitCompletion(tasks); } return false; } } internal WhenAllPromise(Task[] tasks) { m_tasks = tasks; m_count = tasks.Length; if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(base.Id, "Task.WhenAll", 0L); } if (s_asyncDebuggingEnabled) { AddToActiveTasks(this); } foreach (Task task in tasks) { if (task.IsCompleted) { Invoke(task); } else { task.AddCompletionAction(this); } } } public void Invoke(Task ignored) { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationRelation(base.Id, CausalityRelation.Join); } if (Interlocked.Decrement(ref m_count) != 0) { return; } T[] array = new T[m_tasks.Length]; List list = null; Task task = null; for (int i = 0; i < m_tasks.Length; i++) { Task task2 = m_tasks[i]; if (task2.IsFaulted) { if (list == null) { list = new List(); } list.AddRange(task2.GetExceptionDispatchInfos()); } else if (task2.IsCanceled) { if (task == null) { task = task2; } } else { array[i] = task2.GetResultCore(waitCompletionNotification: false); } if (task2.IsWaitNotificationEnabled) { SetNotificationForWaitCompletion(enabled: true); } else { m_tasks[i] = null; } } if (list != null) { TrySetException(list); return; } if (task != null) { TrySetCanceled(task.CancellationToken, task.GetCancellationExceptionDispatchInfo()); return; } if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(base.Id, AsyncCausalityStatus.Completed); } if (s_asyncDebuggingEnabled) { RemoveFromActiveTasks(this); } TrySetResult(array); } } private sealed class TwoTaskWhenAnyPromise : Task, ITaskCompletionAction where TTask : Task { private TTask _task1; private TTask _task2; public bool InvokeMayRunArbitraryCode => true; public TwoTaskWhenAnyPromise(TTask task1, TTask task2) { _task1 = task1; _task2 = task2; if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(base.Id, "Task.WhenAny", 0L); } if (s_asyncDebuggingEnabled) { AddToActiveTasks(this); } task1.AddCompletionAction(this); task2.AddCompletionAction(this); if (task1.IsCompleted) { task2.RemoveContinuation(this); } } public void Invoke(Task completingTask) { Task task; if ((task = Interlocked.Exchange(ref _task1, null)) != null) { Task task2 = _task2; _task2 = null; if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationRelation(base.Id, CausalityRelation.Choice); TplEventSource.Log.TraceOperationEnd(base.Id, AsyncCausalityStatus.Completed); } if (s_asyncDebuggingEnabled) { RemoveFromActiveTasks(this); } if (!task.IsCompleted) { task.RemoveContinuation(this); } else { task2.RemoveContinuation(this); } bool flag = TrySetResult((TTask)completingTask); } } } [ThreadStatic] internal static Task t_currentTask; internal static int s_taskIdCounter; private int m_taskId; internal Delegate m_action; internal object m_stateObject; internal TaskScheduler m_taskScheduler; internal volatile int m_stateFlags; private volatile object m_continuationObject; private static readonly object s_taskCompletionSentinel = new object(); internal static bool s_asyncDebuggingEnabled; private static Dictionary s_currentActiveTasks; internal ContingentProperties m_contingentProperties; internal static readonly Task s_cachedCompleted = new Task(canceled: false, default(VoidTaskResult), (TaskCreationOptions)16384, default(CancellationToken)); private static readonly ContextCallback s_ecCallback = delegate(object obj) { Unsafe.As(obj).InnerInvoke(); }; private Task? ParentForDebugger => m_contingentProperties?.m_parent; private int StateFlagsForDebugger => m_stateFlags; private TaskStateFlags StateFlags => (TaskStateFlags)(m_stateFlags & -65536); private string DebuggerDisplayMethodDescription => m_action?.Method.ToString() ?? "{null}"; internal TaskCreationOptions Options => OptionsMethod(m_stateFlags); internal bool IsWaitNotificationEnabledOrNotRanToCompletion { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (m_stateFlags & 0x11000000) != 16777216; } } private protected virtual bool ShouldNotifyDebuggerOfWaitCompletion => IsWaitNotificationEnabled; internal bool IsWaitNotificationEnabled => (m_stateFlags & 0x10000000) != 0; public int Id { get { if (Volatile.Read(ref m_taskId) == 0) { int value = NewId(); Interlocked.CompareExchange(ref m_taskId, value, 0); } return m_taskId; } } public static int? CurrentId => InternalCurrent?.Id; internal static Task? InternalCurrent => t_currentTask; public AggregateException? Exception { get { AggregateException result = null; if (IsFaulted) { result = GetExceptions(includeTaskCanceledExceptions: false); } return result; } } public TaskStatus Status { get { int stateFlags = m_stateFlags; if (((uint)stateFlags & 0x200000u) != 0) { return TaskStatus.Faulted; } if (((uint)stateFlags & 0x400000u) != 0) { return TaskStatus.Canceled; } if (((uint)stateFlags & 0x1000000u) != 0) { return TaskStatus.RanToCompletion; } if (((uint)stateFlags & 0x800000u) != 0) { return TaskStatus.WaitingForChildrenToComplete; } if (((uint)stateFlags & 0x20000u) != 0) { return TaskStatus.Running; } if (((uint)stateFlags & 0x10000u) != 0) { return TaskStatus.WaitingToRun; } if (((uint)stateFlags & 0x2000000u) != 0) { return TaskStatus.WaitingForActivation; } return TaskStatus.Created; } } public bool IsCanceled => (m_stateFlags & 0x600000) == 4194304; internal bool IsCancellationRequested { get { ContingentProperties contingentProperties = Volatile.Read(ref m_contingentProperties); if (contingentProperties != null) { if (contingentProperties.m_internalCancellationRequested != 1) { return contingentProperties.m_cancellationToken.IsCancellationRequested; } return true; } return false; } } internal CancellationToken CancellationToken => Volatile.Read(ref m_contingentProperties)?.m_cancellationToken ?? default(CancellationToken); internal bool IsCancellationAcknowledged => (m_stateFlags & 0x100000) != 0; public bool IsCompleted { get { int stateFlags = m_stateFlags; return IsCompletedMethod(stateFlags); } } public bool IsCompletedSuccessfully => (m_stateFlags & 0x1600000) == 16777216; public TaskCreationOptions CreationOptions => Options & (TaskCreationOptions)(-65281); WaitHandle IAsyncResult.AsyncWaitHandle { get { if (((uint)m_stateFlags & 0x40000u) != 0) { ThrowHelper.ThrowObjectDisposedException(ExceptionResource.Task_ThrowIfDisposed); } return CompletedEvent.WaitHandle; } } public object? AsyncState => m_stateObject; bool IAsyncResult.CompletedSynchronously => false; internal TaskScheduler? ExecutingTaskScheduler => m_taskScheduler; public static TaskFactory Factory { get; } = new TaskFactory(); public static Task CompletedTask => s_cachedCompleted; internal ManualResetEventSlim CompletedEvent { get { ContingentProperties contingentProperties = EnsureContingentPropertiesInitialized(); if (contingentProperties.m_completionEvent == null) { bool isCompleted = IsCompleted; ManualResetEventSlim manualResetEventSlim = new ManualResetEventSlim(isCompleted); if (Interlocked.CompareExchange(ref contingentProperties.m_completionEvent, manualResetEventSlim, null) != null) { manualResetEventSlim.Dispose(); } else if (!isCompleted && IsCompleted) { manualResetEventSlim.Set(); } } return contingentProperties.m_completionEvent; } } internal bool ExceptionRecorded { get { ContingentProperties contingentProperties = Volatile.Read(ref m_contingentProperties); if (contingentProperties != null && contingentProperties.m_exceptionsHolder != null) { return contingentProperties.m_exceptionsHolder.ContainsFaultList; } return false; } } public bool IsFaulted => (m_stateFlags & 0x200000) != 0; internal ExecutionContext? CapturedContext { get { if ((m_stateFlags & 0x20000000) == 536870912) { return null; } return m_contingentProperties?.m_capturedContext ?? ExecutionContext.Default; } set { if (value == null) { m_stateFlags |= 536870912; } else if (value != ExecutionContext.Default) { EnsureContingentPropertiesInitializedUnsafe().m_capturedContext = value; } } } internal bool IsExceptionObservedByParent => (m_stateFlags & 0x80000) != 0; internal bool IsDelegateInvoked => (m_stateFlags & 0x20000) != 0; internal static bool AddToActiveTasks(Task task) { Dictionary dictionary = Volatile.Read(ref s_currentActiveTasks) ?? Interlocked.CompareExchange(ref s_currentActiveTasks, new Dictionary(), null) ?? s_currentActiveTasks; int id = task.Id; lock (dictionary) { dictionary[id] = task; } return true; } internal static void RemoveFromActiveTasks(Task task) { Dictionary dictionary = s_currentActiveTasks; if (dictionary == null) { return; } int id = task.Id; lock (dictionary) { dictionary.Remove(id); } } internal Task(bool canceled, TaskCreationOptions creationOptions, CancellationToken ct) { if (canceled) { m_stateFlags = (int)((TaskCreationOptions)5242880 | creationOptions); m_contingentProperties = new ContingentProperties { m_cancellationToken = ct, m_internalCancellationRequested = 1 }; } else { m_stateFlags = (int)((TaskCreationOptions)16777216 | creationOptions); } } internal Task() { m_stateFlags = 33555456; } internal Task(object state, TaskCreationOptions creationOptions, bool promiseStyle) { if (((uint)creationOptions & 0xFFFFFFBBu) != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions); } if ((creationOptions & TaskCreationOptions.AttachedToParent) != 0) { Task internalCurrent = InternalCurrent; if (internalCurrent != null) { EnsureContingentPropertiesInitializedUnsafe().m_parent = internalCurrent; } } TaskConstructorCore(null, state, default(CancellationToken), creationOptions, InternalTaskOptions.PromiseTask, null); } public Task(Action action) : this(action, null, null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, null) { } public Task(Action action, CancellationToken cancellationToken) : this(action, null, null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, null) { } public Task(Action action, TaskCreationOptions creationOptions) : this(action, null, InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, InternalTaskOptions.None, null) { } public Task(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : this(action, null, InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, null) { } public Task(Action action, object? state) : this(action, state, null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.None, null) { } public Task(Action action, object? state, CancellationToken cancellationToken) : this(action, state, null, cancellationToken, TaskCreationOptions.None, InternalTaskOptions.None, null) { } public Task(Action action, object? state, TaskCreationOptions creationOptions) : this(action, state, InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, InternalTaskOptions.None, null) { } public Task(Action action, object? state, CancellationToken cancellationToken, TaskCreationOptions creationOptions) : this(action, state, InternalCurrentIfAttached(creationOptions), cancellationToken, creationOptions, InternalTaskOptions.None, null) { } internal Task(Delegate action, object state, Task parent, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) { if ((object)action == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.action); } if (parent != null && (creationOptions & TaskCreationOptions.AttachedToParent) != 0) { EnsureContingentPropertiesInitializedUnsafe().m_parent = parent; } TaskConstructorCore(action, state, cancellationToken, creationOptions, internalOptions, scheduler); CapturedContext = ExecutionContext.Capture(); } internal void TaskConstructorCore(Delegate action, object state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions, TaskScheduler scheduler) { m_action = action; m_stateObject = state; m_taskScheduler = scheduler; if (((uint)creationOptions & 0xFFFFFFA0u) != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions); } int num = (int)creationOptions | (int)internalOptions; m_stateFlags = (((object)m_action == null || (internalOptions & InternalTaskOptions.ContinuationTask) != 0) ? (num | 0x2000000) : num); ContingentProperties contingentProperties = m_contingentProperties; if (contingentProperties != null) { Task parent = contingentProperties.m_parent; if (parent != null && (creationOptions & TaskCreationOptions.AttachedToParent) != 0 && (parent.CreationOptions & TaskCreationOptions.DenyChildAttach) == 0) { parent.AddNewChild(); } } if (cancellationToken.CanBeCanceled) { AssignCancellationToken(cancellationToken, null, null); } } private void AssignCancellationToken(CancellationToken cancellationToken, Task antecedent, TaskContinuation continuation) { ContingentProperties contingentProperties = EnsureContingentPropertiesInitializedUnsafe(); contingentProperties.m_cancellationToken = cancellationToken; try { if ((Options & (TaskCreationOptions)13312) != 0) { return; } if (cancellationToken.IsCancellationRequested) { InternalCancel(); return; } CancellationTokenRegistration value = ((antecedent != null) ? cancellationToken.UnsafeRegister(delegate(object t) { TupleSlim tupleSlim = (TupleSlim)t; Task item = tupleSlim.Item1; Task item2 = tupleSlim.Item2; item2.RemoveContinuation(tupleSlim.Item3); item.InternalCancel(); }, new TupleSlim(this, antecedent, continuation)) : cancellationToken.UnsafeRegister(delegate(object t) { ((Task)t).InternalCancel(); }, this)); contingentProperties.m_cancellationRegistration = new StrongBox(value); } catch { Task task = m_contingentProperties?.m_parent; if (task != null && (Options & TaskCreationOptions.AttachedToParent) != 0 && (task.Options & TaskCreationOptions.DenyChildAttach) == 0) { task.DisregardChild(); } throw; } } internal static TaskCreationOptions OptionsMethod(int flags) { return (TaskCreationOptions)(flags & 0xFFFF); } internal bool AtomicStateUpdate(int newBits, int illegalBits) { int stateFlags = m_stateFlags; if ((stateFlags & illegalBits) == 0) { if (Interlocked.CompareExchange(ref m_stateFlags, stateFlags | newBits, stateFlags) != stateFlags) { return AtomicStateUpdateSlow(newBits, illegalBits); } return true; } return false; } private bool AtomicStateUpdateSlow(int newBits, int illegalBits) { int num = m_stateFlags; while (true) { if ((num & illegalBits) != 0) { return false; } int num2 = Interlocked.CompareExchange(ref m_stateFlags, num | newBits, num); if (num2 == num) { break; } num = num2; } return true; } internal bool AtomicStateUpdate(int newBits, int illegalBits, ref int oldFlags) { int num = (oldFlags = m_stateFlags); while (true) { if ((num & illegalBits) != 0) { return false; } oldFlags = Interlocked.CompareExchange(ref m_stateFlags, num | newBits, num); if (oldFlags == num) { break; } num = oldFlags; } return true; } internal void SetNotificationForWaitCompletion(bool enabled) { if (enabled) { bool flag = AtomicStateUpdate(268435456, 90177536); } else { Interlocked.And(ref m_stateFlags, -268435457); } } internal bool NotifyDebuggerOfWaitCompletionIfNecessary() { if (IsWaitNotificationEnabled && ShouldNotifyDebuggerOfWaitCompletion) { NotifyDebuggerOfWaitCompletion(); return true; } return false; } internal static bool AnyTaskRequiresNotifyDebuggerOfWaitCompletion(Task[] tasks) { foreach (Task task in tasks) { if (task != null && task.IsWaitNotificationEnabled && task.ShouldNotifyDebuggerOfWaitCompletion) { return true; } } return false; } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private void NotifyDebuggerOfWaitCompletion() { SetNotificationForWaitCompletion(enabled: false); } internal bool MarkStarted() { return AtomicStateUpdate(65536, 4259840); } internal void FireTaskScheduledIfNeeded(TaskScheduler ts) { if ((m_stateFlags & 0x40000000) == 0) { m_stateFlags |= 1073741824; if (TplEventSource.Log.IsEnabled()) { Task internalCurrent = InternalCurrent; Task task = m_contingentProperties?.m_parent; TplEventSource.Log.TaskScheduled(ts.Id, internalCurrent?.Id ?? 0, Id, task?.Id ?? 0, (int)Options); } } } internal void AddNewChild() { ContingentProperties contingentProperties = EnsureContingentPropertiesInitialized(); if (contingentProperties.m_completionCountdown == 1) { contingentProperties.m_completionCountdown++; } else { Interlocked.Increment(ref contingentProperties.m_completionCountdown); } } internal void DisregardChild() { ContingentProperties contingentProperties = EnsureContingentPropertiesInitialized(); Interlocked.Decrement(ref contingentProperties.m_completionCountdown); } public void Start() { Start(TaskScheduler.Current); } public void Start(TaskScheduler scheduler) { int stateFlags = m_stateFlags; if (IsCompletedMethod(stateFlags)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Start_TaskCompleted); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } TaskCreationOptions taskCreationOptions = OptionsMethod(stateFlags); if ((taskCreationOptions & (TaskCreationOptions)1024) != 0) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Start_Promise); } if ((taskCreationOptions & (TaskCreationOptions)512) != 0) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Start_ContinuationTask); } if (Interlocked.CompareExchange(ref m_taskScheduler, scheduler, null) != null) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Start_AlreadyStarted); } ScheduleAndStart(needsProtection: true); } public void RunSynchronously() { InternalRunSynchronously(TaskScheduler.Current, waitForCompletion: true); } public void RunSynchronously(TaskScheduler scheduler) { if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } InternalRunSynchronously(scheduler, waitForCompletion: true); } internal void InternalRunSynchronously(TaskScheduler scheduler, bool waitForCompletion) { int stateFlags = m_stateFlags; TaskCreationOptions taskCreationOptions = OptionsMethod(stateFlags); if ((taskCreationOptions & (TaskCreationOptions)512) != 0) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_Continuation); } if ((taskCreationOptions & (TaskCreationOptions)1024) != 0) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_Promise); } if (IsCompletedMethod(stateFlags)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_TaskCompleted); } if (Interlocked.CompareExchange(ref m_taskScheduler, scheduler, null) != null) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_AlreadyStarted); } if (MarkStarted()) { bool flag = false; try { if (!scheduler.TryRunInline(this, taskWasPreviouslyQueued: false)) { scheduler.InternalQueueTask(this); flag = true; } if (waitForCompletion && !IsCompleted) { SpinThenBlockingWait(-1, default(CancellationToken)); } return; } catch (Exception innerException) { if (!flag) { TaskSchedulerException ex = new TaskSchedulerException(innerException); AddException(ex); Finish(userDelegateExecute: false); m_contingentProperties.m_exceptionsHolder.MarkAsHandled(calledFromFinalizer: false); throw ex; } throw; } } ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_RunSynchronously_TaskCompleted); } internal static Task InternalStartNew(Task creatingTask, Delegate action, object state, CancellationToken cancellationToken, TaskScheduler scheduler, TaskCreationOptions options, InternalTaskOptions internalOptions) { if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } Task task = new Task(action, state, creatingTask, cancellationToken, options, internalOptions | InternalTaskOptions.QueuedByRuntime, scheduler); task.ScheduleAndStart(needsProtection: false); return task; } internal static int NewId() { int num; do { num = Interlocked.Increment(ref s_taskIdCounter); } while (num == 0); if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.NewID(num); } return num; } internal static Task InternalCurrentIfAttached(TaskCreationOptions creationOptions) { if ((creationOptions & TaskCreationOptions.AttachedToParent) == 0) { return null; } return InternalCurrent; } internal ContingentProperties EnsureContingentPropertiesInitialized() { return Volatile.Read(ref m_contingentProperties) ?? InitializeContingentProperties(); ContingentProperties InitializeContingentProperties() { Interlocked.CompareExchange(ref m_contingentProperties, new ContingentProperties(), null); return m_contingentProperties; } } internal ContingentProperties EnsureContingentPropertiesInitializedUnsafe() { return m_contingentProperties ?? (m_contingentProperties = new ContingentProperties()); } private static bool IsCompletedMethod(int flags) { return (flags & 0x1600000) != 0; } internal void SpinUntilCompleted() { SpinWait spinWait = default(SpinWait); while (!IsCompleted) { spinWait.SpinOnce(); } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if ((Options & (TaskCreationOptions)16384) != 0) { return; } if (!IsCompleted) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Task_Dispose_NotCompleted); } ContingentProperties contingentProperties = Volatile.Read(ref m_contingentProperties); if (contingentProperties != null) { ManualResetEventSlim completionEvent = contingentProperties.m_completionEvent; if (completionEvent != null) { contingentProperties.m_completionEvent = null; if (!completionEvent.IsSet) { completionEvent.Set(); } completionEvent.Dispose(); } } } m_stateFlags |= 262144; } internal void ScheduleAndStart(bool needsProtection) { if (needsProtection) { if (!MarkStarted()) { return; } } else { m_stateFlags |= 65536; } if (s_asyncDebuggingEnabled) { AddToActiveTasks(this); } if (TplEventSource.Log.IsEnabled() && (Options & (TaskCreationOptions)512) == 0) { TplEventSource.Log.TraceOperationBegin(Id, "Task: " + m_action.Method.Name, 0L); } try { m_taskScheduler.InternalQueueTask(this); } catch (Exception innerException) { TaskSchedulerException ex = new TaskSchedulerException(innerException); AddException(ex); Finish(userDelegateExecute: false); if ((Options & (TaskCreationOptions)512) == 0) { m_contingentProperties.m_exceptionsHolder.MarkAsHandled(calledFromFinalizer: false); } throw ex; } } internal void AddException(object exceptionObject) { AddException(exceptionObject, representsCancellation: false); } internal void AddException(object exceptionObject, bool representsCancellation) { ContingentProperties contingentProperties = EnsureContingentPropertiesInitialized(); if (contingentProperties.m_exceptionsHolder == null) { TaskExceptionHolder taskExceptionHolder = new TaskExceptionHolder(this); if (Interlocked.CompareExchange(ref contingentProperties.m_exceptionsHolder, taskExceptionHolder, null) != null) { taskExceptionHolder.MarkAsHandled(calledFromFinalizer: false); } } lock (contingentProperties) { contingentProperties.m_exceptionsHolder.Add(exceptionObject, representsCancellation); } } private AggregateException GetExceptions(bool includeTaskCanceledExceptions) { Exception ex = null; if (includeTaskCanceledExceptions && IsCanceled) { ex = new TaskCanceledException(this); ex.SetCurrentStackTrace(); } if (ExceptionRecorded) { return m_contingentProperties.m_exceptionsHolder.CreateExceptionObject(calledFromFinalizer: false, ex); } if (ex != null) { return new AggregateException(ex); } return null; } internal List GetExceptionDispatchInfos() { return m_contingentProperties.m_exceptionsHolder.GetExceptionDispatchInfos(); } internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo() { ContingentProperties contingentProperties = Volatile.Read(ref m_contingentProperties); if (contingentProperties == null) { return null; } return contingentProperties.m_exceptionsHolder?.GetCancellationExceptionDispatchInfo(); } internal void MarkExceptionsAsHandled() { ContingentProperties contingentProperties = Volatile.Read(ref m_contingentProperties); if (contingentProperties != null) { contingentProperties.m_exceptionsHolder?.MarkAsHandled(calledFromFinalizer: false); } } internal void ThrowIfExceptional(bool includeTaskCanceledExceptions) { Exception exceptions = GetExceptions(includeTaskCanceledExceptions); if (exceptions != null) { UpdateExceptionObservedStatus(); throw exceptions; } } internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext) { ExceptionDispatchInfo state2 = ExceptionDispatchInfo.Capture(exception); if (targetContext != null) { try { targetContext.Post(delegate(object state) { ((ExceptionDispatchInfo)state).Throw(); }, state2); return; } catch (Exception ex) { state2 = ExceptionDispatchInfo.Capture(new AggregateException(exception, ex)); } } ThreadPool.QueueUserWorkItem(delegate(object state) { ((ExceptionDispatchInfo)state).Throw(); }, state2); } internal void UpdateExceptionObservedStatus() { Task task = m_contingentProperties?.m_parent; if (task != null && (Options & TaskCreationOptions.AttachedToParent) != 0 && (task.CreationOptions & TaskCreationOptions.DenyChildAttach) == 0 && InternalCurrent == task) { m_stateFlags |= 524288; } } internal void Finish(bool userDelegateExecute) { if (m_contingentProperties == null) { FinishStageTwo(); } else { FinishSlow(userDelegateExecute); } } private void FinishSlow(bool userDelegateExecute) { if (!userDelegateExecute) { FinishStageTwo(); return; } ContingentProperties contingentProperties = m_contingentProperties; if (contingentProperties.m_completionCountdown == 1 || Interlocked.Decrement(ref contingentProperties.m_completionCountdown) == 0) { FinishStageTwo(); } else { AtomicStateUpdate(8388608, 23068672); } List exceptionalChildren = contingentProperties.m_exceptionalChildren; if (exceptionalChildren == null) { return; } lock (exceptionalChildren) { exceptionalChildren.RemoveAll((Task t) => t.IsExceptionObservedByParent); } } private void FinishStageTwo() { ContingentProperties contingentProperties = Volatile.Read(ref m_contingentProperties); if (contingentProperties != null) { AddExceptionsFromChildren(contingentProperties); } int num; if (ExceptionRecorded) { num = 2097152; if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(Id, AsyncCausalityStatus.Error); } if (s_asyncDebuggingEnabled) { RemoveFromActiveTasks(this); } } else if (IsCancellationRequested && IsCancellationAcknowledged) { num = 4194304; if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(Id, AsyncCausalityStatus.Canceled); } if (s_asyncDebuggingEnabled) { RemoveFromActiveTasks(this); } } else { num = 16777216; if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(Id, AsyncCausalityStatus.Completed); } if (s_asyncDebuggingEnabled) { RemoveFromActiveTasks(this); } } Interlocked.Exchange(ref m_stateFlags, m_stateFlags | num); contingentProperties = Volatile.Read(ref m_contingentProperties); if (contingentProperties != null) { contingentProperties.SetCompleted(); contingentProperties.UnregisterCancellationCallback(); } FinishStageThree(); } internal void FinishStageThree() { m_action = null; ContingentProperties contingentProperties = m_contingentProperties; if (contingentProperties != null) { contingentProperties.m_capturedContext = null; NotifyParentIfPotentiallyAttachedTask(); } FinishContinuations(); } internal void NotifyParentIfPotentiallyAttachedTask() { Task task = m_contingentProperties?.m_parent; if (task != null && (task.CreationOptions & TaskCreationOptions.DenyChildAttach) == 0 && ((uint)m_stateFlags & 0xFFFFu & 4u) != 0) { task.ProcessChildCompletion(this); } } internal void ProcessChildCompletion(Task childTask) { ContingentProperties contingentProperties = Volatile.Read(ref m_contingentProperties); if (childTask.IsFaulted && !childTask.IsExceptionObservedByParent) { if (contingentProperties.m_exceptionalChildren == null) { Interlocked.CompareExchange(ref contingentProperties.m_exceptionalChildren, new List(), null); } List exceptionalChildren = contingentProperties.m_exceptionalChildren; if (exceptionalChildren != null) { lock (exceptionalChildren) { exceptionalChildren.Add(childTask); } } } if (Interlocked.Decrement(ref contingentProperties.m_completionCountdown) == 0) { FinishStageTwo(); } } internal void AddExceptionsFromChildren(ContingentProperties props) { List exceptionalChildren = props.m_exceptionalChildren; if (exceptionalChildren == null) { return; } lock (exceptionalChildren) { foreach (Task item in exceptionalChildren) { if (item.IsFaulted && !item.IsExceptionObservedByParent) { TaskExceptionHolder exceptionsHolder = Volatile.Read(ref item.m_contingentProperties).m_exceptionsHolder; AddException(exceptionsHolder.CreateExceptionObject(calledFromFinalizer: false, null)); } } } props.m_exceptionalChildren = null; } internal bool ExecuteEntry() { int oldFlags = 0; if (!AtomicStateUpdate(131072, 23199744, ref oldFlags) && (oldFlags & 0x400000) == 0) { return false; } if (!IsCancellationRequested & !IsCanceled) { ExecuteWithThreadLocal(ref t_currentTask); } else { ExecuteEntryCancellationRequestedOrCanceled(); } return true; } internal virtual void ExecuteFromThreadPool(Thread threadPoolThread) { ExecuteEntryUnsafe(threadPoolThread); } internal void ExecuteEntryUnsafe(Thread threadPoolThread) { m_stateFlags |= 131072; if (!IsCancellationRequested & !IsCanceled) { ExecuteWithThreadLocal(ref t_currentTask, threadPoolThread); } else { ExecuteEntryCancellationRequestedOrCanceled(); } } internal void ExecuteEntryCancellationRequestedOrCanceled() { if (!IsCanceled) { int num = Interlocked.Exchange(ref m_stateFlags, m_stateFlags | 0x400000); if ((num & 0x400000) == 0) { CancellationCleanupLogic(); } } } private void ExecuteWithThreadLocal(ref Task currentTaskSlot, Thread threadPoolThread = null) { Task task = currentTaskSlot; TplEventSource log = TplEventSource.Log; Guid oldActivityThatWillContinue = default(Guid); bool flag = log.IsEnabled(); if (flag) { if (log.TasksSetActivityIds) { EventSource.SetCurrentThreadActivityId(TplEventSource.CreateGuidForTaskID(Id), out oldActivityThatWillContinue); } if (task != null) { log.TaskStarted(task.m_taskScheduler.Id, task.Id, Id); } else { log.TaskStarted(TaskScheduler.Current.Id, 0, Id); } log.TraceSynchronousWorkBegin(Id, CausalitySynchronousWork.Execution); } try { currentTaskSlot = this; try { ExecutionContext capturedContext = CapturedContext; if (capturedContext == null) { InnerInvoke(); } else if (threadPoolThread == null) { ExecutionContext.RunInternal(capturedContext, s_ecCallback, this); } else { ExecutionContext.RunFromThreadPoolDispatchLoop(threadPoolThread, capturedContext, s_ecCallback, this); } } catch (Exception unhandledException) { HandleException(unhandledException); } if (flag) { log.TraceSynchronousWorkEnd(CausalitySynchronousWork.Execution); } Finish(userDelegateExecute: true); } finally { currentTaskSlot = task; if (flag) { if (task != null) { log.TaskCompleted(task.m_taskScheduler.Id, task.Id, Id, IsFaulted); } else { log.TaskCompleted(TaskScheduler.Current.Id, 0, Id, IsFaulted); } if (log.TasksSetActivityIds) { EventSource.SetCurrentThreadActivityId(oldActivityThatWillContinue); } } } } internal virtual void InnerInvoke() { if (m_action is Action action) { action(); } else if (m_action is Action action2) { action2(m_stateObject); } } private void HandleException(Exception unhandledException) { if (unhandledException is OperationCanceledException ex && IsCancellationRequested && m_contingentProperties.m_cancellationToken == ex.CancellationToken) { SetCancellationAcknowledged(); AddException(ex, representsCancellation: true); } else { AddException(unhandledException); } } public TaskAwaiter GetAwaiter() { return new TaskAwaiter(this); } public ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) { return new ConfiguredTaskAwaitable(this, continueOnCapturedContext); } internal void SetContinuationForAwait(Action continuationAction, bool continueOnCapturedContext, bool flowExecutionContext) { TaskContinuation taskContinuation = null; if (continueOnCapturedContext) { SynchronizationContext current = SynchronizationContext.Current; if (current != null && current.GetType() != typeof(SynchronizationContext)) { taskContinuation = new SynchronizationContextAwaitTaskContinuation(current, continuationAction, flowExecutionContext); } else { TaskScheduler internalCurrent = TaskScheduler.InternalCurrent; if (internalCurrent != null && internalCurrent != TaskScheduler.Default) { taskContinuation = new TaskSchedulerAwaitTaskContinuation(internalCurrent, continuationAction, flowExecutionContext); } } } if (taskContinuation == null && flowExecutionContext) { taskContinuation = new AwaitTaskContinuation(continuationAction, flowExecutionContext: true); } if (taskContinuation != null) { if (!AddTaskContinuation(taskContinuation, addBeforeOthers: false)) { taskContinuation.Run(this, canInlineContinuationTask: false); } } else if (!AddTaskContinuation(continuationAction, addBeforeOthers: false)) { AwaitTaskContinuation.UnsafeScheduleAction(continuationAction, this); } } internal void UnsafeSetContinuationForAwait(IAsyncStateMachineBox stateMachineBox, bool continueOnCapturedContext) { if (continueOnCapturedContext) { SynchronizationContext current = SynchronizationContext.Current; if (current != null && current.GetType() != typeof(SynchronizationContext)) { SynchronizationContextAwaitTaskContinuation synchronizationContextAwaitTaskContinuation = new SynchronizationContextAwaitTaskContinuation(current, stateMachineBox.MoveNextAction, flowExecutionContext: false); if (!AddTaskContinuation(synchronizationContextAwaitTaskContinuation, addBeforeOthers: false)) { synchronizationContextAwaitTaskContinuation.Run(this, canInlineContinuationTask: false); } return; } TaskScheduler internalCurrent = TaskScheduler.InternalCurrent; if (internalCurrent != null && internalCurrent != TaskScheduler.Default) { TaskSchedulerAwaitTaskContinuation taskSchedulerAwaitTaskContinuation = new TaskSchedulerAwaitTaskContinuation(internalCurrent, stateMachineBox.MoveNextAction, flowExecutionContext: false); if (!AddTaskContinuation(taskSchedulerAwaitTaskContinuation, addBeforeOthers: false)) { taskSchedulerAwaitTaskContinuation.Run(this, canInlineContinuationTask: false); } return; } } if (!AddTaskContinuation(stateMachineBox, addBeforeOthers: false)) { ThreadPool.UnsafeQueueUserWorkItemInternal(stateMachineBox, preferLocal: true); } } public static YieldAwaitable Yield() { return default(YieldAwaitable); } public void Wait() { Wait(-1, default(CancellationToken)); } public bool Wait(TimeSpan timeout) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.timeout); } return Wait((int)num, default(CancellationToken)); } public void Wait(CancellationToken cancellationToken) { Wait(-1, cancellationToken); } public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, default(CancellationToken)); } public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { if (millisecondsTimeout < -1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsTimeout); } if (!IsWaitNotificationEnabledOrNotRanToCompletion) { return true; } if (!InternalWait(millisecondsTimeout, cancellationToken)) { return false; } if (IsWaitNotificationEnabledOrNotRanToCompletion) { NotifyDebuggerOfWaitCompletionIfNecessary(); if (IsCanceled) { cancellationToken.ThrowIfCancellationRequested(); } ThrowIfExceptional(includeTaskCanceledExceptions: true); } return true; } public Task WaitAsync(CancellationToken cancellationToken) { return WaitAsync(uint.MaxValue, cancellationToken); } public Task WaitAsync(TimeSpan timeout) { return WaitAsync(ValidateTimeout(timeout, ExceptionArgument.timeout), default(CancellationToken)); } public Task WaitAsync(TimeSpan timeout, CancellationToken cancellationToken) { return WaitAsync(ValidateTimeout(timeout, ExceptionArgument.timeout), cancellationToken); } private Task WaitAsync(uint millisecondsTimeout, CancellationToken cancellationToken) { if (IsCompleted || (!cancellationToken.CanBeCanceled && millisecondsTimeout == uint.MaxValue)) { return this; } if (cancellationToken.IsCancellationRequested) { return FromCanceled(cancellationToken); } if (millisecondsTimeout == 0) { return FromException(new TimeoutException()); } return new CancellationPromise(this, millisecondsTimeout, cancellationToken); } private bool WrappedTryRunInline() { if (m_taskScheduler == null) { return false; } try { return m_taskScheduler.TryRunInline(this, taskWasPreviouslyQueued: true); } catch (Exception innerException) { throw new TaskSchedulerException(innerException); } } [MethodImpl(MethodImplOptions.NoOptimization)] internal bool InternalWait(int millisecondsTimeout, CancellationToken cancellationToken) { return InternalWaitCore(millisecondsTimeout, cancellationToken); } private bool InternalWaitCore(int millisecondsTimeout, CancellationToken cancellationToken) { if (IsCompleted) { return true; } TplEventSource log = TplEventSource.Log; bool flag = log.IsEnabled(); if (flag) { Task internalCurrent = InternalCurrent; log.TaskWaitBegin(internalCurrent?.m_taskScheduler.Id ?? TaskScheduler.Default.Id, internalCurrent?.Id ?? 0, Id, TplEventSource.TaskWaitBehavior.Synchronous, 0); } Debugger.NotifyOfCrossThreadDependency(); bool result = (millisecondsTimeout == -1 && !cancellationToken.CanBeCanceled && WrappedTryRunInline() && IsCompleted) || SpinThenBlockingWait(millisecondsTimeout, cancellationToken); if (flag) { Task internalCurrent2 = InternalCurrent; if (internalCurrent2 != null) { log.TaskWaitEnd(internalCurrent2.m_taskScheduler.Id, internalCurrent2.Id, Id); } else { log.TaskWaitEnd(TaskScheduler.Default.Id, 0, Id); } log.TaskWaitContinuationComplete(Id); } return result; } private bool SpinThenBlockingWait(int millisecondsTimeout, CancellationToken cancellationToken) { bool flag = millisecondsTimeout == -1; uint num = ((!flag) ? ((uint)Environment.TickCount) : 0u); bool flag2 = SpinWait(millisecondsTimeout); if (!flag2) { SetOnInvokeMres setOnInvokeMres = new SetOnInvokeMres(); try { AddCompletionAction(setOnInvokeMres, addBeforeOthers: true); if (flag) { bool flag3 = ThreadPool.NotifyThreadBlocked(); try { flag2 = setOnInvokeMres.Wait(-1, cancellationToken); } finally { if (flag3) { ThreadPool.NotifyThreadUnblocked(); } } } else { uint num2 = (uint)Environment.TickCount - num; if (num2 < millisecondsTimeout) { bool flag4 = ThreadPool.NotifyThreadBlocked(); try { flag2 = setOnInvokeMres.Wait((int)(millisecondsTimeout - num2), cancellationToken); } finally { if (flag4) { ThreadPool.NotifyThreadUnblocked(); } } } } } finally { if (!IsCompleted) { RemoveContinuation(setOnInvokeMres); } } } return flag2; } private bool SpinWait(int millisecondsTimeout) { if (IsCompleted) { return true; } if (millisecondsTimeout == 0) { return false; } int spinCountforSpinBeforeWait = System.Threading.SpinWait.SpinCountforSpinBeforeWait; SpinWait spinWait = default(SpinWait); while (spinWait.Count < spinCountforSpinBeforeWait) { spinWait.SpinOnce(-1); if (IsCompleted) { return true; } } return false; } internal void InternalCancel() { TaskSchedulerException ex = null; bool flag = false; if (((uint)m_stateFlags & 0x10000u) != 0) { TaskScheduler taskScheduler = m_taskScheduler; try { flag = taskScheduler?.TryDequeue(this) ?? false; } catch (Exception innerException) { ex = new TaskSchedulerException(innerException); } } RecordInternalCancellationRequest(); bool flag2 = false; if (flag) { flag2 = AtomicStateUpdate(4194304, 4325376); } else if ((m_stateFlags & 0x10000) == 0) { flag2 = AtomicStateUpdate(4194304, 23265280); } if (flag2) { CancellationCleanupLogic(); } if (ex != null) { throw ex; } } internal void InternalCancelContinueWithInitialState() { m_stateFlags |= 4194304; CancellationCleanupLogic(); } internal void RecordInternalCancellationRequest() { EnsureContingentPropertiesInitialized().m_internalCancellationRequested = 1; } internal void RecordInternalCancellationRequest(CancellationToken tokenToRecord, object cancellationException) { RecordInternalCancellationRequest(); if (tokenToRecord != default(CancellationToken)) { m_contingentProperties.m_cancellationToken = tokenToRecord; } if (cancellationException != null) { AddException(cancellationException, representsCancellation: true); } } internal void CancellationCleanupLogic() { Interlocked.Exchange(ref m_stateFlags, m_stateFlags | 0x400000); ContingentProperties contingentProperties = Volatile.Read(ref m_contingentProperties); if (contingentProperties != null) { contingentProperties.SetCompleted(); contingentProperties.UnregisterCancellationCallback(); } if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(Id, AsyncCausalityStatus.Canceled); } if (s_asyncDebuggingEnabled) { RemoveFromActiveTasks(this); } FinishStageThree(); } private void SetCancellationAcknowledged() { m_stateFlags |= 1048576; } internal bool TrySetResult() { if (AtomicStateUpdate(83886080, 90177536)) { ContingentProperties contingentProperties = m_contingentProperties; if (contingentProperties != null) { NotifyParentIfPotentiallyAttachedTask(); contingentProperties.SetCompleted(); } FinishContinuations(); return true; } return false; } internal bool TrySetException(object exceptionObject) { bool result = false; EnsureContingentPropertiesInitialized(); if (AtomicStateUpdate(67108864, 90177536)) { AddException(exceptionObject); Finish(userDelegateExecute: false); result = true; } return result; } internal bool TrySetCanceled(CancellationToken tokenToRecord) { return TrySetCanceled(tokenToRecord, null); } internal bool TrySetCanceled(CancellationToken tokenToRecord, object cancellationException) { bool result = false; if (AtomicStateUpdate(67108864, 90177536)) { RecordInternalCancellationRequest(tokenToRecord, cancellationException); CancellationCleanupLogic(); result = true; } return result; } internal void FinishContinuations() { object obj = Interlocked.Exchange(ref m_continuationObject, s_taskCompletionSentinel); if (obj != null) { RunContinuations(obj); } } private void RunContinuations(object continuationObject) { TplEventSource log = TplEventSource.Log; bool flag = log.IsEnabled(); if (flag) { log.TraceSynchronousWorkBegin(Id, CausalitySynchronousWork.CompletionNotification); } bool flag2 = (m_stateFlags & 0x40) == 0 && RuntimeHelpers.TryEnsureSufficientExecutionStack(); if (!(continuationObject is IAsyncStateMachineBox box)) { if (!(continuationObject is Action action)) { if (!(continuationObject is TaskContinuation taskContinuation)) { if (continuationObject is ITaskCompletionAction completionAction) { RunOrQueueCompletionAction(completionAction, flag2); LogFinishCompletionNotification(); return; } List list = (List)continuationObject; lock (list) { } int count = list.Count; if (flag2) { bool flag3 = false; for (int i = 0; i < count; i++) { object obj = list[i]; if (obj == null) { continue; } if (obj is ContinueWithTaskContinuation continueWithTaskContinuation) { if ((continueWithTaskContinuation.m_options & TaskContinuationOptions.ExecuteSynchronously) == 0) { list[i] = null; if (flag) { log.RunningContinuationList(Id, i, continueWithTaskContinuation); } continueWithTaskContinuation.Run(this, canInlineContinuationTask: false); } } else { if (obj is ITaskCompletionAction) { continue; } if (flag3) { list[i] = null; if (flag) { log.RunningContinuationList(Id, i, obj); } if (!(obj is IAsyncStateMachineBox box2)) { if (obj is Action action2) { AwaitTaskContinuation.RunOrScheduleAction(action2, allowInlining: false); } else { ((TaskContinuation)obj).Run(this, canInlineContinuationTask: false); } } else { AwaitTaskContinuation.RunOrScheduleAction(box2, allowInlining: false); } } flag3 = true; } } } for (int j = 0; j < count; j++) { object obj2 = list[j]; if (obj2 == null) { continue; } list[j] = null; if (flag) { log.RunningContinuationList(Id, j, obj2); } if (!(obj2 is IAsyncStateMachineBox box3)) { if (!(obj2 is Action action3)) { if (obj2 is TaskContinuation taskContinuation2) { taskContinuation2.Run(this, flag2); } else { RunOrQueueCompletionAction((ITaskCompletionAction)obj2, flag2); } } else { AwaitTaskContinuation.RunOrScheduleAction(action3, flag2); } } else { AwaitTaskContinuation.RunOrScheduleAction(box3, flag2); } } LogFinishCompletionNotification(); } else { taskContinuation.Run(this, flag2); LogFinishCompletionNotification(); } } else { AwaitTaskContinuation.RunOrScheduleAction(action, flag2); LogFinishCompletionNotification(); } } else { AwaitTaskContinuation.RunOrScheduleAction(box, flag2); LogFinishCompletionNotification(); } } private void RunOrQueueCompletionAction(ITaskCompletionAction completionAction, bool allowInlining) { if (allowInlining || !completionAction.InvokeMayRunArbitraryCode) { completionAction.Invoke(this); } else { ThreadPool.UnsafeQueueUserWorkItemInternal(new CompletionActionInvoker(completionAction, this), preferLocal: true); } } private static void LogFinishCompletionNotification() { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceSynchronousWorkEnd(CausalitySynchronousWork.CompletionNotification); } } public Task ContinueWith(Action continuationAction) { return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Action continuationAction, CancellationToken cancellationToken) { return ContinueWith(continuationAction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); } public Task ContinueWith(Action continuationAction, TaskScheduler scheduler) { return ContinueWith(continuationAction, scheduler, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Action continuationAction, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationAction, TaskScheduler.Current, default(CancellationToken), continuationOptions); } public Task ContinueWith(Action continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { return ContinueWith(continuationAction, scheduler, cancellationToken, continuationOptions); } private Task ContinueWith(Action continuationAction, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { if (continuationAction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationAction); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } CreationOptionsFromContinuationOptions(continuationOptions, out var creationOptions, out var internalOptions); Task task = new ContinuationTaskFromTask(this, continuationAction, null, creationOptions, internalOptions); ContinueWithCore(task, scheduler, cancellationToken, continuationOptions); return task; } public Task ContinueWith(Action continuationAction, object? state) { return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Action continuationAction, object? state, CancellationToken cancellationToken) { return ContinueWith(continuationAction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); } public Task ContinueWith(Action continuationAction, object? state, TaskScheduler scheduler) { return ContinueWith(continuationAction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Action continuationAction, object? state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationAction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions); } public Task ContinueWith(Action continuationAction, object? state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { return ContinueWith(continuationAction, state, scheduler, cancellationToken, continuationOptions); } private Task ContinueWith(Action continuationAction, object state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { if (continuationAction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationAction); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } CreationOptionsFromContinuationOptions(continuationOptions, out var creationOptions, out var internalOptions); Task task = new ContinuationTaskFromTask(this, continuationAction, state, creationOptions, internalOptions); ContinueWithCore(task, scheduler, cancellationToken, continuationOptions); return task; } public Task ContinueWith(Func continuationFunction) { return ContinueWith(continuationFunction, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Func continuationFunction, CancellationToken cancellationToken) { return ContinueWith(continuationFunction, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); } public Task ContinueWith(Func continuationFunction, TaskScheduler scheduler) { return ContinueWith(continuationFunction, scheduler, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Func continuationFunction, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationFunction, TaskScheduler.Current, default(CancellationToken), continuationOptions); } public Task ContinueWith(Func continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { return ContinueWith(continuationFunction, scheduler, cancellationToken, continuationOptions); } private Task ContinueWith(Func continuationFunction, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } CreationOptionsFromContinuationOptions(continuationOptions, out var creationOptions, out var internalOptions); Task task = new ContinuationResultTaskFromTask(this, continuationFunction, null, creationOptions, internalOptions); ContinueWithCore(task, scheduler, cancellationToken, continuationOptions); return task; } public Task ContinueWith(Func continuationFunction, object? state) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Func continuationFunction, object? state, CancellationToken cancellationToken) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, cancellationToken, TaskContinuationOptions.None); } public Task ContinueWith(Func continuationFunction, object? state, TaskScheduler scheduler) { return ContinueWith(continuationFunction, state, scheduler, default(CancellationToken), TaskContinuationOptions.None); } public Task ContinueWith(Func continuationFunction, object? state, TaskContinuationOptions continuationOptions) { return ContinueWith(continuationFunction, state, TaskScheduler.Current, default(CancellationToken), continuationOptions); } public Task ContinueWith(Func continuationFunction, object? state, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { return ContinueWith(continuationFunction, state, scheduler, cancellationToken, continuationOptions); } private Task ContinueWith(Func continuationFunction, object state, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.continuationFunction); } if (scheduler == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.scheduler); } CreationOptionsFromContinuationOptions(continuationOptions, out var creationOptions, out var internalOptions); Task task = new ContinuationResultTaskFromTask(this, continuationFunction, state, creationOptions, internalOptions); ContinueWithCore(task, scheduler, cancellationToken, continuationOptions); return task; } internal static void CreationOptionsFromContinuationOptions(TaskContinuationOptions continuationOptions, out TaskCreationOptions creationOptions, out InternalTaskOptions internalOptions) { if ((continuationOptions & (TaskContinuationOptions.LongRunning | TaskContinuationOptions.ExecuteSynchronously)) == (TaskContinuationOptions.LongRunning | TaskContinuationOptions.ExecuteSynchronously)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.continuationOptions, ExceptionResource.Task_ContinueWith_ESandLR); } if (((uint)continuationOptions & 0xFFF0FF80u) != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.continuationOptions); } if ((continuationOptions & (TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.NotOnRanToCompletion)) == (TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.NotOnRanToCompletion)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.continuationOptions, ExceptionResource.Task_ContinueWith_NotOnAnything); } creationOptions = (TaskCreationOptions)(continuationOptions & (TaskContinuationOptions.PreferFairness | TaskContinuationOptions.LongRunning | TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.HideScheduler | TaskContinuationOptions.RunContinuationsAsynchronously)); internalOptions = (((continuationOptions & TaskContinuationOptions.LazyCancellation) != 0) ? (InternalTaskOptions.ContinuationTask | InternalTaskOptions.LazyCancellation) : InternalTaskOptions.ContinuationTask); } internal void ContinueWithCore(Task continuationTask, TaskScheduler scheduler, CancellationToken cancellationToken, TaskContinuationOptions options) { TaskContinuation taskContinuation = new ContinueWithTaskContinuation(continuationTask, options, scheduler); if (cancellationToken.CanBeCanceled) { if (IsCompleted || cancellationToken.IsCancellationRequested) { continuationTask.AssignCancellationToken(cancellationToken, null, null); } else { continuationTask.AssignCancellationToken(cancellationToken, this, taskContinuation); } } if (continuationTask.IsCompleted) { return; } if ((Options & (TaskCreationOptions)1024) != 0 && !(this is ITaskCompletionAction)) { TplEventSource log = TplEventSource.Log; if (log.IsEnabled()) { log.AwaitTaskContinuationScheduled(TaskScheduler.Current.Id, CurrentId.GetValueOrDefault(), continuationTask.Id); } } if (!AddTaskContinuation(taskContinuation, addBeforeOthers: false)) { taskContinuation.Run(this, canInlineContinuationTask: true); } } internal void AddCompletionAction(ITaskCompletionAction action, bool addBeforeOthers = false) { if (!AddTaskContinuation(action, addBeforeOthers)) { action.Invoke(this); } } private bool AddTaskContinuationComplex(object tc, bool addBeforeOthers) { object continuationObject = m_continuationObject; if (continuationObject != s_taskCompletionSentinel && !(continuationObject is List)) { Interlocked.CompareExchange(ref m_continuationObject, new List { continuationObject }, continuationObject); } if (m_continuationObject is List list) { lock (list) { if (m_continuationObject != s_taskCompletionSentinel) { if (list.Count == list.Capacity) { list.RemoveAll((object l) => l == null); } if (addBeforeOthers) { list.Insert(0, tc); } else { list.Add(tc); } return true; } } } return false; } private bool AddTaskContinuation(object tc, bool addBeforeOthers) { if (IsCompleted) { return false; } if (m_continuationObject != null || Interlocked.CompareExchange(ref m_continuationObject, tc, null) != null) { return AddTaskContinuationComplex(tc, addBeforeOthers); } return true; } internal void RemoveContinuation(object continuationObject) { object continuationObject2 = m_continuationObject; if (continuationObject2 == s_taskCompletionSentinel) { return; } List list = continuationObject2 as List; if (list == null) { if (Interlocked.CompareExchange(ref m_continuationObject, new List(), continuationObject) == continuationObject) { return; } list = m_continuationObject as List; } if (list == null) { return; } lock (list) { if (m_continuationObject != s_taskCompletionSentinel) { int num = list.IndexOf(continuationObject); if (num != -1) { list[num] = null; } } } } [MethodImpl(MethodImplOptions.NoOptimization)] [UnsupportedOSPlatform("browser")] public static void WaitAll(params Task[] tasks) { WaitAllCore(tasks, -1, default(CancellationToken)); } [MethodImpl(MethodImplOptions.NoOptimization)] [UnsupportedOSPlatform("browser")] public static bool WaitAll(Task[] tasks, TimeSpan timeout) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.timeout); } return WaitAllCore(tasks, (int)num, default(CancellationToken)); } [MethodImpl(MethodImplOptions.NoOptimization)] [UnsupportedOSPlatform("browser")] public static bool WaitAll(Task[] tasks, int millisecondsTimeout) { return WaitAllCore(tasks, millisecondsTimeout, default(CancellationToken)); } [MethodImpl(MethodImplOptions.NoOptimization)] [UnsupportedOSPlatform("browser")] public static void WaitAll(Task[] tasks, CancellationToken cancellationToken) { WaitAllCore(tasks, -1, cancellationToken); } [MethodImpl(MethodImplOptions.NoOptimization)] [UnsupportedOSPlatform("browser")] public static bool WaitAll(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) { return WaitAllCore(tasks, millisecondsTimeout, cancellationToken); } [UnsupportedOSPlatform("browser")] private static bool WaitAllCore(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) { if (tasks == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } if (millisecondsTimeout < -1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsTimeout); } cancellationToken.ThrowIfCancellationRequested(); List exceptions = null; List list = null; List list2 = null; bool flag = false; bool flag2 = false; bool flag3 = true; for (int num = tasks.Length - 1; num >= 0; num--) { Task task = tasks[num]; if (task == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_WaitMulti_NullTask, ExceptionArgument.tasks); } bool flag4 = task.IsCompleted; if (!flag4) { if (millisecondsTimeout != -1 || cancellationToken.CanBeCanceled) { AddToList(task, ref list, tasks.Length); } else { flag4 = task.WrappedTryRunInline() && task.IsCompleted; if (!flag4) { AddToList(task, ref list, tasks.Length); } } } if (flag4) { if (task.IsFaulted) { flag = true; } else if (task.IsCanceled) { flag2 = true; } if (task.IsWaitNotificationEnabled) { AddToList(task, ref list2, 1); } } } if (list != null) { flag3 = WaitAllBlockingCore(list, millisecondsTimeout, cancellationToken); if (flag3) { foreach (Task item in list) { if (item.IsFaulted) { flag = true; } else if (item.IsCanceled) { flag2 = true; } if (item.IsWaitNotificationEnabled) { AddToList(item, ref list2, 1); } } } GC.KeepAlive(tasks); } if (flag3 && list2 != null) { foreach (Task item2 in list2) { if (item2.NotifyDebuggerOfWaitCompletionIfNecessary()) { break; } } } if (flag3 && (flag || flag2)) { if (!flag) { cancellationToken.ThrowIfCancellationRequested(); } foreach (Task t in tasks) { AddExceptionsForCompletedTask(ref exceptions, t); } ThrowHelper.ThrowAggregateException(exceptions); } return flag3; } private static void AddToList(T item, ref List list, int initSize) { if (list == null) { list = new List(initSize); } list.Add(item); } [UnsupportedOSPlatform("browser")] private static bool WaitAllBlockingCore(List tasks, int millisecondsTimeout, CancellationToken cancellationToken) { bool flag = false; SetOnCountdownMres setOnCountdownMres = new SetOnCountdownMres(tasks.Count); try { foreach (Task task in tasks) { task.AddCompletionAction(setOnCountdownMres, addBeforeOthers: true); } flag = setOnCountdownMres.Wait(millisecondsTimeout, cancellationToken); } finally { if (!flag) { foreach (Task task2 in tasks) { if (!task2.IsCompleted) { task2.RemoveContinuation(setOnCountdownMres); } } } } return flag; } internal static void AddExceptionsForCompletedTask(ref List exceptions, Task t) { AggregateException exceptions2 = t.GetExceptions(includeTaskCanceledExceptions: true); if (exceptions2 != null) { t.UpdateExceptionObservedStatus(); if (exceptions == null) { exceptions = new List(exceptions2.InnerExceptionCount); } exceptions.AddRange(exceptions2.InternalInnerExceptions); } } [MethodImpl(MethodImplOptions.NoOptimization)] public static int WaitAny(params Task[] tasks) { return WaitAnyCore(tasks, -1, default(CancellationToken)); } [MethodImpl(MethodImplOptions.NoOptimization)] public static int WaitAny(Task[] tasks, TimeSpan timeout) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > int.MaxValue) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.timeout); } return WaitAnyCore(tasks, (int)num, default(CancellationToken)); } [MethodImpl(MethodImplOptions.NoOptimization)] public static int WaitAny(Task[] tasks, CancellationToken cancellationToken) { return WaitAnyCore(tasks, -1, cancellationToken); } [MethodImpl(MethodImplOptions.NoOptimization)] public static int WaitAny(Task[] tasks, int millisecondsTimeout) { return WaitAnyCore(tasks, millisecondsTimeout, default(CancellationToken)); } [MethodImpl(MethodImplOptions.NoOptimization)] public static int WaitAny(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) { return WaitAnyCore(tasks, millisecondsTimeout, cancellationToken); } private static int WaitAnyCore(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) { if (tasks == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } if (millisecondsTimeout < -1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsTimeout); } cancellationToken.ThrowIfCancellationRequested(); int num = -1; for (int i = 0; i < tasks.Length; i++) { Task task = tasks[i]; if (task == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_WaitMulti_NullTask, ExceptionArgument.tasks); } if (num == -1 && task.IsCompleted) { num = i; } } if (num == -1 && tasks.Length != 0) { Task task2 = TaskFactory.CommonCWAnyLogic(tasks, isSyncBlocking: true); if (task2.Wait(millisecondsTimeout, cancellationToken)) { num = Array.IndexOf(tasks, task2.Result); } else { TaskFactory.CommonCWAnyLogicCleanup(task2); } } GC.KeepAlive(tasks); return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Task FromResult(TResult result) { if (result == null) { return Task.s_defaultResultTask; } if (typeof(TResult).IsValueType) { if (typeof(TResult) == typeof(bool)) { Task value = (((bool)(object)result) ? TaskCache.s_trueTask : TaskCache.s_falseTask); return Unsafe.As>(value); } if (typeof(TResult) == typeof(int)) { int num = (int)(object)result; if ((uint)(num - -1) < 10u) { Task value2 = TaskCache.s_int32Tasks[num - -1]; return Unsafe.As>(value2); } } else if ((typeof(TResult) == typeof(uint) && (uint)(object)result == 0) || (typeof(TResult) == typeof(byte) && (byte)(object)result == 0) || (typeof(TResult) == typeof(sbyte) && (sbyte)(object)result == 0) || (typeof(TResult) == typeof(char) && (char)(object)result == '\0') || (typeof(TResult) == typeof(long) && (long)(object)result == 0L) || (typeof(TResult) == typeof(ulong) && (ulong)(object)result == 0L) || (typeof(TResult) == typeof(short) && (short)(object)result == 0) || (typeof(TResult) == typeof(ushort) && (ushort)(object)result == 0) || (typeof(TResult) == typeof(IntPtr) && (IntPtr)0 == (IntPtr)(object)result) || (typeof(TResult) == typeof(UIntPtr) && (UIntPtr)0u == (UIntPtr)(object)result)) { return Task.s_defaultResultTask; } } return new Task(result); } public static Task FromException(Exception exception) { if (exception == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); } Task task = new Task(); bool flag = task.TrySetException(exception); return task; } public static Task FromException(Exception exception) { if (exception == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); } Task task = new Task(); bool flag = task.TrySetException(exception); return task; } public static Task FromCanceled(CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.cancellationToken); } return new Task(canceled: true, TaskCreationOptions.None, cancellationToken); } public static Task FromCanceled(CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.cancellationToken); } return new Task(canceled: true, default(TResult), TaskCreationOptions.None, cancellationToken); } internal static Task FromCanceled(OperationCanceledException exception) { Task task = new Task(); bool flag = task.TrySetCanceled(exception.CancellationToken, exception); return task; } internal static Task FromCanceled(OperationCanceledException exception) { Task task = new Task(); bool flag = task.TrySetCanceled(exception.CancellationToken, exception); return task; } public static Task Run(Action action) { return InternalStartNew(null, action, null, default(CancellationToken), TaskScheduler.Default, TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None); } public static Task Run(Action action, CancellationToken cancellationToken) { return InternalStartNew(null, action, null, cancellationToken, TaskScheduler.Default, TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None); } public static Task Run(Func function) { return Task.StartNew(null, function, default(CancellationToken), TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, TaskScheduler.Default); } public static Task Run(Func function, CancellationToken cancellationToken) { return Task.StartNew(null, function, cancellationToken, TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, TaskScheduler.Default); } public static Task Run(Func function) { return Run(function, default(CancellationToken)); } public static Task Run(Func function, CancellationToken cancellationToken) { if (function == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function); } if (cancellationToken.IsCancellationRequested) { return FromCanceled(cancellationToken); } Task outerTask = Task.Factory.StartNew(function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); return new UnwrapPromise(outerTask, lookForOce: true); } public static Task Run(Func?> function) { return Run(function, default(CancellationToken)); } public static Task Run(Func?> function, CancellationToken cancellationToken) { if (function == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.function); } if (cancellationToken.IsCancellationRequested) { return FromCanceled(cancellationToken); } Task> outerTask = Task>.Factory.StartNew(function, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); return new UnwrapPromise(outerTask, lookForOce: true); } public static Task Delay(TimeSpan delay) { return Delay(delay, default(CancellationToken)); } public static Task Delay(TimeSpan delay, CancellationToken cancellationToken) { return Delay(ValidateTimeout(delay, ExceptionArgument.delay), cancellationToken); } public static Task Delay(int millisecondsDelay) { return Delay(millisecondsDelay, default(CancellationToken)); } public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken) { if (millisecondsDelay < -1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.millisecondsDelay, ExceptionResource.Task_Delay_InvalidMillisecondsDelay); } return Delay((uint)millisecondsDelay, cancellationToken); } private static Task Delay(uint millisecondsDelay, CancellationToken cancellationToken) { if (!cancellationToken.IsCancellationRequested) { if (millisecondsDelay != 0) { if (!cancellationToken.CanBeCanceled) { return new DelayPromise(millisecondsDelay); } return new DelayPromiseWithCancellation(millisecondsDelay, cancellationToken); } return CompletedTask; } return FromCanceled(cancellationToken); } internal static uint ValidateTimeout(TimeSpan timeout, ExceptionArgument argument) { long num = (long)timeout.TotalMilliseconds; if (num < -1 || num > 4294967294u) { ThrowHelper.ThrowArgumentOutOfRangeException(argument, ExceptionResource.Task_InvalidTimerTimeSpan); } return (uint)num; } public static Task WhenAll(IEnumerable tasks) { if (tasks is ICollection collection) { if (tasks is Task[] tasks2) { return WhenAll(tasks2); } int num = 0; Task[] array = new Task[collection.Count]; foreach (Task task in tasks) { if (task == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); } array[num++] = task; } return InternalWhenAll(array); } if (tasks == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } List list = new List(); foreach (Task task2 in tasks) { if (task2 == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); } list.Add(task2); } return InternalWhenAll(list.ToArray()); } public static Task WhenAll(params Task[] tasks) { if (tasks == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } int num = tasks.Length; if (num == 0) { return InternalWhenAll(tasks); } Task[] array = new Task[num]; for (int i = 0; i < num; i++) { Task task = tasks[i]; if (task == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); } array[i] = task; } return InternalWhenAll(array); } private static Task InternalWhenAll(Task[] tasks) { if (tasks.Length != 0) { return new WhenAllPromise(tasks); } return CompletedTask; } public static Task WhenAll(IEnumerable> tasks) { if (tasks is Task[] tasks2) { return WhenAll(tasks2); } if (tasks is ICollection> collection) { int num = 0; Task[] array = new Task[collection.Count]; foreach (Task task in tasks) { if (task == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); } array[num++] = task; } return InternalWhenAll(array); } if (tasks == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } List> list = new List>(); foreach (Task task2 in tasks) { if (task2 == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); } list.Add(task2); } return InternalWhenAll(list.ToArray()); } public static Task WhenAll(params Task[] tasks) { if (tasks == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } int num = tasks.Length; if (num == 0) { return InternalWhenAll(tasks); } Task[] array = new Task[num]; for (int i = 0; i < num; i++) { Task task = tasks[i]; if (task == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); } array[i] = task; } return InternalWhenAll(array); } private static Task InternalWhenAll(Task[] tasks) { if (tasks.Length != 0) { return new WhenAllPromise(tasks); } return new Task(canceled: false, Array.Empty(), TaskCreationOptions.None, default(CancellationToken)); } public static Task WhenAny(params Task[] tasks) { if (tasks == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } if (tasks.Length == 2) { return WhenAny(tasks[0], tasks[1]); } if (tasks.Length == 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks); } int num = tasks.Length; Task[] array = new Task[num]; for (int i = 0; i < num; i++) { Task task = tasks[i]; if (task == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); } array[i] = task; } return TaskFactory.CommonCWAnyLogic(array); } public static Task WhenAny(Task task1, Task task2) { if (task1 != null && task2 != null) { if (!task1.IsCompleted) { if (!task2.IsCompleted) { return new TwoTaskWhenAnyPromise(task1, task2); } return FromResult(task2); } return FromResult(task1); } throw new ArgumentNullException((task1 == null) ? "task1" : "task2"); } public static Task WhenAny(IEnumerable tasks) { if (tasks is ICollection collection) { if (tasks is Task[] tasks2) { return WhenAny(tasks2); } int count = collection.Count; if (count <= 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks); } int num = 0; Task[] array = new Task[count]; foreach (Task task in tasks) { if (task == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); } array[num++] = task; } return TaskFactory.CommonCWAnyLogic(array); } if (tasks == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.tasks); } List list = new List(); foreach (Task task2 in tasks) { if (task2 == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_NullTask, ExceptionArgument.tasks); } list.Add(task2); } if (list.Count == 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Task_MultiTaskContinuation_EmptyTaskList, ExceptionArgument.tasks); } return TaskFactory.CommonCWAnyLogic(list); } public static Task> WhenAny(params Task[] tasks) { if (tasks != null && tasks.Length == 2) { return WhenAny(tasks[0], tasks[1]); } Task task = WhenAny((Task[])tasks); return task.ContinueWith(Task.TaskWhenAnyCast.Value, default(CancellationToken), TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } public static Task> WhenAny(Task task1, Task task2) { if (task1 != null && task2 != null) { if (!task1.IsCompleted) { if (!task2.IsCompleted) { return new TwoTaskWhenAnyPromise>(task1, task2); } return FromResult(task2); } return FromResult(task1); } throw new ArgumentNullException((task1 == null) ? "task1" : "task2"); } public static Task> WhenAny(IEnumerable> tasks) { Task task = WhenAny((IEnumerable)tasks); return task.ContinueWith(Task.TaskWhenAnyCast.Value, default(CancellationToken), TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } internal static Task CreateUnwrapPromise(Task outerTask, bool lookForOce) { return new UnwrapPromise(outerTask, lookForOce); } internal virtual Delegate[] GetDelegateContinuationsForDebugger() { if (m_continuationObject != this) { return GetDelegatesFromContinuationObject(m_continuationObject); } return null; } private static Delegate[] GetDelegatesFromContinuationObject(object continuationObject) { if (continuationObject != null) { if (continuationObject is Action action) { return new Delegate[1] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(action) }; } if (continuationObject is TaskContinuation taskContinuation) { return taskContinuation.GetDelegateContinuationsForDebugger(); } if (continuationObject is Task task) { Delegate[] delegateContinuationsForDebugger = task.GetDelegateContinuationsForDebugger(); if (delegateContinuationsForDebugger != null) { return delegateContinuationsForDebugger; } } if (continuationObject is ITaskCompletionAction taskCompletionAction) { return new Delegate[1] { new Action(taskCompletionAction.Invoke) }; } if (continuationObject is List list) { List list2 = new List(); foreach (object item in list) { Delegate[] delegatesFromContinuationObject = GetDelegatesFromContinuationObject(item); if (delegatesFromContinuationObject == null) { continue; } Delegate[] array = delegatesFromContinuationObject; foreach (Delegate @delegate in array) { if ((object)@delegate != null) { list2.Add(@delegate); } } } return list2.ToArray(); } } return null; } private static Task GetActiveTaskFromId(int taskId) { Task value = null; s_currentActiveTasks?.TryGetValue(taskId, out value); return value; } } internal sealed class CompletionActionInvoker : IThreadPoolWorkItem { private readonly ITaskCompletionAction m_action; private readonly Task m_completingTask; internal CompletionActionInvoker(ITaskCompletionAction action, Task completingTask) { m_action = action; m_completingTask = completingTask; } void IThreadPoolWorkItem.Execute() { m_action.Invoke(m_completingTask); } } internal sealed class SystemThreadingTasks_TaskDebugView { private readonly Task m_task; public object AsyncState => m_task.AsyncState; public TaskCreationOptions CreationOptions => m_task.CreationOptions; public Exception Exception => m_task.Exception; public int Id => m_task.Id; public bool CancellationPending { get { if (m_task.Status == TaskStatus.WaitingToRun) { return m_task.CancellationToken.IsCancellationRequested; } return false; } } public TaskStatus Status => m_task.Status; public SystemThreadingTasks_TaskDebugView(Task task) { m_task = task; } } [Flags] public enum TaskCreationOptions { None = 0, PreferFairness = 1, LongRunning = 2, AttachedToParent = 4, DenyChildAttach = 8, HideScheduler = 0x10, RunContinuationsAsynchronously = 0x40 } [Flags] internal enum InternalTaskOptions { None = 0, InternalOptionsMask = 0xFF00, ContinuationTask = 0x200, PromiseTask = 0x400, LazyCancellation = 0x1000, QueuedByRuntime = 0x2000, DoNotDispose = 0x4000 } [Flags] public enum TaskContinuationOptions { None = 0, PreferFairness = 1, LongRunning = 2, AttachedToParent = 4, DenyChildAttach = 8, HideScheduler = 0x10, LazyCancellation = 0x20, RunContinuationsAsynchronously = 0x40, NotOnRanToCompletion = 0x10000, NotOnFaulted = 0x20000, NotOnCanceled = 0x40000, OnlyOnRanToCompletion = 0x60000, OnlyOnFaulted = 0x50000, OnlyOnCanceled = 0x30000, ExecuteSynchronously = 0x80000 } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct VoidTaskResult { } internal interface ITaskCompletionAction { bool InvokeMayRunArbitraryCode { get; } void Invoke(Task completingTask); } internal sealed class UnwrapPromise : Task, ITaskCompletionAction { private byte _state; private readonly bool _lookForOce; public bool InvokeMayRunArbitraryCode => true; public UnwrapPromise(Task outerTask, bool lookForOce) : base((object)null, outerTask.CreationOptions & TaskCreationOptions.AttachedToParent) { _lookForOce = lookForOce; if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(base.Id, "Task.Unwrap", 0L); } if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(this); } if (outerTask.IsCompleted) { ProcessCompletedOuterTask(outerTask); } else { outerTask.AddCompletionAction(this); } } public void Invoke(Task completingTask) { if (RuntimeHelpers.TryEnsureSufficientExecutionStack()) { InvokeCore(completingTask); } else { InvokeCoreAsync(completingTask); } } private void InvokeCore(Task completingTask) { switch (_state) { case 0: ProcessCompletedOuterTask(completingTask); break; case 1: { bool flag = TrySetFromTask(completingTask, lookForOce: false); _state = 2; break; } } } private void InvokeCoreAsync(Task completingTask) { ThreadPool.UnsafeQueueUserWorkItem(delegate(object state) { TupleSlim, Task> tupleSlim = (TupleSlim, Task>)state; tupleSlim.Item1.InvokeCore(tupleSlim.Item2); }, new TupleSlim, Task>(this, completingTask)); } private void ProcessCompletedOuterTask(Task task) { _state = 1; switch (task.Status) { case TaskStatus.Canceled: case TaskStatus.Faulted: { bool flag = TrySetFromTask(task, _lookForOce); break; } case TaskStatus.RanToCompletion: ProcessInnerTask((task is Task> task2) ? task2.Result : ((Task)task).Result); break; } } private bool TrySetFromTask(Task task, bool lookForOce) { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationRelation(base.Id, CausalityRelation.Join); } bool result = false; switch (task.Status) { case TaskStatus.Canceled: result = TrySetCanceled(task.CancellationToken, task.GetCancellationExceptionDispatchInfo()); break; case TaskStatus.Faulted: { List exceptionDispatchInfos = task.GetExceptionDispatchInfos(); ExceptionDispatchInfo exceptionDispatchInfo; result = ((!lookForOce || exceptionDispatchInfos.Count <= 0 || (exceptionDispatchInfo = exceptionDispatchInfos[0]) == null || !(exceptionDispatchInfo.SourceException is OperationCanceledException ex)) ? TrySetException(exceptionDispatchInfos) : TrySetCanceled(ex.CancellationToken, exceptionDispatchInfo)); break; } case TaskStatus.RanToCompletion: if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(base.Id, AsyncCausalityStatus.Completed); } if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(this); } result = TrySetResult((task is Task task2) ? task2.Result : default(TResult)); break; } return result; } private void ProcessInnerTask(Task task) { if (task == null) { TrySetCanceled(default(CancellationToken)); _state = 2; } else if (task.IsCompleted) { TrySetFromTask(task, lookForOce: false); _state = 2; } else { task.AddCompletionAction(this); } } } public static class TaskAsyncEnumerableExtensions { public static ConfiguredAsyncDisposable ConfigureAwait(this IAsyncDisposable source, bool continueOnCapturedContext) { return new ConfiguredAsyncDisposable(source, continueOnCapturedContext); } public static ConfiguredCancelableAsyncEnumerable ConfigureAwait(this IAsyncEnumerable source, bool continueOnCapturedContext) { return new ConfiguredCancelableAsyncEnumerable(source, continueOnCapturedContext, default(CancellationToken)); } public static ConfiguredCancelableAsyncEnumerable WithCancellation(this IAsyncEnumerable source, CancellationToken cancellationToken) { return new ConfiguredCancelableAsyncEnumerable(source, continueOnCapturedContext: true, cancellationToken); } } internal static class TaskCache { internal static readonly Task s_trueTask = CreateCacheableTask(result: true); internal static readonly Task s_falseTask = CreateCacheableTask(result: false); internal static readonly Task[] s_int32Tasks = CreateInt32Tasks(); internal static Task CreateCacheableTask(TResult result) { return new Task(canceled: false, result, (TaskCreationOptions)16384, default(CancellationToken)); } private static Task[] CreateInt32Tasks() { Task[] array = new Task[10]; for (int i = 0; i < array.Length; i++) { array[i] = CreateCacheableTask(i + -1); } return array; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class TaskCanceledException : OperationCanceledException { [NonSerialized] private readonly Task _canceledTask; public Task? Task => _canceledTask; public TaskCanceledException() : base(SR.TaskCanceledException_ctor_DefaultMessage) { } public TaskCanceledException(string? message) : base(message) { } public TaskCanceledException(string? message, Exception? innerException) : base(message, innerException) { } public TaskCanceledException(string? message, Exception? innerException, CancellationToken token) : base(message, innerException, token) { } public TaskCanceledException(Task? task) : base(SR.TaskCanceledException_ctor_DefaultMessage, task?.CancellationToken ?? CancellationToken.None) { _canceledTask = task; } protected TaskCanceledException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class TaskCompletionSource { private readonly Task _task; public Task Task => _task; public TaskCompletionSource() { _task = new Task(); } public TaskCompletionSource(TaskCreationOptions creationOptions) : this(null, creationOptions) { } public TaskCompletionSource(object? state) : this(state, TaskCreationOptions.None) { } public TaskCompletionSource(object? state, TaskCreationOptions creationOptions) { _task = new Task(state, creationOptions, promiseStyle: true); } public void SetException(Exception exception) { if (!TrySetException(exception)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } public void SetException(IEnumerable exceptions) { if (!TrySetException(exceptions)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } public bool TrySetException(Exception exception) { if (exception == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); } bool flag = _task.TrySetException(exception); if (!flag && !_task.IsCompleted) { _task.SpinUntilCompleted(); } return flag; } public bool TrySetException(IEnumerable exceptions) { if (exceptions == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exceptions); } List list = new List(); foreach (Exception exception in exceptions) { if (exception == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.TaskCompletionSourceT_TrySetException_NullException, ExceptionArgument.exceptions); } list.Add(exception); } if (list.Count == 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.TaskCompletionSourceT_TrySetException_NoExceptions, ExceptionArgument.exceptions); } bool flag = _task.TrySetException(list); if (!flag && !_task.IsCompleted) { _task.SpinUntilCompleted(); } return flag; } public void SetResult() { if (!TrySetResult()) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } public bool TrySetResult() { bool flag = _task.TrySetResult(); if (!flag) { _task.SpinUntilCompleted(); } return flag; } public void SetCanceled() { SetCanceled(default(CancellationToken)); } public void SetCanceled(CancellationToken cancellationToken) { if (!TrySetCanceled(cancellationToken)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } public bool TrySetCanceled() { return TrySetCanceled(default(CancellationToken)); } public bool TrySetCanceled(CancellationToken cancellationToken) { bool flag = _task.TrySetCanceled(cancellationToken); if (!flag && !_task.IsCompleted) { _task.SpinUntilCompleted(); } return flag; } } public class TaskCompletionSource { private readonly Task _task; public Task Task => _task; public TaskCompletionSource() { _task = new Task(); } public TaskCompletionSource(TaskCreationOptions creationOptions) : this((object?)null, creationOptions) { } public TaskCompletionSource(object? state) : this(state, TaskCreationOptions.None) { } public TaskCompletionSource(object? state, TaskCreationOptions creationOptions) { _task = new Task(state, creationOptions); } public void SetException(Exception exception) { if (!TrySetException(exception)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } public void SetException(IEnumerable exceptions) { if (!TrySetException(exceptions)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } public bool TrySetException(Exception exception) { if (exception == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); } bool flag = _task.TrySetException(exception); if (!flag && !_task.IsCompleted) { _task.SpinUntilCompleted(); } return flag; } public bool TrySetException(IEnumerable exceptions) { if (exceptions == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exceptions); } List list = new List(); foreach (Exception exception in exceptions) { if (exception == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.TaskCompletionSourceT_TrySetException_NullException, ExceptionArgument.exceptions); } list.Add(exception); } if (list.Count == 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.TaskCompletionSourceT_TrySetException_NoExceptions, ExceptionArgument.exceptions); } bool flag = _task.TrySetException(list); if (!flag && !_task.IsCompleted) { _task.SpinUntilCompleted(); } return flag; } public void SetResult(TResult result) { if (!TrySetResult(result)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } public bool TrySetResult(TResult result) { bool flag = _task.TrySetResult(result); if (!flag) { _task.SpinUntilCompleted(); } return flag; } public void SetCanceled() { SetCanceled(default(CancellationToken)); } public void SetCanceled(CancellationToken cancellationToken) { if (!TrySetCanceled(cancellationToken)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } public bool TrySetCanceled() { return TrySetCanceled(default(CancellationToken)); } public bool TrySetCanceled(CancellationToken cancellationToken) { bool flag = _task.TrySetCanceled(cancellationToken); if (!flag && !_task.IsCompleted) { _task.SpinUntilCompleted(); } return flag; } } internal sealed class ContinuationTaskFromTask : Task { private Task m_antecedent; public ContinuationTaskFromTask(Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { m_antecedent = antecedent; } internal override void InnerInvoke() { Task antecedent = m_antecedent; m_antecedent = null; antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); if (m_action is Action action) { action(antecedent); } else if (m_action is Action action2) { action2(antecedent, m_stateObject); } } } internal sealed class ContinuationResultTaskFromTask : Task { private Task m_antecedent; public ContinuationResultTaskFromTask(Task antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, (TaskScheduler)null) { m_antecedent = antecedent; } internal override void InnerInvoke() { Task antecedent = m_antecedent; m_antecedent = null; antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); if (m_action is Func func) { m_result = func(antecedent); } else if (m_action is Func func2) { m_result = func2(antecedent, m_stateObject); } } } internal sealed class ContinuationTaskFromResultTask : Task { private Task m_antecedent; public ContinuationTaskFromResultTask(Task antecedent, Delegate action, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(action, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, null) { m_antecedent = antecedent; } internal override void InnerInvoke() { Task antecedent = m_antecedent; m_antecedent = null; antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); if (m_action is Action> action) { action(antecedent); } else if (m_action is Action, object> action2) { action2(antecedent, m_stateObject); } } } internal sealed class ContinuationResultTaskFromResultTask : Task { private Task m_antecedent; public ContinuationResultTaskFromResultTask(Task antecedent, Delegate function, object state, TaskCreationOptions creationOptions, InternalTaskOptions internalOptions) : base(function, state, Task.InternalCurrentIfAttached(creationOptions), default(CancellationToken), creationOptions, internalOptions, (TaskScheduler)null) { m_antecedent = antecedent; } internal override void InnerInvoke() { Task antecedent = m_antecedent; m_antecedent = null; antecedent.NotifyDebuggerOfWaitCompletionIfNecessary(); if (m_action is Func, TResult> func) { m_result = func(antecedent); } else if (m_action is Func, object, TResult> func2) { m_result = func2(antecedent, m_stateObject); } } } internal abstract class TaskContinuation { internal abstract void Run(Task completedTask, bool canInlineContinuationTask); protected static void InlineIfPossibleOrElseQueue(Task task, bool needsProtection) { if (needsProtection) { if (!task.MarkStarted()) { return; } } else { task.m_stateFlags |= 65536; } try { if (!task.m_taskScheduler.TryRunInline(task, taskWasPreviouslyQueued: false)) { task.m_taskScheduler.InternalQueueTask(task); } } catch (Exception innerException) { TaskSchedulerException exceptionObject = new TaskSchedulerException(innerException); task.AddException(exceptionObject); task.Finish(userDelegateExecute: false); } } internal abstract Delegate[] GetDelegateContinuationsForDebugger(); } internal sealed class ContinueWithTaskContinuation : TaskContinuation { internal Task m_task; internal readonly TaskContinuationOptions m_options; private readonly TaskScheduler m_taskScheduler; internal ContinueWithTaskContinuation(Task task, TaskContinuationOptions options, TaskScheduler scheduler) { m_task = task; m_options = options; m_taskScheduler = scheduler; if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(m_task.Id, "Task.ContinueWith: " + task.m_action.Method.Name, 0L); } if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(m_task); } } internal override void Run(Task completedTask, bool canInlineContinuationTask) { Task task = m_task; m_task = null; TaskContinuationOptions options = m_options; if (completedTask.IsCompletedSuccessfully ? ((options & TaskContinuationOptions.NotOnRanToCompletion) == 0) : (completedTask.IsCanceled ? ((options & TaskContinuationOptions.NotOnCanceled) == 0) : ((options & TaskContinuationOptions.NotOnFaulted) == 0))) { if (TplEventSource.Log.IsEnabled() && !task.IsCanceled) { TplEventSource.Log.TraceOperationRelation(task.Id, CausalityRelation.AssignDelegate); } task.m_taskScheduler = m_taskScheduler; if (!canInlineContinuationTask || (options & TaskContinuationOptions.ExecuteSynchronously) == 0) { try { task.ScheduleAndStart(needsProtection: true); return; } catch (TaskSchedulerException) { return; } } TaskContinuation.InlineIfPossibleOrElseQueue(task, needsProtection: true); } else { Task.ContingentProperties contingentProperties = task.m_contingentProperties; if (contingentProperties == null || contingentProperties.m_cancellationToken == default(CancellationToken)) { task.InternalCancelContinueWithInitialState(); } else { task.InternalCancel(); } } } internal override Delegate[] GetDelegateContinuationsForDebugger() { if (m_task != null) { if ((object)m_task.m_action != null) { return new Delegate[1] { m_task.m_action }; } return m_task.GetDelegateContinuationsForDebugger(); } return null; } } internal sealed class SynchronizationContextAwaitTaskContinuation : AwaitTaskContinuation { private static readonly SendOrPostCallback s_postCallback = delegate(object state) { ((Action)state)(); }; private static ContextCallback s_postActionCallback; private readonly SynchronizationContext m_syncContext; internal SynchronizationContextAwaitTaskContinuation(SynchronizationContext context, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { m_syncContext = context; } internal sealed override void Run(Task task, bool canInlineContinuationTask) { if (canInlineContinuationTask && m_syncContext == SynchronizationContext.Current) { RunCallback(AwaitTaskContinuation.GetInvokeActionCallback(), m_action, ref Task.t_currentTask); return; } TplEventSource log = TplEventSource.Log; if (log.IsEnabled()) { m_continuationId = Task.NewId(); log.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, m_continuationId); } RunCallback(GetPostActionCallback(), this, ref Task.t_currentTask); } private static void PostAction(object state) { SynchronizationContextAwaitTaskContinuation synchronizationContextAwaitTaskContinuation = (SynchronizationContextAwaitTaskContinuation)state; TplEventSource log = TplEventSource.Log; if (log.IsEnabled() && log.TasksSetActivityIds && synchronizationContextAwaitTaskContinuation.m_continuationId != 0) { synchronizationContextAwaitTaskContinuation.m_syncContext.Post(s_postCallback, GetActionLogDelegate(synchronizationContextAwaitTaskContinuation.m_continuationId, synchronizationContextAwaitTaskContinuation.m_action)); } else { synchronizationContextAwaitTaskContinuation.m_syncContext.Post(s_postCallback, synchronizationContextAwaitTaskContinuation.m_action); } } private static Action GetActionLogDelegate(int continuationId, Action action) { return delegate { Guid activityId = TplEventSource.CreateGuidForTaskID(continuationId); EventSource.SetCurrentThreadActivityId(activityId, out var oldActivityThatWillContinue); try { action(); } finally { EventSource.SetCurrentThreadActivityId(oldActivityThatWillContinue); } }; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ContextCallback GetPostActionCallback() { return PostAction; } } internal sealed class TaskSchedulerAwaitTaskContinuation : AwaitTaskContinuation { private readonly TaskScheduler m_scheduler; internal TaskSchedulerAwaitTaskContinuation(TaskScheduler scheduler, Action action, bool flowExecutionContext) : base(action, flowExecutionContext) { m_scheduler = scheduler; } internal sealed override void Run(Task ignored, bool canInlineContinuationTask) { if (m_scheduler == TaskScheduler.Default) { base.Run(ignored, canInlineContinuationTask); return; } bool flag = canInlineContinuationTask && (TaskScheduler.InternalCurrent == m_scheduler || Thread.CurrentThread.IsThreadPoolThread); Task task = CreateTask(delegate(object state) { try { ((Action)state)(); } catch (Exception exception) { Task.ThrowAsync(exception, null); } }, m_action, m_scheduler); if (flag) { TaskContinuation.InlineIfPossibleOrElseQueue(task, needsProtection: false); return; } try { task.ScheduleAndStart(needsProtection: false); } catch (TaskSchedulerException) { } } } internal class AwaitTaskContinuation : TaskContinuation, IThreadPoolWorkItem { private readonly ExecutionContext m_capturedContext; protected readonly Action m_action; protected int m_continuationId; private static readonly ContextCallback s_invokeContextCallback = delegate(object state) { ((Action)state)(); }; private static readonly Action s_invokeAction = delegate(Action action) { action(); }; internal static bool IsValidLocationForInlining { get { SynchronizationContext current = SynchronizationContext.Current; if (current != null && current.GetType() != typeof(SynchronizationContext)) { return false; } TaskScheduler internalCurrent = TaskScheduler.InternalCurrent; if (internalCurrent != null) { return internalCurrent == TaskScheduler.Default; } return true; } } internal AwaitTaskContinuation(Action action, bool flowExecutionContext) { m_action = action; if (flowExecutionContext) { m_capturedContext = ExecutionContext.Capture(); } } protected Task CreateTask(Action action, object state, TaskScheduler scheduler) { return new Task(action, state, null, default(CancellationToken), TaskCreationOptions.None, InternalTaskOptions.QueuedByRuntime, scheduler) { CapturedContext = m_capturedContext }; } internal override void Run(Task task, bool canInlineContinuationTask) { if (canInlineContinuationTask && IsValidLocationForInlining) { RunCallback(GetInvokeActionCallback(), m_action, ref Task.t_currentTask); return; } TplEventSource log = TplEventSource.Log; if (log.IsEnabled()) { m_continuationId = Task.NewId(); log.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, m_continuationId); } ThreadPool.UnsafeQueueUserWorkItemInternal(this, preferLocal: true); } void IThreadPoolWorkItem.Execute() { TplEventSource log = TplEventSource.Log; ExecutionContext capturedContext = m_capturedContext; if (!log.IsEnabled() && capturedContext == null) { m_action(); return; } Guid oldActivityThatWillContinue = default(Guid); if (log.IsEnabled() && log.TasksSetActivityIds && m_continuationId != 0) { Guid activityId = TplEventSource.CreateGuidForTaskID(m_continuationId); EventSource.SetCurrentThreadActivityId(activityId, out oldActivityThatWillContinue); } try { if (capturedContext == null || capturedContext.IsDefault) { m_action(); } else { ExecutionContext.RunForThreadPoolUnsafe(capturedContext, s_invokeAction, in m_action); } } finally { if (log.IsEnabled() && log.TasksSetActivityIds && m_continuationId != 0) { EventSource.SetCurrentThreadActivityId(oldActivityThatWillContinue); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected static ContextCallback GetInvokeActionCallback() { return s_invokeContextCallback; } protected void RunCallback(ContextCallback callback, object state, ref Task currentTask) { Task task = currentTask; try { if (task != null) { currentTask = null; } ExecutionContext capturedContext = m_capturedContext; if (capturedContext == null) { callback(state); } else { ExecutionContext.RunInternal(capturedContext, callback, state); } } catch (Exception exception) { Task.ThrowAsync(exception, null); } finally { if (task != null) { currentTask = task; } } } internal static void RunOrScheduleAction(Action action, bool allowInlining) { Task t_currentTask = Task.t_currentTask; if (!allowInlining || !IsValidLocationForInlining) { UnsafeScheduleAction(action, t_currentTask); return; } try { if (t_currentTask != null) { Task.t_currentTask = null; } action(); } catch (Exception exception) { Task.ThrowAsync(exception, null); } finally { if (t_currentTask != null) { Task.t_currentTask = t_currentTask; } } } internal static void RunOrScheduleAction(IAsyncStateMachineBox box, bool allowInlining) { Task t_currentTask = Task.t_currentTask; if (!allowInlining || !IsValidLocationForInlining) { if (TplEventSource.Log.IsEnabled()) { UnsafeScheduleAction(box.MoveNextAction, t_currentTask); } else { ThreadPool.UnsafeQueueUserWorkItemInternal(box, preferLocal: true); } return; } try { if (t_currentTask != null) { Task.t_currentTask = null; } box.MoveNext(); } catch (Exception exception) { Task.ThrowAsync(exception, null); } finally { if (t_currentTask != null) { Task.t_currentTask = t_currentTask; } } } internal static void UnsafeScheduleAction(Action action, Task task) { AwaitTaskContinuation awaitTaskContinuation = new AwaitTaskContinuation(action, flowExecutionContext: false); TplEventSource log = TplEventSource.Log; if (log.IsEnabled() && task != null) { awaitTaskContinuation.m_continuationId = Task.NewId(); log.AwaitTaskContinuationScheduled((task.ExecutingTaskScheduler ?? TaskScheduler.Default).Id, task.Id, awaitTaskContinuation.m_continuationId); } ThreadPool.UnsafeQueueUserWorkItemInternal(awaitTaskContinuation, preferLocal: true); } internal override Delegate[] GetDelegateContinuationsForDebugger() { return new Delegate[1] { AsyncMethodBuilderCore.TryGetStateMachineForDebugger(m_action) }; } } internal sealed class TaskExceptionHolder { private readonly Task m_task; private volatile List m_faultExceptions; private ExceptionDispatchInfo m_cancellationException; private volatile bool m_isHandled; internal bool ContainsFaultList => m_faultExceptions != null; internal TaskExceptionHolder(Task task) { m_task = task; } ~TaskExceptionHolder() { if (m_faultExceptions != null && !m_isHandled) { AggregateException exception = new AggregateException(SR.TaskExceptionHolder_UnhandledException, m_faultExceptions); UnobservedTaskExceptionEventArgs ueea = new UnobservedTaskExceptionEventArgs(exception); TaskScheduler.PublishUnobservedTaskException(m_task, ueea); } } internal void Add(object exceptionObject, bool representsCancellation) { if (representsCancellation) { SetCancellationException(exceptionObject); } else { AddFaultException(exceptionObject); } } private void SetCancellationException(object exceptionObject) { if (exceptionObject is OperationCanceledException source) { m_cancellationException = ExceptionDispatchInfo.Capture(source); } else { ExceptionDispatchInfo cancellationException = exceptionObject as ExceptionDispatchInfo; m_cancellationException = cancellationException; } MarkAsHandled(calledFromFinalizer: false); } private void AddFaultException(object exceptionObject) { List list = m_faultExceptions; if (list == null) { list = (m_faultExceptions = new List(1)); } if (exceptionObject is Exception source) { list.Add(ExceptionDispatchInfo.Capture(source)); } else if (exceptionObject is ExceptionDispatchInfo item) { list.Add(item); } else if (exceptionObject is IEnumerable enumerable) { foreach (Exception item2 in enumerable) { list.Add(ExceptionDispatchInfo.Capture(item2)); } } else { if (!(exceptionObject is IEnumerable collection)) { throw new ArgumentException(SR.TaskExceptionHolder_UnknownExceptionType, "exceptionObject"); } list.AddRange(collection); } if (list.Count > 0) { MarkAsUnhandled(); } } private void MarkAsUnhandled() { if (m_isHandled) { GC.ReRegisterForFinalize(this); m_isHandled = false; } } internal void MarkAsHandled(bool calledFromFinalizer) { if (!m_isHandled) { if (!calledFromFinalizer) { GC.SuppressFinalize(this); } m_isHandled = true; } } internal AggregateException CreateExceptionObject(bool calledFromFinalizer, Exception includeThisException) { List faultExceptions = m_faultExceptions; MarkAsHandled(calledFromFinalizer); if (includeThisException == null) { return new AggregateException(faultExceptions); } Exception[] array = new Exception[faultExceptions.Count + 1]; for (int i = 0; i < array.Length - 1; i++) { array[i] = faultExceptions[i].SourceException; } array[^1] = includeThisException; return new AggregateException(array); } internal List GetExceptionDispatchInfos() { List faultExceptions = m_faultExceptions; MarkAsHandled(calledFromFinalizer: false); return faultExceptions; } internal ExceptionDispatchInfo GetCancellationExceptionDispatchInfo() { return m_cancellationException; } } public static class TaskExtensions { public static Task Unwrap(this Task task) { if (task == null) { throw new ArgumentNullException("task"); } object task2; if (task.IsCompletedSuccessfully) { task2 = task.Result; if (task2 == null) { return Task.FromCanceled(new CancellationToken(canceled: true)); } } else { task2 = Task.CreateUnwrapPromise(task, lookForOce: false); } return (Task)task2; } public static Task Unwrap(this Task> task) { if (task == null) { throw new ArgumentNullException("task"); } Task task2; if (task.IsCompletedSuccessfully) { task2 = task.Result; if (task2 == null) { return Task.FromCanceled(new CancellationToken(canceled: true)); } } else { task2 = Task.CreateUnwrapPromise(task, lookForOce: false); } return task2; } } public class TaskFactory { private sealed class CompleteOnCountdownPromise : Task, ITaskCompletionAction { private readonly Task[] _tasks; private int _count; public bool InvokeMayRunArbitraryCode => true; private protected override bool ShouldNotifyDebuggerOfWaitCompletion { get { if (base.ShouldNotifyDebuggerOfWaitCompletion) { return Task.AnyTaskRequiresNotifyDebuggerOfWaitCompletion(_tasks); } return false; } } internal CompleteOnCountdownPromise(Task[] tasksCopy) { _tasks = tasksCopy; _count = tasksCopy.Length; if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(base.Id, "TaskFactory.ContinueWhenAll", 0L); } if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(this); } } public void Invoke(Task completingTask) { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationRelation(base.Id, CausalityRelation.Join); } if (completingTask.IsWaitNotificationEnabled) { SetNotificationForWaitCompletion(enabled: true); } if (Interlocked.Decrement(ref _count) == 0) { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(base.Id, AsyncCausalityStatus.Completed); } if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(this); } TrySetResult(_tasks); } } } private sealed class CompleteOnCountdownPromise : Task[]>, ITaskCompletionAction { private readonly Task[] _tasks; private int _count; public bool InvokeMayRunArbitraryCode => true; private protected override bool ShouldNotifyDebuggerOfWaitCompletion { get { if (base.ShouldNotifyDebuggerOfWaitCompletion) { Task[] tasks = _tasks; return Task.AnyTaskRequiresNotifyDebuggerOfWaitCompletion(tasks); } return false; } } internal CompleteOnCountdownPromise(Task[] tasksCopy) { _tasks = tasksCopy; _count = tasksCopy.Length; if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(base.Id, "TaskFactory.ContinueWhenAll<>", 0L); } if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(this); } } public void Invoke(Task completingTask) { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationRelation(base.Id, CausalityRelation.Join); } if (completingTask.IsWaitNotificationEnabled) { SetNotificationForWaitCompletion(enabled: true); } if (Interlocked.Decrement(ref _count) == 0) { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(base.Id, AsyncCausalityStatus.Completed); } if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(this); } TrySetResult(_tasks); } } } internal sealed class CompleteOnInvokePromise : Task, ITaskCompletionAction { private IList _tasks; private int _stateFlags; public bool InvokeMayRunArbitraryCode => (_stateFlags & 2) == 0; public CompleteOnInvokePromise(IList tasks, bool isSyncBlocking) { _tasks = tasks; if (isSyncBlocking) { _stateFlags = 2; } if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(base.Id, "TaskFactory.ContinueWhenAny", 0L); } if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(this); } } public void Invoke(Task completingTask) { int stateFlags = _stateFlags; int num = stateFlags & 2; if (((uint)stateFlags & (true ? 1u : 0u)) != 0 || Interlocked.Exchange(ref _stateFlags, num | 1) != num) { return; } if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationRelation(base.Id, CausalityRelation.Choice); TplEventSource.Log.TraceOperationEnd(base.Id, AsyncCausalityStatus.Completed); } if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(this); } bool flag = TrySetResult(completingTask); IList tasks = _tasks; int count = tasks.Count; for (int i = 0; i < count; i++) { Task task = tasks[i]; if (task != null && !task.IsCompleted) { task.RemoveContinuation(this); } } _tasks = null; } } private readonly CancellationToken m_defaultCancellationToken; private readonly TaskScheduler m_defaultScheduler; private readonly TaskCreationOptions m_defaultCreationOptions; private readonly TaskContinuationOptions m_defaultContinuationOptions; private TaskScheduler DefaultScheduler => m_defaultScheduler ?? TaskScheduler.Current; public CancellationToken CancellationToken => m_defaultCancellationToken; public TaskScheduler? Scheduler => m_defaultScheduler; public TaskCreationOptions CreationOptions => m_defaultCreationOptions; public TaskContinuationOptions ContinuationOptions => m_defaultContinuationOptions; private TaskScheduler GetDefaultScheduler(Task currTask) { TaskScheduler? taskScheduler = m_defaultScheduler; if (taskScheduler == null) { if (currTask == null || (currTask.CreationOptions & TaskCreationOptions.HideScheduler) != 0) { return TaskScheduler.Default; } taskScheduler = currTask.ExecutingTaskScheduler; } return taskScheduler; } public TaskFactory() { } public TaskFactory(CancellationToken cancellationToken) { m_defaultCancellationToken = cancellationToken; } public TaskFactory(TaskScheduler? scheduler) { m_defaultScheduler = scheduler; } public TaskFactory(TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions) { CheckMultiTaskContinuationOptions(continuationOptions); CheckCreationOptions(creationOptions); m_defaultCreationOptions = creationOptions; m_defaultContinuationOptions = continuationOptions; } public TaskFactory(CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskContinuationOptions continuationOptions, TaskScheduler? scheduler) : this(creationOptions, continuationOptions) { m_defaultCancellationToken = cancellationToken; m_defaultScheduler = scheduler; } internal static void CheckCreationOptions(TaskCreationOptions creationOptions) { if (((uint)creationOptions & 0xFFFFFFA0u) != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions); } } public Task StartNew(Action action) { Task internalCurrent = Task.InternalCurrent; return Task.InternalStartNew(internalCurrent, action, null, m_defaultCancellationToken, GetDefaultScheduler(internalCurrent), m_defaultCreationOptions, InternalTaskOptions.None); } public Task StartNew(Action action, CancellationToken cancellationToken) { Task internalCurrent = Task.InternalCurrent; return Task.InternalStartNew(internalCurrent, action, null, cancellationToken, GetDefaultScheduler(internalCurrent), m_defaultCreationOptions, InternalTaskOptions.None); } public Task StartNew(Action action, TaskCreationOptions creationOptions) { Task internalCurrent = Task.InternalCurrent; return Task.InternalStartNew(internalCurrent, action, null, m_defaultCancellationToken, GetDefaultScheduler(internalCurrent), creationOptions, InternalTaskOptions.None); } public Task StartNew(Action action, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return Task.InternalStartNew(Task.InternalCurrentIfAttached(creationOptions), action, null, cancellationToken, scheduler, creationOptions, InternalTaskOptions.None); } public Task StartNew(Action action, object? state) { Task internalCurrent = Task.InternalCurrent; return Task.InternalStartNew(internalCurrent, action, state, m_defaultCancellationToken, GetDefaultScheduler(internalCurrent), m_defaultCreationOptions, InternalTaskOptions.None); } public Task StartNew(Action action, object? state, CancellationToken cancellationToken) { Task internalCurrent = Task.InternalCurrent; return Task.InternalStartNew(internalCurrent, action, state, cancellationToken, GetDefaultScheduler(internalCurrent), m_defaultCreationOptions, InternalTaskOptions.None); } public Task StartNew(Action action, object? state, TaskCreationOptions creationOptions) { Task internalCurrent = Task.InternalCurrent; return Task.InternalStartNew(internalCurrent, action, state, m_defaultCancellationToken, GetDefaultScheduler(internalCurrent), creationOptions, InternalTaskOptions.None); } public Task StartNew(Action action, object? state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return Task.InternalStartNew(Task.InternalCurrentIfAttached(creationOptions), action, state, cancellationToken, scheduler, creationOptions, InternalTaskOptions.None); } public Task StartNew(Func function) { Task internalCurrent = Task.InternalCurrent; return Task.StartNew(internalCurrent, function, m_defaultCancellationToken, m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(internalCurrent)); } public Task StartNew(Func function, CancellationToken cancellationToken) { Task internalCurrent = Task.InternalCurrent; return Task.StartNew(internalCurrent, function, cancellationToken, m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(internalCurrent)); } public Task StartNew(Func function, TaskCreationOptions creationOptions) { Task internalCurrent = Task.InternalCurrent; return Task.StartNew(internalCurrent, function, m_defaultCancellationToken, creationOptions, InternalTaskOptions.None, GetDefaultScheduler(internalCurrent)); } public Task StartNew(Func function, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return Task.StartNew(Task.InternalCurrentIfAttached(creationOptions), function, cancellationToken, creationOptions, InternalTaskOptions.None, scheduler); } public Task StartNew(Func function, object? state) { Task internalCurrent = Task.InternalCurrent; return Task.StartNew(internalCurrent, function, state, m_defaultCancellationToken, m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(internalCurrent)); } public Task StartNew(Func function, object? state, CancellationToken cancellationToken) { Task internalCurrent = Task.InternalCurrent; return Task.StartNew(internalCurrent, function, state, cancellationToken, m_defaultCreationOptions, InternalTaskOptions.None, GetDefaultScheduler(internalCurrent)); } public Task StartNew(Func function, object? state, TaskCreationOptions creationOptions) { Task internalCurrent = Task.InternalCurrent; return Task.StartNew(internalCurrent, function, state, m_defaultCancellationToken, creationOptions, InternalTaskOptions.None, GetDefaultScheduler(internalCurrent)); } public Task StartNew(Func function, object? state, CancellationToken cancellationToken, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return Task.StartNew(Task.InternalCurrentIfAttached(creationOptions), function, state, cancellationToken, creationOptions, InternalTaskOptions.None, scheduler); } public Task FromAsync(IAsyncResult asyncResult, Action endMethod) { return FromAsync(asyncResult, endMethod, m_defaultCreationOptions, DefaultScheduler); } public Task FromAsync(IAsyncResult asyncResult, Action endMethod, TaskCreationOptions creationOptions) { return FromAsync(asyncResult, endMethod, creationOptions, DefaultScheduler); } public Task FromAsync(IAsyncResult asyncResult, Action endMethod, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return TaskFactory.FromAsyncImpl(asyncResult, null, endMethod, creationOptions, scheduler); } public Task FromAsync(Func beginMethod, Action endMethod, object? state) { return FromAsync(beginMethod, endMethod, state, m_defaultCreationOptions); } public Task FromAsync(Func beginMethod, Action endMethod, object? state, TaskCreationOptions creationOptions) { return TaskFactory.FromAsyncImpl(beginMethod, null, endMethod, state, creationOptions); } public Task FromAsync(Func beginMethod, Action endMethod, TArg1 arg1, object? state) { return FromAsync(beginMethod, endMethod, arg1, state, m_defaultCreationOptions); } public Task FromAsync(Func beginMethod, Action endMethod, TArg1 arg1, object? state, TaskCreationOptions creationOptions) { return TaskFactory.FromAsyncImpl(beginMethod, null, endMethod, arg1, state, creationOptions); } public Task FromAsync(Func beginMethod, Action endMethod, TArg1 arg1, TArg2 arg2, object? state) { return FromAsync(beginMethod, endMethod, arg1, arg2, state, m_defaultCreationOptions); } public Task FromAsync(Func beginMethod, Action endMethod, TArg1 arg1, TArg2 arg2, object? state, TaskCreationOptions creationOptions) { return TaskFactory.FromAsyncImpl(beginMethod, null, endMethod, arg1, arg2, state, creationOptions); } public Task FromAsync(Func beginMethod, Action endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, object? state) { return FromAsync(beginMethod, endMethod, arg1, arg2, arg3, state, m_defaultCreationOptions); } public Task FromAsync(Func beginMethod, Action endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, object? state, TaskCreationOptions creationOptions) { return TaskFactory.FromAsyncImpl(beginMethod, null, endMethod, arg1, arg2, arg3, state, creationOptions); } public Task FromAsync(IAsyncResult asyncResult, Func endMethod) { return TaskFactory.FromAsyncImpl(asyncResult, endMethod, null, m_defaultCreationOptions, DefaultScheduler); } public Task FromAsync(IAsyncResult asyncResult, Func endMethod, TaskCreationOptions creationOptions) { return TaskFactory.FromAsyncImpl(asyncResult, endMethod, null, creationOptions, DefaultScheduler); } public Task FromAsync(IAsyncResult asyncResult, Func endMethod, TaskCreationOptions creationOptions, TaskScheduler scheduler) { return TaskFactory.FromAsyncImpl(asyncResult, endMethod, null, creationOptions, scheduler); } public Task FromAsync(Func beginMethod, Func endMethod, object? state) { return TaskFactory.FromAsyncImpl(beginMethod, endMethod, null, state, m_defaultCreationOptions); } public Task FromAsync(Func beginMethod, Func endMethod, object? state, TaskCreationOptions creationOptions) { return TaskFactory.FromAsyncImpl(beginMethod, endMethod, null, state, creationOptions); } public Task FromAsync(Func beginMethod, Func endMethod, TArg1 arg1, object? state) { return TaskFactory.FromAsyncImpl(beginMethod, endMethod, null, arg1, state, m_defaultCreationOptions); } public Task FromAsync(Func beginMethod, Func endMethod, TArg1 arg1, object? state, TaskCreationOptions creationOptions) { return TaskFactory.FromAsyncImpl(beginMethod, endMethod, null, arg1, state, creationOptions); } public Task FromAsync(Func beginMethod, Func endMethod, TArg1 arg1, TArg2 arg2, object? state) { return TaskFactory.FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, state, m_defaultCreationOptions); } public Task FromAsync(Func beginMethod, Func endMethod, TArg1 arg1, TArg2 arg2, object? state, TaskCreationOptions creationOptions) { return TaskFactory.FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, state, creationOptions); } public Task FromAsync(Func beginMethod, Func endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, object? state) { return TaskFactory.FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, arg3, state, m_defaultCreationOptions); } public Task FromAsync(Func beginMethod, Func endMethod, TArg1 arg1, TArg2 arg2, TArg3 arg3, object? state, TaskCreationOptions creationOptions) { return TaskFactory.FromAsyncImpl(beginMethod, endMethod, null, arg1, arg2, arg3, state, creationOptions); } internal static void CheckFromAsyncOptions(TaskCreationOptions creationOptions, bool hasBeginMethod) { if (hasBeginMethod) { if ((creationOptions & TaskCreationOptions.LongRunning) != 0) { throw new ArgumentOutOfRangeException("creationOptions", SR.Task_FromAsync_LongRunning); } if ((creationOptions & TaskCreationOptions.PreferFairness) != 0) { throw new ArgumentOutOfRangeException("creationOptions", SR.Task_FromAsync_PreferFairness); } } if (((uint)creationOptions & 0xFFFFFFE0u) != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.creationOptions); } } internal static Task CommonCWAllLogic(Task[] tasksCopy) { CompleteOnCountdownPromise completeOnCountdownPromise = new CompleteOnCountdownPromise(tasksCopy); for (int i = 0; i < tasksCopy.Length; i++) { if (tasksCopy[i].IsCompleted) { completeOnCountdownPromise.Invoke(tasksCopy[i]); } else { tasksCopy[i].AddCompletionAction(completeOnCountdownPromise); } } return completeOnCountdownPromise; } internal static Task[]> CommonCWAllLogic(Task[] tasksCopy) { CompleteOnCountdownPromise completeOnCountdownPromise = new CompleteOnCountdownPromise(tasksCopy); for (int i = 0; i < tasksCopy.Length; i++) { if (tasksCopy[i].IsCompleted) { completeOnCountdownPromise.Invoke(tasksCopy[i]); } else { tasksCopy[i].AddCompletionAction(completeOnCountdownPromise); } } return completeOnCountdownPromise; } public Task ContinueWhenAll(Task[] tasks, Action continuationAction) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Action continuationAction, CancellationToken cancellationToken) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Action continuationAction, TaskContinuationOptions continuationOptions) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Action continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction, CancellationToken cancellationToken) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction, TaskContinuationOptions continuationOptions) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Action[]> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAllImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } public Task ContinueWhenAll(Task[] tasks, Func continuationFunction) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, CancellationToken cancellationToken) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAll(Task[] tasks, Func[], TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAllImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } internal static Task CommonCWAnyLogic(IList tasks, bool isSyncBlocking = false) { CompleteOnInvokePromise completeOnInvokePromise = new CompleteOnInvokePromise(tasks, isSyncBlocking); bool flag = false; int count = tasks.Count; for (int i = 0; i < count; i++) { Task task = tasks[i]; if (task == null) { throw new ArgumentException(SR.Task_MultiTaskContinuation_NullTask, "tasks"); } if (flag) { continue; } if (completeOnInvokePromise.IsCompleted) { flag = true; continue; } if (task.IsCompleted) { completeOnInvokePromise.Invoke(task); flag = true; continue; } task.AddCompletionAction(completeOnInvokePromise, isSyncBlocking); if (completeOnInvokePromise.IsCompleted) { task.RemoveContinuation(completeOnInvokePromise); } } return completeOnInvokePromise; } internal static void CommonCWAnyLogicCleanup(Task continuation) { ((CompleteOnInvokePromise)continuation).Invoke(null); } public Task ContinueWhenAny(Task[] tasks, Action continuationAction) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Action continuationAction, CancellationToken cancellationToken) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Action continuationAction, TaskContinuationOptions continuationOptions) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Action continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } public Task ContinueWhenAny(Task[] tasks, Func continuationFunction) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Func continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, CancellationToken cancellationToken) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, TaskContinuationOptions continuationOptions) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Func, TResult> continuationFunction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationFunction == null) { throw new ArgumentNullException("continuationFunction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, continuationFunction, null, continuationOptions, cancellationToken, scheduler); } public Task ContinueWhenAny(Task[] tasks, Action> continuationAction) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Action> continuationAction, CancellationToken cancellationToken) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, m_defaultContinuationOptions, cancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Action> continuationAction, TaskContinuationOptions continuationOptions) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, m_defaultCancellationToken, DefaultScheduler); } public Task ContinueWhenAny(Task[] tasks, Action> continuationAction, CancellationToken cancellationToken, TaskContinuationOptions continuationOptions, TaskScheduler scheduler) { if (continuationAction == null) { throw new ArgumentNullException("continuationAction"); } return TaskFactory.ContinueWhenAnyImpl(tasks, null, continuationAction, continuationOptions, cancellationToken, scheduler); } internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks) { if (tasks == null) { throw new ArgumentNullException("tasks"); } if (tasks.Length == 0) { throw new ArgumentException(SR.Task_MultiTaskContinuation_EmptyTaskList, "tasks"); } Task[] array = new Task[tasks.Length]; for (int i = 0; i < tasks.Length; i++) { array[i] = tasks[i]; if (array[i] == null) { throw new ArgumentException(SR.Task_MultiTaskContinuation_NullTask, "tasks"); } } return array; } internal static Task[] CheckMultiContinuationTasksAndCopy(Task[] tasks) { if (tasks == null) { throw new ArgumentNullException("tasks"); } if (tasks.Length == 0) { throw new ArgumentException(SR.Task_MultiTaskContinuation_EmptyTaskList, "tasks"); } Task[] array = new Task[tasks.Length]; for (int i = 0; i < tasks.Length; i++) { array[i] = tasks[i]; if (array[i] == null) { throw new ArgumentException(SR.Task_MultiTaskContinuation_NullTask, "tasks"); } } return array; } internal static void CheckMultiTaskContinuationOptions(TaskContinuationOptions continuationOptions) { if ((continuationOptions & (TaskContinuationOptions.LongRunning | TaskContinuationOptions.ExecuteSynchronously)) == (TaskContinuationOptions.LongRunning | TaskContinuationOptions.ExecuteSynchronously)) { throw new ArgumentOutOfRangeException("continuationOptions", SR.Task_ContinueWith_ESandLR); } if (((uint)continuationOptions & 0xFFF0FFC0u) != 0) { throw new ArgumentOutOfRangeException("continuationOptions"); } if ((continuationOptions & (TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.NotOnRanToCompletion)) != 0) { throw new ArgumentOutOfRangeException("continuationOptions", SR.Task_MultiTaskContinuation_FireOptions); } } } [DebuggerDisplay("Id={Id}")] [DebuggerTypeProxy(typeof(SystemThreadingTasks_TaskSchedulerDebugView))] public abstract class TaskScheduler { internal sealed class SystemThreadingTasks_TaskSchedulerDebugView { private readonly TaskScheduler m_taskScheduler; public int Id => m_taskScheduler.Id; public IEnumerable ScheduledTasks => m_taskScheduler.GetScheduledTasks(); public SystemThreadingTasks_TaskSchedulerDebugView(TaskScheduler scheduler) { m_taskScheduler = scheduler; } } internal readonly struct TaskSchedulerAwaiter : ICriticalNotifyCompletion, INotifyCompletion { private readonly TaskScheduler _scheduler; public bool IsCompleted => false; public TaskSchedulerAwaiter(TaskScheduler scheduler) { _scheduler = scheduler; } public void GetResult() { } public void OnCompleted(Action continuation) { Task.Factory.StartNew(continuation, CancellationToken.None, TaskCreationOptions.DenyChildAttach, _scheduler); } public void UnsafeOnCompleted(Action continuation) { if (_scheduler == Default) { ThreadPool.UnsafeQueueUserWorkItem(delegate(Action s) { s(); }, continuation, preferLocal: true); } else { OnCompleted(continuation); } } } private static ConditionalWeakTable s_activeTaskSchedulers; private static readonly TaskScheduler s_defaultTaskScheduler = new ThreadPoolTaskScheduler(); internal static int s_taskSchedulerIdCounter; private volatile int m_taskSchedulerId; public virtual int MaximumConcurrencyLevel => int.MaxValue; public static TaskScheduler Default => s_defaultTaskScheduler; public static TaskScheduler Current => InternalCurrent ?? Default; internal static TaskScheduler? InternalCurrent { get { Task internalCurrent = Task.InternalCurrent; if (internalCurrent == null || (internalCurrent.CreationOptions & TaskCreationOptions.HideScheduler) != 0) { return null; } return internalCurrent.ExecutingTaskScheduler; } } public int Id { get { if (m_taskSchedulerId == 0) { int num; do { num = Interlocked.Increment(ref s_taskSchedulerIdCounter); } while (num == 0); Interlocked.CompareExchange(ref m_taskSchedulerId, num, 0); } return m_taskSchedulerId; } } public static event EventHandler? UnobservedTaskException; protected internal abstract void QueueTask(Task task); protected abstract bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued); protected abstract IEnumerable? GetScheduledTasks(); internal bool TryRunInline(Task task, bool taskWasPreviouslyQueued) { TaskScheduler executingTaskScheduler = task.ExecutingTaskScheduler; if (executingTaskScheduler != this && executingTaskScheduler != null) { return executingTaskScheduler.TryRunInline(task, taskWasPreviouslyQueued); } if (executingTaskScheduler == null || (object)task.m_action == null || task.IsDelegateInvoked || task.IsCanceled || !RuntimeHelpers.TryEnsureSufficientExecutionStack()) { return false; } if (TplEventSource.Log.IsEnabled()) { task.FireTaskScheduledIfNeeded(this); } bool flag = TryExecuteTaskInline(task, taskWasPreviouslyQueued); if (flag && !task.IsDelegateInvoked && !task.IsCanceled) { throw new InvalidOperationException(SR.TaskScheduler_InconsistentStateAfterTryExecuteTaskInline); } return flag; } protected internal virtual bool TryDequeue(Task task) { return false; } internal virtual void NotifyWorkItemProgress() { } internal void InternalQueueTask(Task task) { if (TplEventSource.Log.IsEnabled()) { task.FireTaskScheduledIfNeeded(this); } QueueTask(task); } protected TaskScheduler() { if (Debugger.IsAttached) { AddToActiveTaskSchedulers(); } } private void AddToActiveTaskSchedulers() { ConditionalWeakTable conditionalWeakTable = s_activeTaskSchedulers; if (conditionalWeakTable == null) { Interlocked.CompareExchange(ref s_activeTaskSchedulers, new ConditionalWeakTable(), null); conditionalWeakTable = s_activeTaskSchedulers; } conditionalWeakTable.Add(this, null); } public static TaskScheduler FromCurrentSynchronizationContext() { return new SynchronizationContextTaskScheduler(); } protected bool TryExecuteTask(Task task) { if (task.ExecutingTaskScheduler != this) { throw new InvalidOperationException(SR.TaskScheduler_ExecuteTask_WrongTaskScheduler); } return task.ExecuteEntry(); } internal static void PublishUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs ueea) { TaskScheduler.UnobservedTaskException?.Invoke(sender, ueea); } internal Task[] GetScheduledTasksForDebugger() { IEnumerable scheduledTasks = GetScheduledTasks(); if (scheduledTasks == null) { return null; } Task[] array = scheduledTasks as Task[]; if (array == null) { array = new List(scheduledTasks).ToArray(); } Task[] array2 = array; foreach (Task task in array2) { _ = task.Id; } return array; } internal static TaskScheduler[] GetTaskSchedulersForDebugger() { if (s_activeTaskSchedulers == null) { return new TaskScheduler[1] { s_defaultTaskScheduler }; } List list = new List(); foreach (KeyValuePair item in (IEnumerable>)s_activeTaskSchedulers) { list.Add(item.Key); } if (!list.Contains(s_defaultTaskScheduler)) { list.Add(s_defaultTaskScheduler); } TaskScheduler[] array = list.ToArray(); TaskScheduler[] array2 = array; foreach (TaskScheduler taskScheduler in array2) { _ = taskScheduler.Id; } return array; } internal TaskSchedulerAwaiter GetAwaiter() { return new TaskSchedulerAwaiter(this); } } internal sealed class SynchronizationContextTaskScheduler : TaskScheduler { private readonly SynchronizationContext m_synchronizationContext; private static readonly SendOrPostCallback s_postCallback = delegate(object s) { ((Task)s).ExecuteEntry(); }; public override int MaximumConcurrencyLevel => 1; internal SynchronizationContextTaskScheduler() { m_synchronizationContext = SynchronizationContext.Current ?? throw new InvalidOperationException(SR.TaskScheduler_FromCurrentSynchronizationContext_NoCurrent); } protected internal override void QueueTask(Task task) { m_synchronizationContext.Post(s_postCallback, task); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (SynchronizationContext.Current == m_synchronizationContext) { return TryExecuteTask(task); } return false; } protected override IEnumerable GetScheduledTasks() { return null; } } public class UnobservedTaskExceptionEventArgs : EventArgs { private readonly AggregateException m_exception; internal bool m_observed; public bool Observed => m_observed; public AggregateException Exception => m_exception; public UnobservedTaskExceptionEventArgs(AggregateException exception) { m_exception = exception; } public void SetObserved() { m_observed = true; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class TaskSchedulerException : Exception { public TaskSchedulerException() : base(SR.TaskSchedulerException_ctor_DefaultMessage) { } public TaskSchedulerException(string? message) : base(message) { } public TaskSchedulerException(Exception? innerException) : base(SR.TaskSchedulerException_ctor_DefaultMessage, innerException) { } public TaskSchedulerException(string? message, Exception? innerException) : base(message, innerException) { } protected TaskSchedulerException(SerializationInfo info, StreamingContext context) : base(info, context) { } } internal sealed class ThreadPoolTaskScheduler : TaskScheduler { private static readonly ParameterizedThreadStart s_longRunningThreadWork = delegate(object s) { ((Task)s).ExecuteEntryUnsafe(null); }; internal ThreadPoolTaskScheduler() { _ = base.Id; } protected internal override void QueueTask(Task task) { TaskCreationOptions options = task.Options; _ = Thread.IsThreadStartSupported; if ((options & TaskCreationOptions.LongRunning) != 0) { Thread thread = new Thread(s_longRunningThreadWork); thread.IsBackground = true; thread.Name = ".NET Long Running Task"; thread.UnsafeStart(task); } else { ThreadPool.UnsafeQueueUserWorkItemInternal(task, (options & TaskCreationOptions.PreferFairness) == 0); } } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { if (taskWasPreviouslyQueued && !ThreadPool.TryPopCustomWorkItem(task)) { return false; } try { task.ExecuteEntryUnsafe(null); } finally { if (taskWasPreviouslyQueued) { NotifyWorkItemProgress(); } } return true; } protected internal override bool TryDequeue(Task task) { return ThreadPool.TryPopCustomWorkItem(task); } protected override IEnumerable GetScheduledTasks() { return FilterTasksFromWorkItems(ThreadPool.GetQueuedWorkItems()); } private static IEnumerable FilterTasksFromWorkItems(IEnumerable tpwItems) { foreach (object tpwItem in tpwItems) { if (tpwItem is Task task) { yield return task; } } } internal override void NotifyWorkItemProgress() { ThreadPool.NotifyWorkItemProgress(); } } [EventSource(Name = "System.Threading.Tasks.TplEventSource", Guid = "2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5", LocalizationResources = "System.Private.CoreLib.Strings")] internal sealed class TplEventSource : EventSource { public enum TaskWaitBehavior { Synchronous = 1, Asynchronous } public static class Tasks { public const EventTask Loop = (EventTask)1; public const EventTask Invoke = (EventTask)2; public const EventTask TaskExecute = (EventTask)3; public const EventTask TaskWait = (EventTask)4; public const EventTask ForkJoin = (EventTask)5; public const EventTask TaskScheduled = (EventTask)6; public const EventTask AwaitTaskContinuationScheduled = (EventTask)7; public const EventTask TraceOperation = (EventTask)8; public const EventTask TraceSynchronousWork = (EventTask)9; } public static class Keywords { public const EventKeywords TaskTransfer = (EventKeywords)1L; public const EventKeywords Tasks = (EventKeywords)2L; public const EventKeywords Parallel = (EventKeywords)4L; public const EventKeywords AsyncCausalityOperation = (EventKeywords)8L; public const EventKeywords AsyncCausalityRelation = (EventKeywords)16L; public const EventKeywords AsyncCausalitySynchronousWork = (EventKeywords)32L; public const EventKeywords TaskStops = (EventKeywords)64L; public const EventKeywords TasksFlowActivityIds = (EventKeywords)128L; public const EventKeywords AsyncMethod = (EventKeywords)256L; public const EventKeywords TasksSetActivityIds = (EventKeywords)65536L; public const EventKeywords Debug = (EventKeywords)131072L; public const EventKeywords DebugActivityId = (EventKeywords)262144L; } private const string EventSourceSuppressMessage = "Parameters to this method are primitive and are trimmer safe"; internal bool TasksSetActivityIds; internal bool Debug; private bool DebugActivityId; private const int DefaultAppDomainID = 1; public static readonly TplEventSource Log = new TplEventSource(); private const int TASKSCHEDULED_ID = 7; private const int TASKSTARTED_ID = 8; private const int TASKCOMPLETED_ID = 9; private const int TASKWAITBEGIN_ID = 10; private const int TASKWAITEND_ID = 11; private const int AWAITTASKCONTINUATIONSCHEDULED_ID = 12; private const int TASKWAITCONTINUATIONCOMPLETE_ID = 13; private const int TASKWAITCONTINUATIONSTARTED_ID = 19; private const int TRACEOPERATIONSTART_ID = 14; private const int TRACEOPERATIONSTOP_ID = 15; private const int TRACEOPERATIONRELATION_ID = 16; private const int TRACESYNCHRONOUSWORKSTART_ID = 17; private const int TRACESYNCHRONOUSWORKSTOP_ID = 18; private protected override ReadOnlySpan ProviderMetadata => new byte[40] { 40, 0, 83, 121, 115, 116, 101, 109, 46, 84, 104, 114, 101, 97, 100, 105, 110, 103, 46, 84, 97, 115, 107, 115, 46, 84, 112, 108, 69, 118, 101, 110, 116, 83, 111, 117, 114, 99, 101, 0 }; protected override void OnEventCommand(EventCommandEventArgs command) { if (IsEnabled(EventLevel.Informational, (EventKeywords)128L)) { ActivityTracker.Instance.Enable(); } else { TasksSetActivityIds = IsEnabled(EventLevel.Informational, (EventKeywords)65536L); } Debug = IsEnabled(EventLevel.Informational, (EventKeywords)131072L); DebugActivityId = IsEnabled(EventLevel.Informational, (EventKeywords)262144L); } private TplEventSource(int _) { } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "Parameters to this method are primitive and are trimmer safe")] [Event(7, Task = (EventTask)6, Version = 1, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = (EventKeywords)3L)] public unsafe void TaskScheduled(int OriginatingTaskSchedulerID, int OriginatingTaskID, int TaskID, int CreatingTaskID, int TaskCreationOptions, int appDomain = 1) { if (IsEnabled() && IsEnabled(EventLevel.Informational, (EventKeywords)3L)) { EventData* ptr = stackalloc EventData[6]; ptr->Size = 4; ptr->DataPointer = (IntPtr)(&OriginatingTaskSchedulerID); ptr->Reserved = 0; ptr[1].Size = 4; ptr[1].DataPointer = (IntPtr)(&OriginatingTaskID); ptr[1].Reserved = 0; ptr[2].Size = 4; ptr[2].DataPointer = (IntPtr)(&TaskID); ptr[2].Reserved = 0; ptr[3].Size = 4; ptr[3].DataPointer = (IntPtr)(&CreatingTaskID); ptr[3].Reserved = 0; ptr[4].Size = 4; ptr[4].DataPointer = (IntPtr)(&TaskCreationOptions); ptr[4].Reserved = 0; ptr[5].Size = 4; ptr[5].DataPointer = (IntPtr)(&appDomain); ptr[5].Reserved = 0; if (TasksSetActivityIds) { Guid guid = CreateGuidForTaskID(TaskID); WriteEventWithRelatedActivityIdCore(7, &guid, 6, ptr); } else { WriteEventCore(7, 6, ptr); } } } [Event(8, Level = EventLevel.Informational, Keywords = (EventKeywords)2L)] public void TaskStarted(int OriginatingTaskSchedulerID, int OriginatingTaskID, int TaskID) { if (IsEnabled(EventLevel.Informational, (EventKeywords)2L)) { WriteEvent(8, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "Parameters to this method are primitive and are trimmer safe")] [Event(9, Version = 1, Level = EventLevel.Informational, Keywords = (EventKeywords)64L)] public unsafe void TaskCompleted(int OriginatingTaskSchedulerID, int OriginatingTaskID, int TaskID, bool IsExceptional) { if (IsEnabled() && IsEnabled(EventLevel.Informational, (EventKeywords)2L)) { EventData* ptr = stackalloc EventData[4]; int num = (IsExceptional ? 1 : 0); ptr->Size = 4; ptr->DataPointer = (IntPtr)(&OriginatingTaskSchedulerID); ptr->Reserved = 0; ptr[1].Size = 4; ptr[1].DataPointer = (IntPtr)(&OriginatingTaskID); ptr[1].Reserved = 0; ptr[2].Size = 4; ptr[2].DataPointer = (IntPtr)(&TaskID); ptr[2].Reserved = 0; ptr[3].Size = 4; ptr[3].DataPointer = (IntPtr)(&num); ptr[3].Reserved = 0; WriteEventCore(9, 4, ptr); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "Parameters to this method are primitive and are trimmer safe")] [Event(10, Version = 3, Task = (EventTask)4, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = (EventKeywords)3L)] public unsafe void TaskWaitBegin(int OriginatingTaskSchedulerID, int OriginatingTaskID, int TaskID, TaskWaitBehavior Behavior, int ContinueWithTaskID) { if (IsEnabled() && IsEnabled(EventLevel.Informational, (EventKeywords)3L)) { EventData* ptr = stackalloc EventData[5]; ptr->Size = 4; ptr->DataPointer = (IntPtr)(&OriginatingTaskSchedulerID); ptr->Reserved = 0; ptr[1].Size = 4; ptr[1].DataPointer = (IntPtr)(&OriginatingTaskID); ptr[1].Reserved = 0; ptr[2].Size = 4; ptr[2].DataPointer = (IntPtr)(&TaskID); ptr[2].Reserved = 0; ptr[3].Size = 4; ptr[3].DataPointer = (IntPtr)(&Behavior); ptr[3].Reserved = 0; ptr[4].Size = 4; ptr[4].DataPointer = (IntPtr)(&ContinueWithTaskID); ptr[4].Reserved = 0; if (TasksSetActivityIds) { Guid guid = CreateGuidForTaskID(TaskID); WriteEventWithRelatedActivityIdCore(10, &guid, 5, ptr); } else { WriteEventCore(10, 5, ptr); } } } [Event(11, Level = EventLevel.Verbose, Keywords = (EventKeywords)2L)] public void TaskWaitEnd(int OriginatingTaskSchedulerID, int OriginatingTaskID, int TaskID) { if (IsEnabled() && IsEnabled(EventLevel.Verbose, (EventKeywords)2L)) { WriteEvent(11, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID); } } [Event(13, Level = EventLevel.Verbose, Keywords = (EventKeywords)64L)] public void TaskWaitContinuationComplete(int TaskID) { if (IsEnabled() && IsEnabled(EventLevel.Verbose, (EventKeywords)64L)) { WriteEvent(13, TaskID); } } [Event(19, Level = EventLevel.Verbose, Keywords = (EventKeywords)2L)] public void TaskWaitContinuationStarted(int TaskID) { if (IsEnabled() && IsEnabled(EventLevel.Verbose, (EventKeywords)2L)) { WriteEvent(19, TaskID); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "Parameters to this method are primitive and are trimmer safe")] [Event(12, Task = (EventTask)7, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = (EventKeywords)3L)] public unsafe void AwaitTaskContinuationScheduled(int OriginatingTaskSchedulerID, int OriginatingTaskID, int ContinueWithTaskId) { if (IsEnabled() && IsEnabled(EventLevel.Informational, (EventKeywords)3L)) { EventData* ptr = stackalloc EventData[3]; ptr->Size = 4; ptr->DataPointer = (IntPtr)(&OriginatingTaskSchedulerID); ptr->Reserved = 0; ptr[1].Size = 4; ptr[1].DataPointer = (IntPtr)(&OriginatingTaskID); ptr[1].Reserved = 0; ptr[2].Size = 4; ptr[2].DataPointer = (IntPtr)(&ContinueWithTaskId); ptr[2].Reserved = 0; if (TasksSetActivityIds) { Guid guid = CreateGuidForTaskID(ContinueWithTaskId); WriteEventWithRelatedActivityIdCore(12, &guid, 3, ptr); } else { WriteEventCore(12, 3, ptr); } } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "Parameters to this method are primitive and are trimmer safe")] [Event(14, Version = 1, Level = EventLevel.Informational, Keywords = (EventKeywords)8L)] public unsafe void TraceOperationBegin(int TaskID, string OperationName, long RelatedContext) { if (IsEnabled() && IsEnabled(EventLevel.Informational, (EventKeywords)8L)) { fixed (char* ptr2 = OperationName) { EventData* ptr = stackalloc EventData[3]; ptr->Size = 4; ptr->DataPointer = (IntPtr)(&TaskID); ptr->Reserved = 0; ptr[1].Size = (OperationName.Length + 1) * 2; ptr[1].DataPointer = (IntPtr)ptr2; ptr[1].Reserved = 0; ptr[2].Size = 8; ptr[2].DataPointer = (IntPtr)(&RelatedContext); ptr[2].Reserved = 0; WriteEventCore(14, 3, ptr); } } } [Event(16, Version = 1, Level = EventLevel.Informational, Keywords = (EventKeywords)16L)] public void TraceOperationRelation(int TaskID, CausalityRelation Relation) { if (IsEnabled() && IsEnabled(EventLevel.Informational, (EventKeywords)16L)) { WriteEvent(16, TaskID, (int)Relation); } } [Event(15, Version = 1, Level = EventLevel.Informational, Keywords = (EventKeywords)8L)] public void TraceOperationEnd(int TaskID, AsyncCausalityStatus Status) { if (IsEnabled() && IsEnabled(EventLevel.Informational, (EventKeywords)8L)) { WriteEvent(15, TaskID, (int)Status); } } [Event(17, Version = 1, Level = EventLevel.Informational, Keywords = (EventKeywords)32L)] public void TraceSynchronousWorkBegin(int TaskID, CausalitySynchronousWork Work) { if (IsEnabled() && IsEnabled(EventLevel.Informational, (EventKeywords)32L)) { WriteEvent(17, TaskID, (int)Work); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "Parameters to this method are primitive and are trimmer safe")] [Event(18, Version = 1, Level = EventLevel.Informational, Keywords = (EventKeywords)32L)] public unsafe void TraceSynchronousWorkEnd(CausalitySynchronousWork Work) { if (IsEnabled() && IsEnabled(EventLevel.Informational, (EventKeywords)32L)) { EventData* ptr = stackalloc EventData[1]; ptr->Size = 4; ptr->DataPointer = (IntPtr)(&Work); ptr->Reserved = 0; WriteEventCore(18, 1, ptr); } } [NonEvent] public unsafe void RunningContinuation(int TaskID, object Object) { RunningContinuation(TaskID, (long)(nuint)(*(nint*)Unsafe.AsPointer(ref Object))); } [Event(20, Keywords = (EventKeywords)131072L)] private void RunningContinuation(int TaskID, long Object) { if (Debug) { WriteEvent(20, TaskID, Object); } } [NonEvent] public unsafe void RunningContinuationList(int TaskID, int Index, object Object) { RunningContinuationList(TaskID, Index, (long)(nuint)(*(nint*)Unsafe.AsPointer(ref Object))); } [Event(21, Keywords = (EventKeywords)131072L)] public void RunningContinuationList(int TaskID, int Index, long Object) { if (Debug) { WriteEvent(21, TaskID, Index, Object); } } [Event(23, Keywords = (EventKeywords)131072L)] public void DebugFacilityMessage(string Facility, string Message) { WriteEvent(23, Facility, Message); } [Event(24, Keywords = (EventKeywords)131072L)] public void DebugFacilityMessage1(string Facility, string Message, string Value1) { WriteEvent(24, Facility, Message, Value1); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "Guid parameter is safe with WriteEvent")] [Event(25, Keywords = (EventKeywords)262144L)] public void SetActivityId(Guid NewId) { if (DebugActivityId) { WriteEvent(25, NewId); } } [Event(26, Keywords = (EventKeywords)131072L)] public void NewID(int TaskID) { if (Debug) { WriteEvent(26, TaskID); } } [NonEvent] public void IncompleteAsyncMethod(IAsyncStateMachineBox stateMachineBox) { if (IsEnabled() && IsEnabled(EventLevel.Warning, (EventKeywords)256L)) { IAsyncStateMachine stateMachineObject = stateMachineBox.GetStateMachineObject(); if (stateMachineObject != null) { string asyncStateMachineDescription = AsyncMethodBuilderCore.GetAsyncStateMachineDescription(stateMachineObject); IncompleteAsyncMethod(asyncStateMachineDescription); } } } [Event(27, Level = EventLevel.Warning, Keywords = (EventKeywords)256L)] private void IncompleteAsyncMethod(string stateMachineDescription) { WriteEvent(27, stateMachineDescription); } internal static Guid CreateGuidForTaskID(int taskID) { int processId = Environment.ProcessId; return new Guid(taskID, 1, 0, (byte)processId, (byte)(processId >> 8), (byte)(processId >> 16), (byte)(processId >> 24), byte.MaxValue, 220, 215, 181); } private TplEventSource() : base(new Guid(777894471u, 41938, 19734, 142, 224, 102, 113, byte.MaxValue, 220, 215, 181), "System.Threading.Tasks.TplEventSource") { } } [StructLayout(LayoutKind.Auto)] [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder))] public readonly struct ValueTask : IEquatable { private sealed class ValueTaskSourceAsTask : Task { private static readonly Action s_completionAction = delegate(object state) { if (state is ValueTaskSourceAsTask valueTaskSourceAsTask) { IValueTaskSource source = valueTaskSourceAsTask._source; if (source != null) { valueTaskSourceAsTask._source = null; ValueTaskSourceStatus status = source.GetStatus(valueTaskSourceAsTask._token); try { source.GetResult(valueTaskSourceAsTask._token); valueTaskSourceAsTask.TrySetResult(); return; } catch (Exception ex) { if (status == ValueTaskSourceStatus.Canceled) { if (ex is OperationCanceledException ex2) { valueTaskSourceAsTask.TrySetCanceled(ex2.CancellationToken, ex2); } else { valueTaskSourceAsTask.TrySetCanceled(new CancellationToken(canceled: true)); } } else { valueTaskSourceAsTask.TrySetException(ex); } return; } } } ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.state); }; private IValueTaskSource _source; private readonly short _token; internal ValueTaskSourceAsTask(IValueTaskSource source, short token) { _token = token; _source = source; source.OnCompleted(s_completionAction, this, token, ValueTaskSourceOnCompletedFlags.None); } } private static volatile Task s_canceledTask; internal readonly object _obj; internal readonly short _token; internal readonly bool _continueOnCapturedContext; public static ValueTask CompletedTask => default(ValueTask); public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object obj = _obj; if (obj == null) { return true; } if (obj is Task task) { return task.IsCompleted; } return Unsafe.As(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.IsCompletedSuccessfully; } return Unsafe.As(obj).GetStatus(_token) == ValueTaskSourceStatus.Succeeded; } } public bool IsFaulted { get { object obj = _obj; if (obj == null) { return false; } if (obj is Task task) { return task.IsFaulted; } return Unsafe.As(obj).GetStatus(_token) == ValueTaskSourceStatus.Faulted; } } public bool IsCanceled { get { object obj = _obj; if (obj == null) { return false; } if (obj is Task task) { return task.IsCanceled; } return Unsafe.As(obj).GetStatus(_token) == ValueTaskSourceStatus.Canceled; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(Task task) { if (task == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.task); } _obj = task; _continueOnCapturedContext = true; _token = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(IValueTaskSource source, short token) { if (source == null) { ThrowHelper.ThrowArgumentNullException(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 static ValueTask FromResult(TResult result) { return new ValueTask(result); } public static ValueTask FromCanceled(CancellationToken cancellationToken) { return new ValueTask(Task.FromCanceled(cancellationToken)); } public static ValueTask FromCanceled(CancellationToken cancellationToken) { return new ValueTask(Task.FromCanceled(cancellationToken)); } public static ValueTask FromException(Exception exception) { return new ValueTask(Task.FromException(exception)); } public static ValueTask FromException(Exception exception) { return new ValueTask(Task.FromException(exception)); } public override int GetHashCode() { return _obj?.GetHashCode() ?? 0; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ValueTask) { return Equals((ValueTask)obj); } return false; } public bool Equals(ValueTask other) { if (_obj == other._obj) { return _token == other._token; } return false; } public static bool operator ==(ValueTask left, ValueTask right) { return left.Equals(right); } public static bool operator !=(ValueTask left, ValueTask right) { return !left.Equals(right); } public Task AsTask() { object obj = _obj; object obj2; if (obj != null) { obj2 = obj as Task; if (obj2 == null) { return GetTaskForValueTaskSource(Unsafe.As(obj)); } } else { obj2 = Task.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 Task.CompletedTask; } catch (Exception ex) { if (status == ValueTaskSourceStatus.Canceled) { if (ex is OperationCanceledException ex2) { Task task = new Task(); task.TrySetCanceled(ex2.CancellationToken, ex2); return task; } return s_canceledTask ?? (s_canceledTask = Task.FromCanceled(new CancellationToken(canceled: true))); } return Task.FromException(ex); } } return new ValueTaskSourceAsTask(t, _token); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void ThrowIfCompletedUnsuccessfully() { object obj = _obj; if (obj != null) { if (obj is Task task) { TaskAwaiter.ValidateEnd(task); } else { Unsafe.As(obj).GetResult(_token); } } } public ValueTaskAwaiter GetAwaiter() { return new ValueTaskAwaiter(in this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) { ValueTask value = new ValueTask(_obj, _token, continueOnCapturedContext); return new ConfiguredValueTaskAwaitable(in value); } } [StructLayout(LayoutKind.Auto)] [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder<>))] public readonly struct ValueTask : IEquatable> { private sealed class ValueTaskSourceAsTask : Task { private static readonly Action s_completionAction = delegate(object state) { if (state is ValueTaskSourceAsTask valueTaskSourceAsTask) { IValueTaskSource source = valueTaskSourceAsTask._source; if (source != null) { valueTaskSourceAsTask._source = null; ValueTaskSourceStatus status = source.GetStatus(valueTaskSourceAsTask._token); try { valueTaskSourceAsTask.TrySetResult(source.GetResult(valueTaskSourceAsTask._token)); return; } catch (Exception ex) { if (status == ValueTaskSourceStatus.Canceled) { if (ex is OperationCanceledException ex2) { valueTaskSourceAsTask.TrySetCanceled(ex2.CancellationToken, ex2); } else { valueTaskSourceAsTask.TrySetCanceled(new CancellationToken(canceled: true)); } } else { valueTaskSourceAsTask.TrySetException(ex); } return; } } } ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.state); }; private IValueTaskSource _source; private readonly short _token; public ValueTaskSourceAsTask(IValueTaskSource source, short token) { _source = source; _token = token; source.OnCompleted(s_completionAction, this, token, ValueTaskSourceOnCompletedFlags.None); } } private static volatile Task 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 task) { return task.IsCompleted; } return Unsafe.As>(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.IsCompletedSuccessfully; } return Unsafe.As>(obj).GetStatus(_token) == ValueTaskSourceStatus.Succeeded; } } public bool IsFaulted { get { object obj = _obj; if (obj == null) { return false; } if (obj is Task task) { return task.IsFaulted; } return Unsafe.As>(obj).GetStatus(_token) == ValueTaskSourceStatus.Faulted; } } public bool IsCanceled { get { object obj = _obj; if (obj == null) { return false; } if (obj is Task task) { return task.IsCanceled; } return Unsafe.As>(obj).GetStatus(_token) == ValueTaskSourceStatus.Canceled; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public TResult Result { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { object obj = _obj; if (obj == null) { return _result; } if (obj is Task task) { TaskAwaiter.ValidateEnd(task); return task.ResultOnSuccess; } return Unsafe.As>(obj).GetResult(_token); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(TResult result) { _result = result; _obj = null; _continueOnCapturedContext = true; _token = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(Task task) { if (task == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.task); } _obj = task; _result = default(TResult); _continueOnCapturedContext = true; _token = 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTask(IValueTaskSource source, short token) { if (source == null) { ThrowHelper.ThrowArgumentNullException(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([NotNullWhen(true)] object? obj) { if (obj is ValueTask) { return Equals((ValueTask)obj); } return false; } public bool Equals(ValueTask other) { if (_obj == null && other._obj == null) { return EqualityComparer.Default.Equals(_result, other._result); } 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; if (obj == null) { return Task.FromResult(_result); } if (obj is Task result) { return result; } return GetTaskForValueTaskSource(Unsafe.As>(obj)); } 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 { return Task.FromResult(t.GetResult(_token)); } catch (Exception ex) { if (status == ValueTaskSourceStatus.Canceled) { if (ex is OperationCanceledException ex2) { Task task = new Task(); task.TrySetCanceled(ex2.CancellationToken, ex2); return task; } return s_canceledTask ?? (s_canceledTask = Task.FromCanceled(new CancellationToken(canceled: true))); } return Task.FromException(ex); } } return new ValueTaskSourceAsTask(t, _token); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ValueTaskAwaiter GetAwaiter() { return new ValueTaskAwaiter(in this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) { ValueTask value = new ValueTask(_obj, _result, _token, continueOnCapturedContext); return new ConfiguredValueTaskAwaitable(in value); } public override string? ToString() { if (IsCompletedSuccessfully) { Debugger.NotifyOfCrossThreadDependency(); TResult result = Result; if (result != null) { return result.ToString(); } } return string.Empty; } } internal static class TaskToApm { internal sealed class TaskAsyncResult : IAsyncResult { internal readonly Task _task; private readonly AsyncCallback _callback; public object AsyncState { get; } public bool CompletedSynchronously { get; } public bool IsCompleted => _task.IsCompleted; public WaitHandle AsyncWaitHandle => ((IAsyncResult)_task).AsyncWaitHandle; internal TaskAsyncResult(Task task, object state, AsyncCallback callback) { _task = task; AsyncState = state; if (task.IsCompleted) { CompletedSynchronously = true; callback?.Invoke(this); } else if (callback != null) { _callback = callback; _task.ConfigureAwait(continueOnCapturedContext: false).GetAwaiter().OnCompleted(InvokeCallback); } } private void InvokeCallback() { _callback(this); } } public static IAsyncResult Begin(Task task, AsyncCallback callback, object state) { return new TaskAsyncResult(task, state, callback); } public static void End(IAsyncResult asyncResult) { Task task = GetTask(asyncResult); if (task != null) { task.GetAwaiter().GetResult(); } else { ThrowArgumentException(asyncResult); } } public static TResult End(IAsyncResult asyncResult) { if (GetTask(asyncResult) is Task task) { return task.GetAwaiter().GetResult(); } ThrowArgumentException(asyncResult); return default(TResult); } public static Task GetTask(IAsyncResult asyncResult) { return (asyncResult as TaskAsyncResult)?._task; } [DoesNotReturn] private static void ThrowArgumentException(IAsyncResult asyncResult) { throw (asyncResult == null) ? new ArgumentNullException("asyncResult") : new ArgumentException(null, "asyncResult"); } } } 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 continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags); void GetResult(short token); } public interface IValueTaskSource { ValueTaskSourceStatus GetStatus(short token); void OnCompleted(Action continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags); TResult GetResult(short token); } [StructLayout(LayoutKind.Auto)] public struct ManualResetValueTaskSourceCore { private Action _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; } [StackTraceHidden] public TResult GetResult(short token) { if (token != _version || !_completed || _error != null) { ThrowForFailedGetResult(token); } return _result; } [StackTraceHidden] private void ThrowForFailedGetResult(short token) { if (token != _version || !_completed) { ThrowHelper.ThrowInvalidOperationException(); } _error?.Throw(); } public void OnCompleted(Action 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 != ManualResetValueTaskSourceCoreShared.s_sentinel) { ThrowHelper.ThrowInvalidOperationException(); } 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) { TupleSlim, object> tupleSlim = (TupleSlim, object>)s; tupleSlim.Item1(tupleSlim.Item2); }, new TupleSlim, object>(continuation, state)); } } else if (_executionContext != null) { ThreadPool.QueueUserWorkItem(continuation, state, preferLocal: true); } else { ThreadPool.UnsafeQueueUserWorkItem(continuation, state, preferLocal: true); } } private void ValidateToken(short token) { if (token != _version) { ThrowHelper.ThrowInvalidOperationException(); } } private void SignalCompletion() { if (_completed) { ThrowHelper.ThrowInvalidOperationException(); } _completed = true; if (_continuation == null && Interlocked.CompareExchange(ref _continuation, ManualResetValueTaskSourceCoreShared.s_sentinel, null) == null) { return; } if (_executionContext == null) { if (_capturedContext == null) { if (RunContinuationsAsynchronously) { ThreadPool.UnsafeQueueUserWorkItem(_continuation, _continuationState, preferLocal: true); } else { _continuation(_continuationState); } } else { InvokeSchedulerContinuation(); } } else { InvokeContinuationWithContext(); } } private void InvokeContinuationWithContext() { ExecutionContext executionContext = ExecutionContext.CaptureForRestore(); ExecutionContext.Restore(_executionContext); if (_capturedContext == null) { if (RunContinuationsAsynchronously) { try { ThreadPool.QueueUserWorkItem(_continuation, _continuationState, preferLocal: true); return; } finally { ExecutionContext.RestoreInternal(executionContext); } } ExceptionDispatchInfo exceptionDispatchInfo = null; SynchronizationContext current = SynchronizationContext.Current; try { _continuation(_continuationState); } catch (Exception source) { exceptionDispatchInfo = ExceptionDispatchInfo.Capture(source); } finally { SynchronizationContext.SetSynchronizationContext(current); ExecutionContext.RestoreInternal(executionContext); } exceptionDispatchInfo?.Throw(); return; } try { InvokeSchedulerContinuation(); } finally { ExecutionContext.RestoreInternal(executionContext); } } private void InvokeSchedulerContinuation() { object capturedContext = _capturedContext; 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) { TupleSlim, object> tupleSlim = (TupleSlim, object>)s; tupleSlim.Item1(tupleSlim.Item2); }, new TupleSlim, object>(_continuation, _continuationState)); } } } internal static class ManualResetValueTaskSourceCoreShared { internal static readonly Action s_sentinel = CompletionSentinel; private static void CompletionSentinel(object _) { ThrowHelper.ThrowInvalidOperationException(); } } } namespace System.Text { [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class StringBuilder : ISerializable { public struct ChunkEnumerator { private sealed class ManyChunkInfo { private readonly StringBuilder[] _chunks; private int _chunkPos; public bool MoveNext(ref StringBuilder current) { int num = ++_chunkPos; if (_chunks.Length <= num) { return false; } current = _chunks[num]; return true; } public ManyChunkInfo(StringBuilder stringBuilder, int chunkCount) { _chunks = new StringBuilder[chunkCount]; while (0 <= --chunkCount) { _chunks[chunkCount] = stringBuilder; stringBuilder = stringBuilder.m_ChunkPrevious; } _chunkPos = -1; } } private readonly StringBuilder _firstChunk; private StringBuilder _currentChunk; private readonly ManyChunkInfo _manyChunks; public ReadOnlyMemory Current { get { if (_currentChunk == null) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return new ReadOnlyMemory(_currentChunk.m_ChunkChars, 0, _currentChunk.m_ChunkLength); } } [EditorBrowsable(EditorBrowsableState.Never)] public ChunkEnumerator GetEnumerator() { return this; } public bool MoveNext() { if (_currentChunk == _firstChunk) { return false; } if (_manyChunks != null) { return _manyChunks.MoveNext(ref _currentChunk); } StringBuilder stringBuilder = _firstChunk; while (stringBuilder.m_ChunkPrevious != _currentChunk) { stringBuilder = stringBuilder.m_ChunkPrevious; } _currentChunk = stringBuilder; return true; } internal ChunkEnumerator(StringBuilder stringBuilder) { _firstChunk = stringBuilder; _currentChunk = null; _manyChunks = null; int num = ChunkCount(stringBuilder); if (8 < num) { _manyChunks = new ManyChunkInfo(stringBuilder, num); } } private static int ChunkCount(StringBuilder stringBuilder) { int num = 0; while (stringBuilder != null) { num++; stringBuilder = stringBuilder.m_ChunkPrevious; } return num; } } [EditorBrowsable(EditorBrowsableState.Never)] [InterpolatedStringHandler] public struct AppendInterpolatedStringHandler { internal readonly StringBuilder _stringBuilder; private readonly IFormatProvider _provider; private readonly bool _hasCustomFormatter; public AppendInterpolatedStringHandler(int literalLength, int formattedCount, StringBuilder stringBuilder) { _stringBuilder = stringBuilder; _provider = null; _hasCustomFormatter = false; } public AppendInterpolatedStringHandler(int literalLength, int formattedCount, StringBuilder stringBuilder, IFormatProvider? provider) { _stringBuilder = stringBuilder; _provider = provider; _hasCustomFormatter = provider != null && DefaultInterpolatedStringHandler.HasCustomFormatter(provider); } public void AppendLiteral(string value) { _stringBuilder.Append(value); } public void AppendFormatted(T value) { if (_hasCustomFormatter) { AppendCustomFormatter(value, null); } else if (value is IFormattable) { if (value is ISpanFormattable) { Span remainingCurrentChunk = _stringBuilder.RemainingCurrentChunk; if (((ISpanFormattable)(object)value).TryFormat(remainingCurrentChunk, out var charsWritten, default(ReadOnlySpan), _provider)) { if ((uint)charsWritten > (uint)remainingCurrentChunk.Length) { FormatError(); } _stringBuilder.m_ChunkLength += charsWritten; } else { AppendFormattedWithTempSpace(value, 0, null); } } else { _stringBuilder.Append(((IFormattable)(object)value).ToString(null, _provider)); } } else if (value != null) { _stringBuilder.Append(value.ToString()); } } public void AppendFormatted(T value, string? format) { if (_hasCustomFormatter) { AppendCustomFormatter(value, format); } else if (value is IFormattable) { if (value is ISpanFormattable) { Span remainingCurrentChunk = _stringBuilder.RemainingCurrentChunk; if (((ISpanFormattable)(object)value).TryFormat(remainingCurrentChunk, out var charsWritten, format, _provider)) { if ((uint)charsWritten > (uint)remainingCurrentChunk.Length) { FormatError(); } _stringBuilder.m_ChunkLength += charsWritten; } else { AppendFormattedWithTempSpace(value, 0, format); } } else { _stringBuilder.Append(((IFormattable)(object)value).ToString(format, _provider)); } } else if (value != null) { _stringBuilder.Append(value.ToString()); } } public void AppendFormatted(T value, int alignment) { AppendFormatted(value, alignment, null); } public void AppendFormatted(T value, int alignment, string? format) { if (alignment == 0) { AppendFormatted(value, format); } else if (alignment < 0) { int length = _stringBuilder.Length; AppendFormatted(value, format); int num = -alignment - (_stringBuilder.Length - length); if (num > 0) { _stringBuilder.Append(' ', num); } } else { AppendFormattedWithTempSpace(value, alignment, format); } } private void AppendFormattedWithTempSpace(T value, int alignment, string format) { IFormatProvider provider = _provider; Span initialBuffer = stackalloc char[256]; DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(0, 0, provider, initialBuffer); defaultInterpolatedStringHandler.AppendFormatted(value, format); AppendFormatted(defaultInterpolatedStringHandler.Text, alignment); defaultInterpolatedStringHandler.Clear(); } public void AppendFormatted(ReadOnlySpan value) { _stringBuilder.Append(value); } public void AppendFormatted(ReadOnlySpan value, int alignment = 0, string? format = null) { if (alignment == 0) { _stringBuilder.Append(value); return; } bool flag = false; if (alignment < 0) { flag = true; alignment = -alignment; } int num = alignment - value.Length; if (num <= 0) { _stringBuilder.Append(value); } else if (flag) { _stringBuilder.Append(value); _stringBuilder.Append(' ', num); } else { _stringBuilder.Append(' ', num); _stringBuilder.Append(value); } } public void AppendFormatted(string? value) { if (!_hasCustomFormatter) { _stringBuilder.Append(value); } else { this.AppendFormatted(value); } } public void AppendFormatted(string? value, int alignment = 0, string? format = null) { this.AppendFormatted(value, alignment, format); } public void AppendFormatted(object? value, int alignment = 0, string? format = null) { this.AppendFormatted(value, alignment, format); } [MethodImpl(MethodImplOptions.NoInlining)] private void AppendCustomFormatter(T value, string format) { ICustomFormatter customFormatter = (ICustomFormatter)_provider.GetFormat(typeof(ICustomFormatter)); if (customFormatter != null) { _stringBuilder.Append(customFormatter.Format(format, value, _provider)); } } } internal char[] m_ChunkChars; internal StringBuilder m_ChunkPrevious; internal int m_ChunkLength; internal int m_ChunkOffset; internal int m_MaxCapacity; public int Capacity { get { return m_ChunkChars.Length + m_ChunkOffset; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NegativeCapacity); } if (value > MaxCapacity) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_Capacity); } if (value < Length) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_SmallCapacity); } if (Capacity != value) { int length = value - m_ChunkOffset; char[] array = GC.AllocateUninitializedArray(length); Array.Copy(m_ChunkChars, array, m_ChunkLength); m_ChunkChars = array; } } } public int MaxCapacity => m_MaxCapacity; public int Length { get { return m_ChunkOffset + m_ChunkLength; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NegativeLength); } if (value > MaxCapacity) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_SmallCapacity); } if (value == 0 && m_ChunkPrevious == null) { m_ChunkLength = 0; m_ChunkOffset = 0; return; } int num = value - Length; if (num > 0) { Append('\0', num); return; } StringBuilder stringBuilder = FindChunkForIndex(value); if (stringBuilder != this) { int num2 = Math.Min(Capacity, Math.Max(Length * 6 / 5, m_ChunkChars.Length)); int num3 = num2 - stringBuilder.m_ChunkOffset; if (num3 > stringBuilder.m_ChunkChars.Length) { char[] array = GC.AllocateUninitializedArray(num3); Array.Copy(stringBuilder.m_ChunkChars, array, stringBuilder.m_ChunkLength); m_ChunkChars = array; } else { m_ChunkChars = stringBuilder.m_ChunkChars; } m_ChunkPrevious = stringBuilder.m_ChunkPrevious; m_ChunkOffset = stringBuilder.m_ChunkOffset; } m_ChunkLength = value - stringBuilder.m_ChunkOffset; } } [IndexerName("Chars")] public char this[int index] { get { StringBuilder stringBuilder = this; do { int num = index - stringBuilder.m_ChunkOffset; if (num >= 0) { if (num >= stringBuilder.m_ChunkLength) { throw new IndexOutOfRangeException(); } return stringBuilder.m_ChunkChars[num]; } stringBuilder = stringBuilder.m_ChunkPrevious; } while (stringBuilder != null); throw new IndexOutOfRangeException(); } set { StringBuilder stringBuilder = this; do { int num = index - stringBuilder.m_ChunkOffset; if (num >= 0) { if (num >= stringBuilder.m_ChunkLength) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } stringBuilder.m_ChunkChars[num] = value; return; } stringBuilder = stringBuilder.m_ChunkPrevious; } while (stringBuilder != null); throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } } private Span RemainingCurrentChunk { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return new Span(m_ChunkChars, m_ChunkLength, m_ChunkChars.Length - m_ChunkLength); } } private int GetReplaceBufferCapacity(int requiredCapacity) { int num = Capacity; if (num < requiredCapacity) { num = (requiredCapacity + 1) & -2; } return num; } internal unsafe void ReplaceBufferInternal(char* newBuffer, int newLength) { if (newLength > m_MaxCapacity) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_Capacity); } if (newLength > m_ChunkChars.Length) { m_ChunkChars = new char[GetReplaceBufferCapacity(newLength)]; } new Span(newBuffer, newLength).CopyTo(m_ChunkChars); m_ChunkLength = newLength; m_ChunkPrevious = null; m_ChunkOffset = 0; } internal void ReplaceBufferUtf8Internal(ReadOnlySpan source) { if (source.Length > m_MaxCapacity) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_Capacity); } int charCount = Encoding.UTF8.GetCharCount(source); if (charCount > m_ChunkChars.Length) { m_ChunkChars = new char[GetReplaceBufferCapacity(charCount)]; } m_ChunkLength = Encoding.UTF8.GetChars(source, m_ChunkChars); m_ChunkPrevious = null; m_ChunkOffset = 0; } internal unsafe void ReplaceBufferAnsiInternal(sbyte* newBuffer, int newLength) { if (newLength > m_MaxCapacity) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_Capacity); } if (newLength > m_ChunkChars.Length) { m_ChunkChars = new char[GetReplaceBufferCapacity(newLength)]; } int chunkLength; fixed (char* lpWideCharStr = m_ChunkChars) { chunkLength = Interop.Kernel32.MultiByteToWideChar(0u, 1u, (byte*)newBuffer, newLength, lpWideCharStr, newLength); } m_ChunkOffset = 0; m_ChunkLength = chunkLength; m_ChunkPrevious = null; } internal unsafe void InternalCopy(IntPtr dest, int charLen) { CopyTo(0, new Span((void*)dest, charLen), charLen); } public StringBuilder() { m_MaxCapacity = int.MaxValue; m_ChunkChars = new char[16]; } public StringBuilder(int capacity) : this(capacity, int.MaxValue) { } public StringBuilder(string? value) : this(value, 16) { } public StringBuilder(string? value, int capacity) : this(value, 0, value?.Length ?? 0, capacity) { } public StringBuilder(string? value, int startIndex, int length, int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", SR.Format(SR.ArgumentOutOfRange_MustBePositive, "capacity")); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, "length")); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex); } if (value == null) { value = string.Empty; } if (startIndex > value.Length - length) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_IndexLength); } m_MaxCapacity = int.MaxValue; if (capacity == 0) { capacity = 16; } capacity = Math.Max(capacity, length); m_ChunkChars = GC.AllocateUninitializedArray(capacity); m_ChunkLength = length; value.AsSpan(startIndex, length).CopyTo(m_ChunkChars); } public StringBuilder(int capacity, int maxCapacity) { if (capacity > maxCapacity) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_Capacity); } if (maxCapacity < 1) { throw new ArgumentOutOfRangeException("maxCapacity", SR.ArgumentOutOfRange_SmallMaxCapacity); } if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", SR.Format(SR.ArgumentOutOfRange_MustBePositive, "capacity")); } if (capacity == 0) { capacity = Math.Min(16, maxCapacity); } m_MaxCapacity = maxCapacity; m_ChunkChars = GC.AllocateUninitializedArray(capacity); } private StringBuilder(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } int num = 0; string text = null; int num2 = int.MaxValue; bool flag = false; SerializationInfoEnumerator enumerator = info.GetEnumerator(); while (enumerator.MoveNext()) { switch (enumerator.Name) { case "m_MaxCapacity": num2 = info.GetInt32("m_MaxCapacity"); break; case "m_StringValue": text = info.GetString("m_StringValue"); break; case "Capacity": num = info.GetInt32("Capacity"); flag = true; break; } } if (text == null) { text = string.Empty; } if (num2 < 1 || text.Length > num2) { throw new SerializationException(SR.Serialization_StringBuilderMaxCapacity); } if (!flag) { num = Math.Min(Math.Max(16, text.Length), num2); } if (num < 0 || num < text.Length || num > num2) { throw new SerializationException(SR.Serialization_StringBuilderCapacity); } m_MaxCapacity = num2; m_ChunkChars = GC.AllocateUninitializedArray(num); text.CopyTo(0, m_ChunkChars, 0, text.Length); m_ChunkLength = text.Length; } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } info.AddValue("m_MaxCapacity", m_MaxCapacity); info.AddValue("Capacity", Capacity); info.AddValue("m_StringValue", ToString()); info.AddValue("m_currentThread", 0); } public int EnsureCapacity(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NegativeCapacity); } if (Capacity < capacity) { Capacity = capacity; } return Capacity; } public override string ToString() { if (Length == 0) { return string.Empty; } string text = string.FastAllocateString(Length); StringBuilder stringBuilder = this; do { if (stringBuilder.m_ChunkLength > 0) { char[] chunkChars = stringBuilder.m_ChunkChars; int chunkOffset = stringBuilder.m_ChunkOffset; int chunkLength = stringBuilder.m_ChunkLength; if ((uint)(chunkLength + chunkOffset) > (uint)text.Length || (uint)chunkLength > (uint)chunkChars.Length) { throw new ArgumentOutOfRangeException("chunkLength", SR.ArgumentOutOfRange_Index); } Buffer.Memmove(ref Unsafe.Add(ref text.GetRawStringData(), chunkOffset), ref MemoryMarshal.GetArrayDataReference(chunkChars), (nuint)chunkLength); } stringBuilder = stringBuilder.m_ChunkPrevious; } while (stringBuilder != null); return text; } public unsafe string ToString(int startIndex, int length) { int length2 = Length; if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex); } if (startIndex > length2) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndexLargerThanLength); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NegativeLength); } if (startIndex > length2 - length) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_IndexLength); } string text = string.FastAllocateString(length); fixed (char* pointer = text) { CopyTo(startIndex, new Span(pointer, length), length); return text; } } public StringBuilder Clear() { Length = 0; return this; } public ChunkEnumerator GetChunks() { return new ChunkEnumerator(this); } public StringBuilder Append(char value, int repeatCount) { if (repeatCount < 0) { throw new ArgumentOutOfRangeException("repeatCount", SR.ArgumentOutOfRange_NegativeCount); } if (repeatCount == 0) { return this; } int num = Length + repeatCount; if (num > m_MaxCapacity || num < repeatCount) { throw new ArgumentOutOfRangeException("repeatCount", SR.ArgumentOutOfRange_LengthGreaterThanCapacity); } int num2 = m_ChunkLength; while (repeatCount > 0) { if (num2 < m_ChunkChars.Length) { m_ChunkChars[num2++] = value; repeatCount--; } else { m_ChunkLength = num2; ExpandByABlock(repeatCount); num2 = 0; } } m_ChunkLength = num2; return this; } public unsafe StringBuilder Append(char[]? value, int startIndex, int charCount) { if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_GenericPositive); } if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_GenericPositive); } if (value == null) { if (startIndex == 0 && charCount == 0) { return this; } throw new ArgumentNullException("value"); } if (charCount > value.Length - startIndex) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_Index); } if (charCount == 0) { return this; } fixed (char* value2 = &value[startIndex]) { Append(value2, charCount); return this; } } public StringBuilder Append(string? value) { if (value != null) { char[] chunkChars = m_ChunkChars; int chunkLength = m_ChunkLength; int length = value.Length; if ((uint)(chunkLength + length) < (uint)chunkChars.Length) { if (length <= 2) { if (length > 0) { chunkChars[chunkLength] = value[0]; } if (length > 1) { chunkChars[chunkLength + 1] = value[1]; } } else { Buffer.Memmove(ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(chunkChars), chunkLength), ref value.GetRawStringData(), (nuint)length); } m_ChunkLength = chunkLength + length; } else { AppendHelper(value); } } return this; } private unsafe void AppendHelper(string value) { fixed (char* value2 = value) { Append(value2, value.Length); } } public unsafe StringBuilder Append(string? value, int startIndex, int count) { if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_GenericPositive); } if (value == null) { if (startIndex == 0 && count == 0) { return this; } throw new ArgumentNullException("value"); } if (count == 0) { return this; } if (startIndex > value.Length - count) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } fixed (char* ptr = value) { Append(ptr + startIndex, count); return this; } } public StringBuilder Append(StringBuilder? value) { if (value != null && value.Length != 0) { return AppendCore(value, 0, value.Length); } return this; } public StringBuilder Append(StringBuilder? value, int startIndex, int count) { if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_GenericPositive); } if (value == null) { if (startIndex == 0 && count == 0) { return this; } throw new ArgumentNullException("value"); } if (count == 0) { return this; } if (count > value.Length - startIndex) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } return AppendCore(value, startIndex, count); } private StringBuilder AppendCore(StringBuilder value, int startIndex, int count) { if (value == this) { return Append(value.ToString(startIndex, count)); } int num = Length + count; if ((uint)num > (uint)m_MaxCapacity) { throw new ArgumentOutOfRangeException("Capacity", SR.ArgumentOutOfRange_Capacity); } while (count > 0) { int num2 = Math.Min(m_ChunkChars.Length - m_ChunkLength, count); if (num2 == 0) { ExpandByABlock(count); num2 = Math.Min(m_ChunkChars.Length - m_ChunkLength, count); } value.CopyTo(startIndex, new Span(m_ChunkChars, m_ChunkLength, num2), num2); m_ChunkLength += num2; startIndex += num2; count -= num2; } return this; } public StringBuilder AppendLine() { return Append(Environment.NewLine); } public StringBuilder AppendLine(string? value) { Append(value); return Append(Environment.NewLine); } public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) { throw new ArgumentNullException("destination"); } if (destinationIndex < 0) { throw new ArgumentOutOfRangeException("destinationIndex", SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, "destinationIndex")); } if (destinationIndex > destination.Length - count) { throw new ArgumentException(SR.ArgumentOutOfRange_OffsetOut); } CopyTo(sourceIndex, new Span(destination).Slice(destinationIndex), count); } public void CopyTo(int sourceIndex, Span destination, int count) { if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.Arg_NegativeArgCount); } if ((uint)sourceIndex > (uint)Length) { throw new ArgumentOutOfRangeException("sourceIndex", SR.ArgumentOutOfRange_Index); } if (sourceIndex > Length - count) { throw new ArgumentException(SR.Arg_LongerThanSrcString); } StringBuilder stringBuilder = this; int num = sourceIndex + count; int num2 = count; while (count > 0) { int num3 = num - stringBuilder.m_ChunkOffset; if (num3 >= 0) { num3 = Math.Min(num3, stringBuilder.m_ChunkLength); int num4 = count; int num5 = num3 - count; if (num5 < 0) { num4 += num5; num5 = 0; } num2 -= num4; count -= num4; new ReadOnlySpan(stringBuilder.m_ChunkChars, num5, num4).CopyTo(destination.Slice(num2)); } stringBuilder = stringBuilder.m_ChunkPrevious; } } public unsafe StringBuilder Insert(int index, string? value, int count) { if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } int length = Length; if ((uint)index > (uint)length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (string.IsNullOrEmpty(value) || count == 0) { return this; } long num = (long)value.Length * (long)count; if (num > MaxCapacity - Length) { throw new OutOfMemoryException(); } MakeRoom(index, (int)num, out var chunk, out var indexInChunk, doNotMoveFollowingChars: false); fixed (char* value2 = value) { while (count > 0) { ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, value2, value.Length); count--; } return this; } } public StringBuilder Remove(int startIndex, int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NegativeLength); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex); } if (length > Length - startIndex) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_Index); } if (Length == length && startIndex == 0) { Length = 0; return this; } if (length > 0) { Remove(startIndex, length, out var _, out var _); } return this; } public StringBuilder Append(bool value) { return Append(value.ToString()); } public StringBuilder Append(char value) { int chunkLength = m_ChunkLength; char[] chunkChars = m_ChunkChars; if ((uint)chunkChars.Length > (uint)chunkLength) { chunkChars[chunkLength] = value; m_ChunkLength++; } else { Append(value, 1); } return this; } [CLSCompliant(false)] public StringBuilder Append(sbyte value) { return AppendSpanFormattable(value); } public StringBuilder Append(byte value) { return AppendSpanFormattable(value); } public StringBuilder Append(short value) { return AppendSpanFormattable(value); } public StringBuilder Append(int value) { return AppendSpanFormattable(value); } public StringBuilder Append(long value) { return AppendSpanFormattable(value); } public StringBuilder Append(float value) { return AppendSpanFormattable(value); } public StringBuilder Append(double value) { return AppendSpanFormattable(value); } public StringBuilder Append(decimal value) { return AppendSpanFormattable(value); } [CLSCompliant(false)] public StringBuilder Append(ushort value) { return AppendSpanFormattable(value); } [CLSCompliant(false)] public StringBuilder Append(uint value) { return AppendSpanFormattable(value); } [CLSCompliant(false)] public StringBuilder Append(ulong value) { return AppendSpanFormattable(value); } private StringBuilder AppendSpanFormattable(T value) where T : ISpanFormattable { if (value.TryFormat(RemainingCurrentChunk, out var charsWritten, default(ReadOnlySpan), null)) { m_ChunkLength += charsWritten; return this; } return Append(value.ToString()); } internal StringBuilder AppendSpanFormattable(T value, string format, IFormatProvider provider) where T : ISpanFormattable { if (value.TryFormat(RemainingCurrentChunk, out var charsWritten, format, provider)) { m_ChunkLength += charsWritten; return this; } return Append(value.ToString(format, provider)); } public StringBuilder Append(object? value) { if (value != null) { return Append(value.ToString()); } return this; } public unsafe StringBuilder Append(char[]? value) { if (value != null && value.Length != 0) { fixed (char* value2 = &value[0]) { Append(value2, value.Length); } } return this; } public unsafe StringBuilder Append(ReadOnlySpan value) { if (value.Length > 0) { fixed (char* value2 = &MemoryMarshal.GetReference(value)) { Append(value2, value.Length); } } return this; } public StringBuilder Append(ReadOnlyMemory value) { return Append(value.Span); } public StringBuilder Append([InterpolatedStringHandlerArgument("")] ref AppendInterpolatedStringHandler handler) { return this; } public StringBuilder Append(IFormatProvider? provider, [InterpolatedStringHandlerArgument(new string[] { "", "provider" })] ref AppendInterpolatedStringHandler handler) { return this; } public StringBuilder AppendLine([InterpolatedStringHandlerArgument("")] ref AppendInterpolatedStringHandler handler) { return AppendLine(); } public StringBuilder AppendLine(IFormatProvider? provider, [InterpolatedStringHandlerArgument(new string[] { "", "provider" })] ref AppendInterpolatedStringHandler handler) { return AppendLine(); } public unsafe StringBuilder AppendJoin(string? separator, params object?[] values) { if (separator == null) { separator = string.Empty; } fixed (char* separator2 = separator) { return AppendJoinCore(separator2, separator.Length, values); } } public unsafe StringBuilder AppendJoin(string? separator, IEnumerable values) { if (separator == null) { separator = string.Empty; } fixed (char* separator2 = separator) { return AppendJoinCore(separator2, separator.Length, values); } } public unsafe StringBuilder AppendJoin(string? separator, params string?[] values) { if (separator == null) { separator = string.Empty; } fixed (char* separator2 = separator) { return AppendJoinCore(separator2, separator.Length, values); } } public unsafe StringBuilder AppendJoin(char separator, params object?[] values) { return AppendJoinCore(&separator, 1, values); } public unsafe StringBuilder AppendJoin(char separator, IEnumerable values) { return AppendJoinCore(&separator, 1, values); } public unsafe StringBuilder AppendJoin(char separator, params string?[] values) { return AppendJoinCore(&separator, 1, values); } private unsafe StringBuilder AppendJoinCore(char* separator, int separatorLength, IEnumerable values) { if (values == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); } using IEnumerator enumerator = values.GetEnumerator(); if (!enumerator.MoveNext()) { return this; } T current = enumerator.Current; if (current != null) { Append(current.ToString()); } while (enumerator.MoveNext()) { Append(separator, separatorLength); current = enumerator.Current; if (current != null) { Append(current.ToString()); } } return this; } private unsafe StringBuilder AppendJoinCore(char* separator, int separatorLength, T[] values) { if (values == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.values); } if (values.Length == 0) { return this; } if (values[0] != null) { Append(values[0].ToString()); } for (int i = 1; i < values.Length; i++) { Append(separator, separatorLength); if (values[i] != null) { Append(values[i].ToString()); } } return this; } public unsafe StringBuilder Insert(int index, string? value) { if ((uint)index > (uint)Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (value != null) { fixed (char* value2 = value) { Insert(index, value2, value.Length); } } return this; } public StringBuilder Insert(int index, bool value) { return Insert(index, value.ToString(), 1); } [CLSCompliant(false)] public StringBuilder Insert(int index, sbyte value) { return Insert(index, value.ToString(), 1); } public StringBuilder Insert(int index, byte value) { return Insert(index, value.ToString(), 1); } public StringBuilder Insert(int index, short value) { return Insert(index, value.ToString(), 1); } public unsafe StringBuilder Insert(int index, char value) { Insert(index, &value, 1); return this; } public StringBuilder Insert(int index, char[]? value) { if ((uint)index > (uint)Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (value != null) { Insert(index, value, 0, value.Length); } return this; } public unsafe StringBuilder Insert(int index, char[]? value, int startIndex, int charCount) { int length = Length; if ((uint)index > (uint)length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (value == null) { if (startIndex == 0 && charCount == 0) { return this; } throw new ArgumentNullException("value", SR.ArgumentNull_String); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex); } if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_GenericPositive); } if (startIndex > value.Length - charCount) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (charCount > 0) { fixed (char* value2 = &value[startIndex]) { Insert(index, value2, charCount); } } return this; } public StringBuilder Insert(int index, int value) { return Insert(index, value.ToString(), 1); } public StringBuilder Insert(int index, long value) { return Insert(index, value.ToString(), 1); } public StringBuilder Insert(int index, float value) { return Insert(index, value.ToString(), 1); } public StringBuilder Insert(int index, double value) { return Insert(index, value.ToString(), 1); } public StringBuilder Insert(int index, decimal value) { return Insert(index, value.ToString(), 1); } [CLSCompliant(false)] public StringBuilder Insert(int index, ushort value) { return Insert(index, value.ToString(), 1); } [CLSCompliant(false)] public StringBuilder Insert(int index, uint value) { return Insert(index, value.ToString(), 1); } [CLSCompliant(false)] public StringBuilder Insert(int index, ulong value) { return Insert(index, value.ToString(), 1); } public StringBuilder Insert(int index, object? value) { if (value != null) { return Insert(index, value.ToString(), 1); } return this; } public unsafe StringBuilder Insert(int index, ReadOnlySpan value) { if ((uint)index > (uint)Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (value.Length > 0) { fixed (char* value2 = &MemoryMarshal.GetReference(value)) { Insert(index, value2, value.Length); } } return this; } public StringBuilder AppendFormat(string format, object? arg0) { return AppendFormatHelper(null, format, new ParamsArray(arg0)); } public StringBuilder AppendFormat(string format, object? arg0, object? arg1) { return AppendFormatHelper(null, format, new ParamsArray(arg0, arg1)); } public StringBuilder AppendFormat(string format, object? arg0, object? arg1, object? arg2) { return AppendFormatHelper(null, format, new ParamsArray(arg0, arg1, arg2)); } public StringBuilder AppendFormat(string format, params object?[] args) { if (args == null) { string paramName = ((format == null) ? "format" : "args"); throw new ArgumentNullException(paramName); } return AppendFormatHelper(null, format, new ParamsArray(args)); } public StringBuilder AppendFormat(IFormatProvider? provider, string format, object? arg0) { return AppendFormatHelper(provider, format, new ParamsArray(arg0)); } public StringBuilder AppendFormat(IFormatProvider? provider, string format, object? arg0, object? arg1) { return AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1)); } public StringBuilder AppendFormat(IFormatProvider? provider, string format, object? arg0, object? arg1, object? arg2) { return AppendFormatHelper(provider, format, new ParamsArray(arg0, arg1, arg2)); } public StringBuilder AppendFormat(IFormatProvider? provider, string format, params object?[] args) { if (args == null) { string paramName = ((format == null) ? "format" : "args"); throw new ArgumentNullException(paramName); } return AppendFormatHelper(provider, format, new ParamsArray(args)); } private static void FormatError() { throw new FormatException(SR.Format_InvalidString); } internal StringBuilder AppendFormatHelper(IFormatProvider provider, string format, ParamsArray args) { if (format == null) { throw new ArgumentNullException("format"); } int num = 0; int length = format.Length; char c = '\0'; ICustomFormatter customFormatter = null; if (provider != null) { customFormatter = (ICustomFormatter)provider.GetFormat(typeof(ICustomFormatter)); } while (true) { if (num < length) { c = format[num]; num++; if (c == '}') { if (num < length && format[num] == '}') { num++; } else { FormatError(); } } else if (c == '{') { if (num >= length || format[num] != '{') { num--; goto IL_008f; } num++; } Append(c); continue; } goto IL_008f; IL_008f: if (num == length) { break; } num++; if (num == length || (c = format[num]) < '0' || c > '9') { FormatError(); } int num2 = 0; do { num2 = num2 * 10 + c - 48; num++; if (num == length) { FormatError(); } c = format[num]; } while (c >= '0' && c <= '9' && num2 < 1000000); if (num2 >= args.Length) { throw new FormatException(SR.Format_IndexOutOfRange); } for (; num < length; num++) { if ((c = format[num]) != ' ') { break; } } bool flag = false; int num3 = 0; if (c == ',') { for (num++; num < length && format[num] == ' '; num++) { } if (num == length) { FormatError(); } c = format[num]; if (c == '-') { flag = true; num++; if (num == length) { FormatError(); } c = format[num]; } if (c < '0' || c > '9') { FormatError(); } do { num3 = num3 * 10 + c - 48; num++; if (num == length) { FormatError(); } c = format[num]; } while (c >= '0' && c <= '9' && num3 < 1000000); } for (; num < length; num++) { if ((c = format[num]) != ' ') { break; } } object obj = args[num2]; ReadOnlySpan readOnlySpan = default(ReadOnlySpan); switch (c) { case ':': { num++; int num4 = num; while (true) { if (num == length) { FormatError(); } c = format[num]; switch (c) { case '{': FormatError(); goto IL_0205; default: goto IL_0205; case '}': break; } break; IL_0205: num++; } if (num > num4) { readOnlySpan = format.AsSpan(num4, num - num4); } break; } default: FormatError(); break; case '}': break; } num++; string text = null; string text2 = null; if (customFormatter != null) { if (readOnlySpan.Length != 0) { text2 = new string(readOnlySpan); } text = customFormatter.Format(text2, obj, provider); } if (text == null) { if (obj is ISpanFormattable spanFormattable && (flag || num3 == 0) && spanFormattable.TryFormat(RemainingCurrentChunk, out var charsWritten, readOnlySpan, provider)) { if ((uint)charsWritten > (uint)RemainingCurrentChunk.Length) { FormatError(); } m_ChunkLength += charsWritten; int num5 = num3 - charsWritten; if (flag && num5 > 0) { Append(' ', num5); } continue; } if (obj is IFormattable formattable) { if (readOnlySpan.Length != 0 && text2 == null) { text2 = new string(readOnlySpan); } text = formattable.ToString(text2, provider); } else if (obj != null) { text = obj.ToString(); } } if (text == null) { text = string.Empty; } int num6 = num3 - text.Length; if (!flag && num6 > 0) { Append(' ', num6); } Append(text); if (flag && num6 > 0) { Append(' ', num6); } } return this; } public StringBuilder Replace(string oldValue, string? newValue) { return Replace(oldValue, newValue, 0, Length); } public bool Equals([NotNullWhen(true)] StringBuilder? sb) { if (sb == null) { return false; } if (Length != sb.Length) { return false; } if (sb == this) { return true; } StringBuilder stringBuilder = this; int num = stringBuilder.m_ChunkLength; StringBuilder stringBuilder2 = sb; int num2 = stringBuilder2.m_ChunkLength; do { num--; num2--; while (num < 0) { stringBuilder = stringBuilder.m_ChunkPrevious; if (stringBuilder == null) { break; } num = stringBuilder.m_ChunkLength + num; } while (num2 < 0) { stringBuilder2 = stringBuilder2.m_ChunkPrevious; if (stringBuilder2 == null) { break; } num2 = stringBuilder2.m_ChunkLength + num2; } if (num < 0) { return num2 < 0; } if (num2 < 0) { return false; } } while (stringBuilder.m_ChunkChars[num] == stringBuilder2.m_ChunkChars[num2]); return false; } public bool Equals(ReadOnlySpan span) { if (span.Length != Length) { return false; } StringBuilder stringBuilder = this; int num = 0; do { int chunkLength = stringBuilder.m_ChunkLength; num += chunkLength; ReadOnlySpan span2 = new ReadOnlySpan(stringBuilder.m_ChunkChars, 0, chunkLength); if (!span2.EqualsOrdinal(span.Slice(span.Length - num, chunkLength))) { return false; } stringBuilder = stringBuilder.m_ChunkPrevious; } while (stringBuilder != null); return true; } public StringBuilder Replace(string oldValue, string? newValue, int startIndex, int count) { int length = Length; if ((uint)startIndex > (uint)length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > length - count) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Index); } if (oldValue == null) { throw new ArgumentNullException("oldValue"); } if (oldValue.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "oldValue"); } if (newValue == null) { newValue = string.Empty; } int[] array = null; int num = 0; StringBuilder stringBuilder = FindChunkForIndex(startIndex); int num2 = startIndex - stringBuilder.m_ChunkOffset; while (count > 0) { if (StartsWith(stringBuilder, num2, count, oldValue)) { if (array == null) { array = new int[5]; } else if (num >= array.Length) { Array.Resize(ref array, array.Length * 3 / 2 + 4); } array[num++] = num2; num2 += oldValue.Length; count -= oldValue.Length; } else { num2++; count--; } if (num2 >= stringBuilder.m_ChunkLength || count == 0) { int num3 = num2 + stringBuilder.m_ChunkOffset; ReplaceAllInChunk(array, num, stringBuilder, oldValue.Length, newValue); num3 += (newValue.Length - oldValue.Length) * num; num = 0; stringBuilder = FindChunkForIndex(num3); num2 = num3 - stringBuilder.m_ChunkOffset; } } return this; } public StringBuilder Replace(char oldChar, char newChar) { return Replace(oldChar, newChar, 0, Length); } public StringBuilder Replace(char oldChar, char newChar, int startIndex, int count) { int length = Length; if ((uint)startIndex > (uint)length) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > length - count) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_Index); } int num = startIndex + count; StringBuilder stringBuilder = this; while (true) { int num2 = num - stringBuilder.m_ChunkOffset; int num3 = startIndex - stringBuilder.m_ChunkOffset; if (num2 >= 0) { int i = Math.Max(num3, 0); for (int num4 = Math.Min(stringBuilder.m_ChunkLength, num2); i < num4; i++) { if (stringBuilder.m_ChunkChars[i] == oldChar) { stringBuilder.m_ChunkChars[i] = newChar; } } } if (num3 >= 0) { break; } stringBuilder = stringBuilder.m_ChunkPrevious; } return this; } [CLSCompliant(false)] public unsafe StringBuilder Append(char* value, int valueCount) { if (valueCount < 0) { throw new ArgumentOutOfRangeException("valueCount", SR.ArgumentOutOfRange_NegativeCount); } int num = Length + valueCount; if (num > m_MaxCapacity || num < valueCount) { throw new ArgumentOutOfRangeException("valueCount", SR.ArgumentOutOfRange_LengthGreaterThanCapacity); } int num2 = valueCount + m_ChunkLength; if (num2 <= m_ChunkChars.Length) { new ReadOnlySpan(value, valueCount).CopyTo(m_ChunkChars.AsSpan(m_ChunkLength)); m_ChunkLength = num2; } else { int num3 = m_ChunkChars.Length - m_ChunkLength; if (num3 > 0) { new ReadOnlySpan(value, num3).CopyTo(m_ChunkChars.AsSpan(m_ChunkLength)); m_ChunkLength = m_ChunkChars.Length; } int num4 = valueCount - num3; ExpandByABlock(num4); new ReadOnlySpan(value + num3, num4).CopyTo(m_ChunkChars); m_ChunkLength = num4; } return this; } private unsafe void Insert(int index, char* value, int valueCount) { if ((uint)index > (uint)Length) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (valueCount > 0) { MakeRoom(index, valueCount, out var chunk, out var indexInChunk, doNotMoveFollowingChars: false); ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, value, valueCount); } } private unsafe void ReplaceAllInChunk(int[] replacements, int replacementsCount, StringBuilder sourceChunk, int removeCount, string value) { if (replacementsCount <= 0) { return; } fixed (char* value2 = value) { long num = (long)(value.Length - removeCount) * (long)replacementsCount; int num2 = (int)num; if (num2 != num) { throw new OutOfMemoryException(); } StringBuilder chunk = sourceChunk; int indexInChunk = replacements[0]; if (num2 > 0) { MakeRoom(chunk.m_ChunkOffset + indexInChunk, num2, out chunk, out indexInChunk, doNotMoveFollowingChars: true); } int num3 = 0; while (true) { ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, value2, value.Length); int num4 = replacements[num3] + removeCount; num3++; if (num3 >= replacementsCount) { break; } int num5 = replacements[num3]; if (num2 != 0) { fixed (char* value3 = &sourceChunk.m_ChunkChars[num4]) { ReplaceInPlaceAtChunk(ref chunk, ref indexInChunk, value3, num5 - num4); } } else { indexInChunk += num5 - num4; } } if (num2 < 0) { Remove(chunk.m_ChunkOffset + indexInChunk, -num2, out chunk, out indexInChunk); } } } private bool StartsWith(StringBuilder chunk, int indexInChunk, int count, string value) { for (int i = 0; i < value.Length; i++) { if (count == 0) { return false; } if (indexInChunk >= chunk.m_ChunkLength) { chunk = Next(chunk); if (chunk == null) { return false; } indexInChunk = 0; } if (value[i] != chunk.m_ChunkChars[indexInChunk]) { return false; } indexInChunk++; count--; } return true; } private unsafe void ReplaceInPlaceAtChunk(ref StringBuilder chunk, ref int indexInChunk, char* value, int count) { if (count == 0) { return; } while (true) { int val = chunk.m_ChunkLength - indexInChunk; int num = Math.Min(val, count); new ReadOnlySpan(value, num).CopyTo(chunk.m_ChunkChars.AsSpan(indexInChunk)); indexInChunk += num; if (indexInChunk >= chunk.m_ChunkLength) { chunk = Next(chunk); indexInChunk = 0; } count -= num; if (count != 0) { value += num; continue; } break; } } private StringBuilder FindChunkForIndex(int index) { StringBuilder stringBuilder = this; while (stringBuilder.m_ChunkOffset > index) { stringBuilder = stringBuilder.m_ChunkPrevious; } return stringBuilder; } private StringBuilder Next(StringBuilder chunk) { if (chunk != this) { return FindChunkForIndex(chunk.m_ChunkOffset + chunk.m_ChunkLength); } return null; } private void ExpandByABlock(int minBlockCharCount) { if (minBlockCharCount + Length > m_MaxCapacity || minBlockCharCount + Length < minBlockCharCount) { throw new ArgumentOutOfRangeException("requiredLength", SR.ArgumentOutOfRange_SmallCapacity); } int num = Math.Max(minBlockCharCount, Math.Min(Length, 8000)); if (m_ChunkOffset + m_ChunkLength + num < num) { throw new OutOfMemoryException(); } char[] chunkChars = GC.AllocateUninitializedArray(num); m_ChunkPrevious = new StringBuilder(this); m_ChunkOffset += m_ChunkLength; m_ChunkLength = 0; m_ChunkChars = chunkChars; } private StringBuilder(StringBuilder from) { m_ChunkLength = from.m_ChunkLength; m_ChunkOffset = from.m_ChunkOffset; m_ChunkChars = from.m_ChunkChars; m_ChunkPrevious = from.m_ChunkPrevious; m_MaxCapacity = from.m_MaxCapacity; } private void MakeRoom(int index, int count, out StringBuilder chunk, out int indexInChunk, bool doNotMoveFollowingChars) { if (count + Length > m_MaxCapacity || count + Length < count) { throw new ArgumentOutOfRangeException("requiredLength", SR.ArgumentOutOfRange_SmallCapacity); } chunk = this; while (chunk.m_ChunkOffset > index) { chunk.m_ChunkOffset += count; chunk = chunk.m_ChunkPrevious; } indexInChunk = index - chunk.m_ChunkOffset; if (!doNotMoveFollowingChars && chunk.m_ChunkLength <= 32 && chunk.m_ChunkChars.Length - chunk.m_ChunkLength >= count) { int num = chunk.m_ChunkLength; while (num > indexInChunk) { num--; chunk.m_ChunkChars[num + count] = chunk.m_ChunkChars[num]; } chunk.m_ChunkLength += count; return; } StringBuilder stringBuilder = new StringBuilder(Math.Max(count, 16), chunk.m_MaxCapacity, chunk.m_ChunkPrevious); stringBuilder.m_ChunkLength = count; int num2 = Math.Min(count, indexInChunk); if (num2 > 0) { new ReadOnlySpan(chunk.m_ChunkChars, 0, num2).CopyTo(stringBuilder.m_ChunkChars); int num3 = indexInChunk - num2; if (num3 >= 0) { new ReadOnlySpan(chunk.m_ChunkChars, num2, num3).CopyTo(chunk.m_ChunkChars); indexInChunk = num3; } } chunk.m_ChunkPrevious = stringBuilder; chunk.m_ChunkOffset += count; if (num2 < count) { chunk = stringBuilder; indexInChunk = num2; } } private StringBuilder(int size, int maxCapacity, StringBuilder previousBlock) { m_ChunkChars = GC.AllocateUninitializedArray(size); m_MaxCapacity = maxCapacity; m_ChunkPrevious = previousBlock; if (previousBlock != null) { m_ChunkOffset = previousBlock.m_ChunkOffset + previousBlock.m_ChunkLength; } } private void Remove(int startIndex, int count, out StringBuilder chunk, out int indexInChunk) { int num = startIndex + count; chunk = this; StringBuilder stringBuilder = null; int num2 = 0; while (true) { if (num - chunk.m_ChunkOffset >= 0) { if (stringBuilder == null) { stringBuilder = chunk; num2 = num - stringBuilder.m_ChunkOffset; } if (startIndex - chunk.m_ChunkOffset >= 0) { break; } } else { chunk.m_ChunkOffset -= count; } chunk = chunk.m_ChunkPrevious; } indexInChunk = startIndex - chunk.m_ChunkOffset; int num3 = indexInChunk; int length = stringBuilder.m_ChunkLength - num2; if (stringBuilder != chunk) { num3 = 0; chunk.m_ChunkLength = indexInChunk; stringBuilder.m_ChunkPrevious = chunk; stringBuilder.m_ChunkOffset = chunk.m_ChunkOffset + chunk.m_ChunkLength; if (indexInChunk == 0) { stringBuilder.m_ChunkPrevious = chunk.m_ChunkPrevious; chunk = stringBuilder; } } stringBuilder.m_ChunkLength -= num2 - num3; if (num3 != num2) { new ReadOnlySpan(stringBuilder.m_ChunkChars, num2, length).CopyTo(stringBuilder.m_ChunkChars.AsSpan(num3)); } } } public class ASCIIEncoding : Encoding { internal sealed class ASCIIEncodingSealed : ASCIIEncoding { public override object Clone() { return new ASCIIEncoding { IsReadOnly = false }; } } internal static readonly ASCIIEncodingSealed s_default = new ASCIIEncodingSealed(); public override bool IsSingleByte => true; public ASCIIEncoding() : base(20127) { } internal sealed override void SetDefaultFallbacks() { encoderFallback = System.Text.EncoderFallback.ReplacementFallback; decoderFallback = System.Text.DecoderFallback.ReplacementFallback; } public unsafe override int GetByteCount(char[] chars, int index, int count) { if (chars == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars, ExceptionResource.ArgumentNull_Array); } if ((index | count) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } fixed (char* ptr = chars) { return GetByteCountCommon(ptr + index, count); } } public unsafe override int GetByteCount(string chars) { if (chars == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); } fixed (char* pChars = chars) { return GetByteCountCommon(pChars, chars.Length); } } [CLSCompliant(false)] public unsafe override int GetByteCount(char* chars, int count) { if (chars == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetByteCountCommon(chars, count); } public unsafe override int GetByteCount(ReadOnlySpan chars) { fixed (char* pChars = &MemoryMarshal.GetReference(chars)) { return GetByteCountCommon(pChars, chars.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetByteCountCommon(char* pChars, int charCount) { int charsConsumed; int num = GetByteCountFast(pChars, charCount, base.EncoderFallback, out charsConsumed); if (charsConsumed != charCount) { num += GetByteCountWithFallback(pChars, charCount, charsConsumed); if (num < 0) { Encoding.ThrowConversionOverflow(); } } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private protected unsafe sealed override int GetByteCountFast(char* pChars, int charsLength, EncoderFallback fallback, out int charsConsumed) { int num = charsLength; if (!(fallback is EncoderReplacementFallback encoderReplacementFallback) || encoderReplacementFallback.MaxCharCount != 1 || encoderReplacementFallback.DefaultString[0] > '\u007f') { num = (int)ASCIIUtility.GetIndexOfFirstNonAsciiChar(pChars, (uint)charsLength); } charsConsumed = num; return num; } public unsafe override int GetBytes(string chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null || bytes == null) { ThrowHelper.ThrowArgumentNullException((chars == null) ? ExceptionArgument.chars : ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((charIndex | charCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((charIndex < 0) ? ExceptionArgument.charIndex : ExceptionArgument.charCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCount); } if ((uint)byteIndex > bytes.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.byteIndex, ExceptionResource.ArgumentOutOfRange_Index); } fixed (char* ptr2 = chars) { fixed (byte[] array = bytes) { byte* ptr = (byte*)((bytes != null && array.Length != 0) ? System.Runtime.CompilerServices.Unsafe.AsPointer(ref array[0]) : null); return GetBytesCommon(ptr2 + charIndex, charCount, ptr + byteIndex, bytes.Length - byteIndex); } } } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null || bytes == null) { ThrowHelper.ThrowArgumentNullException((chars == null) ? ExceptionArgument.chars : ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((charIndex | charCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((charIndex < 0) ? ExceptionArgument.charIndex : ExceptionArgument.charCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCount); } if ((uint)byteIndex > bytes.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.byteIndex, ExceptionResource.ArgumentOutOfRange_Index); } fixed (char* ptr = chars) { fixed (byte* ptr2 = bytes) { return GetBytesCommon(ptr + charIndex, charCount, ptr2 + byteIndex, bytes.Length - byteIndex); } } } [CLSCompliant(false)] public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { if (chars == null || bytes == null) { ThrowHelper.ThrowArgumentNullException((chars == null) ? ExceptionArgument.chars : ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((charCount | byteCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((charCount < 0) ? ExceptionArgument.charCount : ExceptionArgument.byteCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetBytesCommon(chars, charCount, bytes, byteCount); } public unsafe override int GetBytes(ReadOnlySpan chars, Span bytes) { fixed (char* pChars = &MemoryMarshal.GetReference(chars)) { fixed (byte* pBytes = &MemoryMarshal.GetReference(bytes)) { return GetBytesCommon(pChars, chars.Length, pBytes, bytes.Length); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetBytesCommon(char* pChars, int charCount, byte* pBytes, int byteCount) { int charsConsumed; int bytesFast = GetBytesFast(pChars, charCount, pBytes, byteCount, out charsConsumed); if (charsConsumed == charCount) { return bytesFast; } return GetBytesWithFallback(pChars, charCount, pBytes, byteCount, charsConsumed, bytesFast); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private protected unsafe sealed override int GetBytesFast(char* pChars, int charsLength, byte* pBytes, int bytesLength, out int charsConsumed) { return charsConsumed = (int)ASCIIUtility.NarrowUtf16ToAscii(pChars, pBytes, (uint)Math.Min(charsLength, bytesLength)); } private protected unsafe sealed override int GetBytesWithFallback(ReadOnlySpan chars, int originalCharsLength, Span bytes, int originalBytesLength, EncoderNLS encoder) { if (((encoder == null) ? base.EncoderFallback : encoder.Fallback) is EncoderReplacementFallback encoderReplacementFallback && encoderReplacementFallback.MaxCharCount == 1 && encoderReplacementFallback.DefaultString[0] <= '\u007f') { byte b = (byte)encoderReplacementFallback.DefaultString[0]; int num = Math.Min(chars.Length, bytes.Length); int num2 = 0; fixed (char* ptr2 = &MemoryMarshal.GetReference(chars)) { fixed (byte* ptr = &MemoryMarshal.GetReference(bytes)) { while (num2 < num) { ptr[num2++] = b; if (num2 < num) { num2 += (int)ASCIIUtility.NarrowUtf16ToAscii(ptr2 + num2, ptr + num2, (uint)(num - num2)); } } } } chars = chars.Slice(num); bytes = bytes.Slice(num); } if (chars.IsEmpty) { return originalBytesLength - bytes.Length; } return base.GetBytesWithFallback(chars, originalCharsLength, bytes, originalBytesLength, encoder); } public unsafe override int GetCharCount(byte[] bytes, int index, int count) { if (bytes == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((index | count) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } fixed (byte* ptr = bytes) { return GetCharCountCommon(ptr + index, count); } } [CLSCompliant(false)] public unsafe override int GetCharCount(byte* bytes, int count) { if (bytes == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetCharCountCommon(bytes, count); } public unsafe override int GetCharCount(ReadOnlySpan bytes) { fixed (byte* pBytes = &MemoryMarshal.GetReference(bytes)) { return GetCharCountCommon(pBytes, bytes.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetCharCountCommon(byte* pBytes, int byteCount) { int bytesConsumed; int num = GetCharCountFast(pBytes, byteCount, base.DecoderFallback, out bytesConsumed); if (bytesConsumed != byteCount) { num += GetCharCountWithFallback(pBytes, byteCount, bytesConsumed); if (num < 0) { Encoding.ThrowConversionOverflow(); } } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private protected unsafe sealed override int GetCharCountFast(byte* pBytes, int bytesLength, DecoderFallback fallback, out int bytesConsumed) { int num = bytesLength; if (!(fallback is DecoderReplacementFallback decoderReplacementFallback) || decoderReplacementFallback.MaxCharCount != 1) { num = (int)ASCIIUtility.GetIndexOfFirstNonAsciiByte(pBytes, (uint)bytesLength); } bytesConsumed = num; return num; } public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if (bytes == null || chars == null) { ThrowHelper.ThrowArgumentNullException((bytes == null) ? ExceptionArgument.bytes : ExceptionArgument.chars, ExceptionResource.ArgumentNull_Array); } if ((byteIndex | byteCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((byteIndex < 0) ? ExceptionArgument.byteIndex : ExceptionArgument.byteCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } if ((uint)charIndex > (uint)chars.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.charIndex, ExceptionResource.ArgumentOutOfRange_Index); } fixed (byte* ptr = bytes) { fixed (char* ptr2 = chars) { return GetCharsCommon(ptr + byteIndex, byteCount, ptr2 + charIndex, chars.Length - charIndex); } } } [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { if (bytes == null || chars == null) { ThrowHelper.ThrowArgumentNullException((bytes == null) ? ExceptionArgument.bytes : ExceptionArgument.chars, ExceptionResource.ArgumentNull_Array); } if ((byteCount | charCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((byteCount < 0) ? ExceptionArgument.byteCount : ExceptionArgument.charCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetCharsCommon(bytes, byteCount, chars, charCount); } public unsafe override int GetChars(ReadOnlySpan bytes, Span chars) { fixed (byte* pBytes = &MemoryMarshal.GetReference(bytes)) { fixed (char* pChars = &MemoryMarshal.GetReference(chars)) { return GetCharsCommon(pBytes, bytes.Length, pChars, chars.Length); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetCharsCommon(byte* pBytes, int byteCount, char* pChars, int charCount) { int bytesConsumed; int charsFast = GetCharsFast(pBytes, byteCount, pChars, charCount, out bytesConsumed); if (bytesConsumed == byteCount) { return charsFast; } return GetCharsWithFallback(pBytes, byteCount, pChars, charCount, bytesConsumed, charsFast); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private protected unsafe sealed override int GetCharsFast(byte* pBytes, int bytesLength, char* pChars, int charsLength, out int bytesConsumed) { return bytesConsumed = (int)ASCIIUtility.WidenAsciiToUtf16(pBytes, pChars, (uint)Math.Min(bytesLength, charsLength)); } private protected unsafe sealed override int GetCharsWithFallback(ReadOnlySpan bytes, int originalBytesLength, Span chars, int originalCharsLength, DecoderNLS decoder) { if (((decoder == null) ? base.DecoderFallback : decoder.Fallback) is DecoderReplacementFallback decoderReplacementFallback && decoderReplacementFallback.MaxCharCount == 1) { char c = decoderReplacementFallback.DefaultString[0]; int num = Math.Min(bytes.Length, chars.Length); int num2 = 0; fixed (byte* ptr2 = &MemoryMarshal.GetReference(bytes)) { fixed (char* ptr = &MemoryMarshal.GetReference(chars)) { while (num2 < num) { ptr[num2++] = c; if (num2 < num) { num2 += (int)ASCIIUtility.WidenAsciiToUtf16(ptr2 + num2, ptr + num2, (uint)(num - num2)); } } } } bytes = bytes.Slice(num); chars = chars.Slice(num); } if (bytes.IsEmpty) { return originalCharsLength - chars.Length; } return base.GetCharsWithFallback(bytes, originalBytesLength, chars, originalCharsLength, decoder); } public unsafe override string GetString(byte[] bytes, int byteIndex, int byteCount) { if (bytes == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((byteIndex | byteCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((byteIndex < 0) ? ExceptionArgument.byteIndex : ExceptionArgument.byteCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } if (byteCount == 0) { return string.Empty; } fixed (byte* ptr = bytes) { return string.CreateStringFromEncoding(ptr + byteIndex, byteCount, this); } } internal sealed override bool TryGetByteCount(Rune value, out int byteCount) { if (value.IsAscii) { byteCount = 1; return true; } byteCount = 0; return false; } internal sealed override OperationStatus EncodeRune(Rune value, Span bytes, out int bytesWritten) { if (value.IsAscii) { if (!bytes.IsEmpty) { bytes[0] = (byte)value.Value; bytesWritten = 1; return OperationStatus.Done; } bytesWritten = 0; return OperationStatus.DestinationTooSmall; } bytesWritten = 0; return OperationStatus.InvalidData; } internal sealed override OperationStatus DecodeFirstRune(ReadOnlySpan bytes, out Rune value, out int bytesConsumed) { if (!bytes.IsEmpty) { byte b = bytes[0]; if (b <= 127) { value = new Rune(b); bytesConsumed = 1; return OperationStatus.Done; } value = Rune.ReplacementChar; bytesConsumed = 1; return OperationStatus.InvalidData; } value = Rune.ReplacementChar; bytesConsumed = 0; return OperationStatus.NeedMoreData; } public override int GetMaxByteCount(int charCount) { if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } long num = (long)charCount + 1L; if (base.EncoderFallback.MaxCharCount > 1) { num *= base.EncoderFallback.MaxCharCount; } if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_GetByteCountOverflow); } return (int)num; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) { throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } long num = byteCount; if (base.DecoderFallback.MaxCharCount > 1) { num *= base.DecoderFallback.MaxCharCount; } if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_GetCharCountOverflow); } return (int)num; } public override Decoder GetDecoder() { return new DecoderNLS(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } } internal static class ASCIIUtility { [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool AllCharsInUInt32AreAscii(uint value) { return (value & 0xFF80FF80u) == 0; } private static bool FirstCharInUInt32IsAscii(uint value) { _ = BitConverter.IsLittleEndian; if ((value & 0xFF80u) != 0) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static nuint GetIndexOfFirstNonAsciiByte(byte* pBuffer, nuint bufferLength) { if (!Sse2.IsSupported) { if (AdvSimd.Arm64.IsSupported) { } return GetIndexOfFirstNonAsciiByte_Default(pBuffer, bufferLength); } return GetIndexOfFirstNonAsciiByte_Intrinsified(pBuffer, bufferLength); } private unsafe static nuint GetIndexOfFirstNonAsciiByte_Default(byte* pBuffer, nuint bufferLength) { byte* ptr = pBuffer; if (Vector.IsHardwareAccelerated && bufferLength >= (uint)(2 * Vector.Count)) { uint count = (uint)Vector.Count; if (Vector.GreaterThanOrEqualAll(Unsafe.ReadUnaligned>(pBuffer), Vector.Zero)) { byte* ptr2 = pBuffer + bufferLength - count; pBuffer = (byte*)((nuint)(pBuffer + count) & ~(nuint)(count - 1)); while (!Vector.LessThanAny(Unsafe.Read>(pBuffer), Vector.Zero)) { pBuffer += count; if (pBuffer > ptr2) { break; } } bufferLength -= (nuint)pBuffer; bufferLength = (nuint)(bufferLength + ptr); } } while (true) { uint num; if (bufferLength >= 8) { num = Unsafe.ReadUnaligned(pBuffer); uint num2 = Unsafe.ReadUnaligned(pBuffer + 4); if (!AllBytesInUInt32AreAscii(num | num2)) { if (AllBytesInUInt32AreAscii(num)) { num = num2; pBuffer += 4; } goto IL_0100; } pBuffer += 8; bufferLength -= 8; continue; } if ((bufferLength & 4) != 0) { num = Unsafe.ReadUnaligned(pBuffer); if (!AllBytesInUInt32AreAscii(num)) { goto IL_0100; } pBuffer += 4; } if ((bufferLength & 2) != 0) { num = Unsafe.ReadUnaligned(pBuffer); if (!AllBytesInUInt32AreAscii(num) && BitConverter.IsLittleEndian) { goto IL_0100; } pBuffer += 2; } if ((bufferLength & 1) != 0 && *pBuffer >= 0) { pBuffer++; } break; IL_0100: pBuffer += CountNumberOfLeadingAsciiBytesFromUInt32WithSomeNonAsciiData(num); break; } return (nuint)(pBuffer - (nuint)ptr); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool ContainsNonAsciiByte_Sse2(uint sseMask) { return sseMask != 0; } private unsafe static nuint GetIndexOfFirstNonAsciiByte_Intrinsified(byte* pBuffer, nuint bufferLength) { uint num = (uint)Unsafe.SizeOf>(); nuint num2 = num - 1; if (!BitConverter.IsLittleEndian) { } Vector128 vector = Vector128.Create((ushort)4097).AsByte(); uint num3 = uint.MaxValue; uint num4 = uint.MaxValue; uint num5 = uint.MaxValue; uint num6 = uint.MaxValue; byte* ptr = pBuffer; if (bufferLength >= num) { if (Sse2.IsSupported) { num3 = (uint)Sse2.MoveMask(Sse2.LoadVector128(pBuffer)); if (!ContainsNonAsciiByte_Sse2(num3)) { if (bufferLength < 2 * num) { goto IL_0122; } pBuffer = (byte*)((nuint)(pBuffer + num) & ~num2); bufferLength = (nuint)(bufferLength + ptr); bufferLength -= (nuint)pBuffer; if (bufferLength < 2 * num) { goto IL_00ef; } byte* ptr2 = pBuffer + bufferLength - 2 * num; while (true) { if (Sse2.IsSupported) { Vector128 value = Sse2.LoadAlignedVector128(pBuffer); Vector128 value2 = Sse2.LoadAlignedVector128(pBuffer + num); num3 = (uint)Sse2.MoveMask(value); num4 = (uint)Sse2.MoveMask(value2); if (ContainsNonAsciiByte_Sse2(num3 | num4)) { break; } pBuffer += 2 * num; if (pBuffer <= ptr2) { continue; } goto IL_00ef; } if (AdvSimd.Arm64.IsSupported) { } throw new PlatformNotSupportedException(); } if (!Sse2.IsSupported) { if (AdvSimd.IsSupported) { } throw new PlatformNotSupportedException(); } if (!ContainsNonAsciiByte_Sse2(num3)) { pBuffer += num; num3 = num4; } } goto IL_0197; } if (AdvSimd.Arm64.IsSupported) { } throw new PlatformNotSupportedException(); } uint num7; if ((bufferLength & 8) != 0) { if (UIntPtr.Size == 8) { } num7 = Unsafe.ReadUnaligned(pBuffer); uint num8 = Unsafe.ReadUnaligned(pBuffer + 4); if (!AllBytesInUInt32AreAscii(num7 | num8)) { if (AllBytesInUInt32AreAscii(num7)) { num7 = num8; pBuffer += 4; } goto IL_01b8; } pBuffer += 8; } if ((bufferLength & 4) != 0) { num7 = Unsafe.ReadUnaligned(pBuffer); if (!AllBytesInUInt32AreAscii(num7)) { goto IL_01b8; } pBuffer += 4; } if ((bufferLength & 2) != 0) { num7 = Unsafe.ReadUnaligned(pBuffer); if (!AllBytesInUInt32AreAscii(num7)) { pBuffer += (nuint)(((nint)(sbyte)num7 >> 7) + 1); goto IL_016b; } pBuffer += 2; } if ((bufferLength & 1) != 0 && *pBuffer >= 0) { pBuffer++; } goto IL_016b; IL_0122: pBuffer += num; goto IL_0128; IL_016b: return (nuint)(pBuffer - (nuint)ptr); IL_00ef: if ((bufferLength & num) == 0) { goto IL_0128; } if (Sse2.IsSupported) { num3 = (uint)Sse2.MoveMask(Sse2.LoadAlignedVector128(pBuffer)); if (!ContainsNonAsciiByte_Sse2(num3)) { goto IL_0122; } goto IL_0197; } if (AdvSimd.Arm64.IsSupported) { } throw new PlatformNotSupportedException(); IL_0197: if (Sse2.IsSupported) { pBuffer += (uint)BitOperations.TrailingZeroCount(num3); goto IL_016b; } if (AdvSimd.Arm64.IsSupported) { } throw new PlatformNotSupportedException(); IL_0128: if (((byte)bufferLength & num2) != 0) { pBuffer += (bufferLength & num2) - num; if (!Sse2.IsSupported) { if (AdvSimd.Arm64.IsSupported) { } throw new PlatformNotSupportedException(); } num3 = (uint)Sse2.MoveMask(Sse2.LoadVector128(pBuffer)); if (ContainsNonAsciiByte_Sse2(num3)) { goto IL_0197; } pBuffer += num; } goto IL_016b; IL_01b8: pBuffer += CountNumberOfLeadingAsciiBytesFromUInt32WithSomeNonAsciiData(num7); goto IL_016b; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static nuint GetIndexOfFirstNonAsciiChar(char* pBuffer, nuint bufferLength) { if (!Sse2.IsSupported) { return GetIndexOfFirstNonAsciiChar_Default(pBuffer, bufferLength); } return GetIndexOfFirstNonAsciiChar_Sse2(pBuffer, bufferLength); } private unsafe static nuint GetIndexOfFirstNonAsciiChar_Default(char* pBuffer, nuint bufferLength) { char* ptr = pBuffer; if (Vector.IsHardwareAccelerated && bufferLength >= (uint)(2 * Vector.Count)) { uint count = (uint)Vector.Count; uint count2 = (uint)Vector.Count; Vector right = new Vector(127); if (Vector.LessThanOrEqualAll(Unsafe.ReadUnaligned>(pBuffer), right)) { char* ptr2 = pBuffer + bufferLength - count; pBuffer = (char*)((nuint)((byte*)pBuffer + count2) & ~(nuint)(count2 - 1)); while (!Vector.GreaterThanAny(Unsafe.Read>(pBuffer), right)) { pBuffer += count; if (pBuffer > ptr2) { break; } } bufferLength -= (nuint)(nint)(pBuffer - ptr); } } while (true) { uint num; if (bufferLength >= 4) { num = Unsafe.ReadUnaligned(pBuffer); uint num2 = Unsafe.ReadUnaligned(pBuffer + 2); if (!AllCharsInUInt32AreAscii(num | num2)) { if (AllCharsInUInt32AreAscii(num)) { num = num2; pBuffer += 2; } goto IL_0109; } pBuffer += 4; bufferLength -= 4; continue; } if ((bufferLength & 2) != 0) { num = Unsafe.ReadUnaligned(pBuffer); if (!AllCharsInUInt32AreAscii(num)) { goto IL_0109; } pBuffer += 2; } if ((bufferLength & 1) != 0 && *pBuffer <= '\u007f') { pBuffer++; } break; IL_0109: if (FirstCharInUInt32IsAscii(num)) { pBuffer++; } break; } nuint num3 = (nuint)((byte*)pBuffer - (nuint)ptr); return num3 / 2; } private unsafe static nuint GetIndexOfFirstNonAsciiChar_Sse2(char* pBuffer, nuint bufferLength) { if (bufferLength == 0) { return 0u; } uint num = (uint)Unsafe.SizeOf>(); uint num2 = num / 2; char* ptr = pBuffer; Vector128 right; Vector128 right2; Vector128 left; uint num3; if (bufferLength >= num2) { right = Vector128.Create((ushort)65408); right2 = Vector128.Create((ushort)32640); left = Sse2.LoadVector128((ushort*)pBuffer); num3 = (uint)Sse2.MoveMask(Sse2.AddSaturate(left, right2).AsByte()); if ((num3 & 0xAAAA) == 0) { bufferLength <<= 1; if (bufferLength < 2 * num) { goto IL_013e; } pBuffer = (char*)((nuint)((byte*)pBuffer + num) & ~(nuint)(num - 1)); bufferLength = (nuint)(bufferLength + (byte*)ptr); bufferLength -= (nuint)pBuffer; if (bufferLength < 2 * num) { goto IL_00fa; } char* ptr2 = (char*)((byte*)pBuffer + bufferLength - 2 * num); Vector128 vector; while (true) { left = Sse2.LoadAlignedVector128((ushort*)pBuffer); vector = Sse2.LoadAlignedVector128((ushort*)(pBuffer + num2)); Vector128 left2 = Sse2.Or(left, vector); if (Sse41.IsSupported) { if (!Sse41.TestZ(left2, right)) { break; } } else { num3 = (uint)Sse2.MoveMask(Sse2.AddSaturate(left2, right2).AsByte()); if ((num3 & 0xAAAAu) != 0) { break; } } pBuffer += 2 * num2; if (pBuffer <= ptr2) { continue; } goto IL_00fa; } if (Sse41.IsSupported) { if (!Sse41.TestZ(left, right)) { goto IL_01e6; } } else { num3 = (uint)Sse2.MoveMask(Sse2.AddSaturate(left, right2).AsByte()); if ((num3 & 0xAAAAu) != 0) { goto IL_01fa; } } pBuffer += num2; left = vector; goto IL_01e6; } goto IL_01fa; } uint num4; if ((bufferLength & 4) != 0) { if (UIntPtr.Size == 8) { } num4 = Unsafe.ReadUnaligned(pBuffer); uint num5 = Unsafe.ReadUnaligned(pBuffer + 2); if (!AllCharsInUInt32AreAscii(num4 | num5)) { if (AllCharsInUInt32AreAscii(num4)) { num4 = num5; pBuffer += 2; } goto IL_0214; } pBuffer += 4; } if ((bufferLength & 2) != 0) { num4 = Unsafe.ReadUnaligned(pBuffer); if (!AllCharsInUInt32AreAscii(num4)) { goto IL_0214; } pBuffer += 2; } if ((bufferLength & 1) != 0 && *pBuffer <= '\u007f') { pBuffer++; } goto IL_01a1; IL_01a1: return (nuint)(pBuffer - ptr); IL_0148: if (((byte)bufferLength & (num - 1)) != 0) { pBuffer = (char*)((byte*)pBuffer + (bufferLength & (num - 1)) - num); left = Sse2.LoadVector128((ushort*)pBuffer); if (Sse41.IsSupported) { if (!Sse41.TestZ(left, right)) { goto IL_01e6; } } else { num3 = (uint)Sse2.MoveMask(Sse2.AddSaturate(left, right2).AsByte()); if ((num3 & 0xAAAAu) != 0) { goto IL_01fa; } } pBuffer += num2; } goto IL_01a1; IL_0214: if (FirstCharInUInt32IsAscii(num4)) { pBuffer++; } goto IL_01a1; IL_01fa: num3 &= 0xAAAAu; pBuffer = (char*)((byte*)pBuffer + (uint)BitOperations.TrailingZeroCount(num3) - 1); goto IL_01a1; IL_013e: pBuffer += num2; goto IL_0148; IL_01e6: num3 = (uint)Sse2.MoveMask(Sse2.AddSaturate(left, right2).AsByte()); goto IL_01fa; IL_00fa: if ((bufferLength & num) != 0) { left = Sse2.LoadAlignedVector128((ushort*)pBuffer); if (Sse41.IsSupported) { if (!Sse41.TestZ(left, right)) { goto IL_01e6; } } else { num3 = (uint)Sse2.MoveMask(Sse2.AddSaturate(left, right2).AsByte()); if ((num3 & 0xAAAAu) != 0) { goto IL_01fa; } } goto IL_013e; } goto IL_0148; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void NarrowTwoUtf16CharsToAsciiAndWriteToBuffer(ref byte outputBuffer, uint value) { _ = BitConverter.IsLittleEndian; outputBuffer = (byte)value; Unsafe.Add(ref outputBuffer, 1) = (byte)(value >> 16); } public unsafe static nuint NarrowUtf16ToAscii(char* pUtf16Buffer, byte* pAsciiBuffer, nuint elementCount) { nuint num = 0u; uint num2 = 0u; uint num3 = 0u; ulong num4 = 0uL; if (Sse2.IsSupported) { if (elementCount >= (uint)(2 * Unsafe.SizeOf>())) { if (IntPtr.Size >= 8) { } num2 = Unsafe.ReadUnaligned(pUtf16Buffer); num3 = Unsafe.ReadUnaligned(pUtf16Buffer + 2); if (!AllCharsInUInt32AreAscii(num2 | num3)) { goto IL_01c7; } num = NarrowUtf16ToAscii_Sse2(pUtf16Buffer, pAsciiBuffer, elementCount); } } else if (Vector.IsHardwareAccelerated) { uint num5 = (uint)Unsafe.SizeOf>(); if (elementCount >= 2 * num5) { if (IntPtr.Size >= 8) { } num2 = Unsafe.ReadUnaligned(pUtf16Buffer); num3 = Unsafe.ReadUnaligned(pUtf16Buffer + 2); if (!AllCharsInUInt32AreAscii(num2 | num3)) { goto IL_01c7; } Vector right = new Vector(127); nuint num6 = elementCount - 2 * num5; do { Vector vector = Unsafe.ReadUnaligned>(pUtf16Buffer + num); Vector vector2 = Unsafe.ReadUnaligned>(pUtf16Buffer + num + Vector.Count); if (Vector.GreaterThanAny(Vector.BitwiseOr(vector, vector2), right)) { break; } Vector value = Vector.Narrow(vector, vector2); Unsafe.WriteUnaligned(pAsciiBuffer + num, value); num += num5; } while (num <= num6); } } nuint num7 = elementCount - num; if (num7 < 4) { goto IL_0173; } nuint num8 = num + num7 - 4; while (true) { if (IntPtr.Size >= 8) { } num2 = Unsafe.ReadUnaligned(pUtf16Buffer + num); num3 = Unsafe.ReadUnaligned(pUtf16Buffer + num + 2); if (!AllCharsInUInt32AreAscii(num2 | num3)) { break; } NarrowTwoUtf16CharsToAsciiAndWriteToBuffer(ref pAsciiBuffer[num], num2); NarrowTwoUtf16CharsToAsciiAndWriteToBuffer(ref pAsciiBuffer[num + 2], num3); num += 4; if (num <= num8) { continue; } goto IL_0173; } goto IL_01c7; IL_01e9: if (FirstCharInUInt32IsAscii(num2)) { if (!BitConverter.IsLittleEndian) { } pAsciiBuffer[num] = (byte)num2; num++; } goto IL_01c5; IL_0173: if (((uint)(int)num7 & 2u) != 0) { num2 = Unsafe.ReadUnaligned(pUtf16Buffer + num); if (!AllCharsInUInt32AreAscii(num2)) { goto IL_01e9; } NarrowTwoUtf16CharsToAsciiAndWriteToBuffer(ref pAsciiBuffer[num], num2); num += 2; } if (((uint)(int)num7 & (true ? 1u : 0u)) != 0) { num2 = pUtf16Buffer[num]; if (num2 <= 127) { pAsciiBuffer[num] = (byte)num2; num++; } } goto IL_01c5; IL_01c7: if (IntPtr.Size >= 8) { } if (AllCharsInUInt32AreAscii(num2)) { NarrowTwoUtf16CharsToAsciiAndWriteToBuffer(ref pAsciiBuffer[num], num2); num2 = num3; num += 2; } goto IL_01e9; IL_01c5: return num; } private unsafe static nuint NarrowUtf16ToAscii_Sse2(char* pUtf16Buffer, byte* pAsciiBuffer, nuint elementCount) { uint num = (uint)Unsafe.SizeOf>(); nuint num2 = num - 1; Vector128 right = Vector128.Create((short)(-128)); Vector128 right2 = Vector128.Create((ushort)32640); Vector128 vector = Sse2.LoadVector128((short*)pUtf16Buffer); if (Sse41.IsSupported) { if (!Sse41.TestZ(vector, right)) { return 0u; } } else if (((uint)Sse2.MoveMask(Sse2.AddSaturate(vector.AsUInt16(), right2).AsByte()) & 0xAAAAu) != 0) { return 0u; } Vector128 vector2 = Sse2.PackUnsignedSaturate(vector, vector); Sse2.StoreScalar((ulong*)pAsciiBuffer, vector2.AsUInt64()); nuint num3 = num / 2; if (((uint)(int)pAsciiBuffer & (num / 2)) != 0) { goto IL_00e7; } vector = Sse2.LoadVector128((short*)(pUtf16Buffer + num3)); if (Sse41.IsSupported) { if (Sse41.TestZ(vector, right)) { goto IL_00ca; } } else if ((Sse2.MoveMask(Sse2.AddSaturate(vector.AsUInt16(), right2).AsByte()) & 0xAAAA) == 0) { goto IL_00ca; } goto IL_0183; IL_0183: return num3; IL_00e7: num3 = num - ((nuint)pAsciiBuffer & num2); nuint num4 = elementCount - num; do { vector = Sse2.LoadVector128((short*)(pUtf16Buffer + num3)); Vector128 right3 = Sse2.LoadVector128((short*)(pUtf16Buffer + num3 + num / 2)); Vector128 vector3 = Sse2.Or(vector, right3); if (Sse41.IsSupported) { if (Sse41.TestZ(vector3, right)) { goto IL_015b; } } else if ((Sse2.MoveMask(Sse2.AddSaturate(vector3.AsUInt16(), right2).AsByte()) & 0xAAAA) == 0) { goto IL_015b; } if (Sse41.IsSupported) { if (!Sse41.TestZ(vector, right)) { break; } } else if (((uint)Sse2.MoveMask(Sse2.AddSaturate(vector.AsUInt16(), right2).AsByte()) & 0xAAAAu) != 0) { break; } vector2 = Sse2.PackUnsignedSaturate(vector, vector); Sse2.StoreScalar((ulong*)(pAsciiBuffer + num3), vector2.AsUInt64()); num3 += num / 2; break; IL_015b: vector2 = Sse2.PackUnsignedSaturate(vector, right3); Sse2.StoreAligned(pAsciiBuffer + num3, vector2); num3 += num; } while (num3 <= num4); goto IL_0183; IL_00ca: vector2 = Sse2.PackUnsignedSaturate(vector, vector); Sse2.StoreScalar((ulong*)(pAsciiBuffer + num3), vector2.AsUInt64()); goto IL_00e7; } public unsafe static nuint WidenAsciiToUtf16(byte* pAsciiBuffer, char* pUtf16Buffer, nuint elementCount) { nuint num = 0u; _ = BitConverter.IsLittleEndian; if (Sse2.IsSupported || AdvSimd.Arm64.IsSupported) { if (elementCount >= (uint)(2 * Unsafe.SizeOf>())) { num = WidenAsciiToUtf16_Intrinsified(pAsciiBuffer, pUtf16Buffer, elementCount); } } else if (Vector.IsHardwareAccelerated) { uint num2 = (uint)Unsafe.SizeOf>(); if (elementCount >= num2) { nuint num3 = elementCount - num2; do { Vector vector = Unsafe.ReadUnaligned>(pAsciiBuffer + num); if (Vector.LessThanAny(vector, Vector.Zero)) { break; } Vector.Widen(Vector.AsVectorByte(vector), out var low, out var high); Unsafe.WriteUnaligned(pUtf16Buffer + num, low); Unsafe.WriteUnaligned(pUtf16Buffer + num + Vector.Count, high); num += num2; } while (num <= num3); } } nuint num4 = elementCount - num; if (num4 < 4) { goto IL_00df; } nuint num5 = num + num4 - 4; uint num6; while (true) { num6 = Unsafe.ReadUnaligned(pAsciiBuffer + num); if (!AllBytesInUInt32AreAscii(num6)) { break; } WidenFourAsciiBytesToUtf16AndWriteToBuffer(ref pUtf16Buffer[num], num6); num += 4; if (num <= num5) { continue; } goto IL_00df; } goto IL_014f; IL_014d: return num; IL_014f: _ = BitConverter.IsLittleEndian; while (((byte)num6 & 0x80) == 0) { pUtf16Buffer[num] = (char)(byte)num6; num++; num6 >>= 8; } goto IL_014d; IL_00df: if (((uint)(int)num4 & 2u) != 0) { num6 = Unsafe.ReadUnaligned(pAsciiBuffer + num); if (!AllBytesInUInt32AreAscii(num6) && BitConverter.IsLittleEndian) { goto IL_014f; } _ = BitConverter.IsLittleEndian; pUtf16Buffer[num] = (char)(byte)num6; pUtf16Buffer[num + 1] = (char)(num6 >> 8); num += 2; } if (((uint)(int)num4 & (true ? 1u : 0u)) != 0) { num6 = pAsciiBuffer[num]; if (((byte)num6 & 0x80) == 0) { pUtf16Buffer[num] = (char)num6; num++; } } goto IL_014d; } private unsafe static nuint WidenAsciiToUtf16_Intrinsified(byte* pAsciiBuffer, char* pUtf16Buffer, nuint elementCount) { uint num = (uint)Unsafe.SizeOf>(); nuint num2 = num - 1; if (Sse2.IsSupported) { Vector128 vector = Sse2.LoadVector128(pAsciiBuffer); if (Sse2.MoveMask(vector) != 0) { return 0u; } Vector128 zero = Vector128.Zero; if (Sse2.IsSupported) { Vector128 source = Sse2.UnpackLow(vector, zero); Sse2.Store((byte*)pUtf16Buffer, source); nuint num3 = (num >> 1) - (((nuint)pUtf16Buffer >> 1) & (num2 >> 1)); nuint num4 = elementCount - num; char* ptr = pUtf16Buffer + num3; while (true) { if (Sse2.IsSupported) { vector = Sse2.LoadVector128(pAsciiBuffer + num3); bool flag = Sse2.MoveMask(vector) != 0; if (!flag) { if (!Sse2.IsSupported) { if (AdvSimd.Arm64.IsSupported) { } throw new PlatformNotSupportedException(); } Vector128 source2 = Sse2.UnpackLow(vector, zero); Sse2.StoreAligned((byte*)ptr, source2); Vector128 source3 = Sse2.UnpackHigh(vector, zero); Sse2.StoreAligned((byte*)ptr + num, source3); num3 += num; ptr += num; if (num3 <= num4) { continue; } } else if (!flag) { if (!Sse2.IsSupported) { break; } source = Sse2.UnpackLow(vector, zero); Sse2.StoreAligned((byte*)(pUtf16Buffer + num3), source); num3 += num / 2; } return num3; } if (AdvSimd.Arm64.IsSupported) { } throw new PlatformNotSupportedException(); } if (AdvSimd.Arm64.IsSupported) { } throw new PlatformNotSupportedException(); } if (AdvSimd.IsSupported) { } throw new PlatformNotSupportedException(); } if (AdvSimd.Arm64.IsSupported) { } throw new PlatformNotSupportedException(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void WidenFourAsciiBytesToUtf16AndWriteToBuffer(ref char outputBuffer, uint value) { if (Sse2.X64.IsSupported) { Vector128 left = Sse2.ConvertScalarToVector128UInt32(value).AsByte(); Vector128 value2 = Sse2.UnpackLow(left, Vector128.Zero).AsUInt64(); Unsafe.WriteUnaligned(ref Unsafe.As(ref outputBuffer), Sse2.X64.ConvertToUInt64(value2)); return; } if (AdvSimd.Arm64.IsSupported) { } _ = BitConverter.IsLittleEndian; outputBuffer = (char)(byte)value; value >>= 8; Unsafe.Add(ref outputBuffer, 1) = (char)(byte)value; value >>= 8; Unsafe.Add(ref outputBuffer, 2) = (char)(byte)value; value >>= 8; Unsafe.Add(ref outputBuffer, 3) = (char)value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool AllBytesInUInt32AreAscii(uint value) { return (value & 0x80808080u) == 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static uint CountNumberOfLeadingAsciiBytesFromUInt32WithSomeNonAsciiData(uint value) { _ = BitConverter.IsLittleEndian; return (uint)BitOperations.TrailingZeroCount(value & 0x80808080u) >> 3; } } internal sealed class CodePageDataItem { public int UIFamilyCodePage { get; } public string WebName { get; } public string HeaderName { get; } public string BodyName { get; } public string DisplayName { get; } public uint Flags { get; } internal CodePageDataItem(int uiFamilyCodePage, string webName, string headerName, string bodyName, string displayName, uint flags) { UIFamilyCodePage = uiFamilyCodePage; WebName = webName; HeaderName = headerName; BodyName = bodyName; DisplayName = displayName; Flags = flags; } } public abstract class Decoder { internal DecoderFallback _fallback; internal DecoderFallbackBuffer _fallbackBuffer; public DecoderFallback? Fallback { get { return _fallback; } set { if (value == null) { throw new ArgumentNullException("value"); } if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) { throw new ArgumentException(SR.Argument_FallbackBufferNotEmpty, "value"); } _fallback = value; _fallbackBuffer = null; } } public DecoderFallbackBuffer FallbackBuffer { get { if (_fallbackBuffer == null) { if (_fallback != null) { _fallbackBuffer = _fallback.CreateFallbackBuffer(); } else { _fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); } } return _fallbackBuffer; } } internal bool InternalHasFallbackBuffer => _fallbackBuffer != null; public virtual void Reset() { byte[] bytes = Array.Empty(); char[] chars = new char[GetCharCount(bytes, 0, 0, flush: true)]; GetChars(bytes, 0, 0, chars, 0, flush: true); _fallbackBuffer?.Reset(); } public abstract int GetCharCount(byte[] bytes, int index, int count); public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush) { return GetCharCount(bytes, index, count); } [CLSCompliant(false)] public unsafe virtual int GetCharCount(byte* bytes, int count, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } byte[] array = new byte[count]; for (int i = 0; i < count; i++) { array[i] = bytes[i]; } return GetCharCount(array, 0, count); } public unsafe virtual int GetCharCount(ReadOnlySpan bytes, bool flush) { fixed (byte* bytes2 = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return GetCharCount(bytes2, bytes.Length, flush); } } public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex); public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex); } [CLSCompliant(false)] public unsafe virtual int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { if (chars == null || bytes == null) { throw new ArgumentNullException((chars == null) ? "chars" : "bytes", SR.ArgumentNull_Array); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } byte[] array = new byte[byteCount]; for (int i = 0; i < byteCount; i++) { array[i] = bytes[i]; } char[] array2 = new char[charCount]; int chars2 = GetChars(array, 0, byteCount, array2, 0, flush); if (chars2 < charCount) { charCount = chars2; } for (int i = 0; i < charCount; i++) { chars[i] = array2[i]; } return charCount; } public unsafe virtual int GetChars(ReadOnlySpan bytes, Span chars, bool flush) { fixed (byte* bytes2 = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { fixed (char* chars2 = &MemoryMarshal.GetNonNullPinnableReference(chars)) { return GetChars(bytes2, bytes.Length, chars2, chars.Length, flush); } } } public virtual void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); } for (bytesUsed = byteCount; bytesUsed > 0; bytesUsed /= 2) { if (GetCharCount(bytes, byteIndex, bytesUsed, flush) <= charCount) { charsUsed = GetChars(bytes, byteIndex, bytesUsed, chars, charIndex, flush); completed = bytesUsed == byteCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0); return; } flush = false; } throw new ArgumentException(SR.Argument_ConversionOverflow); } [CLSCompliant(false)] public unsafe virtual void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (chars == null || bytes == null) { throw new ArgumentNullException((chars == null) ? "chars" : "bytes", SR.ArgumentNull_Array); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } for (bytesUsed = byteCount; bytesUsed > 0; bytesUsed /= 2) { if (GetCharCount(bytes, bytesUsed, flush) <= charCount) { charsUsed = GetChars(bytes, bytesUsed, chars, charCount, flush); completed = bytesUsed == byteCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0); return; } flush = false; } throw new ArgumentException(SR.Argument_ConversionOverflow); } public unsafe virtual void Convert(ReadOnlySpan bytes, Span chars, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { fixed (byte* bytes2 = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { fixed (char* chars2 = &MemoryMarshal.GetNonNullPinnableReference(chars)) { Convert(bytes2, bytes.Length, chars2, chars.Length, flush, out bytesUsed, out charsUsed, out completed); } } } } public sealed class DecoderExceptionFallback : DecoderFallback { internal static readonly DecoderExceptionFallback s_default = new DecoderExceptionFallback(); public override int MaxCharCount => 0; public override DecoderFallbackBuffer CreateFallbackBuffer() { return new DecoderExceptionFallbackBuffer(); } public override bool Equals([NotNullWhen(true)] object? value) { return value is DecoderExceptionFallback; } public override int GetHashCode() { return 879; } } public sealed class DecoderExceptionFallbackBuffer : DecoderFallbackBuffer { public override int Remaining => 0; public override bool Fallback(byte[] bytesUnknown, int index) { Throw(bytesUnknown, index); return true; } public override char GetNextChar() { return '\0'; } public override bool MovePrevious() { return false; } [DoesNotReturn] private static void Throw(byte[] bytesUnknown, int index) { if (bytesUnknown == null) { bytesUnknown = Array.Empty(); } StringBuilder stringBuilder = new StringBuilder(bytesUnknown.Length * 4); for (int i = 0; i < bytesUnknown.Length && i < 20; i++) { StringBuilder stringBuilder2 = stringBuilder; StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(2, 1, stringBuilder2); handler.AppendLiteral("["); handler.AppendFormatted(bytesUnknown[i], "X2"); handler.AppendLiteral("]"); stringBuilder2.Append(ref handler); } if (bytesUnknown.Length > 20) { stringBuilder.Append(" ..."); } throw new DecoderFallbackException(SR.Format(SR.Argument_InvalidCodePageBytesIndex, stringBuilder, index), bytesUnknown, index); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class DecoderFallbackException : ArgumentException { private readonly byte[] _bytesUnknown; private readonly int _index; public byte[]? BytesUnknown => _bytesUnknown; public int Index => _index; public DecoderFallbackException() : base(SR.Arg_ArgumentException) { base.HResult = -2147024809; } public DecoderFallbackException(string? message) : base(message) { base.HResult = -2147024809; } public DecoderFallbackException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2147024809; } public DecoderFallbackException(string? message, byte[]? bytesUnknown, int index) : base(message) { _bytesUnknown = bytesUnknown; _index = index; } private DecoderFallbackException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { } } public abstract class DecoderFallback { public static DecoderFallback ReplacementFallback => DecoderReplacementFallback.s_default; public static DecoderFallback ExceptionFallback => DecoderExceptionFallback.s_default; public abstract int MaxCharCount { get; } public abstract DecoderFallbackBuffer CreateFallbackBuffer(); } public abstract class DecoderFallbackBuffer { internal unsafe byte* byteStart; internal unsafe char* charEnd; internal Encoding _encoding; internal DecoderNLS _decoder; private int _originalByteCount; public abstract int Remaining { get; } public abstract bool Fallback(byte[] bytesUnknown, int index); public abstract char GetNextChar(); public abstract bool MovePrevious(); public virtual void Reset() { while (GetNextChar() != 0) { } } internal unsafe void InternalReset() { byteStart = null; Reset(); } internal unsafe void InternalInitialize(byte* byteStart, char* charEnd) { this.byteStart = byteStart; this.charEnd = charEnd; } internal static DecoderFallbackBuffer CreateAndInitialize(Encoding encoding, DecoderNLS decoder, int originalByteCount) { DecoderFallbackBuffer decoderFallbackBuffer = ((decoder == null) ? encoding.DecoderFallback.CreateFallbackBuffer() : decoder.FallbackBuffer); decoderFallbackBuffer._encoding = encoding; decoderFallbackBuffer._decoder = decoder; decoderFallbackBuffer._originalByteCount = originalByteCount; return decoderFallbackBuffer; } internal unsafe virtual bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars) { if (Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) { char* ptr = chars; bool flag = false; char nextChar; while ((nextChar = GetNextChar()) != 0) { if (char.IsSurrogate(nextChar)) { if (char.IsHighSurrogate(nextChar)) { if (flag) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); } flag = true; } else { if (!flag) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); } flag = false; } } if (ptr >= charEnd) { return false; } *(ptr++) = nextChar; } if (flag) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); } chars = ptr; } return true; } internal unsafe virtual int InternalFallback(byte[] bytes, byte* pBytes) { if (Fallback(bytes, (int)(pBytes - byteStart - bytes.Length))) { int num = 0; bool flag = false; char nextChar; while ((nextChar = GetNextChar()) != 0) { if (char.IsSurrogate(nextChar)) { if (char.IsHighSurrogate(nextChar)) { if (flag) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); } flag = true; } else { if (!flag) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); } flag = false; } } num++; } if (flag) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); } return num; } return 0; } internal int InternalFallbackGetCharCount(ReadOnlySpan remainingBytes, int fallbackLength) { if (!Fallback(remainingBytes.Slice(0, fallbackLength).ToArray(), _originalByteCount - remainingBytes.Length)) { return 0; } return DrainRemainingDataForGetCharCount(); } internal bool TryInternalFallbackGetChars(ReadOnlySpan remainingBytes, int fallbackLength, Span chars, out int charsWritten) { if (Fallback(remainingBytes.Slice(0, fallbackLength).ToArray(), _originalByteCount - remainingBytes.Length)) { return TryDrainRemainingDataForGetChars(chars, out charsWritten); } charsWritten = 0; return true; } private Rune GetNextRune() { char nextChar = GetNextChar(); if (!Rune.TryCreate(nextChar, out var result) && !Rune.TryCreate(nextChar, GetNextChar(), out result)) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); } return result; } internal int DrainRemainingDataForGetCharCount() { int num = 0; while (true) { Rune nextRune; Rune rune = (nextRune = GetNextRune()); if (rune.Value == 0) { break; } num += nextRune.Utf16SequenceLength; if (num < 0) { InternalReset(); Encoding.ThrowConversionOverflow(); } } return num; } internal bool TryDrainRemainingDataForGetChars(Span chars, out int charsWritten) { int length = chars.Length; while (true) { Rune nextRune; Rune rune = (nextRune = GetNextRune()); if (rune.Value == 0) { break; } if (nextRune.TryEncodeToUtf16(chars, out var charsWritten2)) { chars = chars.Slice(charsWritten2); continue; } InternalReset(); charsWritten = 0; return false; } charsWritten = length - chars.Length; return true; } [DoesNotReturn] internal static void ThrowLastBytesRecursive(byte[] bytesUnknown) { if (bytesUnknown == null) { bytesUnknown = Array.Empty(); } StringBuilder stringBuilder = new StringBuilder(bytesUnknown.Length * 3); int i; for (i = 0; i < bytesUnknown.Length && i < 20; i++) { if (stringBuilder.Length > 0) { stringBuilder.Append(' '); } StringBuilder stringBuilder2 = stringBuilder; StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(2, 1, stringBuilder2); handler.AppendLiteral("\\x"); handler.AppendFormatted(bytesUnknown[i], "X2"); stringBuilder2.Append(ref handler); } if (i == 20) { stringBuilder.Append(" ..."); } throw new ArgumentException(SR.Format(SR.Argument_RecursiveFallbackBytes, stringBuilder.ToString()), "bytesUnknown"); } } internal class DecoderNLS : Decoder { private readonly Encoding _encoding; private bool _mustFlush; internal bool _throwOnOverflow; internal int _bytesUsed; private int _leftoverBytes; private int _leftoverByteCount; public bool MustFlush => _mustFlush; internal virtual bool HasState => _leftoverByteCount != 0; internal bool HasLeftoverData => _leftoverByteCount != 0; internal DecoderNLS(Encoding encoding) { _encoding = encoding; _fallback = _encoding.DecoderFallback; Reset(); } public override void Reset() { ClearLeftoverData(); _fallbackBuffer?.Reset(); } public override int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, flush: false); } public unsafe override int GetCharCount(byte[] bytes, int index, int count, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } fixed (byte* ptr = &MemoryMarshal.GetReference(bytes)) { return GetCharCount(ptr + index, count, flush); } } public unsafe override int GetCharCount(byte* bytes, int count, bool flush) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } _mustFlush = flush; _throwOnOverflow = true; return _encoding.GetCharCount(bytes, count, this); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, flush: false); } public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } if (charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); } int charCount = chars.Length - charIndex; fixed (byte* ptr = &MemoryMarshal.GetReference(bytes)) { fixed (char* ptr2 = &MemoryMarshal.GetReference(chars)) { return GetChars(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, flush); } } } public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { if (chars == null || bytes == null) { throw new ArgumentNullException((chars == null) ? "chars" : "bytes", SR.ArgumentNull_Array); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } _mustFlush = flush; _throwOnOverflow = true; return _encoding.GetChars(bytes, byteCount, chars, charCount, this); } public unsafe override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); } fixed (byte* ptr = &MemoryMarshal.GetReference(bytes)) { fixed (char* ptr2 = &MemoryMarshal.GetReference(chars)) { Convert(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } public unsafe override void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (chars == null || bytes == null) { throw new ArgumentNullException((chars == null) ? "chars" : "bytes", SR.ArgumentNull_Array); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } _mustFlush = flush; _throwOnOverflow = false; _bytesUsed = 0; charsUsed = _encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = _bytesUsed; completed = bytesUsed == byteCount && (!flush || !HasState) && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0); } internal void ClearMustFlush() { _mustFlush = false; } internal ReadOnlySpan GetLeftoverData() { return MemoryMarshal.AsBytes(new ReadOnlySpan(ref _leftoverBytes, 1)).Slice(0, _leftoverByteCount); } internal void SetLeftoverData(ReadOnlySpan bytes) { bytes.CopyTo(MemoryMarshal.AsBytes(new Span(ref _leftoverBytes, 1))); _leftoverByteCount = bytes.Length; } internal void ClearLeftoverData() { _leftoverByteCount = 0; } internal int DrainLeftoverDataForGetCharCount(ReadOnlySpan bytes, out int bytesConsumed) { Span span = stackalloc byte[4]; span = span.Slice(0, ConcatInto(GetLeftoverData(), bytes, span)); int result = 0; Rune value; int bytesConsumed2; switch (_encoding.DecodeFirstRune(span, out value, out bytesConsumed2)) { case OperationStatus.Done: result = value.Utf16SequenceLength; break; case OperationStatus.NeedMoreData: if (!MustFlush) { break; } goto default; default: if (base.FallbackBuffer.Fallback(span.Slice(0, bytesConsumed2).ToArray(), -_leftoverByteCount)) { result = _fallbackBuffer.DrainRemainingDataForGetCharCount(); } break; } bytesConsumed = bytesConsumed2 - _leftoverByteCount; return result; } internal int DrainLeftoverDataForGetChars(ReadOnlySpan bytes, Span chars, out int bytesConsumed) { Span span = stackalloc byte[4]; span = span.Slice(0, ConcatInto(GetLeftoverData(), bytes, span)); int charsWritten = 0; bool flag = false; Rune value; int bytesConsumed2; switch (_encoding.DecodeFirstRune(span, out value, out bytesConsumed2)) { case OperationStatus.Done: if (!value.TryEncodeToUtf16(chars, out charsWritten)) { break; } goto IL_00aa; case OperationStatus.NeedMoreData: if (MustFlush) { goto default; } flag = true; goto IL_00aa; default: { if (base.FallbackBuffer.Fallback(span.Slice(0, bytesConsumed2).ToArray(), -_leftoverByteCount) && !_fallbackBuffer.TryDrainRemainingDataForGetChars(chars, out charsWritten)) { break; } goto IL_00aa; } IL_00aa: bytesConsumed = bytesConsumed2 - _leftoverByteCount; if (flag) { SetLeftoverData(span); } else { ClearLeftoverData(); } return charsWritten; } _encoding.ThrowCharsOverflow(this, nothingDecoded: true); throw null; } private static int ConcatInto(ReadOnlySpan srcLeft, ReadOnlySpan srcRight, Span dest) { int num = 0; int num2 = 0; while (true) { if (num2 < srcLeft.Length) { if ((uint)num >= (uint)dest.Length) { break; } dest[num++] = srcLeft[num2]; num2++; continue; } for (int i = 0; i < srcRight.Length; i++) { if ((uint)num >= (uint)dest.Length) { break; } dest[num++] = srcRight[i]; } break; } return num; } } public sealed class DecoderReplacementFallback : DecoderFallback { internal static readonly DecoderReplacementFallback s_default = new DecoderReplacementFallback(); private readonly string _strDefault; public string DefaultString => _strDefault; public override int MaxCharCount => _strDefault.Length; public DecoderReplacementFallback() : this("?") { } public DecoderReplacementFallback(string replacement) { if (replacement == null) { throw new ArgumentNullException("replacement"); } bool flag = false; foreach (char c in replacement) { if (char.IsSurrogate(c)) { if (char.IsHighSurrogate(c)) { if (flag) { break; } flag = true; continue; } if (!flag) { flag = true; break; } flag = false; } else if (flag) { break; } } if (flag) { throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequenceNoIndex, "replacement")); } _strDefault = replacement; } public override DecoderFallbackBuffer CreateFallbackBuffer() { return new DecoderReplacementFallbackBuffer(this); } public override bool Equals([NotNullWhen(true)] object? value) { if (value is DecoderReplacementFallback decoderReplacementFallback) { return _strDefault == decoderReplacementFallback._strDefault; } return false; } public override int GetHashCode() { return _strDefault.GetHashCode(); } } public sealed class DecoderReplacementFallbackBuffer : DecoderFallbackBuffer { private readonly string _strDefault; private int _fallbackCount = -1; private int _fallbackIndex = -1; public override int Remaining { get { if (_fallbackCount >= 0) { return _fallbackCount; } return 0; } } public DecoderReplacementFallbackBuffer(DecoderReplacementFallback fallback) { _strDefault = fallback.DefaultString; } public override bool Fallback(byte[] bytesUnknown, int index) { if (_fallbackCount >= 1) { DecoderFallbackBuffer.ThrowLastBytesRecursive(bytesUnknown); } if (_strDefault.Length == 0) { return false; } _fallbackCount = _strDefault.Length; _fallbackIndex = -1; return true; } public override char GetNextChar() { _fallbackCount--; _fallbackIndex++; if (_fallbackCount < 0) { return '\0'; } if (_fallbackCount == int.MaxValue) { _fallbackCount = -1; return '\0'; } return _strDefault[_fallbackIndex]; } public override bool MovePrevious() { if (_fallbackCount >= -1 && _fallbackIndex >= 0) { _fallbackIndex--; _fallbackCount++; return true; } return false; } public unsafe override void Reset() { _fallbackCount = -1; _fallbackIndex = -1; byteStart = null; } internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes) { return _strDefault.Length; } } public abstract class Encoder { internal EncoderFallback _fallback; internal EncoderFallbackBuffer _fallbackBuffer; public EncoderFallback? Fallback { get { return _fallback; } set { if (value == null) { throw new ArgumentNullException("value"); } if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) { throw new ArgumentException(SR.Argument_FallbackBufferNotEmpty, "value"); } _fallback = value; _fallbackBuffer = null; } } public EncoderFallbackBuffer FallbackBuffer { get { if (_fallbackBuffer == null) { if (_fallback != null) { _fallbackBuffer = _fallback.CreateFallbackBuffer(); } else { _fallbackBuffer = EncoderFallback.ReplacementFallback.CreateFallbackBuffer(); } } return _fallbackBuffer; } } internal bool InternalHasFallbackBuffer => _fallbackBuffer != null; public virtual void Reset() { char[] chars = Array.Empty(); byte[] bytes = new byte[GetByteCount(chars, 0, 0, flush: true)]; GetBytes(chars, 0, 0, bytes, 0, flush: true); if (_fallbackBuffer != null) { _fallbackBuffer.Reset(); } } public abstract int GetByteCount(char[] chars, int index, int count, bool flush); [CLSCompliant(false)] public unsafe virtual int GetByteCount(char* chars, int count, bool flush) { if (chars == null) { throw new ArgumentNullException("chars", SR.ArgumentNull_Array); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } char[] array = new char[count]; for (int i = 0; i < count; i++) { array[i] = chars[i]; } return GetByteCount(array, 0, count, flush); } public unsafe virtual int GetByteCount(ReadOnlySpan chars, bool flush) { fixed (char* chars2 = &MemoryMarshal.GetNonNullPinnableReference(chars)) { return GetByteCount(chars2, chars.Length, flush); } } public abstract int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush); [CLSCompliant(false)] public unsafe virtual int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } char[] array = new char[charCount]; for (int i = 0; i < charCount; i++) { array[i] = chars[i]; } byte[] array2 = new byte[byteCount]; int bytes2 = GetBytes(array, 0, charCount, array2, 0, flush); if (bytes2 < byteCount) { byteCount = bytes2; } for (int i = 0; i < byteCount; i++) { bytes[i] = array2[i]; } return byteCount; } public unsafe virtual int GetBytes(ReadOnlySpan chars, Span bytes, bool flush) { fixed (char* chars2 = &MemoryMarshal.GetNonNullPinnableReference(chars)) { fixed (byte* bytes2 = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return GetBytes(chars2, chars.Length, bytes2, bytes.Length, flush); } } } public virtual void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { if (chars == null || bytes == null) { throw new ArgumentNullException((chars == null) ? "chars" : "bytes", SR.ArgumentNull_Array); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } for (charsUsed = charCount; charsUsed > 0; charsUsed /= 2) { if (GetByteCount(chars, charIndex, charsUsed, flush) <= byteCount) { bytesUsed = GetBytes(chars, charIndex, charsUsed, bytes, byteIndex, flush); completed = charsUsed == charCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0); return; } flush = false; } throw new ArgumentException(SR.Argument_ConversionOverflow); } [CLSCompliant(false)] public unsafe virtual void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } for (charsUsed = charCount; charsUsed > 0; charsUsed /= 2) { if (GetByteCount(chars, charsUsed, flush) <= byteCount) { bytesUsed = GetBytes(chars, charsUsed, bytes, byteCount, flush); completed = charsUsed == charCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0); return; } flush = false; } throw new ArgumentException(SR.Argument_ConversionOverflow); } public unsafe virtual void Convert(ReadOnlySpan chars, Span bytes, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { fixed (char* chars2 = &MemoryMarshal.GetNonNullPinnableReference(chars)) { fixed (byte* bytes2 = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { Convert(chars2, chars.Length, bytes2, bytes.Length, flush, out charsUsed, out bytesUsed, out completed); } } } } public sealed class EncoderExceptionFallback : EncoderFallback { internal static readonly EncoderExceptionFallback s_default = new EncoderExceptionFallback(); public override int MaxCharCount => 0; public override EncoderFallbackBuffer CreateFallbackBuffer() { return new EncoderExceptionFallbackBuffer(); } public override bool Equals([NotNullWhen(true)] object? value) { return value is EncoderExceptionFallback; } public override int GetHashCode() { return 654; } } public sealed class EncoderExceptionFallbackBuffer : EncoderFallbackBuffer { public override int Remaining => 0; public override bool Fallback(char charUnknown, int index) { throw new EncoderFallbackException(SR.Format(SR.Argument_InvalidCodePageConversionIndex, (int)charUnknown, index), charUnknown, index); } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { if (!char.IsHighSurrogate(charUnknownHigh)) { throw new ArgumentOutOfRangeException("charUnknownHigh", SR.Format(SR.ArgumentOutOfRange_Range, 55296, 56319)); } if (!char.IsLowSurrogate(charUnknownLow)) { throw new ArgumentOutOfRangeException("charUnknownLow", SR.Format(SR.ArgumentOutOfRange_Range, 56320, 57343)); } int num = char.ConvertToUtf32(charUnknownHigh, charUnknownLow); throw new EncoderFallbackException(SR.Format(SR.Argument_InvalidCodePageConversionIndex, num, index), charUnknownHigh, charUnknownLow, index); } public override char GetNextChar() { return '\0'; } public override bool MovePrevious() { return false; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class EncoderFallbackException : ArgumentException { private readonly char _charUnknown; private readonly char _charUnknownHigh; private readonly char _charUnknownLow; private readonly int _index; public char CharUnknown => _charUnknown; public char CharUnknownHigh => _charUnknownHigh; public char CharUnknownLow => _charUnknownLow; public int Index => _index; public EncoderFallbackException() : base(SR.Arg_ArgumentException) { base.HResult = -2147024809; } public EncoderFallbackException(string? message) : base(message) { base.HResult = -2147024809; } public EncoderFallbackException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2147024809; } internal EncoderFallbackException(string message, char charUnknown, int index) : base(message) { _charUnknown = charUnknown; _index = index; } internal EncoderFallbackException(string message, char charUnknownHigh, char charUnknownLow, int index) : base(message) { if (!char.IsHighSurrogate(charUnknownHigh)) { throw new ArgumentOutOfRangeException("charUnknownHigh", SR.Format(SR.ArgumentOutOfRange_Range, 55296, 56319)); } if (!char.IsLowSurrogate(charUnknownLow)) { throw new ArgumentOutOfRangeException("CharUnknownLow", SR.Format(SR.ArgumentOutOfRange_Range, 56320, 57343)); } _charUnknownHigh = charUnknownHigh; _charUnknownLow = charUnknownLow; _index = index; } private EncoderFallbackException(SerializationInfo serializationInfo, StreamingContext streamingContext) : base(serializationInfo, streamingContext) { } public bool IsUnknownSurrogate() { return _charUnknownHigh != '\0'; } } public abstract class EncoderFallback { public static EncoderFallback ReplacementFallback => EncoderReplacementFallback.s_default; public static EncoderFallback ExceptionFallback => EncoderExceptionFallback.s_default; public abstract int MaxCharCount { get; } public abstract EncoderFallbackBuffer CreateFallbackBuffer(); } public abstract class EncoderFallbackBuffer { internal unsafe char* charStart; internal unsafe char* charEnd; internal EncoderNLS encoder; internal bool setEncoder; internal bool bUsedEncoder; internal bool bFallingBack; internal int iRecursionCount; private Encoding encoding; private int originalCharCount; public abstract int Remaining { get; } public abstract bool Fallback(char charUnknown, int index); public abstract bool Fallback(char charUnknownHigh, char charUnknownLow, int index); public abstract char GetNextChar(); public abstract bool MovePrevious(); public virtual void Reset() { while (GetNextChar() != 0) { } } internal unsafe void InternalReset() { charStart = null; bFallingBack = false; iRecursionCount = 0; Reset(); } internal unsafe void InternalInitialize(char* charStart, char* charEnd, EncoderNLS encoder, bool setEncoder) { this.charStart = charStart; this.charEnd = charEnd; this.encoder = encoder; this.setEncoder = setEncoder; bUsedEncoder = false; bFallingBack = false; iRecursionCount = 0; } internal static EncoderFallbackBuffer CreateAndInitialize(Encoding encoding, EncoderNLS encoder, int originalCharCount) { EncoderFallbackBuffer encoderFallbackBuffer = ((encoder == null) ? encoding.EncoderFallback.CreateFallbackBuffer() : encoder.FallbackBuffer); encoderFallbackBuffer.encoding = encoding; encoderFallbackBuffer.encoder = encoder; encoderFallbackBuffer.originalCharCount = originalCharCount; return encoderFallbackBuffer; } internal char InternalGetNextChar() { char nextChar = GetNextChar(); bFallingBack = nextChar != '\0'; if (nextChar == '\0') { iRecursionCount = 0; } return nextChar; } private bool InternalFallback(ReadOnlySpan chars, out int charsConsumed) { char c = chars[0]; char c2 = '\0'; if (!chars.IsEmpty) { c = chars[0]; if (chars.Length > 1) { c2 = chars[1]; } } int index = originalCharCount - chars.Length; if (!char.IsSurrogatePair(c, c2)) { charsConsumed = 1; return Fallback(c, index); } charsConsumed = 2; return Fallback(c, c2, index); } internal int InternalFallbackGetByteCount(ReadOnlySpan chars, out int charsConsumed) { int result = 0; if (InternalFallback(chars, out charsConsumed)) { result = DrainRemainingDataForGetByteCount(); } return result; } internal bool TryInternalFallbackGetBytes(ReadOnlySpan chars, Span bytes, out int charsConsumed, out int bytesWritten) { if (InternalFallback(chars, out charsConsumed)) { return TryDrainRemainingDataForGetBytes(bytes, out bytesWritten); } bytesWritten = 0; return true; } internal bool TryDrainRemainingDataForGetBytes(Span bytes, out int bytesWritten) { int length = bytes.Length; while (true) { Rune nextRune; Rune rune = (nextRune = GetNextRune()); if (rune.Value == 0) { break; } int bytesWritten2; switch (encoding.EncodeRune(nextRune, bytes, out bytesWritten2)) { case OperationStatus.Done: bytes = bytes.Slice(bytesWritten2); break; case OperationStatus.DestinationTooSmall: { for (int i = 0; i < nextRune.Utf16SequenceLength; i++) { MovePrevious(); } bytesWritten = length - bytes.Length; return false; } case OperationStatus.InvalidData: ThrowLastCharRecursive(nextRune.Value); break; } } bytesWritten = length - bytes.Length; return true; } internal int DrainRemainingDataForGetByteCount() { int num = 0; while (true) { Rune nextRune; Rune rune = (nextRune = GetNextRune()); if (rune.Value == 0) { break; } if (!encoding.TryGetByteCount(nextRune, out var byteCount)) { ThrowLastCharRecursive(nextRune.Value); } num += byteCount; if (num < 0) { InternalReset(); Encoding.ThrowConversionOverflow(); } } return num; } private Rune GetNextRune() { char nextChar = GetNextChar(); if (Rune.TryCreate(nextChar, out var result) || Rune.TryCreate(nextChar, GetNextChar(), out result)) { return result; } throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); } internal unsafe virtual bool InternalFallback(char ch, ref char* chars) { int index = (int)(chars - charStart) - 1; if (char.IsHighSurrogate(ch)) { if (chars >= charEnd) { if (encoder != null && !encoder.MustFlush) { if (setEncoder) { bUsedEncoder = true; encoder._charLeftOver = ch; } bFallingBack = false; return false; } } else { char c = *chars; if (char.IsLowSurrogate(c)) { if (bFallingBack && iRecursionCount++ > 250) { ThrowLastCharRecursive(char.ConvertToUtf32(ch, c)); } chars++; bFallingBack = Fallback(ch, c, index); return bFallingBack; } } } if (bFallingBack && iRecursionCount++ > 250) { ThrowLastCharRecursive(ch); } bFallingBack = Fallback(ch, index); return bFallingBack; } [DoesNotReturn] internal static void ThrowLastCharRecursive(int charRecursive) { throw new ArgumentException(SR.Format(SR.Argument_RecursiveFallback, charRecursive), "chars"); } } internal sealed class EncoderLatin1BestFitFallback : EncoderFallback { internal static readonly EncoderLatin1BestFitFallback SingletonInstance = new EncoderLatin1BestFitFallback(); public override int MaxCharCount => 1; private EncoderLatin1BestFitFallback() { } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new EncoderLatin1BestFitFallbackBuffer(); } } internal sealed class EncoderLatin1BestFitFallbackBuffer : EncoderFallbackBuffer { private char _cBestFit; private int _iCount = -1; private int _iSize; private static readonly char[] s_arrayCharBestFit = new char[604] { 'Ā', 'A', 'ā', 'a', 'Ă', 'A', 'ă', 'a', 'Ą', 'A', 'ą', 'a', 'Ć', 'C', 'ć', 'c', 'Ĉ', 'C', 'ĉ', 'c', 'Ċ', 'C', 'ċ', 'c', 'Č', 'C', 'č', 'c', 'Ď', 'D', 'ď', 'd', 'Đ', 'D', 'đ', 'd', 'Ē', 'E', 'ē', 'e', 'Ĕ', 'E', 'ĕ', 'e', 'Ė', 'E', 'ė', 'e', 'Ę', 'E', 'ę', 'e', 'Ě', 'E', 'ě', 'e', 'Ĝ', 'G', 'ĝ', 'g', 'Ğ', 'G', 'ğ', 'g', 'Ġ', 'G', 'ġ', 'g', 'Ģ', 'G', 'ģ', 'g', 'Ĥ', 'H', 'ĥ', 'h', 'Ħ', 'H', 'ħ', 'h', 'Ĩ', 'I', 'ĩ', 'i', 'Ī', 'I', 'ī', 'i', 'Ĭ', 'I', 'ĭ', 'i', 'Į', 'I', 'į', 'i', 'İ', 'I', 'ı', 'i', 'Ĵ', 'J', 'ĵ', 'j', 'Ķ', 'K', 'ķ', 'k', 'Ĺ', 'L', 'ĺ', 'l', 'Ļ', 'L', 'ļ', 'l', 'Ľ', 'L', 'ľ', 'l', 'Ł', 'L', 'ł', 'l', 'Ń', 'N', 'ń', 'n', 'Ņ', 'N', 'ņ', 'n', 'Ň', 'N', 'ň', 'n', 'Ō', 'O', 'ō', 'o', 'Ŏ', 'O', 'ŏ', 'o', 'Ő', 'O', 'ő', 'o', 'Œ', 'O', 'œ', 'o', 'Ŕ', 'R', 'ŕ', 'r', 'Ŗ', 'R', 'ŗ', 'r', 'Ř', 'R', 'ř', 'r', 'Ś', 'S', 'ś', 's', 'Ŝ', 'S', 'ŝ', 's', 'Ş', 'S', 'ş', 's', 'Š', 'S', 'š', 's', 'Ţ', 'T', 'ţ', 't', 'Ť', 'T', 'ť', 't', 'Ŧ', 'T', 'ŧ', 't', 'Ũ', 'U', 'ũ', 'u', 'Ū', 'U', 'ū', 'u', 'Ŭ', 'U', 'ŭ', 'u', 'Ů', 'U', 'ů', 'u', 'Ű', 'U', 'ű', 'u', 'Ų', 'U', 'ų', 'u', 'Ŵ', 'W', 'ŵ', 'w', 'Ŷ', 'Y', 'ŷ', 'y', 'Ÿ', 'Y', 'Ź', 'Z', 'ź', 'z', 'Ż', 'Z', 'ż', 'z', 'Ž', 'Z', 'ž', 'z', 'ƀ', 'b', 'Ɖ', 'D', 'Ƒ', 'F', 'ƒ', 'f', 'Ɨ', 'I', 'ƚ', 'l', 'Ɵ', 'O', 'Ơ', 'O', 'ơ', 'o', 'ƫ', 't', 'Ʈ', 'T', 'Ư', 'U', 'ư', 'u', 'ƶ', 'z', 'Ǎ', 'A', 'ǎ', 'a', 'Ǐ', 'I', 'ǐ', 'i', 'Ǒ', 'O', 'ǒ', 'o', 'Ǔ', 'U', 'ǔ', 'u', 'Ǖ', 'U', 'ǖ', 'u', 'Ǘ', 'U', 'ǘ', 'u', 'Ǚ', 'U', 'ǚ', 'u', 'Ǜ', 'U', 'ǜ', 'u', 'Ǟ', 'A', 'ǟ', 'a', 'Ǥ', 'G', 'ǥ', 'g', 'Ǧ', 'G', 'ǧ', 'g', 'Ǩ', 'K', 'ǩ', 'k', 'Ǫ', 'O', 'ǫ', 'o', 'Ǭ', 'O', 'ǭ', 'o', 'ǰ', 'j', 'ɡ', 'g', 'ʹ', '\'', 'ʺ', '"', 'ʼ', '\'', '\u02c4', '^', 'ˆ', '^', 'ˈ', '\'', 'ˉ', '?', 'ˊ', '?', 'ˋ', '`', 'ˍ', '_', '\u02da', '?', '\u02dc', '~', '\u0300', '`', '\u0302', '^', '\u0303', '~', '\u030e', '"', '\u0331', '_', '\u0332', '_', '\u2000', ' ', '\u2001', ' ', '\u2002', ' ', '\u2003', ' ', '\u2004', ' ', '\u2005', ' ', '\u2006', ' ', '‐', '-', '‑', '-', '–', '-', '—', '-', '‘', '\'', '’', '\'', '‚', ',', '“', '"', '”', '"', '„', '"', '†', '?', '‡', '?', '•', '.', '…', '.', '‰', '?', '′', '\'', '‵', '`', '‹', '<', '›', '>', '™', 'T', '!', '!', '"', '"', '#', '#', '$', '$', '%', '%', '&', '&', ''', '\'', '(', '(', ')', ')', '*', '*', '+', '+', ',', ',', '-', '-', '.', '.', '/', '/', '0', '0', '1', '1', '2', '2', '3', '3', '4', '4', '5', '5', '6', '6', '7', '7', '8', '8', '9', '9', ':', ':', ';', ';', '<', '<', '=', '=', '>', '>', '?', '?', '@', '@', 'A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'G', 'G', 'H', 'H', 'I', 'I', 'J', 'J', 'K', 'K', 'L', 'L', 'M', 'M', 'N', 'N', 'O', 'O', 'P', 'P', 'Q', 'Q', 'R', 'R', 'S', 'S', 'T', 'T', 'U', 'U', 'V', 'V', 'W', 'W', 'X', 'X', 'Y', 'Y', 'Z', 'Z', '[', '[', '\', '\\', ']', ']', '\uff3e', '^', '\uff3f', '_', '\uff40', '`', 'a', 'a', 'b', 'b', 'c', 'c', 'd', 'd', 'e', 'e', 'f', 'f', 'g', 'g', 'h', 'h', 'i', 'i', 'j', 'j', 'k', 'k', 'l', 'l', 'm', 'm', 'n', 'n', 'o', 'o', 'p', 'p', 'q', 'q', 'r', 'r', 's', 's', 't', 't', 'u', 'u', 'v', 'v', 'w', 'w', 'x', 'x', 'y', 'y', 'z', 'z', '{', '{', '|', '|', '}', '}', '~', '~' }; public override int Remaining { get { if (_iCount <= 0) { return 0; } return _iCount; } } public override bool Fallback(char charUnknown, int index) { _iCount = (_iSize = 1); _cBestFit = TryBestFit(charUnknown); if (_cBestFit == '\0') { _cBestFit = '?'; } return true; } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { if (!char.IsHighSurrogate(charUnknownHigh)) { throw new ArgumentOutOfRangeException("charUnknownHigh", SR.Format(SR.ArgumentOutOfRange_Range, 55296, 56319)); } if (!char.IsLowSurrogate(charUnknownLow)) { throw new ArgumentOutOfRangeException("charUnknownLow", SR.Format(SR.ArgumentOutOfRange_Range, 56320, 57343)); } _cBestFit = '?'; _iCount = (_iSize = 2); return true; } public override char GetNextChar() { _iCount--; if (_iCount < 0) { return '\0'; } if (_iCount == int.MaxValue) { _iCount = -1; return '\0'; } return _cBestFit; } public override bool MovePrevious() { if (_iCount >= 0) { _iCount++; } if (_iCount >= 0) { return _iCount <= _iSize; } return false; } public unsafe override void Reset() { _iCount = -1; charStart = null; bFallingBack = false; } private static char TryBestFit(char cUnknown) { int num = 0; int num2 = s_arrayCharBestFit.Length; int num3; while ((num3 = num2 - num) > 6) { int num4 = (num3 / 2 + num) & 0xFFFE; char c = s_arrayCharBestFit[num4]; if (c == cUnknown) { return s_arrayCharBestFit[num4 + 1]; } if (c < cUnknown) { num = num4; } else { num2 = num4; } } for (int num4 = num; num4 < num2; num4 += 2) { if (s_arrayCharBestFit[num4] == cUnknown) { return s_arrayCharBestFit[num4 + 1]; } } return '\0'; } } internal class EncoderNLS : Encoder { internal char _charLeftOver; private readonly Encoding _encoding; private bool _mustFlush; internal bool _throwOnOverflow; internal int _charsUsed; public Encoding Encoding => _encoding; public bool MustFlush => _mustFlush; internal bool HasLeftoverData { get { if (_charLeftOver == '\0') { if (_fallbackBuffer != null) { return _fallbackBuffer.Remaining > 0; } return false; } return true; } } internal virtual bool HasState => _charLeftOver != '\0'; internal EncoderNLS(Encoding encoding) { _encoding = encoding; _fallback = _encoding.EncoderFallback; Reset(); } public override void Reset() { _charLeftOver = '\0'; if (_fallbackBuffer != null) { _fallbackBuffer.Reset(); } } public unsafe override int GetByteCount(char[] chars, int index, int count, bool flush) { if (chars == null) { throw new ArgumentNullException("chars", SR.ArgumentNull_Array); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - index < count) { throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); } int num = -1; fixed (char* ptr = &MemoryMarshal.GetReference(chars)) { num = GetByteCount(ptr + index, count, flush); } return num; } public unsafe override int GetByteCount(char* chars, int count, bool flush) { if (chars == null) { throw new ArgumentNullException("chars", SR.ArgumentNull_Array); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } _mustFlush = flush; _throwOnOverflow = true; return _encoding.GetByteCount(chars, count, this); } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { if (chars == null || bytes == null) { throw new ArgumentNullException((chars == null) ? "chars" : "bytes", SR.ArgumentNull_Array); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); } int byteCount = bytes.Length - byteIndex; fixed (char* ptr = &MemoryMarshal.GetReference(chars)) { fixed (byte* ptr2 = &MemoryMarshal.GetReference(bytes)) { return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, flush); } } } public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { if (chars == null || bytes == null) { throw new ArgumentNullException((chars == null) ? "chars" : "bytes", SR.ArgumentNull_Array); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } _mustFlush = flush; _throwOnOverflow = true; return _encoding.GetBytes(chars, charCount, bytes, byteCount, this); } public unsafe override void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { if (chars == null || bytes == null) { throw new ArgumentNullException((chars == null) ? "chars" : "bytes", SR.ArgumentNull_Array); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } fixed (char* ptr = &MemoryMarshal.GetReference(chars)) { fixed (byte* ptr2 = &MemoryMarshal.GetReference(bytes)) { Convert(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed); } } } public unsafe override void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } _mustFlush = flush; _throwOnOverflow = false; _charsUsed = 0; bytesUsed = _encoding.GetBytes(chars, charCount, bytes, byteCount, this); charsUsed = _charsUsed; completed = charsUsed == charCount && (!flush || !HasState) && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0); } internal void ClearMustFlush() { _mustFlush = false; } internal int DrainLeftoverDataForGetByteCount(ReadOnlySpan chars, out int charsConsumed) { if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) { throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, Encoding.EncodingName, _fallbackBuffer.GetType())); } charsConsumed = 0; if (_charLeftOver == '\0') { return 0; } char c = '\0'; if (chars.IsEmpty) { if (!MustFlush) { return 0; } } else { c = chars[0]; } if (Rune.TryCreate(_charLeftOver, c, out var result)) { charsConsumed = 1; if (_encoding.TryGetByteCount(result, out var byteCount)) { return byteCount; } bool flag = base.FallbackBuffer.Fallback(_charLeftOver, c, -1); } else { bool flag = base.FallbackBuffer.Fallback(_charLeftOver, -1); } return _fallbackBuffer.DrainRemainingDataForGetByteCount(); } internal bool TryDrainLeftoverDataForGetBytes(ReadOnlySpan chars, Span bytes, out int charsConsumed, out int bytesWritten) { charsConsumed = 0; bytesWritten = 0; if (_charLeftOver != 0) { char c = '\0'; if (chars.IsEmpty) { if (!MustFlush) { charsConsumed = 0; bytesWritten = 0; return true; } } else { c = chars[0]; } char charLeftOver = _charLeftOver; _charLeftOver = '\0'; if (Rune.TryCreate(charLeftOver, c, out var result)) { charsConsumed = 1; switch (_encoding.EncodeRune(result, bytes, out bytesWritten)) { case OperationStatus.Done: return true; case OperationStatus.DestinationTooSmall: _encoding.ThrowBytesOverflow(this, nothingEncoded: true); break; case OperationStatus.InvalidData: base.FallbackBuffer.Fallback(charLeftOver, c, -1); break; } } else { base.FallbackBuffer.Fallback(charLeftOver, -1); } } if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) { return _fallbackBuffer.TryDrainRemainingDataForGetBytes(bytes, out bytesWritten); } return true; } } public sealed class EncoderReplacementFallback : EncoderFallback { internal static readonly EncoderReplacementFallback s_default = new EncoderReplacementFallback(); private readonly string _strDefault; public string DefaultString => _strDefault; public override int MaxCharCount => _strDefault.Length; public EncoderReplacementFallback() : this("?") { } public EncoderReplacementFallback(string replacement) { if (replacement == null) { throw new ArgumentNullException("replacement"); } bool flag = false; foreach (char c in replacement) { if (char.IsSurrogate(c)) { if (char.IsHighSurrogate(c)) { if (flag) { break; } flag = true; continue; } if (!flag) { flag = true; break; } flag = false; } else if (flag) { break; } } if (flag) { throw new ArgumentException(SR.Format(SR.Argument_InvalidCharSequenceNoIndex, "replacement")); } _strDefault = replacement; } public override EncoderFallbackBuffer CreateFallbackBuffer() { return new EncoderReplacementFallbackBuffer(this); } public override bool Equals([NotNullWhen(true)] object? value) { if (value is EncoderReplacementFallback encoderReplacementFallback) { return _strDefault == encoderReplacementFallback._strDefault; } return false; } public override int GetHashCode() { return _strDefault.GetHashCode(); } } public sealed class EncoderReplacementFallbackBuffer : EncoderFallbackBuffer { private readonly string _strDefault; private int _fallbackCount = -1; private int _fallbackIndex = -1; public override int Remaining { get { if (_fallbackCount >= 0) { return _fallbackCount; } return 0; } } public EncoderReplacementFallbackBuffer(EncoderReplacementFallback fallback) { _strDefault = fallback.DefaultString + fallback.DefaultString; } public override bool Fallback(char charUnknown, int index) { if (_fallbackCount >= 1) { if (char.IsHighSurrogate(charUnknown) && _fallbackCount >= 0 && char.IsLowSurrogate(_strDefault[_fallbackIndex + 1])) { EncoderFallbackBuffer.ThrowLastCharRecursive(char.ConvertToUtf32(charUnknown, _strDefault[_fallbackIndex + 1])); } EncoderFallbackBuffer.ThrowLastCharRecursive(charUnknown); } _fallbackCount = _strDefault.Length / 2; _fallbackIndex = -1; return _fallbackCount != 0; } public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index) { if (!char.IsHighSurrogate(charUnknownHigh)) { throw new ArgumentOutOfRangeException("charUnknownHigh", SR.Format(SR.ArgumentOutOfRange_Range, 55296, 56319)); } if (!char.IsLowSurrogate(charUnknownLow)) { throw new ArgumentOutOfRangeException("charUnknownLow", SR.Format(SR.ArgumentOutOfRange_Range, 56320, 57343)); } if (_fallbackCount >= 1) { EncoderFallbackBuffer.ThrowLastCharRecursive(char.ConvertToUtf32(charUnknownHigh, charUnknownLow)); } _fallbackCount = _strDefault.Length; _fallbackIndex = -1; return _fallbackCount != 0; } public override char GetNextChar() { _fallbackCount--; _fallbackIndex++; if (_fallbackCount < 0) { return '\0'; } if (_fallbackCount == int.MaxValue) { _fallbackCount = -1; return '\0'; } return _strDefault[_fallbackIndex]; } public override bool MovePrevious() { if (_fallbackCount >= -1 && _fallbackIndex >= 0) { _fallbackIndex--; _fallbackCount++; return true; } return false; } public unsafe override void Reset() { _fallbackCount = -1; _fallbackIndex = 0; charStart = null; bFallingBack = false; } } public abstract class Encoding : ICloneable { internal sealed class DefaultEncoder : Encoder, IObjectReference { private readonly Encoding _encoding; public DefaultEncoder(Encoding encoding) { _encoding = encoding; } public object GetRealObject(StreamingContext context) { throw new PlatformNotSupportedException(); } public override int GetByteCount(char[] chars, int index, int count, bool flush) { return _encoding.GetByteCount(chars, index, count); } public unsafe override int GetByteCount(char* chars, int count, bool flush) { return _encoding.GetByteCount(chars, count); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush) { return _encoding.GetBytes(chars, charIndex, charCount, bytes, byteIndex); } public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush) { return _encoding.GetBytes(chars, charCount, bytes, byteCount); } } internal sealed class DefaultDecoder : Decoder, IObjectReference { private readonly Encoding _encoding; public DefaultDecoder(Encoding encoding) { _encoding = encoding; } public object GetRealObject(StreamingContext context) { throw new PlatformNotSupportedException(); } public override int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, flush: false); } public override int GetCharCount(byte[] bytes, int index, int count, bool flush) { return _encoding.GetCharCount(bytes, index, count); } public unsafe override int GetCharCount(byte* bytes, int count, bool flush) { return _encoding.GetCharCount(bytes, count); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, flush: false); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { return _encoding.GetChars(bytes, byteIndex, byteCount, chars, charIndex); } public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { return _encoding.GetChars(bytes, byteCount, chars, charCount); } } internal sealed class EncodingCharBuffer { private unsafe char* _chars; private unsafe readonly char* _charStart; private unsafe readonly char* _charEnd; private int _charCountResult; private readonly Encoding _enc; private readonly DecoderNLS _decoder; private unsafe readonly byte* _byteStart; private unsafe readonly byte* _byteEnd; private unsafe byte* _bytes; private readonly DecoderFallbackBuffer _fallbackBuffer; internal unsafe bool MoreData => _bytes < _byteEnd; internal unsafe int BytesUsed => (int)(_bytes - _byteStart); internal int Count => _charCountResult; internal unsafe EncodingCharBuffer(Encoding enc, DecoderNLS decoder, char* charStart, int charCount, byte* byteStart, int byteCount) { _enc = enc; _decoder = decoder; _chars = charStart; _charStart = charStart; _charEnd = charStart + charCount; _byteStart = byteStart; _bytes = byteStart; _byteEnd = byteStart + byteCount; if (_decoder == null) { _fallbackBuffer = enc.DecoderFallback.CreateFallbackBuffer(); } else { _fallbackBuffer = _decoder.FallbackBuffer; } _fallbackBuffer.InternalInitialize(_bytes, _charEnd); } internal unsafe bool AddChar(char ch, int numBytes) { if (_chars != null) { if (_chars >= _charEnd) { _bytes -= numBytes; _enc.ThrowCharsOverflow(_decoder, _bytes <= _byteStart); return false; } *(_chars++) = ch; } _charCountResult++; return true; } internal bool AddChar(char ch) { return AddChar(ch, 1); } internal unsafe void AdjustBytes(int count) { _bytes += count; } internal unsafe byte GetNextByte() { if (_bytes >= _byteEnd) { return 0; } return *(_bytes++); } internal bool Fallback(byte fallbackByte) { byte[] byteBuffer = new byte[1] { fallbackByte }; return Fallback(byteBuffer); } internal unsafe bool Fallback(byte[] byteBuffer) { if (_chars != null) { char* chars = _chars; if (!_fallbackBuffer.InternalFallback(byteBuffer, _bytes, ref _chars)) { _bytes -= byteBuffer.Length; _fallbackBuffer.InternalReset(); _enc.ThrowCharsOverflow(_decoder, _chars == _charStart); return false; } _charCountResult += (int)(_chars - chars); } else { _charCountResult += _fallbackBuffer.InternalFallback(byteBuffer, _bytes); } return true; } } internal sealed class EncodingByteBuffer { private unsafe byte* _bytes; private unsafe readonly byte* _byteStart; private unsafe readonly byte* _byteEnd; private unsafe char* _chars; private unsafe readonly char* _charStart; private unsafe readonly char* _charEnd; private int _byteCountResult; private readonly Encoding _enc; private readonly EncoderNLS _encoder; internal EncoderFallbackBuffer fallbackBuffer; internal unsafe bool MoreData { get { if (fallbackBuffer.Remaining <= 0) { return _chars < _charEnd; } return true; } } internal unsafe int CharsUsed => (int)(_chars - _charStart); internal int Count => _byteCountResult; internal unsafe EncodingByteBuffer(Encoding inEncoding, EncoderNLS inEncoder, byte* inByteStart, int inByteCount, char* inCharStart, int inCharCount) { _enc = inEncoding; _encoder = inEncoder; _charStart = inCharStart; _chars = inCharStart; _charEnd = inCharStart + inCharCount; _bytes = inByteStart; _byteStart = inByteStart; _byteEnd = inByteStart + inByteCount; if (_encoder == null) { fallbackBuffer = _enc.EncoderFallback.CreateFallbackBuffer(); } else { fallbackBuffer = _encoder.FallbackBuffer; if (_encoder._throwOnOverflow && _encoder.InternalHasFallbackBuffer && fallbackBuffer.Remaining > 0) { throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, _encoder.Encoding.EncodingName, _encoder.Fallback.GetType())); } } fallbackBuffer.InternalInitialize(_chars, _charEnd, _encoder, _bytes != null); } internal unsafe bool AddByte(byte b, int moreBytesExpected) { if (_bytes != null) { if (_bytes >= _byteEnd - moreBytesExpected) { MovePrevious(bThrow: true); return false; } *(_bytes++) = b; } _byteCountResult++; return true; } internal bool AddByte(byte b1) { return AddByte(b1, 0); } internal bool AddByte(byte b1, byte b2) { return AddByte(b1, b2, 0); } internal bool AddByte(byte b1, byte b2, int moreBytesExpected) { if (AddByte(b1, 1 + moreBytesExpected)) { return AddByte(b2, moreBytesExpected); } return false; } internal unsafe void MovePrevious(bool bThrow) { if (fallbackBuffer.bFallingBack) { fallbackBuffer.MovePrevious(); } else if (_chars > _charStart) { _chars--; } if (bThrow) { _enc.ThrowBytesOverflow(_encoder, _bytes == _byteStart); } } internal unsafe char GetNextChar() { char c = fallbackBuffer.InternalGetNextChar(); if (c == '\0' && _chars < _charEnd) { c = *(_chars++); } return c; } } private static readonly UTF8Encoding.UTF8EncodingSealed s_defaultEncoding = new UTF8Encoding.UTF8EncodingSealed(encoderShouldEmitUTF8Identifier: false); internal int _codePage; internal CodePageDataItem _dataItem; [OptionalField(VersionAdded = 2)] private bool _isReadOnly = true; internal EncoderFallback encoderFallback; internal DecoderFallback decoderFallback; public static Encoding Default => s_defaultEncoding; public virtual ReadOnlySpan Preamble => GetPreamble(); public virtual string BodyName { get { if (_dataItem == null) { GetDataItem(); } return _dataItem.BodyName; } } public virtual string EncodingName { get { if (_dataItem == null) { GetDataItem(); } return _dataItem.DisplayName; } } public virtual string HeaderName { get { if (_dataItem == null) { GetDataItem(); } return _dataItem.HeaderName; } } public virtual string WebName { get { if (_dataItem == null) { GetDataItem(); } return _dataItem.WebName; } } public virtual int WindowsCodePage { get { if (_dataItem == null) { GetDataItem(); } return _dataItem.UIFamilyCodePage; } } public virtual bool IsBrowserDisplay { get { if (_dataItem == null) { GetDataItem(); } return (_dataItem.Flags & 2) != 0; } } public virtual bool IsBrowserSave { get { if (_dataItem == null) { GetDataItem(); } return (_dataItem.Flags & 0x200) != 0; } } public virtual bool IsMailNewsDisplay { get { if (_dataItem == null) { GetDataItem(); } return (_dataItem.Flags & 1) != 0; } } public virtual bool IsMailNewsSave { get { if (_dataItem == null) { GetDataItem(); } return (_dataItem.Flags & 0x100) != 0; } } public virtual bool IsSingleByte => false; public EncoderFallback EncoderFallback { get { return encoderFallback; } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } encoderFallback = value; } } public DecoderFallback DecoderFallback { get { return decoderFallback; } set { if (IsReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } if (value == null) { throw new ArgumentNullException("value"); } decoderFallback = value; } } public bool IsReadOnly { get { return _isReadOnly; } private protected set { _isReadOnly = value; } } public static Encoding ASCII => ASCIIEncoding.s_default; public static Encoding Latin1 => Latin1Encoding.s_default; public virtual int CodePage => _codePage; internal bool IsUTF8CodePage => CodePage == 65001; public static Encoding Unicode => UnicodeEncoding.s_littleEndianDefault; public static Encoding BigEndianUnicode => UnicodeEncoding.s_bigEndianDefault; [Obsolete("The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead.", DiagnosticId = "SYSLIB0001", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public static Encoding UTF7 => UTF7Encoding.s_default; public static Encoding UTF8 => UTF8Encoding.s_default; public static Encoding UTF32 => UTF32Encoding.s_default; private static Encoding BigEndianUTF32 => UTF32Encoding.s_bigEndianDefault; protected Encoding() : this(0) { } protected Encoding(int codePage) { if (codePage < 0) { throw new ArgumentOutOfRangeException("codePage"); } _codePage = codePage; SetDefaultFallbacks(); } protected Encoding(int codePage, EncoderFallback? encoderFallback, DecoderFallback? decoderFallback) { if (codePage < 0) { throw new ArgumentOutOfRangeException("codePage"); } _codePage = codePage; this.encoderFallback = encoderFallback ?? System.Text.EncoderFallback.ReplacementFallback; this.decoderFallback = decoderFallback ?? System.Text.DecoderFallback.ReplacementFallback; } [MemberNotNull("encoderFallback")] [MemberNotNull("decoderFallback")] internal virtual void SetDefaultFallbacks() { encoderFallback = System.Text.EncoderFallback.ReplacementFallback; decoderFallback = System.Text.DecoderFallback.ReplacementFallback; } public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes) { if (bytes == null) { throw new ArgumentNullException("bytes"); } return Convert(srcEncoding, dstEncoding, bytes, 0, bytes.Length); } public static byte[] Convert(Encoding srcEncoding, Encoding dstEncoding, byte[] bytes, int index, int count) { if (srcEncoding == null || dstEncoding == null) { throw new ArgumentNullException((srcEncoding == null) ? "srcEncoding" : "dstEncoding", SR.ArgumentNull_Array); } if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } return dstEncoding.GetBytes(srcEncoding.GetChars(bytes, index, count)); } public static void RegisterProvider(EncodingProvider provider) { EncodingProvider.AddProvider(provider); } public static Encoding GetEncoding(int codepage) { Encoding encoding = FilterDisallowedEncodings(EncodingProvider.GetEncodingFromProvider(codepage)); if (encoding != null) { return encoding; } switch (codepage) { case 0: return Default; case 1200: return Unicode; case 1201: return BigEndianUnicode; case 12000: return UTF32; case 12001: return BigEndianUTF32; case 65001: return UTF8; case 20127: return ASCII; case 28591: return Latin1; case 1: case 2: case 3: case 42: throw new ArgumentException(SR.Format(SR.Argument_CodepageNotSupported, codepage), "codepage"); case 65000: { if (LocalAppContextSwitches.EnableUnsafeUTF7Encoding) { return UTF7; } string p = string.Format(CultureInfo.InvariantCulture, "https://aka.ms/dotnet-warnings/{0}", "SYSLIB0001"); string message = SR.Format(SR.Encoding_UTF7_Disabled, p); throw new NotSupportedException(message); } default: if (codepage < 0 || codepage > 65535) { throw new ArgumentOutOfRangeException("codepage", SR.Format(SR.ArgumentOutOfRange_Range, 0, 65535)); } throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, codepage)); } } public static Encoding GetEncoding(int codepage, EncoderFallback encoderFallback, DecoderFallback decoderFallback) { Encoding encoding = FilterDisallowedEncodings(EncodingProvider.GetEncodingFromProvider(codepage, encoderFallback, decoderFallback)); if (encoding != null) { return encoding; } encoding = GetEncoding(codepage); Encoding encoding2 = (Encoding)encoding.Clone(); encoding2.EncoderFallback = encoderFallback; encoding2.DecoderFallback = decoderFallback; return encoding2; } public static Encoding GetEncoding(string name) { return FilterDisallowedEncodings(EncodingProvider.GetEncodingFromProvider(name)) ?? GetEncoding(EncodingTable.GetCodePageFromName(name)); } public static Encoding GetEncoding(string name, EncoderFallback encoderFallback, DecoderFallback decoderFallback) { return FilterDisallowedEncodings(EncodingProvider.GetEncodingFromProvider(name, encoderFallback, decoderFallback)) ?? GetEncoding(EncodingTable.GetCodePageFromName(name), encoderFallback, decoderFallback); } private static Encoding FilterDisallowedEncodings(Encoding encoding) { if (LocalAppContextSwitches.EnableUnsafeUTF7Encoding) { return encoding; } if (encoding == null || encoding.CodePage != 65000) { return encoding; } return null; } public static EncodingInfo[] GetEncodings() { Dictionary encodingListFromProviders = EncodingProvider.GetEncodingListFromProviders(); if (encodingListFromProviders != null) { return EncodingTable.GetEncodings(encodingListFromProviders); } return EncodingTable.GetEncodings(); } public virtual byte[] GetPreamble() { return Array.Empty(); } private void GetDataItem() { if (_dataItem == null) { _dataItem = EncodingTable.GetCodePageDataItem(_codePage); if (_dataItem == null) { throw new NotSupportedException(SR.Format(SR.NotSupported_NoCodepageData, _codePage)); } } } public virtual object Clone() { Encoding encoding = (Encoding)MemberwiseClone(); encoding._isReadOnly = false; return encoding; } public virtual int GetByteCount(char[] chars) { if (chars == null) { throw new ArgumentNullException("chars", SR.ArgumentNull_Array); } return GetByteCount(chars, 0, chars.Length); } public virtual int GetByteCount(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } char[] array = s.ToCharArray(); return GetByteCount(array, 0, array.Length); } public abstract int GetByteCount(char[] chars, int index, int count); public unsafe int GetByteCount(string s, int index, int count) { if (s == null) { throw new ArgumentNullException("s", SR.ArgumentNull_String); } if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (index > s.Length - count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_IndexCount); } fixed (char* ptr = s) { return GetByteCount(ptr + index, count); } } [CLSCompliant(false)] public unsafe virtual int GetByteCount(char* chars, int count) { if (chars == null) { throw new ArgumentNullException("chars", SR.ArgumentNull_Array); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } char[] chars2 = new ReadOnlySpan(chars, count).ToArray(); return GetByteCount(chars2, 0, count); } public unsafe virtual int GetByteCount(ReadOnlySpan chars) { fixed (char* chars2 = &MemoryMarshal.GetNonNullPinnableReference(chars)) { return GetByteCount(chars2, chars.Length); } } public virtual byte[] GetBytes(char[] chars) { if (chars == null) { throw new ArgumentNullException("chars", SR.ArgumentNull_Array); } return GetBytes(chars, 0, chars.Length); } public virtual byte[] GetBytes(char[] chars, int index, int count) { byte[] array = new byte[GetByteCount(chars, index, count)]; GetBytes(chars, index, count, array, 0); return array; } public abstract int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex); public virtual byte[] GetBytes(string s) { if (s == null) { throw new ArgumentNullException("s", SR.ArgumentNull_String); } int byteCount = GetByteCount(s); byte[] array = new byte[byteCount]; int bytes = GetBytes(s, 0, s.Length, array, 0); return array; } public unsafe byte[] GetBytes(string s, int index, int count) { if (s == null) { throw new ArgumentNullException("s", SR.ArgumentNull_String); } if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (index > s.Length - count) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_IndexCount); } fixed (char* ptr = s) { int byteCount = GetByteCount(ptr + index, count); if (byteCount == 0) { return Array.Empty(); } byte[] array = new byte[byteCount]; fixed (byte* bytes = &array[0]) { int bytes2 = GetBytes(ptr + index, count, bytes, byteCount); } return array; } } public virtual int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return GetBytes(s.ToCharArray(), charIndex, charCount, bytes, byteIndex); } [CLSCompliant(false)] public unsafe virtual int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } char[] chars2 = new ReadOnlySpan(chars, charCount).ToArray(); byte[] array = new byte[byteCount]; int bytes2 = GetBytes(chars2, 0, charCount, array, 0); if (bytes2 < byteCount) { byteCount = bytes2; } new ReadOnlySpan(array, 0, byteCount).CopyTo(new Span(bytes, byteCount)); return byteCount; } public unsafe virtual int GetBytes(ReadOnlySpan chars, Span bytes) { fixed (char* chars2 = &MemoryMarshal.GetNonNullPinnableReference(chars)) { fixed (byte* bytes2 = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return GetBytes(chars2, chars.Length, bytes2, bytes.Length); } } } public virtual int GetCharCount(byte[] bytes) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } return GetCharCount(bytes, 0, bytes.Length); } public abstract int GetCharCount(byte[] bytes, int index, int count); [CLSCompliant(false)] public unsafe virtual int GetCharCount(byte* bytes, int count) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } byte[] bytes2 = new ReadOnlySpan(bytes, count).ToArray(); return GetCharCount(bytes2, 0, count); } public unsafe virtual int GetCharCount(ReadOnlySpan bytes) { fixed (byte* bytes2 = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return GetCharCount(bytes2, bytes.Length); } } public virtual char[] GetChars(byte[] bytes) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } return GetChars(bytes, 0, bytes.Length); } public virtual char[] GetChars(byte[] bytes, int index, int count) { char[] array = new char[GetCharCount(bytes, index, count)]; GetChars(bytes, index, count, array, 0); return array; } public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex); [CLSCompliant(false)] public unsafe virtual int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { if (chars == null || bytes == null) { throw new ArgumentNullException((chars == null) ? "chars" : "bytes", SR.ArgumentNull_Array); } if (byteCount < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } byte[] bytes2 = new ReadOnlySpan(bytes, byteCount).ToArray(); char[] array = new char[charCount]; int chars2 = GetChars(bytes2, 0, byteCount, array, 0); if (chars2 < charCount) { charCount = chars2; } new ReadOnlySpan(array, 0, charCount).CopyTo(new Span(chars, charCount)); return charCount; } public unsafe virtual int GetChars(ReadOnlySpan bytes, Span chars) { fixed (byte* bytes2 = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { fixed (char* chars2 = &MemoryMarshal.GetNonNullPinnableReference(chars)) { return GetChars(bytes2, bytes.Length, chars2, chars.Length); } } } [CLSCompliant(false)] public unsafe string GetString(byte* bytes, int byteCount) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } if (byteCount < 0) { throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } return string.CreateStringFromEncoding(bytes, byteCount, this); } public unsafe string GetString(ReadOnlySpan bytes) { fixed (byte* bytes2 = &MemoryMarshal.GetNonNullPinnableReference(bytes)) { return string.CreateStringFromEncoding(bytes2, bytes.Length, this); } } public bool IsAlwaysNormalized() { return IsAlwaysNormalized(NormalizationForm.FormC); } public virtual bool IsAlwaysNormalized(NormalizationForm form) { return false; } public virtual Decoder GetDecoder() { return new DefaultDecoder(this); } public virtual Encoder GetEncoder() { return new DefaultEncoder(this); } public abstract int GetMaxByteCount(int charCount); public abstract int GetMaxCharCount(int byteCount); public virtual string GetString(byte[] bytes) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } return GetString(bytes, 0, bytes.Length); } public virtual string GetString(byte[] bytes, int index, int count) { return new string(GetChars(bytes, index, count)); } public override bool Equals([NotNullWhen(true)] object? value) { if (value is Encoding encoding && _codePage == encoding._codePage && EncoderFallback.Equals(encoding.EncoderFallback)) { return DecoderFallback.Equals(encoding.DecoderFallback); } return false; } public override int GetHashCode() { return _codePage + EncoderFallback.GetHashCode() + DecoderFallback.GetHashCode(); } public static Stream CreateTranscodingStream(Stream innerStream, Encoding innerStreamEncoding, Encoding outerStreamEncoding, bool leaveOpen = false) { if (innerStream == null) { throw new ArgumentNullException("innerStream"); } if (innerStreamEncoding == null) { throw new ArgumentNullException("innerStreamEncoding"); } if (outerStreamEncoding == null) { throw new ArgumentNullException("outerStreamEncoding"); } return new TranscodingStream(innerStream, innerStreamEncoding, outerStreamEncoding, leaveOpen); } [DoesNotReturn] internal void ThrowBytesOverflow() { throw new ArgumentException(SR.Format(SR.Argument_EncodingConversionOverflowBytes, EncodingName, EncoderFallback.GetType()), "bytes"); } internal void ThrowBytesOverflow(EncoderNLS encoder, bool nothingEncoded) { if ((encoder?._throwOnOverflow ?? true) || nothingEncoded) { if (encoder != null && encoder.InternalHasFallbackBuffer) { encoder.FallbackBuffer.InternalReset(); } ThrowBytesOverflow(); } encoder.ClearMustFlush(); } [DoesNotReturn] [StackTraceHidden] internal static void ThrowConversionOverflow() { throw new ArgumentException(SR.Argument_ConversionOverflow); } [DoesNotReturn] [StackTraceHidden] internal void ThrowCharsOverflow() { throw new ArgumentException(SR.Format(SR.Argument_EncodingConversionOverflowChars, EncodingName, DecoderFallback.GetType()), "chars"); } internal void ThrowCharsOverflow(DecoderNLS decoder, bool nothingDecoded) { if ((decoder?._throwOnOverflow ?? true) || nothingDecoded) { if (decoder != null && decoder.InternalHasFallbackBuffer) { decoder.FallbackBuffer.InternalReset(); } ThrowCharsOverflow(); } decoder.ClearMustFlush(); } internal virtual OperationStatus DecodeFirstRune(ReadOnlySpan bytes, out Rune value, out int bytesConsumed) { throw NotImplemented.ByDesign; } internal virtual OperationStatus EncodeRune(Rune value, Span bytes, out int bytesWritten) { throw NotImplemented.ByDesign; } internal virtual bool TryGetByteCount(Rune value, out int byteCount) { throw NotImplemented.ByDesign; } internal unsafe virtual int GetByteCount(char* pChars, int charCount, EncoderNLS encoder) { int num = 0; int charsConsumed = 0; if (!encoder.HasLeftoverData) { num = GetByteCountFast(pChars, charCount, encoder.Fallback, out charsConsumed); if (charsConsumed == charCount) { return num; } } num += GetByteCountWithFallback(pChars, charCount, charsConsumed, encoder); if (num < 0) { ThrowConversionOverflow(); } return num; } private protected unsafe virtual int GetByteCountFast(char* pChars, int charsLength, EncoderFallback fallback, out int charsConsumed) { throw NotImplemented.ByDesign; } [MethodImpl(MethodImplOptions.NoInlining)] private protected unsafe int GetByteCountWithFallback(char* pCharsOriginal, int originalCharCount, int charsConsumedSoFar) { return GetByteCountWithFallback(new ReadOnlySpan(pCharsOriginal, originalCharCount).Slice(charsConsumedSoFar), originalCharCount, null); } private unsafe int GetByteCountWithFallback(char* pOriginalChars, int originalCharCount, int charsConsumedSoFar, EncoderNLS encoder) { ReadOnlySpan readOnlySpan = new ReadOnlySpan(pOriginalChars, originalCharCount).Slice(charsConsumedSoFar); int num = encoder.DrainLeftoverDataForGetByteCount(readOnlySpan, out var charsConsumed); readOnlySpan = readOnlySpan.Slice(charsConsumed); num += GetByteCountFast((char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(readOnlySpan)), readOnlySpan.Length, encoder.Fallback, out charsConsumed); if (num < 0) { ThrowConversionOverflow(); } readOnlySpan = readOnlySpan.Slice(charsConsumed); if (!readOnlySpan.IsEmpty) { num += GetByteCountWithFallback(readOnlySpan, originalCharCount, encoder); if (num < 0) { ThrowConversionOverflow(); } } return num; } private protected unsafe virtual int GetByteCountWithFallback(ReadOnlySpan chars, int originalCharsLength, EncoderNLS encoder) { fixed (char* ptr = &MemoryMarshal.GetReference(chars)) { EncoderFallbackBuffer encoderFallbackBuffer = EncoderFallbackBuffer.CreateAndInitialize(this, encoder, originalCharsLength); int num = 0; Rune result; int charsConsumed; while (Rune.DecodeFromUtf16(chars, out result, out charsConsumed) != OperationStatus.NeedMoreData || encoder == null || encoder.MustFlush) { int num2 = encoderFallbackBuffer.InternalFallbackGetByteCount(chars, out charsConsumed); num += num2; if (num < 0) { ThrowConversionOverflow(); } chars = chars.Slice(charsConsumed); if (!chars.IsEmpty) { num2 = GetByteCountFast((char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(chars)), chars.Length, null, out charsConsumed); num += num2; if (num < 0) { ThrowConversionOverflow(); } chars = chars.Slice(charsConsumed); } if (chars.IsEmpty) { break; } } return num; } } internal unsafe virtual int GetBytes(char* pChars, int charCount, byte* pBytes, int byteCount, EncoderNLS encoder) { int num = 0; int charsConsumed = 0; if (!encoder.HasLeftoverData) { num = GetBytesFast(pChars, charCount, pBytes, byteCount, out charsConsumed); if (charsConsumed == charCount) { encoder._charsUsed = charCount; return num; } } return GetBytesWithFallback(pChars, charCount, pBytes, byteCount, charsConsumed, num, encoder); } private protected unsafe virtual int GetBytesFast(char* pChars, int charsLength, byte* pBytes, int bytesLength, out int charsConsumed) { throw NotImplemented.ByDesign; } [MethodImpl(MethodImplOptions.NoInlining)] private protected unsafe int GetBytesWithFallback(char* pOriginalChars, int originalCharCount, byte* pOriginalBytes, int originalByteCount, int charsConsumedSoFar, int bytesWrittenSoFar) { return GetBytesWithFallback(new ReadOnlySpan(pOriginalChars, originalCharCount).Slice(charsConsumedSoFar), originalCharCount, new Span(pOriginalBytes, originalByteCount).Slice(bytesWrittenSoFar), originalByteCount, null); } private unsafe int GetBytesWithFallback(char* pOriginalChars, int originalCharCount, byte* pOriginalBytes, int originalByteCount, int charsConsumedSoFar, int bytesWrittenSoFar, EncoderNLS encoder) { ReadOnlySpan readOnlySpan = new ReadOnlySpan(pOriginalChars, originalCharCount).Slice(charsConsumedSoFar); Span span = new Span(pOriginalBytes, originalByteCount).Slice(bytesWrittenSoFar); int charsConsumed; int bytesWritten; bool flag = encoder.TryDrainLeftoverDataForGetBytes(readOnlySpan, span, out charsConsumed, out bytesWritten); readOnlySpan = readOnlySpan.Slice(charsConsumed); span = span.Slice(bytesWritten); if (!flag) { ThrowBytesOverflow(encoder, span.Length == originalByteCount); } else { bytesWritten = GetBytesFast((char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(readOnlySpan)), readOnlySpan.Length, (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(span)), span.Length, out charsConsumed); readOnlySpan = readOnlySpan.Slice(charsConsumed); span = span.Slice(bytesWritten); if (!readOnlySpan.IsEmpty) { encoder._charsUsed = originalCharCount; return GetBytesWithFallback(readOnlySpan, originalCharCount, span, originalByteCount, encoder); } } encoder._charsUsed = originalCharCount - readOnlySpan.Length; return originalByteCount - span.Length; } private protected unsafe virtual int GetBytesWithFallback(ReadOnlySpan chars, int originalCharsLength, Span bytes, int originalBytesLength, EncoderNLS encoder) { fixed (char* ptr2 = &MemoryMarshal.GetReference(chars)) { fixed (byte* ptr = &MemoryMarshal.GetReference(bytes)) { EncoderFallbackBuffer encoderFallbackBuffer = EncoderFallbackBuffer.CreateAndInitialize(this, encoder, originalCharsLength); do { Rune result; int charsConsumed; OperationStatus operationStatus = Rune.DecodeFromUtf16(chars, out result, out charsConsumed); if (operationStatus != OperationStatus.NeedMoreData) { if (operationStatus != OperationStatus.InvalidData && EncodeRune(result, bytes, out var _) == OperationStatus.DestinationTooSmall) { break; } } else if (encoder != null && !encoder.MustFlush) { encoder._charLeftOver = chars[0]; chars = ReadOnlySpan.Empty; break; } int bytesWritten2; bool flag = encoderFallbackBuffer.TryInternalFallbackGetBytes(chars, bytes, out charsConsumed, out bytesWritten2); chars = chars.Slice(charsConsumed); bytes = bytes.Slice(bytesWritten2); if (!flag) { break; } if (!chars.IsEmpty) { bytesWritten2 = GetBytesFast((char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(chars)), chars.Length, (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(bytes)), bytes.Length, out charsConsumed); chars = chars.Slice(charsConsumed); bytes = bytes.Slice(bytesWritten2); } } while (!chars.IsEmpty); if (!chars.IsEmpty || encoderFallbackBuffer.Remaining > 0) { ThrowBytesOverflow(encoder, bytes.Length == originalBytesLength); } if (encoder != null) { encoder._charsUsed = originalCharsLength - chars.Length; } return originalBytesLength - bytes.Length; } } } internal unsafe virtual int GetCharCount(byte* pBytes, int byteCount, DecoderNLS decoder) { int num = 0; int bytesConsumed = 0; if (!decoder.HasLeftoverData) { num = GetCharCountFast(pBytes, byteCount, decoder.Fallback, out bytesConsumed); if (bytesConsumed == byteCount) { return num; } } num += GetCharCountWithFallback(pBytes, byteCount, bytesConsumed, decoder); if (num < 0) { ThrowConversionOverflow(); } return num; } private protected unsafe virtual int GetCharCountFast(byte* pBytes, int bytesLength, DecoderFallback fallback, out int bytesConsumed) { throw NotImplemented.ByDesign; } [MethodImpl(MethodImplOptions.NoInlining)] private protected unsafe int GetCharCountWithFallback(byte* pBytesOriginal, int originalByteCount, int bytesConsumedSoFar) { return GetCharCountWithFallback(new ReadOnlySpan(pBytesOriginal, originalByteCount).Slice(bytesConsumedSoFar), originalByteCount, null); } private unsafe int GetCharCountWithFallback(byte* pOriginalBytes, int originalByteCount, int bytesConsumedSoFar, DecoderNLS decoder) { ReadOnlySpan readOnlySpan = new ReadOnlySpan(pOriginalBytes, originalByteCount).Slice(bytesConsumedSoFar); int num = 0; int bytesConsumed; if (decoder.HasLeftoverData) { num = decoder.DrainLeftoverDataForGetCharCount(readOnlySpan, out bytesConsumed); readOnlySpan = readOnlySpan.Slice(bytesConsumed); } num += GetCharCountFast((byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(readOnlySpan)), readOnlySpan.Length, decoder.Fallback, out bytesConsumed); if (num < 0) { ThrowConversionOverflow(); } readOnlySpan = readOnlySpan.Slice(bytesConsumed); if (!readOnlySpan.IsEmpty) { num += GetCharCountWithFallback(readOnlySpan, originalByteCount, decoder); if (num < 0) { ThrowConversionOverflow(); } } return num; } private unsafe int GetCharCountWithFallback(ReadOnlySpan bytes, int originalBytesLength, DecoderNLS decoder) { fixed (byte* ptr = &MemoryMarshal.GetReference(bytes)) { DecoderFallbackBuffer decoderFallbackBuffer = DecoderFallbackBuffer.CreateAndInitialize(this, decoder, originalBytesLength); int num = 0; Rune value; int bytesConsumed; while (DecodeFirstRune(bytes, out value, out bytesConsumed) != OperationStatus.NeedMoreData || decoder == null || decoder.MustFlush) { int num2 = decoderFallbackBuffer.InternalFallbackGetCharCount(bytes, bytesConsumed); num += num2; if (num < 0) { ThrowConversionOverflow(); } bytes = bytes.Slice(bytesConsumed); if (!bytes.IsEmpty) { num2 = GetCharCountFast((byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(bytes)), bytes.Length, null, out bytesConsumed); num += num2; if (num < 0) { ThrowConversionOverflow(); } bytes = bytes.Slice(bytesConsumed); } if (bytes.IsEmpty) { break; } } return num; } } internal unsafe virtual int GetChars(byte* pBytes, int byteCount, char* pChars, int charCount, DecoderNLS decoder) { int num = 0; int bytesConsumed = 0; if (!decoder.HasLeftoverData) { num = GetCharsFast(pBytes, byteCount, pChars, charCount, out bytesConsumed); if (bytesConsumed == byteCount) { decoder._bytesUsed = byteCount; return num; } } return GetCharsWithFallback(pBytes, byteCount, pChars, charCount, bytesConsumed, num, decoder); } private protected unsafe virtual int GetCharsFast(byte* pBytes, int bytesLength, char* pChars, int charsLength, out int bytesConsumed) { throw NotImplemented.ByDesign; } [MethodImpl(MethodImplOptions.NoInlining)] private protected unsafe int GetCharsWithFallback(byte* pOriginalBytes, int originalByteCount, char* pOriginalChars, int originalCharCount, int bytesConsumedSoFar, int charsWrittenSoFar) { return GetCharsWithFallback(new ReadOnlySpan(pOriginalBytes, originalByteCount).Slice(bytesConsumedSoFar), originalByteCount, new Span(pOriginalChars, originalCharCount).Slice(charsWrittenSoFar), originalCharCount, null); } private protected unsafe int GetCharsWithFallback(byte* pOriginalBytes, int originalByteCount, char* pOriginalChars, int originalCharCount, int bytesConsumedSoFar, int charsWrittenSoFar, DecoderNLS decoder) { ReadOnlySpan readOnlySpan = new ReadOnlySpan(pOriginalBytes, originalByteCount).Slice(bytesConsumedSoFar); Span span = new Span(pOriginalChars, originalCharCount).Slice(charsWrittenSoFar); int bytesConsumed; int start; if (decoder.HasLeftoverData) { start = decoder.DrainLeftoverDataForGetChars(readOnlySpan, span, out bytesConsumed); readOnlySpan = readOnlySpan.Slice(bytesConsumed); span = span.Slice(start); } start = GetCharsFast((byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(readOnlySpan)), readOnlySpan.Length, (char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(span)), span.Length, out bytesConsumed); readOnlySpan = readOnlySpan.Slice(bytesConsumed); span = span.Slice(start); decoder._bytesUsed = originalByteCount; if (readOnlySpan.IsEmpty) { return originalCharCount - span.Length; } return GetCharsWithFallback(readOnlySpan, originalByteCount, span, originalCharCount, decoder); } private protected unsafe virtual int GetCharsWithFallback(ReadOnlySpan bytes, int originalBytesLength, Span chars, int originalCharsLength, DecoderNLS decoder) { fixed (byte* ptr2 = &MemoryMarshal.GetReference(bytes)) { fixed (char* ptr = &MemoryMarshal.GetReference(chars)) { DecoderFallbackBuffer decoderFallbackBuffer = DecoderFallbackBuffer.CreateAndInitialize(this, decoder, originalBytesLength); do { Rune value; int bytesConsumed; OperationStatus operationStatus = DecodeFirstRune(bytes, out value, out bytesConsumed); if (operationStatus != OperationStatus.NeedMoreData) { if (operationStatus != OperationStatus.InvalidData) { break; } } else if (decoder != null && !decoder.MustFlush) { decoder.SetLeftoverData(bytes); bytes = ReadOnlySpan.Empty; break; } if (!decoderFallbackBuffer.TryInternalFallbackGetChars(bytes, bytesConsumed, chars, out var charsWritten)) { break; } bytes = bytes.Slice(bytesConsumed); chars = chars.Slice(charsWritten); if (!bytes.IsEmpty) { charsWritten = GetCharsFast((byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(bytes)), bytes.Length, (char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(chars)), chars.Length, out bytesConsumed); bytes = bytes.Slice(bytesConsumed); chars = chars.Slice(charsWritten); } } while (!bytes.IsEmpty); if (!bytes.IsEmpty) { ThrowCharsOverflow(decoder, chars.Length == originalCharsLength); } if (decoder != null) { decoder._bytesUsed = originalBytesLength - bytes.Length; } return originalCharsLength - chars.Length; } } } } internal static class EncodingTable { private static readonly int[] s_encodingNameIndices = new int[43] { 0, 14, 28, 33, 38, 43, 50, 61, 76, 82, 88, 103, 113, 123, 131, 140, 149, 165, 175, 190, 192, 198, 203, 210, 227, 244, 261, 278, 289, 291, 299, 305, 313, 321, 327, 335, 343, 348, 353, 372, 391, 410, 429 }; private static readonly ushort[] s_codePagesByName = new ushort[42] { 20127, 20127, 20127, 20127, 28591, 20127, 28591, 65000, 20127, 28591, 1200, 28591, 28591, 20127, 20127, 28591, 20127, 28591, 28591, 28591, 28591, 1200, 1200, 65000, 65001, 65000, 65001, 1201, 20127, 20127, 1200, 1201, 1200, 12000, 12001, 12000, 65000, 65001, 65000, 65001, 65000, 65001 }; private static readonly ushort[] s_mappedCodePages = new ushort[8] { 1200, 1201, 12000, 12001, 20127, 28591, 65000, 65001 }; private static readonly int[] s_uiFamilyCodePages = new int[8] { 1200, 1200, 1200, 1200, 1252, 1252, 1200, 1200 }; private static readonly int[] s_webNameIndices = new int[9] { 0, 6, 14, 20, 28, 36, 46, 51, 56 }; private static readonly int[] s_englishNameIndices = new int[9] { 0, 7, 27, 43, 70, 78, 100, 115, 130 }; private static readonly uint[] s_flags = new uint[8] { 512u, 0u, 0u, 0u, 257u, 771u, 257u, 771u }; private static readonly Hashtable s_nameToCodePage = Hashtable.Synchronized(new Hashtable(StringComparer.OrdinalIgnoreCase)); private static CodePageDataItem[] s_codePageToCodePageData; internal static int GetCodePageFromName(string name) { if (name == null) { throw new ArgumentNullException("name"); } object obj = s_nameToCodePage[name]; if (obj != null) { return (int)obj; } int num = InternalGetCodePageFromName(name); s_nameToCodePage[name] = num; return num; } private static int InternalGetCodePageFromName(string name) { int i = 0; int num = s_encodingNameIndices.Length - 2; ReadOnlySpan strA = name.ToLowerInvariant().AsSpan(); while (num - i > 3) { int num2 = (num - i) / 2 + i; int num3 = string.CompareOrdinal(strA, "ansi_x3.4-1968ansi_x3.4-1986asciicp367cp819csasciicsisolatin1csunicode11utf7ibm367ibm819iso-10646-ucs-2iso-8859-1iso-ir-100iso-ir-6iso646-usiso8859-1iso_646.irv:1991iso_8859-1iso_8859-1:1987l1latin1ucs-2unicodeunicode-1-1-utf-7unicode-1-1-utf-8unicode-2-0-utf-7unicode-2-0-utf-8unicodefffeusus-asciiutf-16utf-16beutf-16leutf-32utf-32beutf-32leutf-7utf-8x-unicode-1-1-utf-7x-unicode-1-1-utf-8x-unicode-2-0-utf-7x-unicode-2-0-utf-8".AsSpan(s_encodingNameIndices[num2], s_encodingNameIndices[num2 + 1] - s_encodingNameIndices[num2])); if (num3 == 0) { return s_codePagesByName[num2]; } if (num3 < 0) { num = num2; } else { i = num2; } } for (; i <= num; i++) { if (string.CompareOrdinal(strA, "ansi_x3.4-1968ansi_x3.4-1986asciicp367cp819csasciicsisolatin1csunicode11utf7ibm367ibm819iso-10646-ucs-2iso-8859-1iso-ir-100iso-ir-6iso646-usiso8859-1iso_646.irv:1991iso_8859-1iso_8859-1:1987l1latin1ucs-2unicodeunicode-1-1-utf-7unicode-1-1-utf-8unicode-2-0-utf-7unicode-2-0-utf-8unicodefffeusus-asciiutf-16utf-16beutf-16leutf-32utf-32beutf-32leutf-7utf-8x-unicode-1-1-utf-7x-unicode-1-1-utf-8x-unicode-2-0-utf-7x-unicode-2-0-utf-8".AsSpan(s_encodingNameIndices[i], s_encodingNameIndices[i + 1] - s_encodingNameIndices[i])) == 0) { return s_codePagesByName[i]; } } throw new ArgumentException(SR.Format(SR.Argument_EncodingNotSupported, name), "name"); } internal static EncodingInfo[] GetEncodings() { ushort[] array = s_mappedCodePages; EncodingInfo[] array2 = new EncodingInfo[LocalAppContextSwitches.EnableUnsafeUTF7Encoding ? array.Length : (array.Length - 1)]; string text = "utf-16utf-16BEutf-32utf-32BEus-asciiiso-8859-1utf-7utf-8"; int[] array3 = s_webNameIndices; int num = 0; for (int i = 0; i < array.Length; i++) { int num2 = array[i]; if (num2 != 65000 || LocalAppContextSwitches.EnableUnsafeUTF7Encoding) { array2[num++] = new EncodingInfo(num2, text[array3[i]..array3[i + 1]], GetDisplayName(num2, i)); } } return array2; } internal static EncodingInfo[] GetEncodings(Dictionary encodingInfoList) { ushort[] array = s_mappedCodePages; string text = "utf-16utf-16BEutf-32utf-32BEus-asciiiso-8859-1utf-7utf-8"; int[] array2 = s_webNameIndices; for (int i = 0; i < array.Length; i++) { int num = array[i]; if (!encodingInfoList.ContainsKey(num) && (num != 65000 || LocalAppContextSwitches.EnableUnsafeUTF7Encoding)) { encodingInfoList[num] = new EncodingInfo(num, text[array2[i]..array2[i + 1]], GetDisplayName(num, i)); } } if (!LocalAppContextSwitches.EnableUnsafeUTF7Encoding) { encodingInfoList.Remove(65000); } EncodingInfo[] array3 = new EncodingInfo[encodingInfoList.Count]; int num2 = 0; foreach (KeyValuePair encodingInfo in encodingInfoList) { array3[num2++] = encodingInfo.Value; } return array3; } internal static CodePageDataItem GetCodePageDataItem(int codePage) { if (s_codePageToCodePageData == null) { Interlocked.CompareExchange(ref s_codePageToCodePageData, new CodePageDataItem[s_mappedCodePages.Length], null); } int num; switch (codePage) { case 1200: num = 0; break; case 1201: num = 1; break; case 12000: num = 2; break; case 12001: num = 3; break; case 20127: num = 4; break; case 28591: num = 5; break; case 65000: num = 6; break; case 65001: num = 7; break; default: return null; } CodePageDataItem codePageDataItem = s_codePageToCodePageData[num]; if (codePageDataItem == null) { Interlocked.CompareExchange(ref s_codePageToCodePageData[num], InternalGetCodePageDataItem(codePage, num), null); codePageDataItem = s_codePageToCodePageData[num]; } return codePageDataItem; } private static CodePageDataItem InternalGetCodePageDataItem(int codePage, int index) { int uiFamilyCodePage = s_uiFamilyCodePages[index]; string text = "utf-16utf-16BEutf-32utf-32BEus-asciiiso-8859-1utf-7utf-8"[s_webNameIndices[index]..s_webNameIndices[index + 1]]; string headerName = text; string bodyName = text; string displayName = GetDisplayName(codePage, index); uint flags = s_flags[index]; return new CodePageDataItem(uiFamilyCodePage, text, headerName, bodyName, displayName, flags); } private static string GetDisplayName(int codePage, int englishNameIndex) { string text = SR.GetResourceString("Globalization_cp_" + codePage); if (string.IsNullOrEmpty(text)) { text = "UnicodeUnicode (Big-Endian)Unicode (UTF-32)Unicode (UTF-32 Big-Endian)US-ASCIIWestern European (ISO)Unicode (UTF-7)Unicode (UTF-8)"[s_englishNameIndices[englishNameIndex]..s_englishNameIndices[englishNameIndex + 1]]; } return text; } } public sealed class EncodingInfo { public int CodePage { get; } public string Name { get; } public string DisplayName { get; } internal EncodingProvider? Provider { get; } public EncodingInfo(EncodingProvider provider, int codePage, string name, string displayName) : this(codePage, name, displayName) { if (name == null || displayName == null || provider == null) { throw new ArgumentNullException((name == null) ? "name" : ((displayName == null) ? "displayName" : "provider")); } Provider = provider; } internal EncodingInfo(int codePage, string name, string displayName) { CodePage = codePage; Name = name; DisplayName = displayName; } public Encoding GetEncoding() { return Provider?.GetEncoding(CodePage) ?? Encoding.GetEncoding(CodePage); } public override bool Equals([NotNullWhen(true)] object? value) { if (value is EncodingInfo encodingInfo) { return CodePage == encodingInfo.CodePage; } return false; } public override int GetHashCode() { return CodePage; } } public abstract class EncodingProvider { private static volatile EncodingProvider[] s_providers; public EncodingProvider() { } public abstract Encoding? GetEncoding(string name); public abstract Encoding? GetEncoding(int codepage); public virtual Encoding? GetEncoding(string name, EncoderFallback encoderFallback, DecoderFallback decoderFallback) { Encoding encoding = GetEncoding(name); if (encoding != null) { encoding = (Encoding)encoding.Clone(); encoding.EncoderFallback = encoderFallback; encoding.DecoderFallback = decoderFallback; } return encoding; } public virtual Encoding? GetEncoding(int codepage, EncoderFallback encoderFallback, DecoderFallback decoderFallback) { Encoding encoding = GetEncoding(codepage); if (encoding != null) { encoding = (Encoding)encoding.Clone(); encoding.EncoderFallback = encoderFallback; encoding.DecoderFallback = decoderFallback; } return encoding; } public virtual IEnumerable GetEncodings() { return Array.Empty(); } internal static void AddProvider(EncodingProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } if (s_providers == null && Interlocked.CompareExchange(ref s_providers, new EncodingProvider[1] { provider }, null) == null) { return; } EncodingProvider[] array; EncodingProvider[] array2; do { array = s_providers; if (Array.IndexOf(array, provider) >= 0) { break; } array2 = new EncodingProvider[array.Length + 1]; Array.Copy(array, array2, array.Length); array2[^1] = provider; } while (Interlocked.CompareExchange(ref s_providers, array2, array) != array); } internal static Encoding GetEncodingFromProvider(int codepage) { EncodingProvider[] array = s_providers; if (array == null) { return null; } EncodingProvider[] array2 = array; foreach (EncodingProvider encodingProvider in array2) { Encoding encoding = encodingProvider.GetEncoding(codepage); if (encoding != null) { return encoding; } } return null; } internal static Dictionary GetEncodingListFromProviders() { EncodingProvider[] array = s_providers; if (array == null) { return null; } Dictionary dictionary = new Dictionary(); EncodingProvider[] array2 = array; foreach (EncodingProvider encodingProvider in array2) { IEnumerable encodings = encodingProvider.GetEncodings(); if (encodings == null) { continue; } foreach (EncodingInfo item in encodings) { dictionary.TryAdd(item.CodePage, item); } } return dictionary; } internal static Encoding GetEncodingFromProvider(string encodingName) { if (s_providers == null) { return null; } EncodingProvider[] array = s_providers; EncodingProvider[] array2 = array; foreach (EncodingProvider encodingProvider in array2) { Encoding encoding = encodingProvider.GetEncoding(encodingName); if (encoding != null) { return encoding; } } return null; } internal static Encoding GetEncodingFromProvider(int codepage, EncoderFallback enc, DecoderFallback dec) { if (s_providers == null) { return null; } EncodingProvider[] array = s_providers; EncodingProvider[] array2 = array; foreach (EncodingProvider encodingProvider in array2) { Encoding encoding = encodingProvider.GetEncoding(codepage, enc, dec); if (encoding != null) { return encoding; } } return null; } internal static Encoding GetEncodingFromProvider(string encodingName, EncoderFallback enc, DecoderFallback dec) { if (s_providers == null) { return null; } EncodingProvider[] array = s_providers; EncodingProvider[] array2 = array; foreach (EncodingProvider encodingProvider in array2) { Encoding encoding = encodingProvider.GetEncoding(encodingName, enc, dec); if (encoding != null) { return encoding; } } return null; } } internal class Latin1Encoding : Encoding { internal sealed class Latin1EncodingSealed : Latin1Encoding { public override object Clone() { return new Latin1Encoding { IsReadOnly = false }; } } internal static readonly Latin1EncodingSealed s_default = new Latin1EncodingSealed(); public override ReadOnlySpan Preamble => default(ReadOnlySpan); public override bool IsSingleByte => true; public Latin1Encoding() : base(28591) { } internal override void SetDefaultFallbacks() { encoderFallback = EncoderLatin1BestFitFallback.SingletonInstance; decoderFallback = System.Text.DecoderFallback.ReplacementFallback; } public unsafe override int GetByteCount(char* chars, int count) { if (chars == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetByteCountCommon(chars, count); } public unsafe override int GetByteCount(char[] chars, int index, int count) { if (chars == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars, ExceptionResource.ArgumentNull_Array); } if ((index | count) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } fixed (char* ptr = chars) { return GetByteCountCommon(ptr + index, count); } } public unsafe override int GetByteCount(ReadOnlySpan chars) { fixed (char* pChars = &MemoryMarshal.GetReference(chars)) { return GetByteCountCommon(pChars, chars.Length); } } public unsafe override int GetByteCount(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } fixed (char* pChars = s) { return GetByteCountCommon(pChars, s.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetByteCountCommon(char* pChars, int charCount) { int charsConsumed; int num = GetByteCountFast(pChars, charCount, null, out charsConsumed); if (charsConsumed != charCount) { num += GetByteCountWithFallback(pChars, charCount, charsConsumed); if (num < 0) { Encoding.ThrowConversionOverflow(); } } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private protected unsafe sealed override int GetByteCountFast(char* pChars, int charsLength, EncoderFallback fallback, out int charsConsumed) { int num = charsLength; if (!FallbackSupportsFastGetByteCount(fallback)) { num = (int)Latin1Utility.GetIndexOfFirstNonLatin1Char(pChars, (uint)charsLength); } charsConsumed = num; return num; } public override int GetMaxByteCount(int charCount) { if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } long num = (long)charCount + 1L; if (base.EncoderFallback.MaxCharCount > 1) { num *= base.EncoderFallback.MaxCharCount; } if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_GetByteCountOverflow); } return (int)num; } public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { if (chars == null || bytes == null) { ThrowHelper.ThrowArgumentNullException((chars == null) ? ExceptionArgument.chars : ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((charCount | byteCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((charCount < 0) ? ExceptionArgument.charCount : ExceptionArgument.byteCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetBytesCommon(chars, charCount, bytes, byteCount); } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null || bytes == null) { ThrowHelper.ThrowArgumentNullException((chars == null) ? ExceptionArgument.chars : ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((charIndex | charCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((charIndex < 0) ? ExceptionArgument.charIndex : ExceptionArgument.charCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCount); } if ((uint)byteIndex > bytes.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.byteIndex, ExceptionResource.ArgumentOutOfRange_Index); } fixed (char* ptr = chars) { fixed (byte* ptr2 = bytes) { return GetBytesCommon(ptr + charIndex, charCount, ptr2 + byteIndex, bytes.Length - byteIndex); } } } public unsafe override int GetBytes(ReadOnlySpan chars, Span bytes) { fixed (char* pChars = &MemoryMarshal.GetReference(chars)) { fixed (byte* pBytes = &MemoryMarshal.GetReference(bytes)) { return GetBytesCommon(pChars, chars.Length, pBytes, bytes.Length); } } } public unsafe override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) { ThrowHelper.ThrowArgumentNullException((s == null) ? ExceptionArgument.s : ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((charIndex | charCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((charIndex < 0) ? ExceptionArgument.charIndex : ExceptionArgument.charCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (s.Length - charIndex < charCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.s, ExceptionResource.ArgumentOutOfRange_IndexCount); } if ((uint)byteIndex > bytes.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.byteIndex, ExceptionResource.ArgumentOutOfRange_Index); } fixed (char* ptr2 = s) { fixed (byte[] array = bytes) { byte* ptr = (byte*)((bytes != null && array.Length != 0) ? System.Runtime.CompilerServices.Unsafe.AsPointer(ref array[0]) : null); return GetBytesCommon(ptr2 + charIndex, charCount, ptr + byteIndex, bytes.Length - byteIndex); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetBytesCommon(char* pChars, int charCount, byte* pBytes, int byteCount) { int charsConsumed; int bytesFast = GetBytesFast(pChars, charCount, pBytes, byteCount, out charsConsumed); if (charsConsumed == charCount) { return bytesFast; } return GetBytesWithFallback(pChars, charCount, pBytes, byteCount, charsConsumed, bytesFast); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private protected unsafe sealed override int GetBytesFast(char* pChars, int charsLength, byte* pBytes, int bytesLength, out int charsConsumed) { return charsConsumed = (int)Latin1Utility.NarrowUtf16ToLatin1(pChars, pBytes, (uint)Math.Min(charsLength, bytesLength)); } public unsafe override int GetCharCount(byte* bytes, int count) { if (bytes == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return count; } public override int GetCharCount(byte[] bytes) { if (bytes == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes); } return bytes.Length; } public override int GetCharCount(byte[] bytes, int index, int count) { if (bytes == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((index | count) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } return count; } public override int GetCharCount(ReadOnlySpan bytes) { return bytes.Length; } private protected unsafe override int GetCharCountFast(byte* pBytes, int bytesLength, DecoderFallback fallback, out int bytesConsumed) { bytesConsumed = bytesLength; return bytesLength; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.byteCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return byteCount; } public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { if (bytes == null || chars == null) { ThrowHelper.ThrowArgumentNullException((bytes == null) ? ExceptionArgument.bytes : ExceptionArgument.chars, ExceptionResource.ArgumentNull_Array); } if ((byteCount | charCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((byteCount < 0) ? ExceptionArgument.byteCount : ExceptionArgument.charCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetCharsCommon(bytes, byteCount, chars, charCount); } public unsafe override char[] GetChars(byte[] bytes) { if (bytes == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes); } if (bytes.Length == 0) { return Array.Empty(); } char[] array = new char[bytes.Length]; fixed (byte* pBytes = bytes) { fixed (char* pChars = array) { GetCharsCommon(pBytes, bytes.Length, pChars, array.Length); } } return array; } public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if (bytes == null || chars == null) { ThrowHelper.ThrowArgumentNullException((bytes == null) ? ExceptionArgument.bytes : ExceptionArgument.chars, ExceptionResource.ArgumentNull_Array); } if ((byteIndex | byteCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((byteIndex < 0) ? ExceptionArgument.byteIndex : ExceptionArgument.byteCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } if ((uint)charIndex > (uint)chars.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.charIndex, ExceptionResource.ArgumentOutOfRange_Index); } fixed (byte* ptr = bytes) { fixed (char* ptr2 = chars) { return GetCharsCommon(ptr + byteIndex, byteCount, ptr2 + charIndex, chars.Length - charIndex); } } } public unsafe override char[] GetChars(byte[] bytes, int index, int count) { if (bytes == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((index | count) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } char[] array = new char[count]; fixed (byte* ptr = bytes) { fixed (char* pChars = array) { GetCharsCommon(ptr + index, count, pChars, array.Length); } } return array; } public unsafe override int GetChars(ReadOnlySpan bytes, Span chars) { fixed (byte* pBytes = &MemoryMarshal.GetReference(bytes)) { fixed (char* pChars = &MemoryMarshal.GetReference(chars)) { return GetCharsCommon(pBytes, bytes.Length, pChars, chars.Length); } } } public unsafe override string GetString(byte[] bytes) { if (bytes == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes); } return string.Create(bytes.Length, (this, bytes), delegate(Span chars, (Latin1Encoding encoding, byte[] bytes) args) { fixed (byte* pBytes = args.bytes) { fixed (char* pChars = chars) { args.encoding.GetCharsCommon(pBytes, args.bytes.Length, pChars, chars.Length); } } }); } public unsafe override string GetString(byte[] bytes, int index, int count) { if (bytes == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((index | count) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } return string.Create(count, (this, bytes, index), delegate(Span chars, (Latin1Encoding encoding, byte[] bytes, int index) args) { fixed (byte* ptr = args.bytes) { fixed (char* pChars = chars) { args.encoding.GetCharsCommon(ptr + args.index, chars.Length, pChars, chars.Length); } } }); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetCharsCommon(byte* pBytes, int byteCount, char* pChars, int charCount) { if (byteCount > charCount) { ThrowCharsOverflow(); } Latin1Utility.WidenLatin1ToUtf16(pBytes, pChars, (uint)byteCount); return byteCount; } private protected unsafe sealed override int GetCharsFast(byte* pBytes, int bytesLength, char* pChars, int charsLength, out int bytesConsumed) { int num = Math.Min(bytesLength, charsLength); Latin1Utility.WidenLatin1ToUtf16(pBytes, pChars, (uint)num); bytesConsumed = num; return num; } public override Decoder GetDecoder() { return new DecoderNLS(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } internal sealed override bool TryGetByteCount(Rune value, out int byteCount) { if (value.Value <= 255) { byteCount = 1; return true; } byteCount = 0; return false; } internal sealed override OperationStatus EncodeRune(Rune value, Span bytes, out int bytesWritten) { if (value.Value <= 255) { if (!bytes.IsEmpty) { bytes[0] = (byte)value.Value; bytesWritten = 1; return OperationStatus.Done; } bytesWritten = 0; return OperationStatus.DestinationTooSmall; } bytesWritten = 0; return OperationStatus.InvalidData; } internal sealed override OperationStatus DecodeFirstRune(ReadOnlySpan bytes, out Rune value, out int bytesConsumed) { if (!bytes.IsEmpty) { byte b = bytes[0]; if (b <= byte.MaxValue) { value = new Rune(b); bytesConsumed = 1; return OperationStatus.Done; } value = Rune.ReplacementChar; bytesConsumed = 1; return OperationStatus.InvalidData; } value = Rune.ReplacementChar; bytesConsumed = 0; return OperationStatus.NeedMoreData; } public override bool IsAlwaysNormalized(NormalizationForm form) { return form == NormalizationForm.FormC; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool FallbackSupportsFastGetByteCount(EncoderFallback fallback) { if (fallback == null) { return false; } if (fallback is EncoderLatin1BestFitFallback) { return true; } if (fallback is EncoderReplacementFallback encoderReplacementFallback && encoderReplacementFallback.MaxCharCount == 1 && encoderReplacementFallback.DefaultString[0] <= 'ÿ') { return true; } return false; } } internal static class Latin1Utility { [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static nuint GetIndexOfFirstNonLatin1Char(char* pBuffer, nuint bufferLength) { if (!Sse2.IsSupported) { return GetIndexOfFirstNonLatin1Char_Default(pBuffer, bufferLength); } return GetIndexOfFirstNonLatin1Char_Sse2(pBuffer, bufferLength); } private unsafe static nuint GetIndexOfFirstNonLatin1Char_Default(char* pBuffer, nuint bufferLength) { char* ptr = pBuffer; if (Vector.IsHardwareAccelerated && bufferLength >= (uint)(2 * Vector.Count)) { uint count = (uint)Vector.Count; uint count2 = (uint)Vector.Count; Vector right = new Vector(255); if (Vector.LessThanOrEqualAll(Unsafe.ReadUnaligned>(pBuffer), right)) { char* ptr2 = pBuffer + bufferLength - count; pBuffer = (char*)((nuint)((byte*)pBuffer + count2) & ~(nuint)(count2 - 1)); while (!Vector.GreaterThanAny(Unsafe.Read>(pBuffer), right)) { pBuffer += count; if (pBuffer > ptr2) { break; } } bufferLength -= (nuint)(nint)(pBuffer - ptr); } } while (true) { uint num; if (bufferLength >= 4) { num = Unsafe.ReadUnaligned(pBuffer); uint num2 = Unsafe.ReadUnaligned(pBuffer + 2); if (!AllCharsInUInt32AreLatin1(num | num2)) { if (AllCharsInUInt32AreLatin1(num)) { num = num2; pBuffer += 2; } goto IL_010f; } pBuffer += 4; bufferLength -= 4; continue; } if ((bufferLength & 2) != 0) { num = Unsafe.ReadUnaligned(pBuffer); if (!AllCharsInUInt32AreLatin1(num)) { goto IL_010f; } pBuffer += 2; } if ((bufferLength & 1) != 0 && *pBuffer <= 'ÿ') { pBuffer++; } break; IL_010f: if (FirstCharInUInt32IsLatin1(num)) { pBuffer++; } break; } nuint num3 = (nuint)((byte*)pBuffer - (nuint)ptr); return num3 / 2; } private unsafe static nuint GetIndexOfFirstNonLatin1Char_Sse2(char* pBuffer, nuint bufferLength) { if (bufferLength == 0) { return 0u; } uint num = (uint)Unsafe.SizeOf>(); uint num2 = num / 2; char* ptr = pBuffer; Vector128 right; Vector128 right2; Vector128 left; uint num3; if (bufferLength >= num2) { right = Vector128.Create((ushort)65280); right2 = Vector128.Create((ushort)32512); left = Sse2.LoadVector128((ushort*)pBuffer); num3 = (uint)Sse2.MoveMask(Sse2.AddSaturate(left, right2).AsByte()); if ((num3 & 0xAAAA) == 0) { bufferLength <<= 1; if (bufferLength < 2 * num) { goto IL_013e; } pBuffer = (char*)((nuint)((byte*)pBuffer + num) & ~(nuint)(num - 1)); bufferLength = (nuint)(bufferLength + (byte*)ptr); bufferLength -= (nuint)pBuffer; if (bufferLength < 2 * num) { goto IL_00fa; } char* ptr2 = (char*)((byte*)pBuffer + bufferLength - 2 * num); Vector128 vector; while (true) { left = Sse2.LoadAlignedVector128((ushort*)pBuffer); vector = Sse2.LoadAlignedVector128((ushort*)(pBuffer + num2)); Vector128 left2 = Sse2.Or(left, vector); if (Sse41.IsSupported) { if (!Sse41.TestZ(left2, right)) { break; } } else { num3 = (uint)Sse2.MoveMask(Sse2.AddSaturate(left2, right2).AsByte()); if ((num3 & 0xAAAAu) != 0) { break; } } pBuffer += 2 * num2; if (pBuffer <= ptr2) { continue; } goto IL_00fa; } if (Sse41.IsSupported) { if (!Sse41.TestZ(left, right)) { goto IL_01e6; } } else { num3 = (uint)Sse2.MoveMask(Sse2.AddSaturate(left, right2).AsByte()); if ((num3 & 0xAAAAu) != 0) { goto IL_01fa; } } pBuffer += num2; left = vector; goto IL_01e6; } goto IL_01fa; } uint num5; if ((bufferLength & 4) != 0) { if (Bmi1.X64.IsSupported) { ulong num4 = Unsafe.ReadUnaligned(pBuffer); if (!AllCharsInUInt64AreLatin1(num4)) { num4 &= 0xFF00FF00FF00FF00uL; pBuffer = (char*)((byte*)pBuffer + (nuint)((nint)(Bmi1.X64.TrailingZeroCount(num4) / 8) & ~(nint)1)); goto IL_01a1; } } else { num5 = Unsafe.ReadUnaligned(pBuffer); uint num6 = Unsafe.ReadUnaligned(pBuffer + 2); if (!AllCharsInUInt32AreLatin1(num5 | num6)) { if (AllCharsInUInt32AreLatin1(num5)) { num5 = num6; pBuffer += 2; } goto IL_0214; } } pBuffer += 4; } if ((bufferLength & 2) != 0) { num5 = Unsafe.ReadUnaligned(pBuffer); if (!AllCharsInUInt32AreLatin1(num5)) { goto IL_0214; } pBuffer += 2; } if ((bufferLength & 1) != 0 && *pBuffer <= 'ÿ') { pBuffer++; } goto IL_01a1; IL_01a1: return (nuint)(pBuffer - ptr); IL_0148: if (((byte)bufferLength & (num - 1)) != 0) { pBuffer = (char*)((byte*)pBuffer + (bufferLength & (num - 1)) - num); left = Sse2.LoadVector128((ushort*)pBuffer); if (Sse41.IsSupported) { if (!Sse41.TestZ(left, right)) { goto IL_01e6; } } else { num3 = (uint)Sse2.MoveMask(Sse2.AddSaturate(left, right2).AsByte()); if ((num3 & 0xAAAAu) != 0) { goto IL_01fa; } } pBuffer += num2; } goto IL_01a1; IL_0214: if (FirstCharInUInt32IsLatin1(num5)) { pBuffer++; } goto IL_01a1; IL_01fa: num3 &= 0xAAAAu; pBuffer = (char*)((byte*)pBuffer + (uint)BitOperations.TrailingZeroCount(num3) - 1); goto IL_01a1; IL_013e: pBuffer += num2; goto IL_0148; IL_01e6: num3 = (uint)Sse2.MoveMask(Sse2.AddSaturate(left, right2).AsByte()); goto IL_01fa; IL_00fa: if ((bufferLength & num) != 0) { left = Sse2.LoadAlignedVector128((ushort*)pBuffer); if (Sse41.IsSupported) { if (!Sse41.TestZ(left, right)) { goto IL_01e6; } } else { num3 = (uint)Sse2.MoveMask(Sse2.AddSaturate(left, right2).AsByte()); if ((num3 & 0xAAAAu) != 0) { goto IL_01fa; } } goto IL_013e; } goto IL_0148; } public unsafe static nuint NarrowUtf16ToLatin1(char* pUtf16Buffer, byte* pLatin1Buffer, nuint elementCount) { nuint num = 0u; uint num2 = 0u; uint num3 = 0u; ulong num4 = 0uL; if (Sse2.IsSupported) { if (elementCount >= (uint)(2 * Unsafe.SizeOf>())) { if (IntPtr.Size >= 8) { } num2 = Unsafe.ReadUnaligned(pUtf16Buffer); num3 = Unsafe.ReadUnaligned(pUtf16Buffer + 2); if (!AllCharsInUInt32AreLatin1(num2 | num3)) { goto IL_01cd; } num = NarrowUtf16ToLatin1_Sse2(pUtf16Buffer, pLatin1Buffer, elementCount); } } else if (Vector.IsHardwareAccelerated) { uint num5 = (uint)Unsafe.SizeOf>(); if (elementCount >= 2 * num5) { if (IntPtr.Size >= 8) { } num2 = Unsafe.ReadUnaligned(pUtf16Buffer); num3 = Unsafe.ReadUnaligned(pUtf16Buffer + 2); if (!AllCharsInUInt32AreLatin1(num2 | num3)) { goto IL_01cd; } Vector right = new Vector(255); nuint num6 = elementCount - 2 * num5; do { Vector vector = Unsafe.ReadUnaligned>(pUtf16Buffer + num); Vector vector2 = Unsafe.ReadUnaligned>(pUtf16Buffer + num + Vector.Count); if (Vector.GreaterThanAny(Vector.BitwiseOr(vector, vector2), right)) { break; } Vector value = Vector.Narrow(vector, vector2); Unsafe.WriteUnaligned(pLatin1Buffer + num, value); num += num5; } while (num <= num6); } } nuint num7 = elementCount - num; if (num7 < 4) { goto IL_0176; } nuint num8 = num + num7 - 4; while (true) { if (IntPtr.Size >= 8) { } num2 = Unsafe.ReadUnaligned(pUtf16Buffer + num); num3 = Unsafe.ReadUnaligned(pUtf16Buffer + num + 2); if (!AllCharsInUInt32AreLatin1(num2 | num3)) { break; } NarrowTwoUtf16CharsToLatin1AndWriteToBuffer(ref pLatin1Buffer[num], num2); NarrowTwoUtf16CharsToLatin1AndWriteToBuffer(ref pLatin1Buffer[num + 2], num3); num += 4; if (num <= num8) { continue; } goto IL_0176; } goto IL_01cd; IL_01ef: if (FirstCharInUInt32IsLatin1(num2)) { if (!BitConverter.IsLittleEndian) { } pLatin1Buffer[num] = (byte)num2; num++; } goto IL_01cb; IL_0176: if (((uint)(int)num7 & 2u) != 0) { num2 = Unsafe.ReadUnaligned(pUtf16Buffer + num); if (!AllCharsInUInt32AreLatin1(num2)) { goto IL_01ef; } NarrowTwoUtf16CharsToLatin1AndWriteToBuffer(ref pLatin1Buffer[num], num2); num += 2; } if (((uint)(int)num7 & (true ? 1u : 0u)) != 0) { num2 = pUtf16Buffer[num]; if (num2 <= 255) { pLatin1Buffer[num] = (byte)num2; num++; } } goto IL_01cb; IL_01cd: if (IntPtr.Size >= 8) { } if (AllCharsInUInt32AreLatin1(num2)) { NarrowTwoUtf16CharsToLatin1AndWriteToBuffer(ref pLatin1Buffer[num], num2); num2 = num3; num += 2; } goto IL_01ef; IL_01cb: return num; } private unsafe static nuint NarrowUtf16ToLatin1_Sse2(char* pUtf16Buffer, byte* pLatin1Buffer, nuint elementCount) { uint num = (uint)Unsafe.SizeOf>(); nuint num2 = num - 1; Vector128 right = Vector128.Create((short)(-256)); Vector128 right2 = Vector128.Create((ushort)32512); Vector128 vector = Sse2.LoadVector128((short*)pUtf16Buffer); if (Sse41.IsSupported) { if (!Sse41.TestZ(vector, right)) { return 0u; } } else if (((uint)Sse2.MoveMask(Sse2.AddSaturate(vector.AsUInt16(), right2).AsByte()) & 0xAAAAu) != 0) { return 0u; } Vector128 vector2 = Sse2.PackUnsignedSaturate(vector, vector); Sse2.StoreScalar((ulong*)pLatin1Buffer, vector2.AsUInt64()); nuint num3 = num / 2; if (((uint)(int)pLatin1Buffer & (num / 2)) != 0) { goto IL_00ea; } vector = Sse2.LoadVector128((short*)(pUtf16Buffer + num3)); if (Sse41.IsSupported) { if (Sse41.TestZ(vector, right)) { goto IL_00cd; } } else if ((Sse2.MoveMask(Sse2.AddSaturate(vector.AsUInt16(), right2).AsByte()) & 0xAAAA) == 0) { goto IL_00cd; } goto IL_0186; IL_0186: return num3; IL_00ea: num3 = num - ((nuint)pLatin1Buffer & num2); nuint num4 = elementCount - num; do { vector = Sse2.LoadVector128((short*)(pUtf16Buffer + num3)); Vector128 right3 = Sse2.LoadVector128((short*)(pUtf16Buffer + num3 + num / 2)); Vector128 vector3 = Sse2.Or(vector, right3); if (Sse41.IsSupported) { if (Sse41.TestZ(vector3, right)) { goto IL_015e; } } else if ((Sse2.MoveMask(Sse2.AddSaturate(vector3.AsUInt16(), right2).AsByte()) & 0xAAAA) == 0) { goto IL_015e; } if (Sse41.IsSupported) { if (!Sse41.TestZ(vector, right)) { break; } } else if (((uint)Sse2.MoveMask(Sse2.AddSaturate(vector.AsUInt16(), right2).AsByte()) & 0xAAAAu) != 0) { break; } vector2 = Sse2.PackUnsignedSaturate(vector, vector); Sse2.StoreScalar((ulong*)(pLatin1Buffer + num3), vector2.AsUInt64()); num3 += num / 2; break; IL_015e: vector2 = Sse2.PackUnsignedSaturate(vector, right3); Sse2.StoreAligned(pLatin1Buffer + num3, vector2); num3 += num; } while (num3 <= num4); goto IL_0186; IL_00cd: vector2 = Sse2.PackUnsignedSaturate(vector, vector); Sse2.StoreScalar((ulong*)(pLatin1Buffer + num3), vector2.AsUInt64()); goto IL_00ea; } public unsafe static void WidenLatin1ToUtf16(byte* pLatin1Buffer, char* pUtf16Buffer, nuint elementCount) { if (Sse2.IsSupported) { WidenLatin1ToUtf16_Sse2(pLatin1Buffer, pUtf16Buffer, elementCount); } else { WidenLatin1ToUtf16_Fallback(pLatin1Buffer, pUtf16Buffer, elementCount); } } private unsafe static void WidenLatin1ToUtf16_Sse2(byte* pLatin1Buffer, char* pUtf16Buffer, nuint elementCount) { uint num = (uint)Unsafe.SizeOf>(); nuint num2 = num - 1; nuint num3 = 0u; Vector128 zero = Vector128.Zero; if (elementCount >= num) { Vector128 left = Sse2.LoadScalarVector128((ulong*)pLatin1Buffer).AsByte(); Sse2.Store((byte*)pUtf16Buffer, Sse2.UnpackLow(left, zero)); num3 = (num >> 1) - (((nuint)pUtf16Buffer >> 1) & (num2 >> 1)); char* ptr = pUtf16Buffer + num3; nuint num4 = elementCount - num; while (num3 <= num4) { left = Sse2.LoadVector128(pLatin1Buffer + num3); Vector128 source = Sse2.UnpackLow(left, zero); Sse2.StoreAligned((byte*)ptr, source); Vector128 source2 = Sse2.UnpackHigh(left, zero); Sse2.StoreAligned((byte*)ptr + num, source2); num3 += num; ptr += num; } } uint num5 = (uint)((int)elementCount - (int)num3); if ((num5 & 8u) != 0) { Vector128 left = Sse2.LoadScalarVector128((ulong*)(pLatin1Buffer + num3)).AsByte(); Sse2.Store((byte*)(pUtf16Buffer + num3), Sse2.UnpackLow(left, zero)); num3 += 8; } if ((num5 & 4u) != 0) { Vector128 left = Sse2.LoadScalarVector128((uint*)(pLatin1Buffer + num3)).AsByte(); Sse2.StoreScalar((ulong*)(pUtf16Buffer + num3), Sse2.UnpackLow(left, zero).AsUInt64()); num3 += 4; } if ((num5 & 3) == 0) { return; } pUtf16Buffer[num3] = (char)pLatin1Buffer[num3]; if ((num5 & 2u) != 0) { pUtf16Buffer[num3 + 1] = (char)pLatin1Buffer[num3 + 1]; if ((num5 & (true ? 1u : 0u)) != 0) { pUtf16Buffer[num3 + 2] = (char)pLatin1Buffer[num3 + 2]; } } } private unsafe static void WidenLatin1ToUtf16_Fallback(byte* pLatin1Buffer, char* pUtf16Buffer, nuint elementCount) { nuint num = 0u; if (Vector.IsHardwareAccelerated) { uint count = (uint)Vector.Count; if (elementCount >= count) { nuint num2 = elementCount - count; do { Vector value = Unsafe.ReadUnaligned>(pLatin1Buffer + num); Vector.Widen(Vector.AsVectorByte(value), out var low, out var high); Unsafe.WriteUnaligned(pUtf16Buffer + num, low); Unsafe.WriteUnaligned(pUtf16Buffer + num + Vector.Count, high); num += count; } while (num <= num2); } } for (; num < elementCount; num++) { pUtf16Buffer[num] = (char)pLatin1Buffer[num]; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool AllCharsInUInt32AreLatin1(uint value) { return (value & 0xFF00FF00u) == 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool AllCharsInUInt64AreLatin1(ulong value) { return (value & 0xFF00FF00FF00FF00uL) == 0; } private static bool FirstCharInUInt32IsLatin1(uint value) { _ = BitConverter.IsLittleEndian; if ((value & 0xFF00u) != 0) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void NarrowTwoUtf16CharsToLatin1AndWriteToBuffer(ref byte outputBuffer, uint value) { _ = BitConverter.IsLittleEndian; outputBuffer = (byte)value; Unsafe.Add(ref outputBuffer, 1) = (byte)(value >> 16); } } public enum NormalizationForm { FormC = 1, FormD = 2, [UnsupportedOSPlatform("browser")] FormKC = 5, [UnsupportedOSPlatform("browser")] FormKD = 6 } [DebuggerDisplay("{DebuggerDisplay,nq}")] public readonly struct Rune : IComparable, IComparable, IEquatable, ISpanFormattable, IFormattable { private readonly uint _value; private static ReadOnlySpan AsciiCharInfo => new byte[128] { 14, 14, 14, 14, 14, 14, 14, 14, 14, 142, 142, 142, 142, 142, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 139, 24, 24, 24, 26, 24, 24, 24, 20, 21, 24, 25, 24, 19, 24, 24, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 24, 24, 25, 25, 25, 24, 24, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 20, 24, 21, 27, 18, 27, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 65, 20, 25, 21, 25, 14 }; private string DebuggerDisplay { get { IFormatProvider invariantCulture = CultureInfo.InvariantCulture; DefaultInterpolatedStringHandler handler = new DefaultInterpolatedStringHandler(5, 2, invariantCulture); handler.AppendLiteral("U+"); handler.AppendFormatted(_value, "X4"); handler.AppendLiteral(" '"); handler.AppendFormatted(IsValid(_value) ? ToString() : "\ufffd"); handler.AppendLiteral("'"); return string.Create(invariantCulture, ref handler); } } public bool IsAscii => UnicodeUtility.IsAsciiCodePoint(_value); public bool IsBmp => UnicodeUtility.IsBmpCodePoint(_value); public int Plane => UnicodeUtility.GetPlane(_value); public static Rune ReplacementChar => UnsafeCreate(65533u); public int Utf16SequenceLength => UnicodeUtility.GetUtf16SequenceLength(_value); public int Utf8SequenceLength => UnicodeUtility.GetUtf8SequenceLength(_value); public int Value => (int)_value; public Rune(char ch) { if (UnicodeUtility.IsSurrogateCodePoint(ch)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.ch); } _value = ch; } public Rune(char highSurrogate, char lowSurrogate) : this((uint)char.ConvertToUtf32(highSurrogate, lowSurrogate), unused: false) { } public Rune(int value) : this((uint)value) { } [CLSCompliant(false)] public Rune(uint value) { if (!UnicodeUtility.IsValidUnicodeScalar(value)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value); } _value = value; } private Rune(uint scalarValue, bool unused) { _value = scalarValue; } public static bool operator ==(Rune left, Rune right) { return left._value == right._value; } public static bool operator !=(Rune left, Rune right) { return left._value != right._value; } public static bool 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 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 explicit operator Rune(char ch) { return new Rune(ch); } [CLSCompliant(false)] public static explicit operator Rune(uint value) { return new Rune(value); } public static explicit operator Rune(int value) { return new Rune(value); } private static Rune ChangeCaseCultureAware(Rune rune, TextInfo textInfo, bool toUpper) { Span span = stackalloc char[2]; Span destination = stackalloc char[2]; int length = rune.EncodeToUtf16(span); span = span.Slice(0, length); destination = destination.Slice(0, length); if (toUpper) { textInfo.ChangeCaseToUpper(span, destination); } else { textInfo.ChangeCaseToLower(span, destination); } if (rune.IsBmp) { return UnsafeCreate(destination[0]); } return UnsafeCreate(UnicodeUtility.GetScalarFromUtf16SurrogatePair(destination[0], destination[1])); } public int CompareTo(Rune other) { return Value - other.Value; } public static OperationStatus DecodeFromUtf16(ReadOnlySpan 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 (source.Length > 1) { 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 source, out Rune result, out int bytesConsumed) { int num = 0; uint num2; if ((uint)num < (uint)source.Length) { num2 = source[num]; if (UnicodeUtility.IsAsciiCodePoint(num2)) { goto IL_0021; } if (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 (UnicodeUtility.IsInRangeInclusive(num2, 2080u, 3343u) && !UnicodeUtility.IsInRangeInclusive(num2, 2912u, 2943u) && !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 static OperationStatus DecodeLastFromUtf16(ReadOnlySpan source, out Rune result, out int charsConsumed) { int num = source.Length - 1; if ((uint)num < (uint)source.Length) { char c = source[num]; if (TryCreate(c, out result)) { charsConsumed = 1; return OperationStatus.Done; } if (char.IsLowSurrogate(c)) { num--; if ((uint)num < (uint)source.Length) { char highSurrogate = source[num]; if (TryCreate(highSurrogate, c, out result)) { charsConsumed = 2; return OperationStatus.Done; } } charsConsumed = 1; result = ReplacementChar; return OperationStatus.InvalidData; } } charsConsumed = -source.Length >>> 31; result = ReplacementChar; return OperationStatus.NeedMoreData; } public static OperationStatus DecodeLastFromUtf8(ReadOnlySpan source, out Rune value, out int bytesConsumed) { int num = source.Length - 1; if ((uint)num < (uint)source.Length) { uint num2 = source[num]; if (UnicodeUtility.IsAsciiCodePoint(num2)) { bytesConsumed = 1; value = UnsafeCreate(num2); return OperationStatus.Done; } if (((byte)num2 & 0x40u) != 0) { return DecodeFromUtf8(source.Slice(num), out value, out bytesConsumed); } int num3 = 3; OperationStatus result2; Rune result; int bytesConsumed2; while (true) { if (num3 > 0) { num--; if ((uint)num < (uint)source.Length) { if ((sbyte)source[num] < -64) { num3--; continue; } source = source.Slice(num); result2 = DecodeFromUtf8(source, out result, out bytesConsumed2); if (bytesConsumed2 == source.Length) { break; } } } value = ReplacementChar; bytesConsumed = 1; return OperationStatus.InvalidData; } bytesConsumed = bytesConsumed2; value = result; return result2; } value = ReplacementChar; bytesConsumed = 0; return OperationStatus.NeedMoreData; } public int EncodeToUtf16(Span destination) { if (!TryEncodeToUtf16(destination, out var charsWritten)) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } return charsWritten; } public int EncodeToUtf8(Span destination) { if (!TryEncodeToUtf8(destination, out var bytesWritten)) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } return bytesWritten; } 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 Rune GetRuneAt(string input, int index) { int num = ReadRuneFromString(input, index); if (num < 0) { ThrowHelper.ThrowArgumentException_CannotExtractScalar(ExceptionArgument.index); } return UnsafeCreate((uint)num); } public static bool IsValid(int value) { return IsValid((uint)value); } [CLSCompliant(false)] public static bool IsValid(uint value) { return UnicodeUtility.IsValidUnicodeScalar(value); } internal static int ReadFirstRuneFromUtf16Buffer(ReadOnlySpan input) { if (input.IsEmpty) { return -1; } uint num = input[0]; if (UnicodeUtility.IsSurrogateCodePoint(num)) { if (!UnicodeUtility.IsHighSurrogateCodePoint(num)) { return -1; } if (input.Length <= 1) { return -1; } uint num2 = input[1]; if (!UnicodeUtility.IsLowSurrogateCodePoint(num2)) { return -1; } num = UnicodeUtility.GetScalarFromUtf16SurrogatePair(num, num2); } return (int)num; } private static int ReadRuneFromString(string input, int index) { if (input == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input); } if ((uint)index >= (uint)input.Length) { ThrowHelper.ThrowArgumentOutOfRange_IndexException(); } uint num = input[index]; if (UnicodeUtility.IsSurrogateCodePoint(num)) { if (!UnicodeUtility.IsHighSurrogateCodePoint(num)) { return -1; } index++; if ((uint)index >= (uint)input.Length) { return -1; } uint num2 = input[index]; if (!UnicodeUtility.IsLowSurrogateCodePoint(num2)) { return -1; } num = UnicodeUtility.GetScalarFromUtf16SurrogatePair(num, num2); } return (int)num; } public override string ToString() { if (IsBmp) { return string.CreateFromChar((char)_value); } UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneScalar(_value, out var highSurrogateCodePoint, out var lowSurrogateCodePoint); return string.CreateFromChar(highSurrogateCodePoint, lowSurrogateCodePoint); } bool ISpanFormattable.TryFormat(Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider provider) { return TryEncodeToUtf16(destination, out charsWritten); } string IFormattable.ToString(string format, IFormatProvider formatProvider) { return ToString(); } public static bool TryCreate(char ch, out Rune result) { if (!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 static bool TryCreate(int value, out Rune result) { return TryCreate((uint)value, out result); } [CLSCompliant(false)] public static bool TryCreate(uint value, out Rune result) { if (UnicodeUtility.IsValidUnicodeScalar(value)) { result = UnsafeCreate(value); return true; } result = default(Rune); return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryEncodeToUtf16(Span destination, out int charsWritten) { return TryEncodeToUtf16(this, destination, out charsWritten); } private static bool TryEncodeToUtf16(Rune value, Span destination, out int charsWritten) { if (!destination.IsEmpty) { if (value.IsBmp) { destination[0] = (char)value._value; charsWritten = 1; return true; } if (1u < (uint)destination.Length) { UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneScalar(value._value, out destination[0], out destination[1]); charsWritten = 2; return true; } } charsWritten = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryEncodeToUtf8(Span destination, out int bytesWritten) { return TryEncodeToUtf8(this, destination, out bytesWritten); } private static bool TryEncodeToUtf8(Rune value, Span destination, out int bytesWritten) { if (!destination.IsEmpty) { if (value.IsAscii) { destination[0] = (byte)value._value; bytesWritten = 1; return true; } if (1u < (uint)destination.Length) { if ((long)value.Value <= 2047L) { destination[0] = (byte)(value._value + 12288 >> 6); destination[1] = (byte)((value._value & 0x3F) + 128); bytesWritten = 2; return true; } if (2u < (uint)destination.Length) { if ((long)value.Value <= 65535L) { destination[0] = (byte)(value._value + 917504 >> 12); destination[1] = (byte)(((value._value & 0xFC0) >> 6) + 128); destination[2] = (byte)((value._value & 0x3F) + 128); bytesWritten = 3; return true; } if (3u < (uint)destination.Length) { destination[0] = (byte)(value._value + 62914560 >> 18); destination[1] = (byte)(((value._value & 0x3F000) >> 12) + 128); destination[2] = (byte)(((value._value & 0xFC0) >> 6) + 128); destination[3] = (byte)((value._value & 0x3F) + 128); bytesWritten = 4; return true; } } } } bytesWritten = 0; return false; } public static bool TryGetRuneAt(string input, int index, out Rune value) { int num = ReadRuneFromString(input, index); if (num >= 0) { value = UnsafeCreate((uint)num); return true; } value = default(Rune); return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static Rune UnsafeCreate(uint scalarValue) { return new Rune(scalarValue, unused: false); } public static double GetNumericValue(Rune value) { if (value.IsAscii) { uint num = value._value - 48; if (num > 9) { return -1.0; } return num; } return CharUnicodeInfo.GetNumericValue(value.Value); } public static UnicodeCategory GetUnicodeCategory(Rune value) { if (value.IsAscii) { return (UnicodeCategory)(AsciiCharInfo[value.Value] & 0x1F); } return GetUnicodeCategoryNonAscii(value); } private static UnicodeCategory GetUnicodeCategoryNonAscii(Rune value) { return CharUnicodeInfo.GetUnicodeCategory(value.Value); } private static bool IsCategoryLetter(UnicodeCategory category) { return UnicodeUtility.IsInRangeInclusive((uint)category, 0u, 4u); } private static bool IsCategoryLetterOrDecimalDigit(UnicodeCategory category) { if (!UnicodeUtility.IsInRangeInclusive((uint)category, 0u, 4u)) { return category == UnicodeCategory.DecimalDigitNumber; } return true; } private static bool IsCategoryNumber(UnicodeCategory category) { return UnicodeUtility.IsInRangeInclusive((uint)category, 8u, 10u); } private static bool IsCategoryPunctuation(UnicodeCategory category) { return UnicodeUtility.IsInRangeInclusive((uint)category, 18u, 24u); } private static bool IsCategorySeparator(UnicodeCategory category) { return UnicodeUtility.IsInRangeInclusive((uint)category, 11u, 13u); } private static bool IsCategorySymbol(UnicodeCategory category) { return UnicodeUtility.IsInRangeInclusive((uint)category, 25u, 28u); } public static bool IsControl(Rune value) { return ((value._value + 1) & 0xFFFFFF7Fu) <= 32; } public static bool IsDigit(Rune value) { if (value.IsAscii) { return UnicodeUtility.IsInRangeInclusive(value._value, 48u, 57u); } return GetUnicodeCategoryNonAscii(value) == UnicodeCategory.DecimalDigitNumber; } public static bool IsLetter(Rune value) { if (value.IsAscii) { return ((value._value - 65) & 0xFFFFFFDFu) <= 25; } return IsCategoryLetter(GetUnicodeCategoryNonAscii(value)); } public static bool IsLetterOrDigit(Rune value) { if (value.IsAscii) { return (AsciiCharInfo[value.Value] & 0x40) != 0; } return IsCategoryLetterOrDecimalDigit(GetUnicodeCategoryNonAscii(value)); } public static bool IsLower(Rune value) { if (value.IsAscii) { return UnicodeUtility.IsInRangeInclusive(value._value, 97u, 122u); } return GetUnicodeCategoryNonAscii(value) == UnicodeCategory.LowercaseLetter; } public static bool IsNumber(Rune value) { if (value.IsAscii) { return UnicodeUtility.IsInRangeInclusive(value._value, 48u, 57u); } return IsCategoryNumber(GetUnicodeCategoryNonAscii(value)); } public static bool IsPunctuation(Rune value) { return IsCategoryPunctuation(GetUnicodeCategory(value)); } public static bool IsSeparator(Rune value) { return IsCategorySeparator(GetUnicodeCategory(value)); } public static bool IsSymbol(Rune value) { return IsCategorySymbol(GetUnicodeCategory(value)); } public static bool IsUpper(Rune value) { if (value.IsAscii) { return UnicodeUtility.IsInRangeInclusive(value._value, 65u, 90u); } return GetUnicodeCategoryNonAscii(value) == UnicodeCategory.UppercaseLetter; } public static bool IsWhiteSpace(Rune value) { if (value.IsAscii) { return (AsciiCharInfo[value.Value] & 0x80) != 0; } if (value.IsBmp) { return CharUnicodeInfo.GetIsWhiteSpace((char)value._value); } return false; } public static Rune ToLower(Rune value, CultureInfo culture) { if (culture == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.culture); } if (GlobalizationMode.Invariant) { return ToLowerInvariant(value); } return ChangeCaseCultureAware(value, culture.TextInfo, toUpper: false); } public static Rune ToLowerInvariant(Rune value) { if (value.IsAscii) { return UnsafeCreate(Utf16Utility.ConvertAllAsciiCharsInUInt32ToLowercase(value._value)); } if (GlobalizationMode.Invariant) { return UnsafeCreate(CharUnicodeInfo.ToLower(value._value)); } return ChangeCaseCultureAware(value, TextInfo.Invariant, toUpper: false); } public static Rune ToUpper(Rune value, CultureInfo culture) { if (culture == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.culture); } if (GlobalizationMode.Invariant) { return ToUpperInvariant(value); } return ChangeCaseCultureAware(value, culture.TextInfo, toUpper: true); } public static Rune ToUpperInvariant(Rune value) { if (value.IsAscii) { return UnsafeCreate(Utf16Utility.ConvertAllAsciiCharsInUInt32ToUppercase(value._value)); } if (GlobalizationMode.Invariant) { return UnsafeCreate(CharUnicodeInfo.ToUpper(value._value)); } return ChangeCaseCultureAware(value, TextInfo.Invariant, toUpper: true); } int IComparable.CompareTo(object obj) { if (obj == null) { return 1; } if (obj is Rune other) { return CompareTo(other); } throw new ArgumentException(SR.Arg_MustBeRune); } } public ref struct SpanLineEnumerator { private ReadOnlySpan _remaining; private ReadOnlySpan _current; private bool _isEnumeratorActive; public ReadOnlySpan Current => _current; internal SpanLineEnumerator(ReadOnlySpan buffer) { _remaining = buffer; _current = default(ReadOnlySpan); _isEnumeratorActive = true; } public SpanLineEnumerator GetEnumerator() { return this; } public bool MoveNext() { if (!_isEnumeratorActive) { return false; } int stride; int num = string.IndexOfNewlineChar(_remaining, out stride); if (num >= 0) { _current = _remaining.Slice(0, num); _remaining = _remaining.Slice(num + stride); } else { _current = _remaining; _remaining = default(ReadOnlySpan); _isEnumeratorActive = false; } return true; } } public ref struct SpanRuneEnumerator { private ReadOnlySpan _remaining; private Rune _current; public Rune Current => _current; internal SpanRuneEnumerator(ReadOnlySpan buffer) { _remaining = buffer; _current = default(Rune); } public SpanRuneEnumerator GetEnumerator() { return this; } public bool MoveNext() { if (_remaining.IsEmpty) { _current = default(Rune); return false; } int num = Rune.ReadFirstRuneFromUtf16Buffer(_remaining); if (num < 0) { num = Rune.ReplacementChar.Value; } _current = Rune.UnsafeCreate((uint)num); _remaining = _remaining.Slice(_current.Utf16SequenceLength); return true; } } public struct StringRuneEnumerator : IEnumerable, System.Collections.IEnumerable, IEnumerator, IDisposable, System.Collections.IEnumerator { private readonly string _string; private Rune _current; private int _nextIndex; public Rune Current => _current; object? System.Collections.IEnumerator.Current => _current; internal StringRuneEnumerator(string value) { _string = value; _current = default(Rune); _nextIndex = 0; } public StringRuneEnumerator GetEnumerator() { return this; } public bool MoveNext() { if ((uint)_nextIndex >= _string.Length) { _current = default(Rune); return false; } if (!Rune.TryGetRuneAt(_string, _nextIndex, out _current)) { _current = Rune.ReplacementChar; } _nextIndex += _current.Utf16SequenceLength; return true; } void IDisposable.Dispose() { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this; } IEnumerator IEnumerable.GetEnumerator() { return this; } void System.Collections.IEnumerator.Reset() { _current = default(Rune); _nextIndex = 0; } } internal sealed class TranscodingStream : Stream { private readonly Encoding _innerEncoding; private readonly Encoding _thisEncoding; private Stream _innerStream; private readonly bool _leaveOpen; private Encoder _innerEncoder; private Decoder _thisDecoder; private Encoder _thisEncoder; private Decoder _innerDecoder; private int _readCharBufferMaxSize; private byte[] _readBuffer; private int _readBufferOffset; private int _readBufferCount; public override bool CanRead => _innerStream?.CanRead ?? false; public override bool CanSeek => false; public override bool CanWrite => _innerStream?.CanWrite ?? false; public override long Length { get { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } } public override long Position { get { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } set { ThrowHelper.ThrowNotSupportedException_UnseekableStream(); } } internal TranscodingStream(Stream innerStream, Encoding innerEncoding, Encoding thisEncoding, bool leaveOpen) { _innerStream = innerStream; _leaveOpen = leaveOpen; _innerEncoding = innerEncoding; _thisEncoding = thisEncoding; } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state); } protected override void Dispose(bool disposing) { if (_innerStream != null) { ArraySegment arraySegment = FinalFlushWriteBuffers(); if (arraySegment.Count != 0) { _innerStream.Write(arraySegment); } Stream innerStream = _innerStream; _innerStream = null; if (!_leaveOpen) { innerStream.Dispose(); } } } public override ValueTask DisposeAsync() { if (_innerStream == null) { return default(ValueTask); } ArraySegment pendingData2 = FinalFlushWriteBuffers(); if (pendingData2.Count == 0) { Stream innerStream = _innerStream; _innerStream = null; if (!_leaveOpen) { return innerStream.DisposeAsync(); } return default(ValueTask); } return DisposeAsyncCore(pendingData2); async ValueTask DisposeAsyncCore(ArraySegment pendingData) { Stream innerStream2 = _innerStream; _innerStream = null; await innerStream2.WriteAsync(pendingData.AsMemory()).ConfigureAwait(continueOnCapturedContext: false); if (!_leaveOpen) { await innerStream2.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false); } } } public override int EndRead(IAsyncResult asyncResult) { return TaskToApm.End(asyncResult); } public override void EndWrite(IAsyncResult asyncResult) { TaskToApm.End(asyncResult); } [MemberNotNull(new string[] { "_innerDecoder", "_thisEncoder", "_readBuffer" })] private void EnsurePreReadConditions() { ThrowIfDisposed(); if (_innerDecoder == null) { InitializeReadDataStructures(); } void InitializeReadDataStructures() { if (!CanRead) { ThrowHelper.ThrowNotSupportedException_UnreadableStream(); } _innerDecoder = _innerEncoding.GetDecoder(); _thisEncoder = _thisEncoding.GetEncoder(); _readCharBufferMaxSize = _innerEncoding.GetMaxCharCount(4096); _readBuffer = GC.AllocateUninitializedArray(_thisEncoding.GetMaxByteCount(_readCharBufferMaxSize)); } } [MemberNotNull(new string[] { "_thisDecoder", "_innerEncoder" })] private void EnsurePreWriteConditions() { ThrowIfDisposed(); if (_innerEncoder == null) { InitializeReadDataStructures(); } void InitializeReadDataStructures() { if (!CanWrite) { ThrowHelper.ThrowNotSupportedException_UnwritableStream(); } _innerEncoder = _innerEncoding.GetEncoder(); _thisDecoder = _thisEncoding.GetDecoder(); } } private ArraySegment FinalFlushWriteBuffers() { if (_thisDecoder == null || _innerEncoder == null) { return default(ArraySegment); } char[] chars = Array.Empty(); int num = _thisDecoder.GetCharCount(Array.Empty(), 0, 0, flush: true); if (num > 0) { chars = new char[num]; num = _thisDecoder.GetChars(Array.Empty(), 0, 0, chars, 0, flush: true); } byte[] array = Array.Empty(); int num2 = _innerEncoder.GetByteCount(chars, 0, num, flush: true); if (num2 > 0) { array = new byte[num2]; num2 = _innerEncoder.GetBytes(chars, 0, num, array, 0, flush: true); } return new ArraySegment(array, 0, num2); } public override void Flush() { ThrowIfDisposed(); _innerStream.Flush(); } public override Task FlushAsync(CancellationToken cancellationToken) { ThrowIfDisposed(); return _innerStream.FlushAsync(cancellationToken); } public override int Read(byte[] buffer, int offset, int count) { Stream.ValidateBufferArguments(buffer, offset, count); return Read(new Span(buffer, offset, count)); } public override int Read(Span buffer) { EnsurePreReadConditions(); if (_readBufferCount == 0) { byte[] array = ArrayPool.Shared.Rent(4096); char[] array2 = ArrayPool.Shared.Rent(_readCharBufferMaxSize); try { bool flag; int bytes; do { int num = _innerStream.Read(array, 0, 4096); flag = num == 0; int chars = _innerDecoder.GetChars(array, 0, num, array2, 0, flag); bytes = _thisEncoder.GetBytes(array2, 0, chars, _readBuffer, 0, flag); } while (!flag && bytes == 0); _readBufferOffset = 0; _readBufferCount = bytes; } finally { ArrayPool.Shared.Return(array); ArrayPool.Shared.Return(array2); } } int num2 = Math.Min(_readBufferCount, buffer.Length); _readBuffer.AsSpan(_readBufferOffset, num2).CopyTo(buffer); _readBufferOffset += num2; _readBufferCount -= num2; return num2; } public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Stream.ValidateBufferArguments(buffer, offset, count); return ReadAsync(new Memory(buffer, offset, count), cancellationToken).AsTask(); } public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken) { EnsurePreReadConditions(); if (cancellationToken.IsCancellationRequested) { return ValueTask.FromCanceled(cancellationToken); } return ReadAsyncCore(buffer, cancellationToken); async ValueTask ReadAsyncCore(Memory buffer, CancellationToken cancellationToken) { if (_readBufferCount == 0) { byte[] rentedBytes = ArrayPool.Shared.Rent(4096); char[] rentedChars = ArrayPool.Shared.Rent(_readCharBufferMaxSize); try { bool flag; int bytes; do { int num = await _innerStream.ReadAsync(rentedBytes.AsMemory(0, 4096), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); flag = num == 0; int chars = _innerDecoder.GetChars(rentedBytes, 0, num, rentedChars, 0, flag); bytes = _thisEncoder.GetBytes(rentedChars, 0, chars, _readBuffer, 0, flag); } while (!flag && bytes == 0); _readBufferOffset = 0; _readBufferCount = bytes; } finally { ArrayPool.Shared.Return(rentedBytes); ArrayPool.Shared.Return(rentedChars); } } int num2 = Math.Min(_readBufferCount, buffer.Length); _readBuffer.AsSpan(_readBufferOffset, num2).CopyTo(buffer.Span); _readBufferOffset += num2; _readBufferCount -= num2; return num2; } } public unsafe override int ReadByte() { System.Runtime.CompilerServices.Unsafe.SkipInit(out byte result); if (Read(new Span(&result, 1)) == 0) { return -1; } return result; } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } public override void SetLength(long value) { ThrowHelper.ThrowNotSupportedException_UnseekableStream(); } [StackTraceHidden] private void ThrowIfDisposed() { if (_innerStream == null) { ThrowObjectDisposedException(); } } [DoesNotReturn] [StackTraceHidden] private void ThrowObjectDisposedException() { ThrowHelper.ThrowObjectDisposedException_StreamClosed(GetType().Name); } public override void Write(byte[] buffer, int offset, int count) { Stream.ValidateBufferArguments(buffer, offset, count); Write(new ReadOnlySpan(buffer, offset, count)); } public override void Write(ReadOnlySpan buffer) { EnsurePreWriteConditions(); if (buffer.IsEmpty) { return; } int minimumLength = Math.Clamp(buffer.Length, 4096, 1048576); char[] array = ArrayPool.Shared.Rent(minimumLength); byte[] array2 = ArrayPool.Shared.Rent(minimumLength); try { bool completed; do { _thisDecoder.Convert(buffer, array, flush: false, out var bytesUsed, out var charsUsed, out completed); buffer = buffer.Slice(bytesUsed); Span span = array.AsSpan(0, charsUsed); bool completed2; do { _innerEncoder.Convert(span, array2, flush: false, out var charsUsed2, out var bytesUsed2, out completed2); span = span.Slice(charsUsed2); _innerStream.Write(array2, 0, bytesUsed2); } while (!completed2); } while (!completed); } finally { ArrayPool.Shared.Return(array); ArrayPool.Shared.Return(array2); } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Stream.ValidateBufferArguments(buffer, offset, count); return WriteAsync(new ReadOnlyMemory(buffer, offset, count), cancellationToken).AsTask(); } public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken) { EnsurePreWriteConditions(); if (cancellationToken.IsCancellationRequested) { return ValueTask.FromCanceled(cancellationToken); } if (buffer.IsEmpty) { return ValueTask.CompletedTask; } return WriteAsyncCore(buffer, cancellationToken); async ValueTask WriteAsyncCore(ReadOnlyMemory remainingOuterEncodedBytes, CancellationToken cancellationToken) { int minimumLength = Math.Clamp(remainingOuterEncodedBytes.Length, 4096, 1048576); char[] scratchChars = ArrayPool.Shared.Rent(minimumLength); byte[] scratchBytes = ArrayPool.Shared.Rent(minimumLength); try { bool decoderFinished; do { _thisDecoder.Convert(remainingOuterEncodedBytes.Span, scratchChars, flush: false, out var bytesUsed, out var charsUsed, out decoderFinished); remainingOuterEncodedBytes = remainingOuterEncodedBytes.Slice(bytesUsed); ArraySegment decodedChars = new ArraySegment(scratchChars, 0, charsUsed); bool encoderFinished; do { _innerEncoder.Convert(decodedChars, scratchBytes, flush: false, out var charsUsed2, out var bytesUsed2, out encoderFinished); decodedChars = decodedChars.Slice(charsUsed2); await _innerStream.WriteAsync(new ReadOnlyMemory(scratchBytes, 0, bytesUsed2), cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } while (!encoderFinished); } while (!decoderFinished); } finally { ArrayPool.Shared.Return(scratchChars); ArrayPool.Shared.Return(scratchBytes); } } } public unsafe override void WriteByte(byte value) { Write(new ReadOnlySpan(&value, 1)); } } [Flags] internal enum TrimType { Head = 1, Tail = 2, Both = 3 } public class UnicodeEncoding : Encoding { private sealed class Decoder : DecoderNLS { internal int lastByte = -1; internal char lastChar; internal override bool HasState { get { if (lastByte == -1) { return lastChar != '\0'; } return true; } } public Decoder(UnicodeEncoding encoding) : base(encoding) { } public override void Reset() { lastByte = -1; lastChar = '\0'; if (_fallbackBuffer != null) { _fallbackBuffer.Reset(); } } } internal static readonly UnicodeEncoding s_bigEndianDefault = new UnicodeEncoding(bigEndian: true, byteOrderMark: true); internal static readonly UnicodeEncoding s_littleEndianDefault = new UnicodeEncoding(bigEndian: false, byteOrderMark: true); private readonly bool isThrowException; private readonly bool bigEndian; private readonly bool byteOrderMark; public const int CharSize = 2; public override ReadOnlySpan Preamble { get { if (!(GetType() != typeof(UnicodeEncoding))) { if (byteOrderMark) { if (bigEndian) { return new byte[2] { 254, 255 }; } return new byte[2] { 255, 254 }; } return default(ReadOnlySpan); } return new ReadOnlySpan(GetPreamble()); } } public UnicodeEncoding() : this(bigEndian: false, byteOrderMark: true) { } public UnicodeEncoding(bool bigEndian, bool byteOrderMark) : base(bigEndian ? 1201 : 1200) { this.bigEndian = bigEndian; this.byteOrderMark = byteOrderMark; } public UnicodeEncoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidBytes) : this(bigEndian, byteOrderMark) { isThrowException = throwOnInvalidBytes; if (isThrowException) { SetDefaultFallbacks(); } } internal sealed override void SetDefaultFallbacks() { if (isThrowException) { encoderFallback = System.Text.EncoderFallback.ExceptionFallback; decoderFallback = System.Text.DecoderFallback.ExceptionFallback; } else { encoderFallback = new EncoderReplacementFallback("\ufffd"); decoderFallback = new DecoderReplacementFallback("\ufffd"); } } public unsafe override int GetByteCount(char[] chars, int index, int count) { if (chars == null) { throw new ArgumentNullException("chars", SR.ArgumentNull_Array); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - index < count) { throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); } if (count == 0) { return 0; } fixed (char* ptr = chars) { return GetByteCount(ptr + index, count, null); } } public unsafe override int GetByteCount(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } fixed (char* pChars = s) { return GetByteCount(pChars, s.Length, null); } } [CLSCompliant(false)] public unsafe override int GetByteCount(char* chars, int count) { if (chars == null) { throw new ArgumentNullException("chars", SR.ArgumentNull_Array); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } return GetByteCount(chars, count, null); } public unsafe override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) { throw new ArgumentNullException((s == null) ? "s" : "bytes", SR.ArgumentNull_Array); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (s.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); } int byteCount = bytes.Length - byteIndex; fixed (char* ptr = s) { fixed (byte* ptr2 = &MemoryMarshal.GetReference(bytes)) { return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, null); } } } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null || bytes == null) { throw new ArgumentNullException((chars == null) ? "chars" : "bytes", SR.ArgumentNull_Array); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); } if (charCount == 0) { return 0; } int byteCount = bytes.Length - byteIndex; fixed (char* ptr = chars) { fixed (byte* ptr2 = &MemoryMarshal.GetReference(bytes)) { return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, null); } } } [CLSCompliant(false)] public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } return GetBytes(chars, charCount, bytes, byteCount, null); } public unsafe override int GetCharCount(byte[] bytes, int index, int count) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } if (count == 0) { return 0; } fixed (byte* ptr = bytes) { return GetCharCount(ptr + index, count, null); } } [CLSCompliant(false)] public unsafe override int GetCharCount(byte* bytes, int count) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } return GetCharCount(bytes, count, null); } public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } if (charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); } if (byteCount == 0) { return 0; } int charCount = chars.Length - charIndex; fixed (byte* ptr = bytes) { fixed (char* ptr2 = &MemoryMarshal.GetReference(chars)) { return GetChars(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, null); } } } [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } return GetChars(bytes, byteCount, chars, charCount, null); } public unsafe override string GetString(byte[] bytes, int index, int count) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } if (count == 0) { return string.Empty; } fixed (byte* ptr = bytes) { return string.CreateStringFromEncoding(ptr + index, count, this); } } internal unsafe sealed override int GetByteCount(char* chars, int count, EncoderNLS encoder) { int num = count << 1; if (num < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_GetByteCountOverflow); } char* charStart = chars; char* ptr = chars + count; char c = '\0'; bool flag = false; EncoderFallbackBuffer encoderFallbackBuffer = null; if (encoder != null) { c = encoder._charLeftOver; if (c > '\0') { num += 2; } if (encoder.InternalHasFallbackBuffer) { encoderFallbackBuffer = encoder.FallbackBuffer; if (encoderFallbackBuffer.Remaining > 0) { throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback?.GetType())); } encoderFallbackBuffer.InternalInitialize(charStart, ptr, encoder, setEncoder: false); } } while (true) { char num2 = encoderFallbackBuffer?.InternalGetNextChar() ?? '\0'; char c2 = num2; char* chars2; if (num2 != 0 || chars < ptr) { if (c2 == '\0') { if ((bigEndian ^ BitConverter.IsLittleEndian) && ((int)chars & 3) == 0 && c == '\0') { ulong* ptr2 = (ulong*)(ptr - 3); ulong* ptr3; for (ptr3 = (ulong*)chars; ptr3 < ptr2; ptr3++) { if ((0x8000800080008000uL & *ptr3) == 0L) { continue; } ulong num3 = (0xF800F800F800F800uL & *ptr3) ^ 0xD800D800D800D800uL; if ((num3 & 0xFFFF000000000000uL) == 0L || (num3 & 0xFFFF00000000L) == 0L || (num3 & 0xFFFF0000u) == 0L || (num3 & 0xFFFF) == 0L) { long num4 = -287953294993589248L & (long)(*ptr3); if (!BitConverter.IsLittleEndian) { } if (num4 != -2593835887162763264L) { break; } } } chars = (char*)ptr3; if (chars >= ptr) { goto IL_0294; } } c2 = *chars; chars++; } else { num += 2; } if (c2 >= '\ud800' && c2 <= '\udfff') { if (c2 <= '\udbff') { if (c > '\0') { chars--; num -= 2; if (encoderFallbackBuffer == null) { encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : encoderFallback.CreateFallbackBuffer()); encoderFallbackBuffer.InternalInitialize(charStart, ptr, encoder, setEncoder: false); } chars2 = chars; encoderFallbackBuffer.InternalFallback(c, ref chars2); chars = chars2; c = '\0'; } else { c = c2; } } else if (c == '\0') { num -= 2; if (encoderFallbackBuffer == null) { encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : encoderFallback.CreateFallbackBuffer()); encoderFallbackBuffer.InternalInitialize(charStart, ptr, encoder, setEncoder: false); } chars2 = chars; encoderFallbackBuffer.InternalFallback(c2, ref chars2); chars = chars2; } else { c = '\0'; } } else if (c > '\0') { chars--; if (encoderFallbackBuffer == null) { encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : encoderFallback.CreateFallbackBuffer()); encoderFallbackBuffer.InternalInitialize(charStart, ptr, encoder, setEncoder: false); } chars2 = chars; encoderFallbackBuffer.InternalFallback(c, ref chars2); chars = chars2; num -= 2; c = '\0'; } continue; } goto IL_0294; IL_0294: if (c <= '\0') { break; } num -= 2; if (encoder != null && !encoder.MustFlush) { break; } if (flag) { throw new ArgumentException(SR.Format(SR.Argument_RecursiveFallback, c), "chars"); } if (encoderFallbackBuffer == null) { encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : encoderFallback.CreateFallbackBuffer()); encoderFallbackBuffer.InternalInitialize(charStart, ptr, encoder, setEncoder: false); } chars2 = chars; encoderFallbackBuffer.InternalFallback(c, ref chars2); chars = chars2; c = '\0'; flag = true; } return num; } internal unsafe sealed override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { char c = '\0'; bool flag = false; byte* ptr = bytes + byteCount; char* ptr2 = chars + charCount; byte* ptr3 = bytes; char* ptr4 = chars; EncoderFallbackBuffer encoderFallbackBuffer = null; if (encoder != null) { c = encoder._charLeftOver; if (encoder.InternalHasFallbackBuffer) { encoderFallbackBuffer = encoder.FallbackBuffer; if (encoderFallbackBuffer.Remaining > 0 && encoder._throwOnOverflow) { throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback?.GetType())); } encoderFallbackBuffer.InternalInitialize(ptr4, ptr2, encoder, setEncoder: false); } } while (true) { char num = encoderFallbackBuffer?.InternalGetNextChar() ?? '\0'; char c2 = num; char* chars2; if (num != 0 || chars < ptr2) { if (c2 == '\0') { if ((bigEndian ^ BitConverter.IsLittleEndian) && ((int)chars & 3) == 0 && c == '\0') { ulong* ptr5 = (ulong*)(chars - 3 + ((ptr - bytes >> 1 < ptr2 - chars) ? (ptr - bytes >> 1) : (ptr2 - chars))); ulong* ptr6 = (ulong*)chars; ulong* ptr7 = (ulong*)bytes; while (ptr6 < ptr5) { if ((0x8000800080008000uL & *ptr6) != 0L) { ulong num2 = (0xF800F800F800F800uL & *ptr6) ^ 0xD800D800D800D800uL; if ((num2 & 0xFFFF000000000000uL) == 0L || (num2 & 0xFFFF00000000L) == 0L || (num2 & 0xFFFF0000u) == 0L || (num2 & 0xFFFF) == 0L) { long num3 = -287953294993589248L & (long)(*ptr6); if (!BitConverter.IsLittleEndian) { } if (num3 != -2593835887162763264L) { break; } } } Unsafe.WriteUnaligned(ptr7, *ptr6); ptr6++; ptr7++; } chars = (char*)ptr6; bytes = (byte*)ptr7; if (chars >= ptr2) { goto IL_039e; } } c2 = *chars; chars++; } if (c2 >= '\ud800' && c2 <= '\udfff') { if (c2 <= '\udbff') { if (c > '\0') { chars--; if (encoderFallbackBuffer == null) { encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : encoderFallback.CreateFallbackBuffer()); encoderFallbackBuffer.InternalInitialize(ptr4, ptr2, encoder, setEncoder: true); } chars2 = chars; encoderFallbackBuffer.InternalFallback(c, ref chars2); chars = chars2; c = '\0'; } else { c = c2; } continue; } if (c == '\0') { if (encoderFallbackBuffer == null) { encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : encoderFallback.CreateFallbackBuffer()); encoderFallbackBuffer.InternalInitialize(ptr4, ptr2, encoder, setEncoder: true); } chars2 = chars; encoderFallbackBuffer.InternalFallback(c2, ref chars2); chars = chars2; continue; } if (bytes + 3 >= ptr) { if (encoderFallbackBuffer != null && encoderFallbackBuffer.bFallingBack) { encoderFallbackBuffer.MovePrevious(); encoderFallbackBuffer.MovePrevious(); } else { chars -= 2; } ThrowBytesOverflow(encoder, bytes == ptr3); c = '\0'; goto IL_039e; } if (bigEndian) { *(bytes++) = (byte)((int)c >> 8); *(bytes++) = (byte)c; } else { *(bytes++) = (byte)c; *(bytes++) = (byte)((int)c >> 8); } c = '\0'; } else if (c > '\0') { chars--; if (encoderFallbackBuffer == null) { encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : encoderFallback.CreateFallbackBuffer()); encoderFallbackBuffer.InternalInitialize(ptr4, ptr2, encoder, setEncoder: true); } chars2 = chars; encoderFallbackBuffer.InternalFallback(c, ref chars2); chars = chars2; c = '\0'; continue; } if (bytes + 1 < ptr) { if (bigEndian) { *(bytes++) = (byte)((int)c2 >> 8); *(bytes++) = (byte)c2; } else { *(bytes++) = (byte)c2; *(bytes++) = (byte)((int)c2 >> 8); } continue; } if (encoderFallbackBuffer != null && encoderFallbackBuffer.bFallingBack) { encoderFallbackBuffer.MovePrevious(); } else { chars--; } ThrowBytesOverflow(encoder, bytes == ptr3); } goto IL_039e; IL_039e: if (c <= '\0' || (encoder != null && !encoder.MustFlush)) { break; } if (flag) { throw new ArgumentException(SR.Format(SR.Argument_RecursiveFallback, c), "chars"); } if (encoderFallbackBuffer == null) { encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : encoderFallback.CreateFallbackBuffer()); encoderFallbackBuffer.InternalInitialize(ptr4, ptr2, encoder, setEncoder: true); } chars2 = chars; encoderFallbackBuffer.InternalFallback(c, ref chars2); chars = chars2; c = '\0'; flag = true; } if (encoder != null) { encoder._charLeftOver = c; encoder._charsUsed = (int)(chars - ptr4); } return (int)(bytes - ptr3); } internal unsafe sealed override int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { Decoder decoder = (Decoder)baseDecoder; byte* ptr = bytes + count; byte* byteStart = bytes; int num = -1; char c = '\0'; int num2 = count >> 1; DecoderFallbackBuffer decoderFallbackBuffer = null; if (decoder != null) { num = decoder.lastByte; c = decoder.lastChar; if (c > '\0') { num2++; } if (num >= 0 && (count & 1) == 1) { num2++; } } while (bytes < ptr) { if ((bigEndian ^ BitConverter.IsLittleEndian) && ((int)bytes & 3) == 0 && num == -1 && c == '\0') { ulong* ptr2 = (ulong*)(ptr - 7); ulong* ptr3; for (ptr3 = (ulong*)bytes; ptr3 < ptr2; ptr3++) { if ((0x8000800080008000uL & *ptr3) == 0L) { continue; } ulong num3 = (0xF800F800F800F800uL & *ptr3) ^ 0xD800D800D800D800uL; if ((num3 & 0xFFFF000000000000uL) == 0L || (num3 & 0xFFFF00000000L) == 0L || (num3 & 0xFFFF0000u) == 0L || (num3 & 0xFFFF) == 0L) { long num4 = -287953294993589248L & (long)(*ptr3); if (!BitConverter.IsLittleEndian) { } if (num4 != -2593835887162763264L) { break; } } } bytes = (byte*)ptr3; if (bytes >= ptr) { break; } } if (num < 0) { num = *(bytes++); if (bytes >= ptr) { break; } } char c2 = ((!bigEndian) ? ((char)((*(bytes++) << 8) | num)) : ((char)((num << 8) | *(bytes++)))); num = -1; if (c2 >= '\ud800' && c2 <= '\udfff') { if (c2 <= '\udbff') { if (c > '\0') { num2--; byte[] array = null; array = ((!bigEndian) ? new byte[2] { (byte)c, (byte)((int)c >> 8) } : new byte[2] { (byte)((int)c >> 8), (byte)c }); if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((decoder != null) ? decoder.FallbackBuffer : decoderFallback.CreateFallbackBuffer()); decoderFallbackBuffer.InternalInitialize(byteStart, null); } num2 += decoderFallbackBuffer.InternalFallback(array, bytes); } c = c2; } else if (c == '\0') { num2--; byte[] array2 = null; array2 = ((!bigEndian) ? new byte[2] { (byte)c2, (byte)((int)c2 >> 8) } : new byte[2] { (byte)((int)c2 >> 8), (byte)c2 }); if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((decoder != null) ? decoder.FallbackBuffer : decoderFallback.CreateFallbackBuffer()); decoderFallbackBuffer.InternalInitialize(byteStart, null); } num2 += decoderFallbackBuffer.InternalFallback(array2, bytes); } else { c = '\0'; } } else if (c > '\0') { num2--; byte[] array3 = null; array3 = ((!bigEndian) ? new byte[2] { (byte)c, (byte)((int)c >> 8) } : new byte[2] { (byte)((int)c >> 8), (byte)c }); if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((decoder != null) ? decoder.FallbackBuffer : decoderFallback.CreateFallbackBuffer()); decoderFallbackBuffer.InternalInitialize(byteStart, null); } num2 += decoderFallbackBuffer.InternalFallback(array3, bytes); c = '\0'; } } if (decoder == null || decoder.MustFlush) { if (c > '\0') { num2--; byte[] array4 = null; array4 = ((!bigEndian) ? new byte[2] { (byte)c, (byte)((int)c >> 8) } : new byte[2] { (byte)((int)c >> 8), (byte)c }); if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((decoder != null) ? decoder.FallbackBuffer : decoderFallback.CreateFallbackBuffer()); decoderFallbackBuffer.InternalInitialize(byteStart, null); } num2 += decoderFallbackBuffer.InternalFallback(array4, bytes); c = '\0'; } if (num >= 0) { if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((decoder != null) ? decoder.FallbackBuffer : decoderFallback.CreateFallbackBuffer()); decoderFallbackBuffer.InternalInitialize(byteStart, null); } num2 += decoderFallbackBuffer.InternalFallback(new byte[1] { (byte)num }, bytes); num = -1; } } if (c > '\0') { num2--; } return num2; } internal unsafe sealed override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { Decoder decoder = (Decoder)baseDecoder; int num = -1; char c = '\0'; if (decoder != null) { num = decoder.lastByte; c = decoder.lastChar; } DecoderFallbackBuffer decoderFallbackBuffer = null; byte* ptr = bytes + byteCount; char* ptr2 = chars + charCount; byte* ptr3 = bytes; char* ptr4 = chars; while (bytes < ptr) { if ((bigEndian ^ BitConverter.IsLittleEndian) && ((int)chars & 3) == 0 && num == -1 && c == '\0') { ulong* ptr5 = (ulong*)(bytes - 7 + ((ptr - bytes >> 1 < ptr2 - chars) ? (ptr - bytes) : (ptr2 - chars << 1))); ulong* ptr6 = (ulong*)bytes; ulong* ptr7 = (ulong*)chars; while (ptr6 < ptr5) { if ((0x8000800080008000uL & *ptr6) != 0L) { ulong num2 = (0xF800F800F800F800uL & *ptr6) ^ 0xD800D800D800D800uL; if ((num2 & 0xFFFF000000000000uL) == 0L || (num2 & 0xFFFF00000000L) == 0L || (num2 & 0xFFFF0000u) == 0L || (num2 & 0xFFFF) == 0L) { long num3 = -287953294993589248L & (long)(*ptr6); if (!BitConverter.IsLittleEndian) { } if (num3 != -2593835887162763264L) { break; } } } Unsafe.WriteUnaligned(ptr7, *ptr6); ptr6++; ptr7++; } chars = (char*)ptr7; bytes = (byte*)ptr6; if (bytes >= ptr) { break; } } if (num < 0) { num = *(bytes++); continue; } char c2 = ((!bigEndian) ? ((char)((*(bytes++) << 8) | num)) : ((char)((num << 8) | *(bytes++)))); num = -1; if (c2 >= '\ud800' && c2 <= '\udfff') { if (c2 <= '\udbff') { if (c > '\0') { byte[] array = null; array = ((!bigEndian) ? new byte[2] { (byte)c, (byte)((int)c >> 8) } : new byte[2] { (byte)((int)c >> 8), (byte)c }); if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((decoder != null) ? decoder.FallbackBuffer : decoderFallback.CreateFallbackBuffer()); decoderFallbackBuffer.InternalInitialize(ptr3, ptr2); } char* chars2 = chars; bool flag = decoderFallbackBuffer.InternalFallback(array, bytes, ref chars2); chars = chars2; if (!flag) { bytes -= 2; decoderFallbackBuffer.InternalReset(); ThrowCharsOverflow(decoder, chars == ptr4); break; } } c = c2; continue; } if (c == '\0') { byte[] array2 = null; array2 = ((!bigEndian) ? new byte[2] { (byte)c2, (byte)((int)c2 >> 8) } : new byte[2] { (byte)((int)c2 >> 8), (byte)c2 }); if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((decoder != null) ? decoder.FallbackBuffer : decoderFallback.CreateFallbackBuffer()); decoderFallbackBuffer.InternalInitialize(ptr3, ptr2); } char* chars2 = chars; bool flag2 = decoderFallbackBuffer.InternalFallback(array2, bytes, ref chars2); chars = chars2; if (!flag2) { bytes -= 2; decoderFallbackBuffer.InternalReset(); ThrowCharsOverflow(decoder, chars == ptr4); break; } continue; } if (chars >= ptr2 - 1) { bytes -= 2; ThrowCharsOverflow(decoder, chars == ptr4); break; } *(chars++) = c; c = '\0'; } else if (c > '\0') { byte[] array3 = null; array3 = ((!bigEndian) ? new byte[2] { (byte)c, (byte)((int)c >> 8) } : new byte[2] { (byte)((int)c >> 8), (byte)c }); if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((decoder != null) ? decoder.FallbackBuffer : decoderFallback.CreateFallbackBuffer()); decoderFallbackBuffer.InternalInitialize(ptr3, ptr2); } char* chars2 = chars; bool flag3 = decoderFallbackBuffer.InternalFallback(array3, bytes, ref chars2); chars = chars2; if (!flag3) { bytes -= 2; decoderFallbackBuffer.InternalReset(); ThrowCharsOverflow(decoder, chars == ptr4); break; } c = '\0'; } if (chars >= ptr2) { bytes -= 2; ThrowCharsOverflow(decoder, chars == ptr4); break; } *(chars++) = c2; } if (decoder == null || decoder.MustFlush) { if (c > '\0') { byte[] array4 = null; array4 = ((!bigEndian) ? new byte[2] { (byte)c, (byte)((int)c >> 8) } : new byte[2] { (byte)((int)c >> 8), (byte)c }); if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((decoder != null) ? decoder.FallbackBuffer : decoderFallback.CreateFallbackBuffer()); decoderFallbackBuffer.InternalInitialize(ptr3, ptr2); } char* chars2 = chars; bool flag4 = decoderFallbackBuffer.InternalFallback(array4, bytes, ref chars2); chars = chars2; if (!flag4) { bytes -= 2; if (num >= 0) { bytes--; } decoderFallbackBuffer.InternalReset(); ThrowCharsOverflow(decoder, chars == ptr4); bytes += 2; if (num >= 0) { bytes++; } goto IL_04de; } c = '\0'; } if (num >= 0) { if (decoderFallbackBuffer == null) { decoderFallbackBuffer = ((decoder != null) ? decoder.FallbackBuffer : decoderFallback.CreateFallbackBuffer()); decoderFallbackBuffer.InternalInitialize(ptr3, ptr2); } char* chars2 = chars; bool flag5 = decoderFallbackBuffer.InternalFallback(new byte[1] { (byte)num }, bytes, ref chars2); chars = chars2; if (!flag5) { bytes--; decoderFallbackBuffer.InternalReset(); ThrowCharsOverflow(decoder, chars == ptr4); bytes++; } else { num = -1; } } } goto IL_04de; IL_04de: if (decoder != null) { decoder._bytesUsed = (int)(bytes - ptr3); decoder.lastChar = c; decoder.lastByte = num; } return (int)(chars - ptr4); } public override Encoder GetEncoder() { return new EncoderNLS(this); } public override System.Text.Decoder GetDecoder() { return new Decoder(this); } public override byte[] GetPreamble() { if (byteOrderMark) { if (!bigEndian) { return new byte[2] { 255, 254 }; } return new byte[2] { 254, 255 }; } return Array.Empty(); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } long num = (long)charCount + 1L; if (base.EncoderFallback.MaxCharCount > 1) { num *= base.EncoderFallback.MaxCharCount; } num <<= 1; if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_GetByteCountOverflow); } return (int)num; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) { throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } long num = (long)(byteCount >> 1) + (long)(byteCount & 1) + 1; if (base.DecoderFallback.MaxCharCount > 1) { num *= base.DecoderFallback.MaxCharCount; } if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_GetCharCountOverflow); } return (int)num; } public override bool Equals([NotNullWhen(true)] object? value) { if (value is UnicodeEncoding unicodeEncoding) { if (CodePage == unicodeEncoding.CodePage && byteOrderMark == unicodeEncoding.byteOrderMark && bigEndian == unicodeEncoding.bigEndian && base.EncoderFallback.Equals(unicodeEncoding.EncoderFallback)) { return base.DecoderFallback.Equals(unicodeEncoding.DecoderFallback); } return false; } return false; } public override int GetHashCode() { return CodePage + base.EncoderFallback.GetHashCode() + base.DecoderFallback.GetHashCode() + (byteOrderMark ? 4 : 0) + (bigEndian ? 8 : 0); } } internal static class UnicodeUtility { 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; } } public sealed class UTF32Encoding : Encoding { private sealed class UTF32Decoder : DecoderNLS { internal int iChar; internal int readByteCount; internal override bool HasState => readByteCount != 0; public UTF32Decoder(UTF32Encoding encoding) : base(encoding) { } public override void Reset() { iChar = 0; readByteCount = 0; if (_fallbackBuffer != null) { _fallbackBuffer.Reset(); } } } internal static readonly UTF32Encoding s_default = new UTF32Encoding(bigEndian: false, byteOrderMark: true); internal static readonly UTF32Encoding s_bigEndianDefault = new UTF32Encoding(bigEndian: true, byteOrderMark: true); private readonly bool _emitUTF32ByteOrderMark; private readonly bool _isThrowException; private readonly bool _bigEndian; public override ReadOnlySpan Preamble { get { if (!(GetType() != typeof(UTF32Encoding))) { if (_emitUTF32ByteOrderMark) { if (_bigEndian) { return new byte[4] { 0, 0, 254, 255 }; } return new byte[4] { 255, 254, 0, 0 }; } return default(ReadOnlySpan); } return new ReadOnlySpan(GetPreamble()); } } public UTF32Encoding() : this(bigEndian: false, byteOrderMark: true) { } public UTF32Encoding(bool bigEndian, bool byteOrderMark) : base(bigEndian ? 12001 : 12000) { _bigEndian = bigEndian; _emitUTF32ByteOrderMark = byteOrderMark; } public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidCharacters) : this(bigEndian, byteOrderMark) { _isThrowException = throwOnInvalidCharacters; if (_isThrowException) { SetDefaultFallbacks(); } } internal override void SetDefaultFallbacks() { if (_isThrowException) { encoderFallback = System.Text.EncoderFallback.ExceptionFallback; decoderFallback = System.Text.DecoderFallback.ExceptionFallback; } else { encoderFallback = new EncoderReplacementFallback("\ufffd"); decoderFallback = new DecoderReplacementFallback("\ufffd"); } } public unsafe override int GetByteCount(char[] chars, int index, int count) { if (chars == null) { throw new ArgumentNullException("chars", SR.ArgumentNull_Array); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - index < count) { throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); } if (count == 0) { return 0; } fixed (char* ptr = chars) { return GetByteCount(ptr + index, count, null); } } public unsafe override int GetByteCount(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } fixed (char* pChars = s) { return GetByteCount(pChars, s.Length, null); } } [CLSCompliant(false)] public unsafe override int GetByteCount(char* chars, int count) { if (chars == null) { throw new ArgumentNullException("chars", SR.ArgumentNull_Array); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } return GetByteCount(chars, count, null); } public unsafe override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) { throw new ArgumentNullException((s == null) ? "s" : "bytes", SR.ArgumentNull_Array); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (s.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); } int byteCount = bytes.Length - byteIndex; fixed (char* ptr = s) { fixed (byte* ptr2 = &MemoryMarshal.GetReference(bytes)) { return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, null); } } } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null || bytes == null) { throw new ArgumentNullException((chars == null) ? "chars" : "bytes", SR.ArgumentNull_Array); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); } if (charCount == 0) { return 0; } int byteCount = bytes.Length - byteIndex; fixed (char* ptr = chars) { fixed (byte* ptr2 = &MemoryMarshal.GetReference(bytes)) { return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, null); } } } [CLSCompliant(false)] public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } return GetBytes(chars, charCount, bytes, byteCount, null); } public unsafe override int GetCharCount(byte[] bytes, int index, int count) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } if (count == 0) { return 0; } fixed (byte* ptr = bytes) { return GetCharCount(ptr + index, count, null); } } [CLSCompliant(false)] public unsafe override int GetCharCount(byte* bytes, int count) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } return GetCharCount(bytes, count, null); } public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } if (charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); } if (byteCount == 0) { return 0; } int charCount = chars.Length - charIndex; fixed (byte* ptr = bytes) { fixed (char* ptr2 = &MemoryMarshal.GetReference(chars)) { return GetChars(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, null); } } } [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } return GetChars(bytes, byteCount, chars, charCount, null); } public unsafe override string GetString(byte[] bytes, int index, int count) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } if (count == 0) { return string.Empty; } fixed (byte* ptr = bytes) { return string.CreateStringFromEncoding(ptr + index, count, this); } } internal unsafe override int GetByteCount(char* chars, int count, EncoderNLS encoder) { char* ptr = chars + count; char* charStart = chars; int num = 0; char c = '\0'; EncoderFallbackBuffer encoderFallbackBuffer = null; if (encoder != null) { c = encoder._charLeftOver; encoderFallbackBuffer = encoder.FallbackBuffer; if (encoderFallbackBuffer.Remaining > 0) { throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback?.GetType().ToString() ?? string.Empty)); } } else { encoderFallbackBuffer = encoderFallback.CreateFallbackBuffer(); } encoderFallbackBuffer.InternalInitialize(charStart, ptr, encoder, setEncoder: false); while (true) { char c2; if ((c2 = encoderFallbackBuffer.InternalGetNextChar()) != 0 || chars < ptr) { if (c2 == '\0') { c2 = *chars; chars++; } if (c != 0) { if (char.IsLowSurrogate(c2)) { c = '\0'; num += 4; continue; } chars--; char* chars2 = chars; encoderFallbackBuffer.InternalFallback(c, ref chars2); chars = chars2; c = '\0'; } else if (char.IsHighSurrogate(c2)) { c = c2; } else if (char.IsLowSurrogate(c2)) { char* chars2 = chars; encoderFallbackBuffer.InternalFallback(c2, ref chars2); chars = chars2; } else { num += 4; } } else { if ((encoder != null && !encoder.MustFlush) || c <= '\0') { break; } char* chars2 = chars; encoderFallbackBuffer.InternalFallback(c, ref chars2); chars = chars2; c = '\0'; } } if (num < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_GetByteCountOverflow); } return num; } internal unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { char* ptr = chars; char* ptr2 = chars + charCount; byte* ptr3 = bytes; byte* ptr4 = bytes + byteCount; char c = '\0'; EncoderFallbackBuffer encoderFallbackBuffer = null; if (encoder != null) { c = encoder._charLeftOver; encoderFallbackBuffer = encoder.FallbackBuffer; if (encoder._throwOnOverflow && encoderFallbackBuffer.Remaining > 0) { throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback?.GetType())); } } else { encoderFallbackBuffer = encoderFallback.CreateFallbackBuffer(); } encoderFallbackBuffer.InternalInitialize(ptr, ptr2, encoder, setEncoder: true); while (true) { char c2; char* chars2; if ((c2 = encoderFallbackBuffer.InternalGetNextChar()) != 0 || chars < ptr2) { if (c2 == '\0') { c2 = *chars; chars++; } if (c != 0) { if (!char.IsLowSurrogate(c2)) { chars--; chars2 = chars; encoderFallbackBuffer.InternalFallback(c, ref chars2); chars = chars2; c = '\0'; continue; } uint surrogate = GetSurrogate(c, c2); c = '\0'; if (bytes + 3 < ptr4) { if (_bigEndian) { *(bytes++) = 0; *(bytes++) = (byte)(surrogate >> 16); *(bytes++) = (byte)(surrogate >> 8); *(bytes++) = (byte)surrogate; } else { *(bytes++) = (byte)surrogate; *(bytes++) = (byte)(surrogate >> 8); *(bytes++) = (byte)(surrogate >> 16); *(bytes++) = 0; } continue; } if (encoderFallbackBuffer.bFallingBack) { encoderFallbackBuffer.MovePrevious(); encoderFallbackBuffer.MovePrevious(); } else { chars -= 2; } ThrowBytesOverflow(encoder, bytes == ptr3); c = '\0'; } else { if (char.IsHighSurrogate(c2)) { c = c2; continue; } if (char.IsLowSurrogate(c2)) { chars2 = chars; encoderFallbackBuffer.InternalFallback(c2, ref chars2); chars = chars2; continue; } if (bytes + 3 < ptr4) { if (_bigEndian) { *(bytes++) = 0; *(bytes++) = 0; *(bytes++) = (byte)((uint)c2 >> 8); *(bytes++) = (byte)c2; } else { *(bytes++) = (byte)c2; *(bytes++) = (byte)((uint)c2 >> 8); *(bytes++) = 0; *(bytes++) = 0; } continue; } if (encoderFallbackBuffer.bFallingBack) { encoderFallbackBuffer.MovePrevious(); } else { chars--; } ThrowBytesOverflow(encoder, bytes == ptr3); } } if ((encoder != null && !encoder.MustFlush) || c <= '\0') { break; } chars2 = chars; encoderFallbackBuffer.InternalFallback(c, ref chars2); chars = chars2; c = '\0'; } if (encoder != null) { encoder._charLeftOver = c; encoder._charsUsed = (int)(chars - ptr); } return (int)(bytes - ptr3); } internal unsafe override int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { UTF32Decoder uTF32Decoder = (UTF32Decoder)baseDecoder; int num = 0; byte* ptr = bytes + count; byte* byteStart = bytes; int num2 = 0; uint num3 = 0u; DecoderFallbackBuffer decoderFallbackBuffer = null; if (uTF32Decoder != null) { num2 = uTF32Decoder.readByteCount; num3 = (uint)uTF32Decoder.iChar; decoderFallbackBuffer = uTF32Decoder.FallbackBuffer; } else { decoderFallbackBuffer = decoderFallback.CreateFallbackBuffer(); } decoderFallbackBuffer.InternalInitialize(byteStart, null); while (bytes < ptr && num >= 0) { if (_bigEndian) { num3 <<= 8; num3 += *(bytes++); } else { num3 >>= 8; num3 += (uint)(*(bytes++) << 24); } num2++; if (num2 < 4) { continue; } num2 = 0; if (num3 > 1114111 || (num3 >= 55296 && num3 <= 57343)) { byte[] bytes2 = ((!_bigEndian) ? new byte[4] { (byte)num3, (byte)(num3 >> 8), (byte)(num3 >> 16), (byte)(num3 >> 24) } : new byte[4] { (byte)(num3 >> 24), (byte)(num3 >> 16), (byte)(num3 >> 8), (byte)num3 }); num += decoderFallbackBuffer.InternalFallback(bytes2, bytes); num3 = 0u; } else { if (num3 >= 65536) { num++; } num++; num3 = 0u; } } if (num2 > 0 && (uTF32Decoder == null || uTF32Decoder.MustFlush)) { byte[] array = new byte[num2]; if (_bigEndian) { while (num2 > 0) { array[--num2] = (byte)num3; num3 >>= 8; } } else { while (num2 > 0) { array[--num2] = (byte)(num3 >> 24); num3 <<= 8; } } num += decoderFallbackBuffer.InternalFallback(array, bytes); } if (num < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_GetByteCountOverflow); } return num; } internal unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { UTF32Decoder uTF32Decoder = (UTF32Decoder)baseDecoder; char* ptr = chars; char* ptr2 = chars + charCount; byte* ptr3 = bytes; byte* ptr4 = bytes + byteCount; int num = 0; uint num2 = 0u; DecoderFallbackBuffer decoderFallbackBuffer = null; if (uTF32Decoder != null) { num = uTF32Decoder.readByteCount; num2 = (uint)uTF32Decoder.iChar; decoderFallbackBuffer = baseDecoder.FallbackBuffer; } else { decoderFallbackBuffer = decoderFallback.CreateFallbackBuffer(); } decoderFallbackBuffer.InternalInitialize(bytes, chars + charCount); while (bytes < ptr4) { if (_bigEndian) { num2 <<= 8; num2 += *(bytes++); } else { num2 >>= 8; num2 += (uint)(*(bytes++) << 24); } num++; if (num < 4) { continue; } num = 0; if (num2 > 1114111 || (num2 >= 55296 && num2 <= 57343)) { byte[] bytes2 = ((!_bigEndian) ? new byte[4] { (byte)num2, (byte)(num2 >> 8), (byte)(num2 >> 16), (byte)(num2 >> 24) } : new byte[4] { (byte)(num2 >> 24), (byte)(num2 >> 16), (byte)(num2 >> 8), (byte)num2 }); char* chars2 = chars; bool flag = decoderFallbackBuffer.InternalFallback(bytes2, bytes, ref chars2); chars = chars2; if (!flag) { bytes -= 4; num2 = 0u; decoderFallbackBuffer.InternalReset(); ThrowCharsOverflow(uTF32Decoder, chars == ptr); break; } num2 = 0u; continue; } if (num2 >= 65536) { if (chars >= ptr2 - 1) { bytes -= 4; num2 = 0u; ThrowCharsOverflow(uTF32Decoder, chars == ptr); break; } *(chars++) = GetHighSurrogate(num2); num2 = GetLowSurrogate(num2); } else if (chars >= ptr2) { bytes -= 4; num2 = 0u; ThrowCharsOverflow(uTF32Decoder, chars == ptr); break; } *(chars++) = (char)num2; num2 = 0u; } if (num > 0 && (uTF32Decoder == null || uTF32Decoder.MustFlush)) { byte[] array = new byte[num]; int num3 = num; if (_bigEndian) { while (num3 > 0) { array[--num3] = (byte)num2; num2 >>= 8; } } else { while (num3 > 0) { array[--num3] = (byte)(num2 >> 24); num2 <<= 8; } } char* chars2 = chars; bool flag2 = decoderFallbackBuffer.InternalFallback(array, bytes, ref chars2); chars = chars2; if (!flag2) { decoderFallbackBuffer.InternalReset(); ThrowCharsOverflow(uTF32Decoder, chars == ptr); } else { num = 0; num2 = 0u; } } if (uTF32Decoder != null) { uTF32Decoder.iChar = (int)num2; uTF32Decoder.readByteCount = num; uTF32Decoder._bytesUsed = (int)(bytes - ptr3); } return (int)(chars - ptr); } private static uint GetSurrogate(char cHigh, char cLow) { return (uint)((cHigh - 55296) * 1024 + (cLow - 56320) + 65536); } private static char GetHighSurrogate(uint iChar) { return (char)((iChar - 65536) / 1024 + 55296); } private static char GetLowSurrogate(uint iChar) { return (char)((iChar - 65536) % 1024 + 56320); } public override Decoder GetDecoder() { return new UTF32Decoder(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } long num = (long)charCount + 1L; if (base.EncoderFallback.MaxCharCount > 1) { num *= base.EncoderFallback.MaxCharCount; } num *= 4; if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_GetByteCountOverflow); } return (int)num; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) { throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } int num = byteCount / 2 + 2; if (base.DecoderFallback.MaxCharCount > 2) { num *= base.DecoderFallback.MaxCharCount; num /= 2; } if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_GetCharCountOverflow); } return num; } public override byte[] GetPreamble() { if (_emitUTF32ByteOrderMark) { if (!_bigEndian) { return new byte[4] { 255, 254, 0, 0 }; } return new byte[4] { 0, 0, 254, 255 }; } return Array.Empty(); } public override bool Equals([NotNullWhen(true)] object? value) { if (value is UTF32Encoding uTF32Encoding) { if (_emitUTF32ByteOrderMark == uTF32Encoding._emitUTF32ByteOrderMark && _bigEndian == uTF32Encoding._bigEndian && base.EncoderFallback.Equals(uTF32Encoding.EncoderFallback)) { return base.DecoderFallback.Equals(uTF32Encoding.DecoderFallback); } return false; } return false; } public override int GetHashCode() { return base.EncoderFallback.GetHashCode() + base.DecoderFallback.GetHashCode() + CodePage + (_emitUTF32ByteOrderMark ? 4 : 0) + (_bigEndian ? 8 : 0); } } public class UTF7Encoding : Encoding { private sealed class Decoder : DecoderNLS { internal int bits; internal int bitCount; internal bool firstByte; internal override bool HasState => bitCount != -1; public Decoder(UTF7Encoding encoding) : base(encoding) { } public override void Reset() { bits = 0; bitCount = -1; firstByte = false; if (_fallbackBuffer != null) { _fallbackBuffer.Reset(); } } } private sealed class Encoder : EncoderNLS { internal int bits; internal int bitCount; internal override bool HasState { get { if (bits == 0) { return bitCount != -1; } return true; } } public Encoder(UTF7Encoding encoding) : base(encoding) { } public override void Reset() { bitCount = -1; bits = 0; if (_fallbackBuffer != null) { _fallbackBuffer.Reset(); } } } private sealed class DecoderUTF7Fallback : DecoderFallback { public override int MaxCharCount => 1; public override DecoderFallbackBuffer CreateFallbackBuffer() { return new DecoderUTF7FallbackBuffer(); } public override bool Equals([NotNullWhen(true)] object value) { return value is DecoderUTF7Fallback; } public override int GetHashCode() { return 984; } } private sealed class DecoderUTF7FallbackBuffer : DecoderFallbackBuffer { private char cFallback; private int iCount = -1; private int iSize; public override int Remaining { get { if (iCount <= 0) { return 0; } return iCount; } } public override bool Fallback(byte[] bytesUnknown, int index) { cFallback = (char)bytesUnknown[0]; if (cFallback == '\0') { return false; } iCount = (iSize = 1); return true; } public override char GetNextChar() { if (iCount-- > 0) { return cFallback; } return '\0'; } public override bool MovePrevious() { if (iCount >= 0) { iCount++; } if (iCount >= 0) { return iCount <= iSize; } return false; } public unsafe override void Reset() { iCount = -1; byteStart = null; } internal unsafe override int InternalFallback(byte[] bytes, byte* pBytes) { if (bytes.Length != 1) { throw new ArgumentException(SR.Argument_InvalidCharSequenceNoIndex); } if (bytes[0] != 0) { return 1; } return 0; } } internal static readonly UTF7Encoding s_default = new UTF7Encoding(); private byte[] _base64Bytes; private sbyte[] _base64Values; private bool[] _directEncode; private readonly bool _allowOptionals; [Obsolete("The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead.", DiagnosticId = "SYSLIB0001", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public UTF7Encoding() : this(allowOptionals: false) { } [Obsolete("The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead.", DiagnosticId = "SYSLIB0001", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public UTF7Encoding(bool allowOptionals) : base(65000) { _allowOptionals = allowOptionals; MakeTables(); } [MemberNotNull("_base64Bytes")] [MemberNotNull("_base64Values")] [MemberNotNull("_directEncode")] private void MakeTables() { _base64Bytes = new byte[64]; for (int i = 0; i < 64; i++) { _base64Bytes[i] = (byte)"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i]; } _base64Values = new sbyte[128]; for (int j = 0; j < 128; j++) { _base64Values[j] = -1; } for (int k = 0; k < 64; k++) { _base64Values[_base64Bytes[k]] = (sbyte)k; } _directEncode = new bool[128]; int length = "\t\n\r '(),-./0123456789:?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".Length; for (int l = 0; l < length; l++) { _directEncode[(uint)"\t\n\r '(),-./0123456789:?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[l]] = true; } if (_allowOptionals) { length = "!\"#$%&*;<=>@[]^_`{|}".Length; for (int m = 0; m < length; m++) { _directEncode[(uint)"!\"#$%&*;<=>@[]^_`{|}"[m]] = true; } } } internal sealed override void SetDefaultFallbacks() { encoderFallback = new EncoderReplacementFallback(string.Empty); decoderFallback = new DecoderUTF7Fallback(); } public override bool Equals([NotNullWhen(true)] object? value) { if (value is UTF7Encoding uTF7Encoding) { if (_allowOptionals == uTF7Encoding._allowOptionals && base.EncoderFallback.Equals(uTF7Encoding.EncoderFallback)) { return base.DecoderFallback.Equals(uTF7Encoding.DecoderFallback); } return false; } return false; } public override int GetHashCode() { return CodePage + base.EncoderFallback.GetHashCode() + base.DecoderFallback.GetHashCode(); } public unsafe override int GetByteCount(char[] chars, int index, int count) { if (chars == null) { throw new ArgumentNullException("chars", SR.ArgumentNull_Array); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - index < count) { throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); } if (count == 0) { return 0; } fixed (char* ptr = chars) { return GetByteCount(ptr + index, count, null); } } public unsafe override int GetByteCount(string s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } fixed (char* pChars = s) { return GetByteCount(pChars, s.Length, null); } } [CLSCompliant(false)] public unsafe override int GetByteCount(char* chars, int count) { if (chars == null) { throw new ArgumentNullException("chars", SR.ArgumentNull_Array); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } return GetByteCount(chars, count, null); } public unsafe override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) { throw new ArgumentNullException((s == null) ? "s" : "bytes", SR.ArgumentNull_Array); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (s.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("s", SR.ArgumentOutOfRange_IndexCount); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); } int byteCount = bytes.Length - byteIndex; fixed (char* ptr = s) { fixed (byte* ptr2 = &MemoryMarshal.GetReference(bytes)) { return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, null); } } } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null || bytes == null) { throw new ArgumentNullException((chars == null) ? "chars" : "bytes", SR.ArgumentNull_Array); } if (charIndex < 0 || charCount < 0) { throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { throw new ArgumentOutOfRangeException("chars", SR.ArgumentOutOfRange_IndexCountBuffer); } if (byteIndex < 0 || byteIndex > bytes.Length) { throw new ArgumentOutOfRangeException("byteIndex", SR.ArgumentOutOfRange_Index); } if (charCount == 0) { return 0; } int byteCount = bytes.Length - byteIndex; fixed (char* ptr = chars) { fixed (byte* ptr2 = &MemoryMarshal.GetReference(bytes)) { return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, null); } } } [CLSCompliant(false)] public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } return GetBytes(chars, charCount, bytes, byteCount, null); } public unsafe override int GetCharCount(byte[] bytes, int index, int count) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } if (count == 0) { return 0; } fixed (byte* ptr = bytes) { return GetCharCount(ptr + index, count, null); } } [CLSCompliant(false)] public unsafe override int GetCharCount(byte* bytes, int count) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } return GetCharCount(bytes, count, null); } public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (byteIndex < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } if (charIndex < 0 || charIndex > chars.Length) { throw new ArgumentOutOfRangeException("charIndex", SR.ArgumentOutOfRange_Index); } if (byteCount == 0) { return 0; } int charCount = chars.Length - charIndex; fixed (byte* ptr = bytes) { fixed (char* ptr2 = &MemoryMarshal.GetReference(chars)) { return GetChars(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, null); } } } [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { if (bytes == null || chars == null) { throw new ArgumentNullException((bytes == null) ? "bytes" : "chars", SR.ArgumentNull_Array); } if (charCount < 0 || byteCount < 0) { throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } return GetChars(bytes, byteCount, chars, charCount, null); } public unsafe override string GetString(byte[] bytes, int index, int count) { if (bytes == null) { throw new ArgumentNullException("bytes", SR.ArgumentNull_Array); } if (index < 0 || count < 0) { throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { throw new ArgumentOutOfRangeException("bytes", SR.ArgumentOutOfRange_IndexCountBuffer); } if (count == 0) { return string.Empty; } fixed (byte* ptr = bytes) { return string.CreateStringFromEncoding(ptr + index, count, this); } } internal unsafe sealed override int GetByteCount(char* chars, int count, EncoderNLS baseEncoder) { return GetBytes(chars, count, null, 0, baseEncoder); } internal unsafe sealed override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS baseEncoder) { Encoder encoder = (Encoder)baseEncoder; int num = 0; int num2 = -1; EncodingByteBuffer encodingByteBuffer = new EncodingByteBuffer(this, encoder, bytes, byteCount, chars, charCount); if (encoder != null) { num = encoder.bits; num2 = encoder.bitCount; while (num2 >= 6) { num2 -= 6; if (!encodingByteBuffer.AddByte(_base64Bytes[(num >> num2) & 0x3F])) { ThrowBytesOverflow(encoder, encodingByteBuffer.Count == 0); } } } while (encodingByteBuffer.MoreData) { char nextChar = encodingByteBuffer.GetNextChar(); if (nextChar < '\u0080' && _directEncode[(uint)nextChar]) { if (num2 >= 0) { if (num2 > 0) { if (!encodingByteBuffer.AddByte(_base64Bytes[(num << 6 - num2) & 0x3F])) { break; } num2 = 0; } if (!encodingByteBuffer.AddByte(45)) { break; } num2 = -1; } if (!encodingByteBuffer.AddByte((byte)nextChar)) { break; } continue; } if (num2 < 0 && nextChar == '+') { if (!encodingByteBuffer.AddByte((byte)43, (byte)45)) { break; } continue; } if (num2 < 0) { if (!encodingByteBuffer.AddByte(43)) { break; } num2 = 0; } num = (num << 16) | nextChar; num2 += 16; while (num2 >= 6) { num2 -= 6; if (!encodingByteBuffer.AddByte(_base64Bytes[(num >> num2) & 0x3F])) { num2 += 6; encodingByteBuffer.GetNextChar(); break; } } if (num2 >= 6) { break; } } if (num2 >= 0 && (encoder == null || encoder.MustFlush)) { if (num2 > 0 && encodingByteBuffer.AddByte(_base64Bytes[(num << 6 - num2) & 0x3F])) { num2 = 0; } if (encodingByteBuffer.AddByte(45)) { num = 0; num2 = -1; } else { encodingByteBuffer.GetNextChar(); } } if (bytes != null && encoder != null) { encoder.bits = num; encoder.bitCount = num2; encoder._charsUsed = encodingByteBuffer.CharsUsed; } return encodingByteBuffer.Count; } internal unsafe sealed override int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { return GetChars(bytes, count, null, 0, baseDecoder); } internal unsafe sealed override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { Decoder decoder = (Decoder)baseDecoder; EncodingCharBuffer encodingCharBuffer = new EncodingCharBuffer(this, decoder, chars, charCount, bytes, byteCount); int num = 0; int num2 = -1; bool flag = false; if (decoder != null) { num = decoder.bits; num2 = decoder.bitCount; flag = decoder.firstByte; } if (num2 >= 16) { if (!encodingCharBuffer.AddChar((char)((uint)(num >> num2 - 16) & 0xFFFFu))) { ThrowCharsOverflow(decoder, nothingDecoded: true); } num2 -= 16; } while (encodingCharBuffer.MoreData) { byte nextByte = encodingCharBuffer.GetNextByte(); int num3; if (num2 >= 0) { sbyte b; if (nextByte < 128 && (b = _base64Values[nextByte]) >= 0) { flag = false; num = (num << 6) | (byte)b; num2 += 6; if (num2 < 16) { continue; } num3 = (num >> num2 - 16) & 0xFFFF; num2 -= 16; } else { num2 = -1; if (nextByte != 45) { if (!encodingCharBuffer.Fallback(nextByte)) { break; } continue; } if (!flag) { continue; } num3 = 43; } } else { if (nextByte == 43) { num2 = 0; flag = true; continue; } if (nextByte >= 128) { if (!encodingCharBuffer.Fallback(nextByte)) { break; } continue; } num3 = nextByte; } if (num3 >= 0 && !encodingCharBuffer.AddChar((char)num3)) { if (num2 >= 0) { encodingCharBuffer.AdjustBytes(1); num2 += 16; } break; } } if (chars != null && decoder != null) { if (decoder.MustFlush) { decoder.bits = 0; decoder.bitCount = -1; decoder.firstByte = false; } else { decoder.bits = num; decoder.bitCount = num2; decoder.firstByte = flag; } decoder._bytesUsed = encodingCharBuffer.BytesUsed; } return encodingCharBuffer.Count; } public override System.Text.Decoder GetDecoder() { return new Decoder(this); } public override System.Text.Encoder GetEncoder() { return new Encoder(this); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } long num = (long)charCount * 3L + 2; if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_GetByteCountOverflow); } return (int)num; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) { throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } int num = byteCount; if (num == 0) { num = 1; } return num; } } public class UTF8Encoding : Encoding { internal sealed class UTF8EncodingSealed : UTF8Encoding { public override ReadOnlySpan Preamble { get { if (!_emitUTF8Identifier) { return default(ReadOnlySpan); } return PreambleSpan; } } public UTF8EncodingSealed(bool encoderShouldEmitUTF8Identifier) : base(encoderShouldEmitUTF8Identifier) { } public override object Clone() { return new UTF8Encoding(_emitUTF8Identifier) { IsReadOnly = false }; } public override byte[] GetBytes(string s) { if (s != null && s.Length <= 32) { return GetBytesForSmallInput(s); } return base.GetBytes(s); } private unsafe byte[] GetBytesForSmallInput(string s) { byte* ptr = stackalloc byte[96]; int length = s.Length; int bytesCommon; fixed (char* pChars = s) { bytesCommon = GetBytesCommon(pChars, length, ptr, 96); } return new Span(ref *ptr, bytesCommon).ToArray(); } public override string GetString(byte[] bytes) { if (bytes != null && bytes.Length <= 32) { return GetStringForSmallInput(bytes); } return base.GetString(bytes); } private unsafe string GetStringForSmallInput(byte[] bytes) { char* ptr = stackalloc char[32]; int byteCount = bytes.Length; int charsCommon; fixed (byte* pBytes = bytes) { charsCommon = GetCharsCommon(pBytes, byteCount, ptr, 32); } return new string(new ReadOnlySpan(ref *ptr, charsCommon)); } } internal static readonly UTF8EncodingSealed s_default = new UTF8EncodingSealed(encoderShouldEmitUTF8Identifier: true); private readonly bool _emitUTF8Identifier; private readonly bool _isThrowException; internal static ReadOnlySpan PreambleSpan => "\ufeff"u8; public override ReadOnlySpan Preamble { get { if (!(GetType() != typeof(UTF8Encoding))) { if (!_emitUTF8Identifier) { return default(ReadOnlySpan); } return PreambleSpan; } return new ReadOnlySpan(GetPreamble()); } } public UTF8Encoding() : base(65001) { } public UTF8Encoding(bool encoderShouldEmitUTF8Identifier) : this() { _emitUTF8Identifier = encoderShouldEmitUTF8Identifier; } public UTF8Encoding(bool encoderShouldEmitUTF8Identifier, bool throwOnInvalidBytes) : this(encoderShouldEmitUTF8Identifier) { _isThrowException = throwOnInvalidBytes; if (_isThrowException) { SetDefaultFallbacks(); } } internal sealed override void SetDefaultFallbacks() { if (_isThrowException) { encoderFallback = System.Text.EncoderFallback.ExceptionFallback; decoderFallback = System.Text.DecoderFallback.ExceptionFallback; } else { encoderFallback = new EncoderReplacementFallback("\ufffd"); decoderFallback = new DecoderReplacementFallback("\ufffd"); } } public unsafe override int GetByteCount(char[] chars, int index, int count) { if (chars == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars, ExceptionResource.ArgumentNull_Array); } if ((index | count) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } fixed (char* ptr = chars) { return GetByteCountCommon(ptr + index, count); } } public unsafe override int GetByteCount(string chars) { if (chars == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); } fixed (char* pChars = chars) { return GetByteCountCommon(pChars, chars.Length); } } [CLSCompliant(false)] public unsafe override int GetByteCount(char* chars, int count) { if (chars == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetByteCountCommon(chars, count); } public unsafe override int GetByteCount(ReadOnlySpan chars) { fixed (char* pChars = &MemoryMarshal.GetReference(chars)) { return GetByteCountCommon(pChars, chars.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetByteCountCommon(char* pChars, int charCount) { int charsConsumed; int num = GetByteCountFast(pChars, charCount, null, out charsConsumed); if (charsConsumed != charCount) { num += GetByteCountWithFallback(pChars, charCount, charsConsumed); if (num < 0) { Encoding.ThrowConversionOverflow(); } } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private protected unsafe sealed override int GetByteCountFast(char* pChars, int charsLength, EncoderFallback fallback, out int charsConsumed) { long utf8CodeUnitCountAdjustment; int scalarCountAdjustment; char* pointerToFirstInvalidChar = Utf16Utility.GetPointerToFirstInvalidChar(pChars, charsLength, out utf8CodeUnitCountAdjustment, out scalarCountAdjustment); long num = (charsConsumed = (int)(pointerToFirstInvalidChar - pChars)) + utf8CodeUnitCountAdjustment; if ((ulong)num > 2147483647uL) { Encoding.ThrowConversionOverflow(); } return (int)num; } public unsafe override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) { ThrowHelper.ThrowArgumentNullException((s == null) ? ExceptionArgument.s : ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((charIndex | charCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((charIndex < 0) ? ExceptionArgument.charIndex : ExceptionArgument.charCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (s.Length - charIndex < charCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.s, ExceptionResource.ArgumentOutOfRange_IndexCount); } if ((uint)byteIndex > bytes.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.byteIndex, ExceptionResource.ArgumentOutOfRange_Index); } fixed (char* ptr2 = s) { fixed (byte[] array = bytes) { byte* ptr = (byte*)((bytes != null && array.Length != 0) ? System.Runtime.CompilerServices.Unsafe.AsPointer(ref array[0]) : null); return GetBytesCommon(ptr2 + charIndex, charCount, ptr + byteIndex, bytes.Length - byteIndex); } } } public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (chars == null || bytes == null) { ThrowHelper.ThrowArgumentNullException((chars == null) ? ExceptionArgument.chars : ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((charIndex | charCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((charIndex < 0) ? ExceptionArgument.charIndex : ExceptionArgument.charCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (chars.Length - charIndex < charCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCount); } if ((uint)byteIndex > bytes.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.byteIndex, ExceptionResource.ArgumentOutOfRange_Index); } fixed (char* ptr = chars) { fixed (byte* ptr2 = bytes) { return GetBytesCommon(ptr + charIndex, charCount, ptr2 + byteIndex, bytes.Length - byteIndex); } } } [CLSCompliant(false)] public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { if (chars == null || bytes == null) { ThrowHelper.ThrowArgumentNullException((chars == null) ? ExceptionArgument.chars : ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((charCount | byteCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((charCount < 0) ? ExceptionArgument.charCount : ExceptionArgument.byteCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetBytesCommon(chars, charCount, bytes, byteCount); } public unsafe override int GetBytes(ReadOnlySpan chars, Span bytes) { fixed (char* pChars = &MemoryMarshal.GetReference(chars)) { fixed (byte* pBytes = &MemoryMarshal.GetReference(bytes)) { return GetBytesCommon(pChars, chars.Length, pBytes, bytes.Length); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetBytesCommon(char* pChars, int charCount, byte* pBytes, int byteCount) { int charsConsumed; int bytesFast = GetBytesFast(pChars, charCount, pBytes, byteCount, out charsConsumed); if (charsConsumed == charCount) { return bytesFast; } return GetBytesWithFallback(pChars, charCount, pBytes, byteCount, charsConsumed, bytesFast); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private protected unsafe sealed override int GetBytesFast(char* pChars, int charsLength, byte* pBytes, int bytesLength, out int charsConsumed) { Utf8Utility.TranscodeToUtf8(pChars, charsLength, pBytes, bytesLength, out var pInputBufferRemaining, out var pOutputBufferRemaining); charsConsumed = (int)(pInputBufferRemaining - pChars); return (int)(pOutputBufferRemaining - pBytes); } public unsafe override int GetCharCount(byte[] bytes, int index, int count) { if (bytes == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((index | count) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } fixed (byte* ptr = bytes) { return GetCharCountCommon(ptr + index, count); } } [CLSCompliant(false)] public unsafe override int GetCharCount(byte* bytes, int count) { if (bytes == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetCharCountCommon(bytes, count); } public unsafe override int GetCharCount(ReadOnlySpan bytes) { fixed (byte* pBytes = &MemoryMarshal.GetReference(bytes)) { return GetCharCountCommon(pBytes, bytes.Length); } } public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { if (bytes == null || chars == null) { ThrowHelper.ThrowArgumentNullException((bytes == null) ? ExceptionArgument.bytes : ExceptionArgument.chars, ExceptionResource.ArgumentNull_Array); } if ((byteIndex | byteCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((byteIndex < 0) ? ExceptionArgument.byteIndex : ExceptionArgument.byteCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - byteIndex < byteCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } if ((uint)charIndex > (uint)chars.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.charIndex, ExceptionResource.ArgumentOutOfRange_Index); } fixed (byte* ptr = bytes) { fixed (char* ptr2 = chars) { return GetCharsCommon(ptr + byteIndex, byteCount, ptr2 + charIndex, chars.Length - charIndex); } } } [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { if (bytes == null || chars == null) { ThrowHelper.ThrowArgumentNullException((bytes == null) ? ExceptionArgument.bytes : ExceptionArgument.chars, ExceptionResource.ArgumentNull_Array); } if ((byteCount | charCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((byteCount < 0) ? ExceptionArgument.byteCount : ExceptionArgument.charCount, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetCharsCommon(bytes, byteCount, chars, charCount); } public unsafe override int GetChars(ReadOnlySpan bytes, Span chars) { fixed (byte* pBytes = &MemoryMarshal.GetReference(bytes)) { fixed (char* pChars = &MemoryMarshal.GetReference(chars)) { return GetCharsCommon(pBytes, bytes.Length, pChars, chars.Length); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetCharsCommon(byte* pBytes, int byteCount, char* pChars, int charCount) { int bytesConsumed; int charsFast = GetCharsFast(pBytes, byteCount, pChars, charCount, out bytesConsumed); if (bytesConsumed == byteCount) { return charsFast; } return GetCharsWithFallback(pBytes, byteCount, pChars, charCount, bytesConsumed, charsFast); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private protected unsafe sealed override int GetCharsFast(byte* pBytes, int bytesLength, char* pChars, int charsLength, out int bytesConsumed) { Utf8Utility.TranscodeToUtf16(pBytes, bytesLength, pChars, charsLength, out var pInputBufferRemaining, out var pOutputBufferRemaining); bytesConsumed = (int)(pInputBufferRemaining - pBytes); return (int)(pOutputBufferRemaining - pChars); } private protected sealed override int GetCharsWithFallback(ReadOnlySpan bytes, int originalBytesLength, Span chars, int originalCharsLength, DecoderNLS decoder) { if (((decoder == null) ? base.DecoderFallback : decoder.Fallback) is DecoderReplacementFallback decoderReplacementFallback && decoderReplacementFallback.MaxCharCount == 1 && decoderReplacementFallback.DefaultString[0] == '\ufffd') { Utf8.ToUtf16(bytes, chars, out var bytesRead, out var charsWritten, replaceInvalidSequences: true, decoder?.MustFlush ?? true); bytes = bytes.Slice(bytesRead); chars = chars.Slice(charsWritten); } if (bytes.IsEmpty) { return originalCharsLength - chars.Length; } return base.GetCharsWithFallback(bytes, originalBytesLength, chars, originalCharsLength, decoder); } public unsafe override string GetString(byte[] bytes, int index, int count) { if (bytes == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((index | count) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } if (count == 0) { return string.Empty; } fixed (byte* ptr = bytes) { return string.CreateStringFromEncoding(ptr + index, count, this); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetCharCountCommon(byte* pBytes, int byteCount) { int bytesConsumed; int num = GetCharCountFast(pBytes, byteCount, null, out bytesConsumed); if (bytesConsumed != byteCount) { num += GetCharCountWithFallback(pBytes, byteCount, bytesConsumed); if (num < 0) { Encoding.ThrowConversionOverflow(); } } return num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private protected unsafe sealed override int GetCharCountFast(byte* pBytes, int bytesLength, DecoderFallback fallback, out int bytesConsumed) { int utf16CodeUnitCountAdjustment; int scalarCountAdjustment; byte* pointerToFirstInvalidByte = Utf8Utility.GetPointerToFirstInvalidByte(pBytes, bytesLength, out utf16CodeUnitCountAdjustment, out scalarCountAdjustment); return (bytesConsumed = (int)(pointerToFirstInvalidByte - pBytes)) + utf16CodeUnitCountAdjustment; } public override Decoder GetDecoder() { return new DecoderNLS(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } internal sealed override bool TryGetByteCount(Rune value, out int byteCount) { byteCount = value.Utf8SequenceLength; return true; } internal sealed override OperationStatus EncodeRune(Rune value, Span bytes, out int bytesWritten) { if (!value.TryEncodeToUtf8(bytes, out bytesWritten)) { return OperationStatus.DestinationTooSmall; } return OperationStatus.Done; } internal sealed override OperationStatus DecodeFirstRune(ReadOnlySpan bytes, out Rune value, out int bytesConsumed) { return Rune.DecodeFromUtf8(bytes, out value, out bytesConsumed); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_NeedNonNegNum); } long num = (long)charCount + 1L; if (base.EncoderFallback.MaxCharCount > 1) { num *= base.EncoderFallback.MaxCharCount; } num *= 3; if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("charCount", SR.ArgumentOutOfRange_GetByteCountOverflow); } return (int)num; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) { throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_NeedNonNegNum); } long num = (long)byteCount + 1L; if (base.DecoderFallback.MaxCharCount > 1) { num *= base.DecoderFallback.MaxCharCount; } if (num > int.MaxValue) { throw new ArgumentOutOfRangeException("byteCount", SR.ArgumentOutOfRange_GetCharCountOverflow); } return (int)num; } public override byte[] GetPreamble() { if (_emitUTF8Identifier) { return new byte[3] { 239, 187, 191 }; } return Array.Empty(); } public override bool Equals([NotNullWhen(true)] object? value) { if (value is UTF8Encoding uTF8Encoding) { if (_emitUTF8Identifier == uTF8Encoding._emitUTF8Identifier && base.EncoderFallback.Equals(uTF8Encoding.EncoderFallback)) { return base.DecoderFallback.Equals(uTF8Encoding.DecoderFallback); } return false; } return false; } public override int GetHashCode() { return base.EncoderFallback.GetHashCode() + base.DecoderFallback.GetHashCode() + 65001 + (_emitUTF8Identifier ? 1 : 0); } } internal ref struct ValueStringBuilder { private char[] _arrayToReturnToPool; private Span _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 RawChars => _chars; internal void AppendSpanFormattable(T value, string format, IFormatProvider provider) where T : ISpanFormattable { if (value.TryFormat(_chars.Slice(_pos), out var charsWritten, format, provider)) { _pos += charsWritten; } else { Append(value.ToString(format, provider)); } } internal void AppendFormatHelper(IFormatProvider provider, string format, ParamsArray args) { if (format == null) { throw new ArgumentNullException("format"); } int num = 0; int length = format.Length; char c = '\0'; ICustomFormatter customFormatter = (ICustomFormatter)(provider?.GetFormat(typeof(ICustomFormatter))); while (true) { if (num < length) { c = format[num]; num++; if (c == '}') { if (num < length && format[num] == '}') { num++; } else { ThrowFormatError(); } } else if (c == '{') { if (num >= length || format[num] != '{') { num--; goto IL_008f; } num++; } Append(c); continue; } goto IL_008f; IL_008f: if (num == length) { break; } num++; if (num == length || (c = format[num]) < '0' || c > '9') { ThrowFormatError(); } int num2 = 0; do { num2 = num2 * 10 + c - 48; num++; if (num == length) { ThrowFormatError(); } c = format[num]; } while (c >= '0' && c <= '9' && num2 < 1000000); if (num2 >= args.Length) { throw new FormatException(SR.Format_IndexOutOfRange); } for (; num < length; num++) { if ((c = format[num]) != ' ') { break; } } bool flag = false; int num3 = 0; if (c == ',') { for (num++; num < length && format[num] == ' '; num++) { } if (num == length) { ThrowFormatError(); } c = format[num]; if (c == '-') { flag = true; num++; if (num == length) { ThrowFormatError(); } c = format[num]; } if (c < '0' || c > '9') { ThrowFormatError(); } do { num3 = num3 * 10 + c - 48; num++; if (num == length) { ThrowFormatError(); } c = format[num]; } while (c >= '0' && c <= '9' && num3 < 1000000); } for (; num < length; num++) { if ((c = format[num]) != ' ') { break; } } object obj = args[num2]; ReadOnlySpan readOnlySpan = default(ReadOnlySpan); switch (c) { case ':': { num++; int num4 = num; while (true) { if (num == length) { ThrowFormatError(); } c = format[num]; switch (c) { case '{': ThrowFormatError(); goto IL_0205; default: goto IL_0205; case '}': break; } break; IL_0205: num++; } if (num > num4) { readOnlySpan = format.AsSpan(num4, num - num4); } break; } default: ThrowFormatError(); break; case '}': break; } num++; string text = null; string text2 = null; if (customFormatter != null) { if (readOnlySpan.Length != 0) { text2 = new string(readOnlySpan); } text = customFormatter.Format(text2, obj, provider); } if (text == null) { if (obj is ISpanFormattable spanFormattable && (flag || num3 == 0) && spanFormattable.TryFormat(_chars.Slice(_pos), out var charsWritten, readOnlySpan, provider)) { _pos += charsWritten; int num5 = num3 - charsWritten; if (flag && num5 > 0) { Append(' ', num5); } continue; } if (obj is IFormattable formattable) { if (readOnlySpan.Length != 0 && text2 == null) { text2 = new string(readOnlySpan); } text = formattable.ToString(text2, provider); } else if (obj != null) { text = obj.ToString(); } } if (text == null) { text = string.Empty; } int num6 = num3 - text.Length; if (!flag && num6 > 0) { Append(' ', num6); } Append(text); if (flag && num6 > 0) { Append(' ', num6); } } } private static void ThrowFormatError() { throw new FormatException(SR.Format_InvalidString); } public ValueStringBuilder(Span initialBuffer) { _arrayToReturnToPool = null; _chars = initialBuffer; _pos = 0; } public ValueStringBuilder(int initialCapacity) { _arrayToReturnToPool = ArrayPool.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 AsSpan(bool terminate) { if (terminate) { EnsureCapacity(Length + 1); _chars[Length] = '\0'; } return _chars.Slice(0, _pos); } public ReadOnlySpan AsSpan() { return _chars.Slice(0, _pos); } public ReadOnlySpan AsSpan(int start) { return _chars.Slice(start, _pos - start); } public ReadOnlySpan AsSpan(int start, int length) { return _chars.Slice(start, length); } public bool TryCopyTo(Span 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, 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.CopyTo(_chars.Slice(index)); _pos += length; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(char c) { int pos = _pos; if ((uint)pos < (uint)_chars.Length) { _chars[pos] = c; _pos = pos + 1; } else { GrowAndAppend(c); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Append(string s) { if (s != null) { int pos = _pos; if (s.Length == 1 && (uint)pos < (uint)_chars.Length) { _chars[pos] = s[0]; _pos = pos + 1; } else { AppendSlow(s); } } } private void AppendSlow(string s) { int pos = _pos; if (pos > _chars.Length - s.Length) { Grow(s.Length); } s.CopyTo(_chars.Slice(pos)); _pos += s.Length; } public void Append(char c, int count) { if (_pos > _chars.Length - count) { Grow(count); } Span 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 span = _chars.Slice(_pos, length); for (int i = 0; i < span.Length; i++) { span[i] = *(value++); } _pos += length; } public void Append(ReadOnlySpan 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 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) { char[] array = ArrayPool.Shared.Rent((int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), (uint)(_chars.Length * 2))); _chars.Slice(0, _pos).CopyTo(array); char[] arrayToReturnToPool = _arrayToReturnToPool; _chars = (_arrayToReturnToPool = array); if (arrayToReturnToPool != null) { ArrayPool.Shared.Return(arrayToReturnToPool); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Dispose() { char[] arrayToReturnToPool = _arrayToReturnToPool; this = default(ValueStringBuilder); if (arrayToReturnToPool != null) { ArrayPool.Shared.Return(arrayToReturnToPool); } } } internal static class StringBuilderCache { [ThreadStatic] private static StringBuilder t_cachedInstance; public static StringBuilder Acquire(int capacity = 16) { if (capacity <= 360) { StringBuilder stringBuilder = t_cachedInstance; if (stringBuilder != null && capacity <= stringBuilder.Capacity) { t_cachedInstance = null; stringBuilder.Clear(); return stringBuilder; } } return new StringBuilder(capacity); } public static void Release(StringBuilder sb) { if (sb.Capacity <= 360) { t_cachedInstance = sb; } } public static string GetStringAndRelease(StringBuilder sb) { string result = sb.ToString(); Release(sb); return result; } } } namespace System.Text.Unicode { internal enum GraphemeClusterBreakType { Other, CR, LF, Control, Extend, ZWJ, Regional_Indicator, Prepend, SpacingMark, L, V, T, LV, LVT, Extended_Pictograph } internal static class TextSegmentationUtility { private delegate OperationStatus DecodeFirstRune(ReadOnlySpan input, out Rune rune, out int elementsConsumed); [StructLayout(LayoutKind.Auto)] private ref struct Processor { private readonly ReadOnlySpan _buffer; private readonly DecodeFirstRune _decoder; private int _codeUnitLengthOfCurrentScalar; public int CurrentCodeUnitOffset { get; private set; } public GraphemeClusterBreakType CurrentType { get; private set; } internal Processor(ReadOnlySpan buffer, DecodeFirstRune decoder) { _buffer = buffer; _decoder = decoder; _codeUnitLengthOfCurrentScalar = 0; CurrentType = GraphemeClusterBreakType.Other; CurrentCodeUnitOffset = 0; } public void MoveNext() { CurrentCodeUnitOffset += _codeUnitLengthOfCurrentScalar; _decoder(_buffer.Slice(CurrentCodeUnitOffset), out var rune, out _codeUnitLengthOfCurrentScalar); CurrentType = CharUnicodeInfo.GetGraphemeClusterBreakType(rune); } } private static readonly DecodeFirstRune _utf16Decoder = Rune.DecodeFromUtf16; private static int GetLengthOfFirstExtendedGraphemeCluster(ReadOnlySpan input, DecodeFirstRune decoder) { Processor processor = new Processor(input, decoder); processor.MoveNext(); while (processor.CurrentType == GraphemeClusterBreakType.Prepend) { processor.MoveNext(); } if (processor.CurrentCodeUnitOffset <= 0 || (processor.CurrentType != GraphemeClusterBreakType.Control && processor.CurrentType != GraphemeClusterBreakType.CR && processor.CurrentType != GraphemeClusterBreakType.LF)) { GraphemeClusterBreakType currentType = processor.CurrentType; processor.MoveNext(); switch (currentType) { case GraphemeClusterBreakType.CR: if (processor.CurrentType == GraphemeClusterBreakType.LF) { processor.MoveNext(); } break; case GraphemeClusterBreakType.L: while (processor.CurrentType == GraphemeClusterBreakType.L) { processor.MoveNext(); } if (processor.CurrentType == GraphemeClusterBreakType.V) { processor.MoveNext(); } else { if (processor.CurrentType != GraphemeClusterBreakType.LV) { if (processor.CurrentType == GraphemeClusterBreakType.LVT) { processor.MoveNext(); goto case GraphemeClusterBreakType.T; } goto default; } processor.MoveNext(); } goto case GraphemeClusterBreakType.V; case GraphemeClusterBreakType.V: case GraphemeClusterBreakType.LV: while (processor.CurrentType == GraphemeClusterBreakType.V) { processor.MoveNext(); } if (processor.CurrentType == GraphemeClusterBreakType.T) { processor.MoveNext(); goto case GraphemeClusterBreakType.T; } goto default; case GraphemeClusterBreakType.T: case GraphemeClusterBreakType.LVT: while (processor.CurrentType == GraphemeClusterBreakType.T) { processor.MoveNext(); } goto default; case GraphemeClusterBreakType.Extended_Pictograph: while (true) { if (processor.CurrentType == GraphemeClusterBreakType.Extend) { processor.MoveNext(); continue; } if (processor.CurrentType != GraphemeClusterBreakType.ZWJ) { break; } processor.MoveNext(); if (processor.CurrentType != GraphemeClusterBreakType.Extended_Pictograph) { break; } processor.MoveNext(); } goto default; case GraphemeClusterBreakType.Regional_Indicator: if (processor.CurrentType == GraphemeClusterBreakType.Regional_Indicator) { processor.MoveNext(); } goto default; default: while (processor.CurrentType == GraphemeClusterBreakType.Extend || processor.CurrentType == GraphemeClusterBreakType.ZWJ || processor.CurrentType == GraphemeClusterBreakType.SpacingMark) { processor.MoveNext(); } break; case GraphemeClusterBreakType.LF: case GraphemeClusterBreakType.Control: break; } } return processor.CurrentCodeUnitOffset; } public static int GetLengthOfFirstUtf16ExtendedGraphemeCluster(ReadOnlySpan input) { return GetLengthOfFirstExtendedGraphemeCluster(input, _utf16Decoder); } } internal static class Utf16Utility { [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool AllCharsInUInt32AreAscii(uint value) { return (value & 0xFF80FF80u) == 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool AllCharsInUInt64AreAscii(ulong value) { return (value & 0xFF80FF80FF80FF80uL) == 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static uint ConvertAllAsciiCharsInUInt32ToLowercase(uint value) { uint num = value + 8388736 - 4259905; uint num2 = value + 8388736 - 5963867; uint num3 = num ^ num2; uint num4 = (num3 & 0x800080) >> 2; return value ^ num4; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static uint ConvertAllAsciiCharsInUInt32ToUppercase(uint value) { uint num = value + 8388736 - 6357089; uint num2 = value + 8388736 - 8061051; uint num3 = num ^ num2; uint num4 = (num3 & 0x800080) >> 2; return value ^ num4; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool UInt32ContainsAnyLowercaseAsciiChar(uint value) { uint num = value + 8388736 - 6357089; uint num2 = value + 8388736 - 8061051; uint num3 = num ^ num2; return (num3 & 0x800080) != 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool UInt32ContainsAnyUppercaseAsciiChar(uint value) { uint num = value + 8388736 - 4259905; uint num2 = value + 8388736 - 5963867; uint num3 = num ^ num2; return (num3 & 0x800080) != 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool UInt32OrdinalIgnoreCaseAscii(uint valueA, uint valueB) { uint num = (valueA ^ valueB) << 2; uint num2 = valueA + 327685; num2 |= 0xA000A0u; num2 += 1703962; num2 |= 0xFF7FFF7Fu; return (num & num2) == 0; } public unsafe static char* GetPointerToFirstInvalidChar(char* pInputBuffer, int inputLength, out long utf8CodeUnitCountAdjustment, out int scalarCountAdjustment) { int num = (int)ASCIIUtility.GetIndexOfFirstNonAsciiChar(pInputBuffer, (uint)inputLength); pInputBuffer += (uint)num; inputLength -= num; if (inputLength == 0) { utf8CodeUnitCountAdjustment = 0L; scalarCountAdjustment = 0; return pInputBuffer; } long num2 = 0L; int num3 = 0; char* ptr = pInputBuffer + (uint)inputLength; if (Sse41.IsSupported) { if (inputLength >= Vector128.Count) { Vector128 right = Vector128.Create((ushort)128); Vector128 vector = Vector128.Create((ushort)30720); Vector128 right2 = Vector128.Create((ushort)40960); if (!BitConverter.IsLittleEndian) { } Vector128 vector2 = Vector128.Create(9241421688590303745uL).AsByte(); char* ptr2 = ptr - Vector128.Count; do { if (AdvSimd.Arm64.IsSupported) { } Vector128 vector3 = Sse2.LoadVector128((ushort*)pInputBuffer); pInputBuffer += Vector128.Count; if (AdvSimd.Arm64.IsSupported) { } Vector128 left = Sse41.Min(vector3, right); if (AdvSimd.IsSupported) { } Vector128 right3 = Sse2.AddSaturate(vector3, vector); uint value = (uint)Sse2.MoveMask(Sse2.Or(left, right3).AsByte()); nuint num4 = (uint)BitOperations.PopCount(value); if (AdvSimd.Arm64.IsSupported) { } value = (uint)Sse2.MoveMask(Sse2.CompareLessThan(Sse2.Add(vector3, right2).AsInt16(), vector.AsInt16()).AsByte()); while (value != 65535) { value = ~value; if (AdvSimd.Arm64.IsSupported) { } uint num5 = (uint)Sse2.MoveMask(Sse2.ShiftRightLogical(vector3, 3).AsByte()); uint num6 = num5 & value; uint num7 = (num5 ^ 0x5555u) & value; num7 <<= 2; if ((ushort)num7 == num6) { if (num7 > 65535) { num7 = (ushort)num7; num4 -= 2; pInputBuffer--; } nuint num8 = (uint)BitOperations.PopCount(num7); num3 -= (int)num8; if (IntPtr.Size == 8) { } num2 -= (uint)(2 * (int)num8); value = 65535u; continue; } goto IL_01c3; } num2 += (long)num4; continue; IL_01c3: pInputBuffer -= Vector128.Count; break; } while (pInputBuffer <= ptr2); } } else if (Vector.IsHardwareAccelerated && inputLength >= Vector.Count) { Vector right4 = new Vector(128); Vector right5 = new Vector(1024); Vector right6 = new Vector(2048); Vector vector4 = new Vector(55296); char* ptr3 = ptr - Vector.Count; while (true) { Vector left2 = Unsafe.ReadUnaligned>(pInputBuffer); Vector vector5 = Vector.GreaterThanOrEqual(left2, right4); Vector vector6 = Vector.GreaterThanOrEqual(left2, right6); Vector vector7 = (Vector)(Vector.Zero - vector5 - vector6); nuint num9 = 0u; for (int i = 0; i < Vector.Count; i++) { num9 += (nuint)(nint)(nuint)vector7[i]; } uint num10 = (uint)num9; if (IntPtr.Size == 8) { } num10 = (ushort)num10 + (num10 >> 16); left2 -= vector4; Vector vector8 = Vector.LessThan(left2, right6); if (vector8 != Vector.Zero) { Vector right7 = Vector.LessThan(left2, right5); Vector vector9 = Vector.AndNot(vector8, right7); if (vector9[0] != 0) { break; } ushort num11 = 0; int num12 = 0; while (num12 < Vector.Count - 1) { num11 -= right7[num12]; if (right7[num12] == vector9[num12 + 1]) { num12++; continue; } goto IL_03d4; } if (right7[Vector.Count - 1] != 0) { pInputBuffer--; num10 -= 2; } nint num13 = num11; num3 -= (int)num13; num2 -= num13; num2 -= num13; } num2 += num10; pInputBuffer += Vector.Count; if (pInputBuffer <= ptr3) { continue; } goto IL_03d4; } goto IL_03d8; } goto IL_03d4; IL_03d8: utf8CodeUnitCountAdjustment = num2; scalarCountAdjustment = num3; return pInputBuffer; IL_03d4: while (pInputBuffer < ptr) { uint num14 = *pInputBuffer; if (num14 > 127) { num2 += num14 + 129024 >> 16; if (UnicodeUtility.IsSurrogateCodePoint(num14)) { num2 -= 2; if ((nuint)((byte*)ptr - (nuint)pInputBuffer) < (nuint)4u) { break; } num14 = Unsafe.ReadUnaligned(pInputBuffer); uint num15 = num14; if (!BitConverter.IsLittleEndian) { } if (((num15 - 3691042816u) & 0xFC00FC00u) != 0) { break; } num3--; num2 += 2; pInputBuffer++; } } pInputBuffer++; } goto IL_03d8; } } public static class Utf8 { public unsafe static OperationStatus FromUtf16(ReadOnlySpan source, Span destination, out int charsRead, out int bytesWritten, bool replaceInvalidSequences = true, bool isFinalBlock = true) { _ = source.Length; _ = destination.Length; fixed (char* ptr = &MemoryMarshal.GetReference(source)) { fixed (byte* ptr2 = &MemoryMarshal.GetReference(destination)) { OperationStatus operationStatus = OperationStatus.Done; char* pInputBufferRemaining = ptr; byte* pOutputBufferRemaining = ptr2; while (!source.IsEmpty) { operationStatus = Utf8Utility.TranscodeToUtf8((char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(source)), source.Length, (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(destination)), destination.Length, out pInputBufferRemaining, out pOutputBufferRemaining); if (operationStatus <= OperationStatus.DestinationTooSmall || (operationStatus == OperationStatus.NeedMoreData && !isFinalBlock)) { break; } if (!replaceInvalidSequences) { operationStatus = OperationStatus.InvalidData; break; } destination = destination.Slice((int)(pOutputBufferRemaining - (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(destination)))); if (destination.Length <= 2) { operationStatus = OperationStatus.DestinationTooSmall; break; } destination[0] = 239; destination[1] = 191; destination[2] = 189; destination = destination.Slice(3); source = source.Slice((int)(pInputBufferRemaining - (char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(source))) + 1); operationStatus = OperationStatus.Done; pInputBufferRemaining = (char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(source)); pOutputBufferRemaining = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(destination)); } charsRead = (int)(pInputBufferRemaining - ptr); bytesWritten = (int)(pOutputBufferRemaining - ptr2); return operationStatus; } } } public unsafe static OperationStatus ToUtf16(ReadOnlySpan source, Span destination, out int bytesRead, out int charsWritten, bool replaceInvalidSequences = true, bool isFinalBlock = true) { _ = source.Length; _ = destination.Length; fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { fixed (char* ptr2 = &MemoryMarshal.GetReference(destination)) { OperationStatus operationStatus = OperationStatus.Done; byte* pInputBufferRemaining = ptr; char* pOutputBufferRemaining = ptr2; while (!source.IsEmpty) { operationStatus = Utf8Utility.TranscodeToUtf16((byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(source)), source.Length, (char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(destination)), destination.Length, out pInputBufferRemaining, out pOutputBufferRemaining); if (operationStatus <= OperationStatus.DestinationTooSmall || (operationStatus == OperationStatus.NeedMoreData && !isFinalBlock)) { break; } if (!replaceInvalidSequences) { operationStatus = OperationStatus.InvalidData; break; } destination = destination.Slice((int)(pOutputBufferRemaining - (char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(destination)))); if (destination.IsEmpty) { operationStatus = OperationStatus.DestinationTooSmall; break; } destination[0] = '\ufffd'; destination = destination.Slice(1); source = source.Slice((int)(pInputBufferRemaining - (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(source)))); Rune.DecodeFromUtf8(source, out var _, out var bytesConsumed); source = source.Slice(bytesConsumed); operationStatus = OperationStatus.Done; pInputBufferRemaining = (byte*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(source)); pOutputBufferRemaining = (char*)Unsafe.AsPointer(ref MemoryMarshal.GetReference(destination)); } bytesRead = (int)(pInputBufferRemaining - ptr); charsWritten = (int)(pOutputBufferRemaining - ptr2); return operationStatus; } } } } internal static class Utf8Utility { [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint ExtractCharFromFirstThreeByteSequence(uint value) { _ = BitConverter.IsLittleEndian; return ((value & 0x3F0000) >> 16) | ((value & 0x3F00) >> 2) | ((value & 0xF) << 12); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint ExtractCharFromFirstTwoByteSequence(uint value) { _ = BitConverter.IsLittleEndian; uint num = (uint)((byte)value << 6); return (byte)(value >> 8) + num - 12288 - 128; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint ExtractCharsFromFourByteSequence(uint value) { _ = BitConverter.IsLittleEndian; uint num = (uint)((byte)value << 8); num |= (value & 0x3F00) >> 6; num |= (value & 0x300000) >> 20; num |= (value & 0x3F000000) >> 8; num |= (value & 0xF0000) << 6; num -= 64; num -= 8192; num += 2048; return num + 3690987520u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint ExtractFourUtf8BytesFromSurrogatePair(uint value) { _ = BitConverter.IsLittleEndian; value += 64; uint value2 = BinaryPrimitives.ReverseEndianness(value & 0x3F0700u); value2 = BitOperations.RotateLeft(value2, 16); uint num = (value & 0xFC) << 6; uint num2 = (value >> 6) & 0xF0000u; num2 |= num; uint num3 = (value & 3) << 20; num3 |= 0x808080F0u; return num3 | value2 | num2; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint ExtractTwoCharsPackedFromTwoAdjacentTwoByteSequences(uint value) { _ = BitConverter.IsLittleEndian; return ((value & 0x3F003F00) >> 8) | ((value & 0x1F001F) << 6); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint ExtractTwoUtf8TwoByteSequencesFromTwoPackedUtf16Chars(uint value) { _ = BitConverter.IsLittleEndian; return ((value >> 6) & 0x1F001F) + ((value << 8) & 0x3F003F00) + 2160099520u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint ExtractUtf8TwoByteSequenceFromFirstUtf16Char(uint value) { _ = BitConverter.IsLittleEndian; uint num = (value << 2) & 0x1F00u; value &= 0x3Fu; return BinaryPrimitives.ReverseEndianness((ushort)(num + value + 49280)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsFirstCharAscii(uint value) { _ = BitConverter.IsLittleEndian; if ((value & 0xFF80u) != 0) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsFirstCharAtLeastThreeUtf8Bytes(uint value) { _ = BitConverter.IsLittleEndian; if ((value & 0xF800) == 0) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsFirstCharSurrogate(uint value) { _ = BitConverter.IsLittleEndian; if (((value - 55296) & 0xF800u) != 0) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsFirstCharTwoUtf8Bytes(uint value) { _ = BitConverter.IsLittleEndian; if (((value - 128) & 0xFFFF) >= 1920) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsLowByteUtf8ContinuationByte(uint value) { return (uint)(byte)(value - 128) <= 63u; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsSecondCharAscii(uint value) { _ = BitConverter.IsLittleEndian; if (value >= 8388608) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsSecondCharAtLeastThreeUtf8Bytes(uint value) { _ = BitConverter.IsLittleEndian; if ((value & 0xF8000000u) == 0) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsSecondCharSurrogate(uint value) { _ = BitConverter.IsLittleEndian; if ((uint)((int)value - -671088640) >= 134217728u) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsSecondCharTwoUtf8Bytes(uint value) { _ = BitConverter.IsLittleEndian; if (!UnicodeUtility.IsInRangeInclusive(value, 8388608u, 134217727u)) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsUtf8ContinuationByte(in byte value) { return (sbyte)value < -64; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsWellFormedUtf16SurrogatePair(uint value) { _ = BitConverter.IsLittleEndian; if (((value - 3691042816u) & 0xFC00FC00u) != 0) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint ToLittleEndian(uint value) { _ = BitConverter.IsLittleEndian; return value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool UInt32BeginsWithOverlongUtf8TwoByteSequence(uint value) { _ = BitConverter.IsLittleEndian; if ((uint)(byte)value >= 194u) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool UInt32BeginsWithUtf8FourByteMask(uint value) { _ = BitConverter.IsLittleEndian; if (((value - 2155905264u) & 0xC0C0C0F8u) != 0) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool UInt32BeginsWithUtf8ThreeByteMask(uint value) { _ = BitConverter.IsLittleEndian; if (((value - 8421600) & 0xC0C0F0u) != 0) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool UInt32BeginsWithUtf8TwoByteMask(uint value) { _ = BitConverter.IsLittleEndian; if (((value - 32960) & 0xC0E0u) != 0) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool UInt32BeginsWithValidUtf8TwoByteSequenceLittleEndian(uint value) { _ = BitConverter.IsLittleEndian; if (!UnicodeUtility.IsInRangeInclusive(value & 0xC0FFu, 32962u, 32991u)) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool UInt32EndsWithValidUtf8TwoByteSequenceLittleEndian(uint value) { _ = BitConverter.IsLittleEndian; if (!UnicodeUtility.IsInRangeInclusive(value & 0xC0FF0000u, 2160197632u, 2162098176u)) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool UInt32FirstByteIsAscii(uint value) { _ = BitConverter.IsLittleEndian; if ((value & 0x80u) != 0) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool UInt32FourthByteIsAscii(uint value) { _ = BitConverter.IsLittleEndian; if ((int)value < 0) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool UInt32SecondByteIsAscii(uint value) { _ = BitConverter.IsLittleEndian; if ((value & 0x8000u) != 0) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool UInt32ThirdByteIsAscii(uint value) { _ = BitConverter.IsLittleEndian; if ((value & 0x800000u) != 0) { if (!BitConverter.IsLittleEndian) { } return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteTwoUtf16CharsAsTwoUtf8ThreeByteSequences(ref byte outputBuffer, uint value) { _ = BitConverter.IsLittleEndian; uint num = ((value << 2) & 0x3F00u) | ((value & 0x3F) << 16); uint num2 = ((value >> 4) & 0xF000000u) | ((value >> 12) & 0xFu); Unsafe.WriteUnaligned(ref outputBuffer, num + num2 + 3766517984u); Unsafe.WriteUnaligned(ref Unsafe.Add(ref outputBuffer, 4), (ushort)(((value >> 22) & 0x3F) + ((value >> 8) & 0x3F00) + 32896)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void WriteFirstUtf16CharAsUtf8ThreeByteSequence(ref byte outputBuffer, uint value) { _ = BitConverter.IsLittleEndian; uint num = (value << 2) & 0x3F00u; uint num2 = (uint)(ushort)value >> 12; Unsafe.WriteUnaligned(ref outputBuffer, (ushort)(num + num2 + 32992)); Unsafe.Add(ref outputBuffer, 2) = (byte)((value & 0x3Fu) | 0xFFFFFF80u); } public unsafe static OperationStatus TranscodeToUtf16(byte* pInputBuffer, int inputLength, char* pOutputBuffer, int outputCharsRemaining, out byte* pInputBufferRemaining, out char* pOutputBufferRemaining) { nuint num = ASCIIUtility.WidenAsciiToUtf16(pInputBuffer, pOutputBuffer, (uint)Math.Min(inputLength, outputCharsRemaining)); pInputBuffer += num; pOutputBuffer += num; if ((int)num == inputLength) { pInputBufferRemaining = pInputBuffer; pOutputBufferRemaining = pOutputBuffer; return OperationStatus.Done; } inputLength -= (int)num; outputCharsRemaining -= (int)num; if (inputLength < 4) { goto IL_0690; } byte* ptr = pInputBuffer + (uint)inputLength - 4; while (true) { IL_004a: uint num2 = Unsafe.ReadUnaligned(pInputBuffer); while (true) { IL_0051: if (!ASCIIUtility.AllBytesInUInt32AreAscii(num2)) { goto IL_0120; } int num4; uint num5; if (outputCharsRemaining >= 4) { ASCIIUtility.WidenFourAsciiBytesToUtf16AndWriteToBuffer(ref *pOutputBuffer, num2); pInputBuffer += 4; pOutputBuffer += 4; outputCharsRemaining -= 4; uint val = (uint)((int)(void*)Unsafe.ByteOffset(ref *pInputBuffer, ref *ptr) + 4); uint num3 = Math.Min(val, (uint)outputCharsRemaining) / 8; num4 = 0; while ((uint)num4 < num3) { num2 = Unsafe.ReadUnaligned(pInputBuffer); num5 = Unsafe.ReadUnaligned(pInputBuffer + 4); if (ASCIIUtility.AllBytesInUInt32AreAscii(num2 | num5)) { pInputBuffer += 8; ASCIIUtility.WidenFourAsciiBytesToUtf16AndWriteToBuffer(ref *pOutputBuffer, num2); ASCIIUtility.WidenFourAsciiBytesToUtf16AndWriteToBuffer(ref pOutputBuffer[4], num5); pOutputBuffer += 8; num4++; continue; } goto IL_00f4; } outputCharsRemaining -= 8 * num4; goto IL_04aa; } goto IL_04b1; IL_04b1: inputLength = (int)(void*)Unsafe.ByteOffset(ref *pInputBuffer, ref *ptr) + 4; goto IL_0690; IL_04aa: if (pInputBuffer <= ptr) { goto IL_004a; } goto IL_04b1; IL_0120: if (UInt32FirstByteIsAscii(num2)) { if (outputCharsRemaining >= 3) { uint num6 = ToLittleEndian(num2); nuint num7 = 1u; *pOutputBuffer = (char)(byte)num6; if (UInt32SecondByteIsAscii(num2)) { num7++; num6 >>= 8; pOutputBuffer[1] = (char)(byte)num6; if (UInt32ThirdByteIsAscii(num2)) { num7++; num6 >>= 8; pOutputBuffer[2] = (char)(byte)num6; } } pInputBuffer += num7; pOutputBuffer += num7; outputCharsRemaining -= (int)num7; } else { if (outputCharsRemaining == 0) { break; } uint num8 = ToLittleEndian(num2); pInputBuffer++; *(pOutputBuffer++) = (char)(byte)num8; outputCharsRemaining--; if (UInt32SecondByteIsAscii(num2)) { if (outputCharsRemaining == 0) { break; } pInputBuffer++; num8 >>= 8; *(pOutputBuffer++) = (char)(byte)num8; if (UInt32ThirdByteIsAscii(num2)) { break; } outputCharsRemaining = 0; } } if (pInputBuffer > ptr) { goto IL_04b1; } num2 = Unsafe.ReadUnaligned(pInputBuffer); } uint num9; while (UInt32BeginsWithUtf8TwoByteMask(num2)) { if (!UInt32BeginsWithOverlongUtf8TwoByteSequence(num2)) { while (true) { _ = BitConverter.IsLittleEndian; if (!UInt32EndsWithValidUtf8TwoByteSequenceLittleEndian(num2) && BitConverter.IsLittleEndian) { break; } if (outputCharsRemaining >= 2) { Unsafe.WriteUnaligned(pOutputBuffer, ExtractTwoCharsPackedFromTwoAdjacentTwoByteSequences(num2)); pInputBuffer += 4; pOutputBuffer += 2; outputCharsRemaining -= 2; if (pInputBuffer <= ptr) { num2 = Unsafe.ReadUnaligned(pInputBuffer); _ = BitConverter.IsLittleEndian; if (!UInt32BeginsWithValidUtf8TwoByteSequenceLittleEndian(num2)) { goto IL_0051; } continue; } } goto IL_04b1; } num9 = ExtractCharFromFirstTwoByteSequence(num2); if (UInt32ThirdByteIsAscii(num2)) { if (UInt32FourthByteIsAscii(num2)) { goto IL_0282; } if (outputCharsRemaining >= 2) { *pOutputBuffer = (char)num9; char* num10 = pOutputBuffer + 1; uint num11 = num2; if (!BitConverter.IsLittleEndian) { } *num10 = (char)(byte)(num11 >> 16); pInputBuffer += 3; pOutputBuffer += 2; outputCharsRemaining -= 2; if (ptr >= pInputBuffer) { num2 = Unsafe.ReadUnaligned(pInputBuffer); continue; } } } else if (outputCharsRemaining != 0) { *pOutputBuffer = (char)num9; pInputBuffer += 2; pOutputBuffer++; outputCharsRemaining--; if (ptr >= pInputBuffer) { num2 = Unsafe.ReadUnaligned(pInputBuffer); break; } } goto IL_04b1; } goto IL_06a3; } if (UInt32BeginsWithUtf8ThreeByteMask(num2)) { while (true) { _ = BitConverter.IsLittleEndian; if ((num2 & 0x200F) == 0 || ((num2 - 8205) & 0x200F) == 0) { break; } if (outputCharsRemaining == 0) { goto end_IL_0051; } _ = BitConverter.IsLittleEndian; if ((((int)num2 - -536870912) & -268435456) == 0 && outputCharsRemaining > 1 && (nint)(void*)Unsafe.ByteOffset(ref *pInputBuffer, ref *ptr) >= (nint)3) { uint num12 = Unsafe.ReadUnaligned(pInputBuffer + 3); if (UInt32BeginsWithUtf8ThreeByteMask(num12) && (num12 & 0x200Fu) != 0 && ((num12 - 8205) & 0x200Fu) != 0) { *pOutputBuffer = (char)ExtractCharFromFirstThreeByteSequence(num2); pOutputBuffer[1] = (char)ExtractCharFromFirstThreeByteSequence(num12); pInputBuffer += 6; pOutputBuffer += 2; outputCharsRemaining -= 2; goto IL_03ff; } } *pOutputBuffer = (char)ExtractCharFromFirstThreeByteSequence(num2); pInputBuffer += 3; pOutputBuffer++; outputCharsRemaining--; goto IL_03ff; IL_03ff: if (UInt32FourthByteIsAscii(num2)) { if (outputCharsRemaining == 0) { goto end_IL_0051; } _ = BitConverter.IsLittleEndian; *pOutputBuffer = (char)(num2 >> 24); pInputBuffer++; pOutputBuffer++; outputCharsRemaining--; } if (pInputBuffer <= ptr) { num2 = Unsafe.ReadUnaligned(pInputBuffer); if (!UInt32BeginsWithUtf8ThreeByteMask(num2)) { goto IL_0051; } continue; } goto IL_04b1; } } else if (UInt32BeginsWithUtf8FourByteMask(num2)) { _ = BitConverter.IsLittleEndian; uint value = num2 & 0xFFFFu; value = BitOperations.RotateRight(value, 8); if (UnicodeUtility.IsInRangeInclusive(value, 4026531984u, 4093640847u)) { if (outputCharsRemaining < 2) { break; } Unsafe.WriteUnaligned(pOutputBuffer, ExtractCharsFromFourByteSequence(num2)); pInputBuffer += 4; pOutputBuffer += 2; outputCharsRemaining -= 2; goto IL_04aa; } } goto IL_06a3; IL_0282: if (outputCharsRemaining >= 3) { *pOutputBuffer = (char)num9; _ = BitConverter.IsLittleEndian; num2 >>= 16; pOutputBuffer[1] = (char)(byte)num2; num2 >>= 8; pOutputBuffer[2] = (char)num2; pInputBuffer += 4; pOutputBuffer += 3; outputCharsRemaining -= 3; goto IL_04aa; } goto IL_04b1; IL_00f4: if (ASCIIUtility.AllBytesInUInt32AreAscii(num2)) { ASCIIUtility.WidenFourAsciiBytesToUtf16AndWriteToBuffer(ref *pOutputBuffer, num2); num2 = num5; pInputBuffer += 4; pOutputBuffer += 4; outputCharsRemaining -= 4; } outputCharsRemaining -= 8 * num4; goto IL_0120; continue; end_IL_0051: break; } break; } goto IL_069f; IL_069f: OperationStatus result = OperationStatus.DestinationTooSmall; goto IL_06a5; IL_06a3: result = OperationStatus.InvalidData; goto IL_06a5; IL_06a5: pInputBufferRemaining = pInputBuffer; pOutputBufferRemaining = pOutputBuffer; return result; IL_0690: while (true) { if (inputLength > 0) { uint num13 = *pInputBuffer; if (num13 <= 127) { if (outputCharsRemaining != 0) { *pOutputBuffer = (char)num13; pInputBuffer++; pOutputBuffer++; inputLength--; outputCharsRemaining--; continue; } goto IL_069f; } num13 -= 194; if ((uint)(byte)num13 <= 29u) { if (inputLength < 2) { goto IL_069b; } uint num14 = pInputBuffer[1]; if (IsLowByteUtf8ContinuationByte(num14)) { if (outputCharsRemaining != 0) { uint num15 = (num13 << 6) + num14 + 128 - 128; *pOutputBuffer = (char)num15; pInputBuffer += 2; pOutputBuffer++; inputLength -= 2; outputCharsRemaining--; continue; } goto IL_069f; } } else if ((uint)(byte)num13 <= 45u) { if (inputLength >= 3) { uint num16 = pInputBuffer[1]; uint num17 = pInputBuffer[2]; if (IsLowByteUtf8ContinuationByte(num16) && IsLowByteUtf8ContinuationByte(num17)) { uint num18 = (num13 << 12) + (num16 << 6); if (num18 >= 133120) { num18 -= 186368; if (num18 >= 2048) { if (outputCharsRemaining != 0) { num18 += num17; num18 += 55296; num18 -= 128; *pOutputBuffer = (char)num18; pInputBuffer += 3; pOutputBuffer++; inputLength -= 3; outputCharsRemaining--; continue; } goto IL_069f; } } } } else { if (inputLength < 2) { goto IL_069b; } uint num19 = pInputBuffer[1]; if (IsLowByteUtf8ContinuationByte(num19)) { uint num20 = (num13 << 6) + num19; if (num20 >= 2080 && !UnicodeUtility.IsInRangeInclusive(num20, 2912u, 2943u)) { goto IL_069b; } } } } else if ((uint)(byte)num13 <= 50u) { if (inputLength < 2) { goto IL_069b; } uint num21 = pInputBuffer[1]; if (IsLowByteUtf8ContinuationByte(num21)) { uint value2 = (num13 << 6) + num21; if (UnicodeUtility.IsInRangeInclusive(value2, 3088u, 3343u)) { if (inputLength < 3) { goto IL_069b; } if (IsLowByteUtf8ContinuationByte(pInputBuffer[2])) { if (inputLength < 4) { goto IL_069b; } if (IsLowByteUtf8ContinuationByte(pInputBuffer[3])) { goto IL_069f; } } } } } goto IL_06a3; } result = OperationStatus.Done; break; IL_069b: result = OperationStatus.NeedMoreData; break; } goto IL_06a5; } public unsafe static OperationStatus TranscodeToUtf8(char* pInputBuffer, int inputLength, byte* pOutputBuffer, int outputBytesRemaining, out char* pInputBufferRemaining, out byte* pOutputBufferRemaining) { nuint num = ASCIIUtility.NarrowUtf16ToAscii(pInputBuffer, pOutputBuffer, (uint)Math.Min(inputLength, outputBytesRemaining)); pInputBuffer += num; pOutputBuffer += num; if ((int)num == inputLength) { pInputBufferRemaining = pInputBuffer; pOutputBufferRemaining = pOutputBuffer; return OperationStatus.Done; } inputLength -= (int)num; outputBytesRemaining -= (int)num; if (inputLength < 2) { goto IL_04f0; } char* ptr = pInputBuffer + (uint)inputLength - 2; Vector128 value; if (Sse41.X64.IsSupported || AdvSimd.Arm64.IsSupported) { value = Vector128.Create((short)(-128)); } uint num2; while (true) { IL_006d: num2 = Unsafe.ReadUnaligned(pInputBuffer); while (true) { IL_0074: if (!Utf16Utility.AllCharsInUInt32AreAscii(num2)) { goto IL_02e9; } if (outputBytesRemaining < 2) { break; } uint num3 = num2 | (num2 >> 8); Unsafe.WriteUnaligned(pOutputBuffer, (ushort)num3); pInputBuffer += 2; pOutputBuffer += 2; outputBytesRemaining -= 2; uint num4 = (uint)((int)(ptr - pInputBuffer) + 2); uint num5 = (uint)Math.Min(num4, outputBytesRemaining); int num7; ulong num8; Vector128 vector; int num10; uint num11; if (Sse41.X64.IsSupported || AdvSimd.Arm64.IsSupported) { uint num6 = num5 / 8; num7 = 0; while ((uint)num7 < num6) { Unsafe.SkipInit>(out value); vector = Unsafe.ReadUnaligned>(pInputBuffer); if (AdvSimd.IsSupported) { } if (Sse41.TestZ(vector, value)) { Sse2.StoreScalar((ulong*)pOutputBuffer, Sse2.PackUnsignedSaturate(vector, vector).AsUInt64()); pInputBuffer += 8; pOutputBuffer += 8; num7++; continue; } goto IL_019c; } outputBytesRemaining -= 8 * num7; if ((num5 & 4u) != 0) { num8 = Unsafe.ReadUnaligned(pInputBuffer); if (!Utf16Utility.AllCharsInUInt64AreAscii(num8)) { goto IL_0213; } vector = Vector128.CreateScalarUnsafe(num8).AsInt16(); if (AdvSimd.IsSupported) { } Unsafe.WriteUnaligned(pOutputBuffer, Sse2.ConvertToUInt32(Sse2.PackUnsignedSaturate(vector, vector).AsUInt32())); pInputBuffer += 4; pOutputBuffer += 4; outputBytesRemaining -= 4; } } else { uint num9 = num5 / 4; num10 = 0; while ((uint)num10 < num9) { num2 = Unsafe.ReadUnaligned(pInputBuffer); num11 = Unsafe.ReadUnaligned(pInputBuffer + 2); if (Utf16Utility.AllCharsInUInt32AreAscii(num2 | num11)) { Unsafe.WriteUnaligned(pOutputBuffer, (ushort)(num2 | (num2 >> 8))); Unsafe.WriteUnaligned(pOutputBuffer + 2, (ushort)(num11 | (num11 >> 8))); pInputBuffer += 4; pOutputBuffer += 4; num10++; continue; } goto IL_02b8; } outputBytesRemaining -= 4 * num10; } goto IL_04de; IL_04ae: if (IsWellFormedUtf16SurrogatePair(num2)) { if (outputBytesRemaining >= 4) { Unsafe.WriteUnaligned(pOutputBuffer, ExtractFourUtf8BytesFromSurrogatePair(num2)); pInputBuffer += 2; pOutputBuffer += 4; outputBytesRemaining -= 4; goto IL_04de; } goto IL_05a7; } goto IL_05ac; IL_038f: if (outputBytesRemaining >= 3) { _ = BitConverter.IsLittleEndian; num2 >>= 16; pOutputBuffer[2] = (byte)num2; pInputBuffer += 2; pOutputBuffer += 3; outputBytesRemaining -= 3; goto IL_04de; } pInputBuffer++; pOutputBuffer += 2; goto IL_05a7; IL_04de: if (pInputBuffer <= ptr) { goto IL_006d; } goto IL_04e5; IL_04e5: inputLength = (int)(ptr - pInputBuffer) + 2; goto IL_04f0; IL_0213: num2 = (uint)num8; if (Utf16Utility.AllCharsInUInt32AreAscii(num2)) { Unsafe.WriteUnaligned(pOutputBuffer, (ushort)(num2 | (num2 >> 8))); pInputBuffer += 2; pOutputBuffer += 2; outputBytesRemaining -= 2; num2 = (uint)(num8 >> 32); } goto IL_02e9; IL_019c: outputBytesRemaining -= 8 * num7; num8 = ((!Sse2.X64.IsSupported) ? vector.AsUInt64().ToScalar() : Sse2.X64.ConvertToUInt64(vector.AsUInt64())); if (Utf16Utility.AllCharsInUInt64AreAscii(num8)) { if (AdvSimd.IsSupported) { } Unsafe.WriteUnaligned(pOutputBuffer, Sse2.ConvertToUInt32(Sse2.PackUnsignedSaturate(vector, vector).AsUInt32())); pInputBuffer += 4; pOutputBuffer += 4; outputBytesRemaining -= 4; num8 = vector.AsUInt64().GetElement(1); } goto IL_0213; IL_02b8: outputBytesRemaining -= 4 * num10; if (Utf16Utility.AllCharsInUInt32AreAscii(num2)) { Unsafe.WriteUnaligned(pOutputBuffer, (ushort)(num2 | (num2 >> 8))); pInputBuffer += 2; pOutputBuffer += 2; outputBytesRemaining -= 2; num2 = num11; } goto IL_02e9; IL_02e9: while (true) { if (IsFirstCharAscii(num2)) { if (outputBytesRemaining == 0) { break; } _ = BitConverter.IsLittleEndian; *pOutputBuffer = (byte)num2; pInputBuffer++; pOutputBuffer++; outputBytesRemaining--; if (pInputBuffer > ptr) { goto IL_04e5; } num2 = Unsafe.ReadUnaligned(pInputBuffer); } if (!IsFirstCharAtLeastThreeUtf8Bytes(num2)) { while (IsSecondCharTwoUtf8Bytes(num2)) { if (outputBytesRemaining < 4) { goto end_IL_0074; } Unsafe.WriteUnaligned(pOutputBuffer, ExtractTwoUtf8TwoByteSequencesFromTwoPackedUtf16Chars(num2)); pInputBuffer += 2; pOutputBuffer += 4; outputBytesRemaining -= 4; if (pInputBuffer <= ptr) { num2 = Unsafe.ReadUnaligned(pInputBuffer); if (!IsFirstCharTwoUtf8Bytes(num2)) { goto IL_0074; } continue; } goto IL_04e5; } if (outputBytesRemaining < 2) { break; } Unsafe.WriteUnaligned(pOutputBuffer, (ushort)ExtractUtf8TwoByteSequenceFromFirstUtf16Char(num2)); if (IsSecondCharAscii(num2)) { goto IL_038f; } pInputBuffer++; pOutputBuffer += 2; outputBytesRemaining -= 2; if (pInputBuffer > ptr) { goto IL_04e5; } num2 = Unsafe.ReadUnaligned(pInputBuffer); } while (!IsFirstCharSurrogate(num2)) { if (IsSecondCharAtLeastThreeUtf8Bytes(num2) && !IsSecondCharSurrogate(num2) && outputBytesRemaining >= 6) { WriteTwoUtf16CharsAsTwoUtf8ThreeByteSequences(ref *pOutputBuffer, num2); pInputBuffer += 2; pOutputBuffer += 6; outputBytesRemaining -= 6; if (pInputBuffer <= ptr) { num2 = Unsafe.ReadUnaligned(pInputBuffer); if (!IsFirstCharAtLeastThreeUtf8Bytes(num2)) { goto IL_0074; } continue; } } else { if (outputBytesRemaining < 3) { goto end_IL_02e9; } WriteFirstUtf16CharAsUtf8ThreeByteSequence(ref *pOutputBuffer, num2); pInputBuffer++; pOutputBuffer += 3; outputBytesRemaining -= 3; if (!IsSecondCharAscii(num2)) { goto IL_049e; } if (outputBytesRemaining == 0) { goto end_IL_02e9; } _ = BitConverter.IsLittleEndian; *pOutputBuffer = (byte)(num2 >> 16); pInputBuffer++; pOutputBuffer++; outputBytesRemaining--; if (pInputBuffer <= ptr) { num2 = Unsafe.ReadUnaligned(pInputBuffer); if (!IsFirstCharAtLeastThreeUtf8Bytes(num2)) { goto IL_0074; } continue; } } goto IL_04e5; } goto IL_04ae; IL_049e: if (pInputBuffer <= ptr) { num2 = Unsafe.ReadUnaligned(pInputBuffer); continue; } goto IL_04e5; continue; end_IL_02e9: break; } goto IL_05a7; continue; end_IL_0074: break; } break; } _ = BitConverter.IsLittleEndian; uint num12 = num2 & 0xFFFFu; goto IL_050b; IL_0599: if (inputLength <= 1) { goto IL_059d; } goto IL_05a7; IL_04f0: if (inputLength != 0) { num12 = *pInputBuffer; goto IL_050b; } goto IL_059d; IL_05ac: OperationStatus result = OperationStatus.InvalidData; goto IL_05af; IL_05a7: result = OperationStatus.DestinationTooSmall; goto IL_05af; IL_05af: pInputBufferRemaining = pInputBuffer; pOutputBufferRemaining = pOutputBuffer; return result; IL_059d: result = OperationStatus.Done; goto IL_05af; IL_050b: if (num12 <= 127) { if (outputBytesRemaining != 0) { *pOutputBuffer = (byte)num12; pInputBuffer++; pOutputBuffer++; goto IL_0599; } } else if (num12 < 2048) { if (outputBytesRemaining >= 2) { pOutputBuffer[1] = (byte)((num12 & 0x3Fu) | 0xFFFFFF80u); *pOutputBuffer = (byte)((num12 >> 6) | 0xFFFFFFC0u); pInputBuffer++; pOutputBuffer += 2; goto IL_0599; } } else { if (UnicodeUtility.IsSurrogateCodePoint(num12)) { if (num12 > 56319) { goto IL_05ac; } result = OperationStatus.NeedMoreData; goto IL_05af; } if (outputBytesRemaining >= 3) { pOutputBuffer[2] = (byte)((num12 & 0x3Fu) | 0xFFFFFF80u); pOutputBuffer[1] = (byte)(((num12 >> 6) & 0x3Fu) | 0xFFFFFF80u); *pOutputBuffer = (byte)((num12 >> 12) | 0xFFFFFFE0u); pInputBuffer++; pOutputBuffer += 3; goto IL_0599; } } goto IL_05a7; } public unsafe static byte* GetPointerToFirstInvalidByte(byte* pInputBuffer, int inputLength, out int utf16CodeUnitCountAdjustment, out int scalarCountAdjustment) { nuint indexOfFirstNonAsciiByte = ASCIIUtility.GetIndexOfFirstNonAsciiByte(pInputBuffer, (uint)inputLength); pInputBuffer += indexOfFirstNonAsciiByte; inputLength -= (int)indexOfFirstNonAsciiByte; if (inputLength == 0) { utf16CodeUnitCountAdjustment = 0; scalarCountAdjustment = 0; return pInputBuffer; } int num = 0; int num2 = 0; nuint num12; if (inputLength >= 4) { byte* ptr = pInputBuffer + (uint)inputLength - 4; while (pInputBuffer <= ptr) { uint num3 = Unsafe.ReadUnaligned(pInputBuffer); while (true) { IL_0043: if (ASCIIUtility.AllBytesInUInt32AreAscii(num3)) { pInputBuffer += 4; if ((nint)(void*)Unsafe.ByteOffset(ref *pInputBuffer, ref *ptr) < (nint)16) { break; } num3 = Unsafe.ReadUnaligned(pInputBuffer); if (ASCIIUtility.AllBytesInUInt32AreAscii(num3)) { pInputBuffer = (byte*)((nuint)(pInputBuffer + 4) & ~(nuint)3u); byte* ptr2 = ptr - 12; if (AdvSimd.Arm64.IsSupported) { } uint num4; while (true) { if (Sse2.IsSupported) { num4 = (uint)Sse2.MoveMask(Sse2.LoadVector128(pInputBuffer)); if (num4 != 0) { break; } goto IL_00da; } if (ASCIIUtility.AllBytesInUInt32AreAscii(*(uint*)pInputBuffer | *(uint*)(pInputBuffer + 4))) { if (ASCIIUtility.AllBytesInUInt32AreAscii(*(uint*)(pInputBuffer + (nint)2 * (nint)4) | *(uint*)(pInputBuffer + (nint)3 * (nint)4))) { goto IL_00da; } pInputBuffer += 8; } num3 = *(uint*)pInputBuffer; if (ASCIIUtility.AllBytesInUInt32AreAscii(num3)) { pInputBuffer += 4; num3 = *(uint*)pInputBuffer; } goto IL_011e; IL_00da: pInputBuffer += 16; if (pInputBuffer > ptr2) { goto end_IL_0043; } } nuint num5 = (nuint)BitOperations.TrailingZeroCount(num4); pInputBuffer += num5; if (pInputBuffer > ptr) { goto end_IL_02e1; } num3 = Unsafe.ReadUnaligned(pInputBuffer); goto IL_013d; } } goto IL_011e; IL_011e: uint num6 = ASCIIUtility.CountNumberOfLeadingAsciiBytesFromUInt32WithSomeNonAsciiData(num3); pInputBuffer += num6; if (ptr < pInputBuffer) { goto end_IL_02e1; } num3 = Unsafe.ReadUnaligned(pInputBuffer); goto IL_013d; IL_013d: while (true) { uint num7 = num3; if (!BitConverter.IsLittleEndian) { } num3 = num7 - 32960; uint num8 = num3; if (!BitConverter.IsLittleEndian) { } if ((num8 & 0xC0E0u) != 0) { break; } _ = BitConverter.IsLittleEndian; if ((uint)(byte)num3 >= 2u) { if (!BitConverter.IsLittleEndian) { } while (true) { _ = BitConverter.IsLittleEndian; if (!UInt32EndsWithValidUtf8TwoByteSequenceLittleEndian(num3) && BitConverter.IsLittleEndian) { break; } pInputBuffer += 4; num -= 2; if (pInputBuffer > ptr) { goto end_IL_02e1; } num3 = Unsafe.ReadUnaligned(pInputBuffer); _ = BitConverter.IsLittleEndian; if (!UInt32BeginsWithValidUtf8TwoByteSequenceLittleEndian(num3)) { goto IL_0043; } } num--; if (UInt32ThirdByteIsAscii(num3)) { if (UInt32FourthByteIsAscii(num3)) { pInputBuffer += 4; goto end_IL_0043; } pInputBuffer += 3; if (pInputBuffer > ptr) { goto end_IL_0043; } num3 = Unsafe.ReadUnaligned(pInputBuffer); continue; } pInputBuffer += 2; goto end_IL_0043; } goto IL_03da; } uint num9 = num3; if (!BitConverter.IsLittleEndian) { } num3 = num9 - 8388640; uint num10 = num3; if (!BitConverter.IsLittleEndian) { } if ((num10 & 0xC0C0F0) == 0) { while (true) { _ = BitConverter.IsLittleEndian; if ((num3 & 0x200F) == 0 || ((num3 - 8205) & 0x200F) == 0) { break; } _ = BitConverter.IsLittleEndian; nint num11 = (int)num3 >> 31; pInputBuffer += 4; pInputBuffer += num11; num -= 2; if (IntPtr.Size >= 8) { } if (pInputBuffer > ptr) { goto end_IL_02e1; } num3 = Unsafe.ReadUnaligned(pInputBuffer); if (!UInt32BeginsWithUtf8ThreeByteMask(num3)) { goto IL_0043; } } } else { _ = BitConverter.IsLittleEndian; num3 &= 0xC0C0FFFFu; if ((int)num3 <= -2147467265) { num3 = BitOperations.RotateRight(num3, 8); if (UnicodeUtility.IsInRangeInclusive(num3, 276824080u, 343932943u)) { pInputBuffer += 4; num -= 2; num2--; break; } } } goto IL_03da; continue; end_IL_0043: break; } continue; end_IL_02e1: break; } num12 = (nuint)((byte*)(void*)Unsafe.ByteOffset(ref *pInputBuffer, ref *ptr) + 4); } else { num12 = (uint)inputLength; } while (num12 != 0) { uint num13 = *pInputBuffer; if ((uint)(byte)num13 < 128u) { pInputBuffer++; num12--; continue; } if (num12 < 2) { break; } uint value = pInputBuffer[1]; if ((uint)(byte)num13 < 224u) { if ((uint)(byte)num13 < 194u || !IsLowByteUtf8ContinuationByte(value)) { break; } pInputBuffer += 2; num--; num12 -= 2; continue; } if (num12 < 3 || (uint)(byte)num13 >= 240u) { break; } if ((byte)num13 == 224) { if (!UnicodeUtility.IsInRangeInclusive(value, 160u, 191u)) { break; } } else if ((byte)num13 == 237) { if (!UnicodeUtility.IsInRangeInclusive(value, 128u, 159u)) { break; } } else if (!IsLowByteUtf8ContinuationByte(value)) { break; } if (!IsUtf8ContinuationByte(in pInputBuffer[2])) { break; } pInputBuffer += 3; num -= 2; num12 -= 3; } goto IL_03da; IL_03da: utf16CodeUnitCountAdjustment = num; scalarCountAdjustment = num2; return pInputBuffer; } } } namespace System.StubHelpers { internal static class AnsiCharMarshaler { internal unsafe static byte[] DoAnsiConversion(string str, bool fBestFit, bool fThrowOnUnmappableChar, out int cbLength) { byte[] array = new byte[checked((str.Length + 1) * Marshal.SystemMaxDBCSCharSize)]; fixed (byte* buffer = &array[0]) { cbLength = Marshal.StringToAnsiString(str, buffer, array.Length, fBestFit, fThrowOnUnmappableChar); } return array; } internal unsafe static byte ConvertToNative(char managedChar, bool fBestFit, bool fThrowOnUnmappableChar) { int num = 2 * Marshal.SystemMaxDBCSCharSize; byte* ptr = stackalloc byte[(int)(uint)num]; int num2 = Marshal.StringToAnsiString(managedChar.ToString(), ptr, num, fBestFit, fThrowOnUnmappableChar); return *ptr; } internal static char ConvertToManaged(byte nativeChar) { ReadOnlySpan bytes = new ReadOnlySpan(ref nativeChar, 1); string @string = Encoding.Default.GetString(bytes); return @string[0]; } } internal static class CSTRMarshaler { internal unsafe static IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer) { if (strManaged == null) { return IntPtr.Zero; } byte* ptr = (byte*)(void*)pNativeBuffer; int num; if (ptr != null || Marshal.SystemMaxDBCSCharSize == 1) { num = checked((strManaged.Length + 1) * Marshal.SystemMaxDBCSCharSize + 1); bool flag = false; if (ptr == null) { ptr = (byte*)(void*)Marshal.AllocCoTaskMem(num); flag = true; } try { num = Marshal.StringToAnsiString(strManaged, ptr, num, (flags & 0xFF) != 0, flags >> 8 != 0); } catch (Exception) when (flag) { Marshal.FreeCoTaskMem((IntPtr)ptr); throw; } } else if (strManaged.Length == 0) { num = 0; ptr = (byte*)(void*)Marshal.AllocCoTaskMem(2); } else { byte[] array = AnsiCharMarshaler.DoAnsiConversion(strManaged, (flags & 0xFF) != 0, flags >> 8 != 0, out num); ptr = (byte*)(void*)Marshal.AllocCoTaskMem(num + 2); Buffer.Memmove(ref *ptr, ref MemoryMarshal.GetArrayDataReference(array), (nuint)num); } ptr[num] = 0; ptr[num + 1] = 0; return (IntPtr)ptr; } internal unsafe static string ConvertToManaged(IntPtr cstr) { if (IntPtr.Zero == cstr) { return null; } return new string((sbyte*)(void*)cstr); } internal static void ClearNative(IntPtr pNative) { Marshal.FreeCoTaskMem(pNative); } internal unsafe static void ConvertFixedToNative(int flags, string strManaged, IntPtr pNativeBuffer, int length) { if (strManaged == null) { if (length > 0) { *(sbyte*)(void*)pNativeBuffer = 0; } return; } int num = strManaged.Length; if (num >= length) { num = length - 1; } byte* ptr = (byte*)(void*)pNativeBuffer; bool flag = flags >> 8 != 0; bool flag2 = (flags & 0xFF) != 0; uint num2 = 0u; int num3; fixed (char* lpWideCharStr = strManaged) { num3 = Interop.Kernel32.WideCharToMultiByte(0u, (!flag2) ? 1024u : 0u, lpWideCharStr, num, ptr, length, IntPtr.Zero, flag ? new IntPtr(&num2) : IntPtr.Zero); } if (num2 != 0) { throw new ArgumentException(SR.Interop_Marshal_Unmappable_Char); } if (num3 == length) { num3--; } ptr[num3] = 0; } internal unsafe static string ConvertFixedToManaged(IntPtr cstr, int length) { int num = SpanHelpers.IndexOf(ref *(byte*)(void*)cstr, 0, length); if (num != -1) { length = num; } return new string((sbyte*)(void*)cstr, 0, length); } } internal static class UTF8Marshaler { internal unsafe static IntPtr ConvertToNative(int flags, string strManaged, IntPtr pNativeBuffer) { if (strManaged == null) { return IntPtr.Zero; } byte* ptr = (byte*)(void*)pNativeBuffer; int cbNativeBuffer; if (ptr != null) { cbNativeBuffer = (strManaged.Length + 1) * 3; cbNativeBuffer = strManaged.GetBytesFromEncoding(ptr, cbNativeBuffer, Encoding.UTF8); } else { cbNativeBuffer = Encoding.UTF8.GetByteCount(strManaged); ptr = (byte*)(void*)Marshal.AllocCoTaskMem(cbNativeBuffer + 1); strManaged.GetBytesFromEncoding(ptr, cbNativeBuffer, Encoding.UTF8); } ptr[cbNativeBuffer] = 0; return (IntPtr)ptr; } internal unsafe static string ConvertToManaged(IntPtr cstr) { if (IntPtr.Zero == cstr) { return null; } byte* ptr = (byte*)(void*)cstr; int byteLength = string.strlen(ptr); return string.CreateStringFromEncoding(ptr, byteLength, Encoding.UTF8); } internal static void ClearNative(IntPtr pNative) { Marshal.FreeCoTaskMem(pNative); } } internal static class UTF8BufferMarshaler { internal unsafe static IntPtr ConvertToNative(StringBuilder sb, IntPtr pNativeBuffer, int flags) { if (sb == null) { return IntPtr.Zero; } string text = sb.ToString(); int byteCount = Encoding.UTF8.GetByteCount(text); byte* ptr = (byte*)(void*)pNativeBuffer; byteCount = text.GetBytesFromEncoding(ptr, byteCount, Encoding.UTF8); ptr[byteCount] = 0; return (IntPtr)ptr; } internal unsafe static void ConvertToManaged(StringBuilder sb, IntPtr pNative) { if (!(pNative == IntPtr.Zero)) { byte* ptr = (byte*)(void*)pNative; int length = string.strlen(ptr); sb.ReplaceBufferUtf8Internal(new ReadOnlySpan(ptr, length)); } } } internal static class BSTRMarshaler { internal unsafe static IntPtr ConvertToNative(string strManaged, IntPtr pNativeBuffer) { if (strManaged == null) { return IntPtr.Zero; } byte data; bool flag = strManaged.TryGetTrailByte(out data); uint num = (uint)(strManaged.Length * 2); if (flag) { num++; } byte* ptr; if (pNativeBuffer != IntPtr.Zero) { *(uint*)(void*)pNativeBuffer = num; ptr = (byte*)(void*)pNativeBuffer + 4; } else { ptr = (byte*)(void*)Marshal.AllocBSTRByteLen(num); } Buffer.Memmove(ref *(char*)ptr, ref strManaged.GetRawStringData(), (nuint)strManaged.Length + (nuint)1u); if (flag) { ptr[num - 1] = data; } return (IntPtr)ptr; } internal unsafe static string ConvertToManaged(IntPtr bstr) { if (IntPtr.Zero == bstr) { return null; } uint num = Marshal.SysStringByteLen(bstr); StubHelpers.CheckStringLength(num); string text = ((num != 1) ? new string((char*)(void*)bstr, 0, (int)(num / 2)) : string.FastAllocateString(0)); if ((num & 1) == 1) { text.SetTrailByte(((byte*)(void*)bstr)[num - 1]); } return text; } internal static void ClearNative(IntPtr pNative) { Marshal.FreeBSTR(pNative); } } internal static class VBByValStrMarshaler { internal unsafe static IntPtr ConvertToNative(string strManaged, bool fBestFit, bool fThrowOnUnmappableChar, ref int cch) { if (strManaged == null) { return IntPtr.Zero; } cch = strManaged.Length; int cb = checked(4 + (cch + 1) * Marshal.SystemMaxDBCSCharSize); byte* ptr = (byte*)(void*)Marshal.AllocCoTaskMem(cb); int* ptr2 = (int*)ptr; ptr += 4; if (cch == 0) { *ptr = 0; *ptr2 = 0; } else { int cbLength; byte[] array = AnsiCharMarshaler.DoAnsiConversion(strManaged, fBestFit, fThrowOnUnmappableChar, out cbLength); Buffer.Memmove(ref *ptr, ref MemoryMarshal.GetArrayDataReference(array), (nuint)cbLength); ptr[cbLength] = 0; *ptr2 = cbLength; } return new IntPtr(ptr); } internal unsafe static string ConvertToManaged(IntPtr pNative, int cch) { if (IntPtr.Zero == pNative) { return null; } return new string((sbyte*)(void*)pNative, 0, cch); } internal static void ClearNative(IntPtr pNative) { if (IntPtr.Zero != pNative) { Marshal.FreeCoTaskMem((IntPtr)((long)pNative - 4)); } } } internal static class AnsiBSTRMarshaler { internal unsafe static IntPtr ConvertToNative(int flags, string strManaged) { if (strManaged == null) { return IntPtr.Zero; } byte[] array = null; int cbLength = 0; if (strManaged.Length > 0) { array = AnsiCharMarshaler.DoAnsiConversion(strManaged, (flags & 0xFF) != 0, flags >> 8 != 0, out cbLength); } uint num = (uint)cbLength; IntPtr intPtr = Marshal.AllocBSTRByteLen(num); if (array != null) { Buffer.Memmove(ref *(byte*)(void*)intPtr, ref MemoryMarshal.GetArrayDataReference(array), num); } return intPtr; } internal unsafe static string ConvertToManaged(IntPtr bstr) { if (IntPtr.Zero == bstr) { return null; } return new string((sbyte*)(void*)bstr); } internal static void ClearNative(IntPtr pNative) { Marshal.FreeBSTR(pNative); } } internal static class FixedWSTRMarshaler { internal unsafe static void ConvertToNative(string strManaged, IntPtr nativeHome, int length) { ReadOnlySpan readOnlySpan = strManaged; Span destination = new Span((void*)nativeHome, length); int num = Math.Min(readOnlySpan.Length, length - 1); readOnlySpan.Slice(0, num).CopyTo(destination); destination[num] = '\0'; } internal unsafe static string ConvertToManaged(IntPtr nativeHome, int length) { int num = SpanHelpers.IndexOf(ref *(char*)(void*)nativeHome, '\0', length); if (num != -1) { length = num; } return new string((char*)(void*)nativeHome, 0, length); } } internal static class ObjectMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertToNative(object objSrc, IntPtr pDstVariant); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern object ConvertToManaged(IntPtr pSrcVariant); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNative(IntPtr pVariant); } internal sealed class HandleMarshaler { internal static IntPtr ConvertSafeHandleToNative(SafeHandle handle, ref CleanupWorkListElement cleanupWorkList) { if (Unsafe.IsNullRef(ref cleanupWorkList)) { throw new InvalidOperationException(SR.Interop_Marshal_SafeHandle_InvalidOperation); } if (handle == null) { throw new ArgumentNullException("handle"); } return StubHelpers.AddToCleanupList(ref cleanupWorkList, handle); } internal static void ThrowSafeHandleFieldChanged() { throw new NotSupportedException(SR.Interop_Marshal_CannotCreateSafeHandleField); } internal static void ThrowCriticalHandleFieldChanged() { throw new NotSupportedException(SR.Interop_Marshal_CannotCreateCriticalHandleField); } } internal static class DateMarshaler { internal static double ConvertToNative(DateTime managedDate) { return managedDate.ToOADate(); } internal static long ConvertToManaged(double nativeDate) { return DateTime.DoubleDateToTicks(nativeDate); } } internal static class InterfaceMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr ConvertToNative(object objSrc, IntPtr itfMT, IntPtr classMT, int flags); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern object ConvertToManaged(ref IntPtr ppUnk, IntPtr itfMT, IntPtr classMT, int flags); [DllImport("QCall")] internal static extern void ClearNative(IntPtr pUnk); } internal static class MngdNativeArrayMarshaler { internal struct MarshalerState { private IntPtr m_pElementMT; private IntPtr m_Array; private IntPtr m_pManagedNativeArrayMarshaler; private int m_NativeDataValid; private int m_BestFitMap; private int m_ThrowOnUnmappableChar; private short m_vt; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int dwFlags, IntPtr pManagedMarshaler); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int cElements); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int cElements); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNativeContents(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, int cElements); } internal static class MngdFixedArrayMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int dwFlags, int cElements, IntPtr pManagedMarshaler); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNativeContents(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); } internal static class MngdSafeArrayMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pMT, int iRank, int dwFlags, IntPtr pManagedMarshaler); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome, object pOriginalManaged); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertSpaceToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); } internal static class MngdRefCustomMarshaler { [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void CreateMarshaler(IntPtr pMarshalState, IntPtr pCMHelper); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ConvertContentsToManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearNative(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearManaged(IntPtr pMarshalState, ref object pManagedHome, IntPtr pNativeHome); } internal struct AsAnyMarshaler { private enum BackPropAction { None, Array, Layout, StringBuilderAnsi, StringBuilderUnicode } private IntPtr pvArrayMarshaler; private BackPropAction backPropAction; private Type layoutType; private CleanupWorkListElement cleanupWorkList; private static bool IsIn(int dwFlags) { return (dwFlags & 0x10000000) != 0; } private static bool IsOut(int dwFlags) { return (dwFlags & 0x20000000) != 0; } private static bool IsAnsi(int dwFlags) { return (dwFlags & 0xFF0000) != 0; } private static bool IsThrowOn(int dwFlags) { return (dwFlags & 0xFF00) != 0; } private static bool IsBestFit(int dwFlags) { return (dwFlags & 0xFF) != 0; } internal AsAnyMarshaler(IntPtr pvArrayMarshaler) { this.pvArrayMarshaler = pvArrayMarshaler; backPropAction = BackPropAction.None; layoutType = null; cleanupWorkList = null; } private unsafe IntPtr ConvertArrayToNative(object pManagedHome, int dwFlags) { Type elementType = pManagedHome.GetType().GetElementType(); VarEnum varEnum = VarEnum.VT_EMPTY; switch (Type.GetTypeCode(elementType)) { case TypeCode.SByte: varEnum = VarEnum.VT_I1; break; case TypeCode.Byte: varEnum = VarEnum.VT_UI1; break; case TypeCode.Int16: varEnum = VarEnum.VT_I2; break; case TypeCode.UInt16: varEnum = VarEnum.VT_UI2; break; case TypeCode.Int32: varEnum = VarEnum.VT_I4; break; case TypeCode.UInt32: varEnum = VarEnum.VT_UI4; break; case TypeCode.Int64: varEnum = VarEnum.VT_I8; break; case TypeCode.UInt64: varEnum = VarEnum.VT_UI8; break; case TypeCode.Single: varEnum = VarEnum.VT_R4; break; case TypeCode.Double: varEnum = VarEnum.VT_R8; break; case TypeCode.Char: varEnum = (IsAnsi(dwFlags) ? ((VarEnum)253) : VarEnum.VT_UI2); break; case TypeCode.Boolean: varEnum = (VarEnum)254; break; case TypeCode.Object: if (elementType == typeof(IntPtr)) { if (IntPtr.Size != 4) { } varEnum = VarEnum.VT_I4; break; } if (elementType == typeof(UIntPtr)) { if (IntPtr.Size != 4) { } varEnum = VarEnum.VT_UI4; break; } goto default; default: throw new ArgumentException(SR.Arg_NDirectBadObject); } int num = (int)varEnum; if (IsBestFit(dwFlags)) { num |= 0x10000; } if (IsThrowOn(dwFlags)) { num |= 0x1000000; } MngdNativeArrayMarshaler.CreateMarshaler(pvArrayMarshaler, IntPtr.Zero, num, IntPtr.Zero); System.Runtime.CompilerServices.Unsafe.SkipInit(out IntPtr result); IntPtr pNativeHome = new IntPtr(&result); MngdNativeArrayMarshaler.ConvertSpaceToNative(pvArrayMarshaler, ref pManagedHome, pNativeHome); if (IsIn(dwFlags)) { MngdNativeArrayMarshaler.ConvertContentsToNative(pvArrayMarshaler, ref pManagedHome, pNativeHome); } if (IsOut(dwFlags)) { backPropAction = BackPropAction.Array; } return result; } private unsafe static IntPtr ConvertStringToNative(string pManagedHome, int dwFlags) { IntPtr intPtr; if (IsAnsi(dwFlags)) { intPtr = CSTRMarshaler.ConvertToNative(dwFlags & 0xFFFF, pManagedHome, IntPtr.Zero); } else { int cb = (pManagedHome.Length + 1) * 2; intPtr = Marshal.AllocCoTaskMem(cb); Buffer.Memmove(ref *(char*)(void*)intPtr, ref pManagedHome.GetRawStringData(), (nuint)pManagedHome.Length + (nuint)1u); } return intPtr; } private unsafe IntPtr ConvertStringBuilderToNative(StringBuilder pManagedHome, int dwFlags) { int capacity = pManagedHome.Capacity; int length = pManagedHome.Length; if (length > capacity) { ThrowHelper.ThrowInvalidOperationException(); } IntPtr intPtr; if (IsAnsi(dwFlags)) { StubHelpers.CheckStringLength(capacity); int num = checked(capacity * Marshal.SystemMaxDBCSCharSize + 4); intPtr = Marshal.AllocCoTaskMem(num); byte* ptr = (byte*)(void*)intPtr; *(ptr + num - 3) = 0; *(ptr + num - 2) = 0; *(ptr + num - 1) = 0; if (IsIn(dwFlags)) { int num2 = Marshal.StringToAnsiString(pManagedHome.ToString(), ptr, num, IsBestFit(dwFlags), IsThrowOn(dwFlags)); } if (IsOut(dwFlags)) { backPropAction = BackPropAction.StringBuilderAnsi; } } else { int num3 = checked(capacity * 2 + 4); intPtr = Marshal.AllocCoTaskMem(num3); byte* ptr2 = (byte*)(void*)intPtr; *(ptr2 + num3 - 1) = 0; *(ptr2 + num3 - 2) = 0; if (IsIn(dwFlags)) { pManagedHome.InternalCopy(intPtr, length); int num4 = length * 2; ptr2[num4] = 0; (ptr2 + num4)[1] = 0; } if (IsOut(dwFlags)) { backPropAction = BackPropAction.StringBuilderUnicode; } } return intPtr; } private unsafe IntPtr ConvertLayoutToNative(object pManagedHome, int dwFlags) { int cb = Marshal.SizeOfHelper(pManagedHome.GetType(), throwIfNotMarshalable: false); IntPtr intPtr = Marshal.AllocCoTaskMem(cb); if (IsIn(dwFlags)) { StubHelpers.FmtClassUpdateNativeInternal(pManagedHome, (byte*)(void*)intPtr, ref cleanupWorkList); } if (IsOut(dwFlags)) { backPropAction = BackPropAction.Layout; } layoutType = pManagedHome.GetType(); return intPtr; } internal IntPtr ConvertToNative(object pManagedHome, int dwFlags) { if (pManagedHome == null) { return IntPtr.Zero; } if (pManagedHome is ArrayWithOffset) { throw new ArgumentException(SR.Arg_MarshalAsAnyRestriction); } if (pManagedHome.GetType().IsArray) { return ConvertArrayToNative(pManagedHome, dwFlags); } if (pManagedHome is string pManagedHome2) { return ConvertStringToNative(pManagedHome2, dwFlags); } if (pManagedHome is StringBuilder pManagedHome3) { return ConvertStringBuilderToNative(pManagedHome3, dwFlags); } if (pManagedHome.GetType().IsLayoutSequential || pManagedHome.GetType().IsExplicitLayout) { return ConvertLayoutToNative(pManagedHome, dwFlags); } throw new ArgumentException(SR.Arg_NDirectBadObject); } internal unsafe void ConvertToManaged(object pManagedHome, IntPtr pNativeHome) { switch (backPropAction) { case BackPropAction.Array: MngdNativeArrayMarshaler.ConvertContentsToManaged(pvArrayMarshaler, ref pManagedHome, new IntPtr(&pNativeHome)); break; case BackPropAction.Layout: StubHelpers.FmtClassUpdateCLRInternal(pManagedHome, (byte*)(void*)pNativeHome); break; case BackPropAction.StringBuilderAnsi: { int newLength2 = ((!(pNativeHome == IntPtr.Zero)) ? string.strlen((byte*)(void*)pNativeHome) : 0); ((StringBuilder)pManagedHome).ReplaceBufferAnsiInternal((sbyte*)(void*)pNativeHome, newLength2); break; } case BackPropAction.StringBuilderUnicode: { int newLength = ((!(pNativeHome == IntPtr.Zero)) ? string.wcslen((char*)(void*)pNativeHome) : 0); ((StringBuilder)pManagedHome).ReplaceBufferInternal((char*)(void*)pNativeHome, newLength); break; } } } internal void ClearNative(IntPtr pNativeHome) { if (pNativeHome != IntPtr.Zero) { if (layoutType != null) { Marshal.DestroyStructure(pNativeHome, layoutType); } Marshal.FreeCoTaskMem(pNativeHome); } StubHelpers.DestroyCleanupList(ref cleanupWorkList); } } internal struct NativeVariant { private ushort vt; private ushort wReserved1; private ushort wReserved2; private ushort wReserved3; private long data1; } internal struct NativeDecimal { private ushort reserved; private ushort signScale; private uint hi32; private ulong lo64; } internal abstract class CleanupWorkListElement { private CleanupWorkListElement m_Next; protected abstract void DestroyCore(); public void Destroy() { DestroyCore(); for (CleanupWorkListElement next = m_Next; next != null; next = next.m_Next) { next.DestroyCore(); } } public static void AddToCleanupList(ref CleanupWorkListElement list, CleanupWorkListElement newElement) { if (list == null) { list = newElement; return; } newElement.m_Next = list; list = newElement; } } internal sealed class KeepAliveCleanupWorkListElement : CleanupWorkListElement { private object m_obj; public KeepAliveCleanupWorkListElement(object obj) { m_obj = obj; } protected override void DestroyCore() { GC.KeepAlive(m_obj); } } internal sealed class SafeHandleCleanupWorkListElement : CleanupWorkListElement { private SafeHandle m_handle; private bool m_owned; public SafeHandleCleanupWorkListElement(SafeHandle handle) { m_handle = handle; } protected override void DestroyCore() { if (m_owned) { StubHelpers.SafeHandleRelease(m_handle); } } public IntPtr AddRef() { return StubHelpers.SafeHandleAddRef(m_handle, ref m_owned); } } internal static class StubHelpers { [ThreadStatic] private static Exception s_pendingExceptionObject; [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void InitDeclaringType(IntPtr pMD); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetNDirectTarget(IntPtr pMD); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetDelegateTarget(Delegate pThis, ref IntPtr pStubArg); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ClearLastError(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void SetLastError(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ThrowInteropParamException(int resID, int paramIdx); internal static IntPtr AddToCleanupList(ref CleanupWorkListElement pCleanupWorkList, SafeHandle handle) { SafeHandleCleanupWorkListElement safeHandleCleanupWorkListElement = new SafeHandleCleanupWorkListElement(handle); CleanupWorkListElement.AddToCleanupList(ref pCleanupWorkList, safeHandleCleanupWorkListElement); return safeHandleCleanupWorkListElement.AddRef(); } internal static void KeepAliveViaCleanupList(ref CleanupWorkListElement pCleanupWorkList, object obj) { KeepAliveCleanupWorkListElement newElement = new KeepAliveCleanupWorkListElement(obj); CleanupWorkListElement.AddToCleanupList(ref pCleanupWorkList, newElement); } internal static void DestroyCleanupList(ref CleanupWorkListElement pCleanupWorkList) { if (pCleanupWorkList != null) { pCleanupWorkList.Destroy(); pCleanupWorkList = null; } } internal static Exception GetHRExceptionObject(int hr) { Exception ex = InternalGetHRExceptionObject(hr); ex.InternalPreserveStackTrace(); return ex; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Exception InternalGetHRExceptionObject(int hr); internal static Exception GetCOMHRExceptionObject(int hr, IntPtr pCPCMD, object pThis) { Exception ex = InternalGetCOMHRExceptionObject(hr, pCPCMD, pThis); ex.InternalPreserveStackTrace(); return ex; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Exception InternalGetCOMHRExceptionObject(int hr, IntPtr pCPCMD, object pThis); internal static Exception GetPendingExceptionObject() { Exception ex = s_pendingExceptionObject; ex?.InternalPreserveStackTrace(); s_pendingExceptionObject = null; return ex; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr CreateCustomMarshalerHelper(IntPtr pMD, int paramToken, IntPtr hndManagedType); internal static IntPtr SafeHandleAddRef(SafeHandle pHandle, ref bool success) { if (pHandle == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pHandle, ExceptionResource.ArgumentNull_SafeHandle); } pHandle.DangerousAddRef(ref success); return pHandle.DangerousGetHandle(); } internal static void SafeHandleRelease(SafeHandle pHandle) { if (pHandle == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pHandle, ExceptionResource.ArgumentNull_SafeHandle); } pHandle.DangerousRelease(); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetCOMIPFromRCW(object objSrc, IntPtr pCPCMD, out IntPtr ppTarget, out bool pfNeedsRelease); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr ProfilerBeginTransitionCallback(IntPtr pSecretParam, IntPtr pThread, object pThis); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ProfilerEndTransitionCallback(IntPtr pMD, IntPtr pThread); internal static void CheckStringLength(int length) { CheckStringLength((uint)length); } internal static void CheckStringLength(uint length) { if (length > 2147483632) { throw new MarshalDirectiveException(SR.Marshaler_StringTooLong); } } [MethodImpl(MethodImplOptions.InternalCall)] internal unsafe static extern void FmtClassUpdateNativeInternal(object obj, byte* pNative, ref CleanupWorkListElement pCleanupWorkList); [MethodImpl(MethodImplOptions.InternalCall)] internal unsafe static extern void FmtClassUpdateCLRInternal(object obj, byte* pNative); [MethodImpl(MethodImplOptions.InternalCall)] internal unsafe static extern void LayoutDestroyNativeInternal(object obj, byte* pNative); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern object AllocateInternal(IntPtr typeHandle); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void MarshalToUnmanagedVaListInternal(IntPtr va_list, uint vaListSize, IntPtr pArgIterator); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void MarshalToManagedVaListInternal(IntPtr va_list, IntPtr pArgIterator); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern uint CalcVaListSize(IntPtr va_list); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ValidateObject(object obj, IntPtr pMD, object pThis); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void LogPinnedArgument(IntPtr localDesc, IntPtr nativeArg); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void ValidateByref(IntPtr byref, IntPtr pMD, object pThis); [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] internal static extern IntPtr GetStubContext(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr NextCallReturnAddress(); } } namespace System.Security { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] public sealed class AllowPartiallyTrustedCallersAttribute : Attribute { public PartialTrustVisibilityLevel PartialTrustVisibilityLevel { get; set; } } [Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId = "SYSLIB0003", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public interface IPermission : ISecurityEncodable { IPermission Copy(); void Demand(); IPermission? Intersect(IPermission? target); bool IsSubsetOf(IPermission? target); IPermission? Union(IPermission? target); } public interface ISecurityEncodable { void FromXml(SecurityElement e); SecurityElement? ToXml(); } [Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId = "SYSLIB0003", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public interface IStackWalk { void Assert(); void Demand(); void Deny(); void PermitOnly(); } public enum PartialTrustVisibilityLevel { VisibleToAllHosts, NotVisibleByDefault } [Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId = "SYSLIB0003", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public class PermissionSet : ICollection, System.Collections.IEnumerable, IDeserializationCallback, ISecurityEncodable, IStackWalk { public virtual int Count => 0; public virtual bool IsReadOnly => false; public virtual bool IsSynchronized => false; public virtual object SyncRoot => this; public PermissionSet(PermissionState state) { } public PermissionSet(PermissionSet? permSet) { } public IPermission? AddPermission(IPermission? perm) { return AddPermissionImpl(perm); } protected virtual IPermission? AddPermissionImpl(IPermission? perm) { return null; } public void Assert() { } public bool ContainsNonCodeAccessPermissions() { return false; } [Obsolete] public static byte[] ConvertPermissionSet(string inFormat, byte[] inData, string outFormat) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); } public virtual PermissionSet Copy() { return new PermissionSet(this); } public virtual void CopyTo(Array array, int index) { } public void Demand() { } [Obsolete] public void Deny() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); } public override bool Equals(object? o) { return base.Equals(o); } public virtual void FromXml(SecurityElement et) { } public System.Collections.IEnumerator GetEnumerator() { return GetEnumeratorImpl(); } protected virtual System.Collections.IEnumerator GetEnumeratorImpl() { return Array.Empty().GetEnumerator(); } public override int GetHashCode() { return base.GetHashCode(); } public IPermission? GetPermission(Type? permClass) { return GetPermissionImpl(permClass); } protected virtual IPermission? GetPermissionImpl(Type? permClass) { return null; } public PermissionSet? Intersect(PermissionSet? other) { return null; } public bool IsEmpty() { return false; } public bool IsSubsetOf(PermissionSet? target) { return false; } public bool IsUnrestricted() { return false; } public void PermitOnly() { throw new PlatformNotSupportedException(SR.PlatformNotSupported_CAS); } public IPermission? RemovePermission(Type? permClass) { return RemovePermissionImpl(permClass); } protected virtual IPermission? RemovePermissionImpl(Type? permClass) { return null; } public static void RevertAssert() { } public IPermission? SetPermission(IPermission? perm) { return SetPermissionImpl(perm); } protected virtual IPermission? SetPermissionImpl(IPermission? perm) { return null; } void IDeserializationCallback.OnDeserialization(object sender) { } public override string ToString() { return base.ToString(); } public virtual SecurityElement? ToXml() { return null; } public PermissionSet? Union(PermissionSet? other) { return null; } } public sealed class SecureString : IDisposable { private sealed class UnmanagedBuffer : SafeBuffer { private int _byteLength; private UnmanagedBuffer() : base(ownsHandle: true) { } public static UnmanagedBuffer Allocate(int byteLength) { UnmanagedBuffer unmanagedBuffer = new UnmanagedBuffer(); unmanagedBuffer.SetHandle(Marshal.AllocHGlobal(byteLength)); unmanagedBuffer.Initialize((ulong)byteLength); unmanagedBuffer._byteLength = byteLength; return unmanagedBuffer; } internal unsafe static void Copy(UnmanagedBuffer source, UnmanagedBuffer destination, ulong bytesLength) { if (bytesLength == 0L) { return; } byte* pointer = null; byte* pointer2 = null; try { source.AcquirePointer(ref pointer); destination.AcquirePointer(ref pointer2); Buffer.MemoryCopy(pointer, pointer2, destination.ByteLength, bytesLength); } finally { if (pointer2 != null) { destination.ReleasePointer(); } if (pointer != null) { source.ReleasePointer(); } } } protected unsafe override bool ReleaseHandle() { new Span((void*)handle, _byteLength).Clear(); Marshal.FreeHGlobal(handle); return true; } } private readonly object _methodLock = new object(); private UnmanagedBuffer _buffer; private int _decryptedLength; private bool _encrypted; private bool _readOnly; public int Length { get { EnsureNotDisposed(); return Volatile.Read(ref _decryptedLength); } } public SecureString() { Initialize(ReadOnlySpan.Empty); } [CLSCompliant(false)] public unsafe SecureString(char* value, int length) { if (value == null) { throw new ArgumentNullException("value"); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NeedNonNegNum); } if (length > 65536) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_Length); } Initialize(new ReadOnlySpan(value, length)); } private void Initialize(ReadOnlySpan value) { _buffer = UnmanagedBuffer.Allocate(GetAlignedByteSize(value.Length)); _decryptedLength = value.Length; SafeBuffer bufferToRelease = null; try { Span destination = AcquireSpan(ref bufferToRelease); value.CopyTo(destination); } finally { ProtectMemory(); bufferToRelease?.DangerousRelease(); } } private SecureString(SecureString str) { _buffer = UnmanagedBuffer.Allocate((int)str._buffer.ByteLength); UnmanagedBuffer.Copy(str._buffer, _buffer, str._buffer.ByteLength); _decryptedLength = str._decryptedLength; _encrypted = str._encrypted; } private void EnsureCapacity(int capacity) { if (capacity > 65536) { throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_Capacity); } if ((uint)(capacity * 2) > _buffer.ByteLength) { UnmanagedBuffer buffer = _buffer; UnmanagedBuffer unmanagedBuffer = UnmanagedBuffer.Allocate(GetAlignedByteSize(capacity)); UnmanagedBuffer.Copy(buffer, unmanagedBuffer, (uint)(_decryptedLength * 2)); _buffer = unmanagedBuffer; buffer.Dispose(); } } public void AppendChar(char c) { lock (_methodLock) { EnsureNotDisposed(); EnsureNotReadOnly(); SafeBuffer bufferToRelease = null; try { UnprotectMemory(); EnsureCapacity(_decryptedLength + 1); AcquireSpan(ref bufferToRelease)[_decryptedLength] = c; _decryptedLength++; } finally { ProtectMemory(); bufferToRelease?.DangerousRelease(); } } } public void Clear() { lock (_methodLock) { EnsureNotDisposed(); EnsureNotReadOnly(); _decryptedLength = 0; SafeBuffer bufferToRelease = null; try { AcquireSpan(ref bufferToRelease).Clear(); } finally { bufferToRelease?.DangerousRelease(); } } } public SecureString Copy() { lock (_methodLock) { EnsureNotDisposed(); return new SecureString(this); } } public void Dispose() { lock (_methodLock) { if (_buffer != null) { _buffer.Dispose(); _buffer = null; } } } public void InsertAt(int index, char c) { lock (_methodLock) { if (index < 0 || index > _decryptedLength) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_IndexString); } EnsureNotDisposed(); EnsureNotReadOnly(); SafeBuffer bufferToRelease = null; try { UnprotectMemory(); EnsureCapacity(_decryptedLength + 1); Span span = AcquireSpan(ref bufferToRelease); span.Slice(index, _decryptedLength - index).CopyTo(span.Slice(index + 1)); span[index] = c; _decryptedLength++; } finally { ProtectMemory(); bufferToRelease?.DangerousRelease(); } } } public bool IsReadOnly() { EnsureNotDisposed(); return Volatile.Read(ref _readOnly); } public void MakeReadOnly() { EnsureNotDisposed(); Volatile.Write(ref _readOnly, value: true); } public void RemoveAt(int index) { lock (_methodLock) { if (index < 0 || index >= _decryptedLength) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_IndexString); } EnsureNotDisposed(); EnsureNotReadOnly(); SafeBuffer bufferToRelease = null; try { UnprotectMemory(); Span span = AcquireSpan(ref bufferToRelease); span.Slice(index + 1, _decryptedLength - (index + 1)).CopyTo(span.Slice(index)); _decryptedLength--; } finally { ProtectMemory(); bufferToRelease?.DangerousRelease(); } } } public void SetAt(int index, char c) { lock (_methodLock) { if (index < 0 || index >= _decryptedLength) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_IndexString); } EnsureNotDisposed(); EnsureNotReadOnly(); SafeBuffer bufferToRelease = null; try { UnprotectMemory(); AcquireSpan(ref bufferToRelease)[index] = c; } finally { ProtectMemory(); bufferToRelease?.DangerousRelease(); } } } private unsafe Span AcquireSpan(ref SafeBuffer bufferToRelease) { SafeBuffer buffer = _buffer; bool success = false; buffer.DangerousAddRef(ref success); bufferToRelease = buffer; return new Span((void*)buffer.DangerousGetHandle(), (int)(buffer.ByteLength / 2)); } private void EnsureNotReadOnly() { if (_readOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } private void EnsureNotDisposed() { if (_buffer == null) { throw new ObjectDisposedException(GetType().Name); } } internal unsafe IntPtr MarshalToBSTR() { lock (_methodLock) { EnsureNotDisposed(); UnprotectMemory(); SafeBuffer bufferToRelease = null; IntPtr intPtr = IntPtr.Zero; int length = 0; try { Span span = AcquireSpan(ref bufferToRelease); length = _decryptedLength; intPtr = Marshal.AllocBSTR(length); span.Slice(0, length).CopyTo(new Span((void*)intPtr, length)); IntPtr result = intPtr; intPtr = IntPtr.Zero; return result; } finally { if (intPtr != IntPtr.Zero) { new Span((void*)intPtr, length).Clear(); Marshal.FreeBSTR(intPtr); } ProtectMemory(); bufferToRelease?.DangerousRelease(); } } } internal unsafe IntPtr MarshalToString(bool globalAlloc, bool unicode) { lock (_methodLock) { EnsureNotDisposed(); UnprotectMemory(); SafeBuffer bufferToRelease = null; IntPtr intPtr = IntPtr.Zero; int num = 0; try { Span span = AcquireSpan(ref bufferToRelease).Slice(0, _decryptedLength); num = ((!unicode) ? Marshal.GetAnsiStringByteCount(span) : ((span.Length + 1) * 2)); intPtr = ((!globalAlloc) ? Marshal.AllocCoTaskMem(num) : Marshal.AllocHGlobal(num)); if (unicode) { Span destination = new Span((void*)intPtr, num / 2); span.CopyTo(destination); destination[destination.Length - 1] = '\0'; } else { Marshal.GetAnsiStringBytes(span, new Span((void*)intPtr, num)); } IntPtr result = intPtr; intPtr = IntPtr.Zero; return result; } finally { if (intPtr != IntPtr.Zero) { new Span((void*)intPtr, num).Clear(); if (globalAlloc) { Marshal.FreeHGlobal(intPtr); } else { Marshal.FreeCoTaskMem(intPtr); } } ProtectMemory(); bufferToRelease?.DangerousRelease(); } } } private static int GetAlignedByteSize(int length) { int num = Math.Max(length, 1) * 2; return (num + 15) / 16 * 16; } private void ProtectMemory() { if (_decryptedLength != 0 && !_encrypted && !Interop.Crypt32.CryptProtectMemory(_buffer, (uint)_buffer.ByteLength, 0u)) { throw new CryptographicException(Marshal.GetLastPInvokeError()); } _encrypted = true; } private void UnprotectMemory() { if (_decryptedLength != 0 && _encrypted && !Interop.Crypt32.CryptUnprotectMemory(_buffer, (uint)_buffer.ByteLength, 0u)) { throw new CryptographicException(Marshal.GetLastPInvokeError()); } _encrypted = false; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class SecurityCriticalAttribute : Attribute { [Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")] public SecurityCriticalScope Scope { get; } public SecurityCriticalAttribute() { } public SecurityCriticalAttribute(SecurityCriticalScope scope) { Scope = scope; } } [Obsolete("SecurityCriticalScope is only used for .NET 2.0 transparency compatibility.")] public enum SecurityCriticalScope { Explicit, Everything } public sealed class SecurityElement { internal string _tag; internal string _text; private ArrayList _children; internal ArrayList _attributes; private static readonly char[] s_tagIllegalCharacters = new char[3] { ' ', '<', '>' }; private static readonly char[] s_textIllegalCharacters = new char[2] { '<', '>' }; private static readonly char[] s_valueIllegalCharacters = new char[3] { '<', '>', '"' }; private static readonly char[] s_escapeChars = new char[5] { '<', '>', '"', '\'', '&' }; private static readonly string[] s_escapeStringPairs = new string[10] { "<", "<", ">", ">", "\"", """, "'", "'", "&", "&" }; public string Tag { get { return _tag; } set { if (value == null) { throw new ArgumentNullException("Tag"); } if (!IsValidTag(value)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidElementTag, value)); } _tag = value; } } public Hashtable? Attributes { get { if (_attributes == null || _attributes.Count == 0) { return null; } Hashtable hashtable = new Hashtable(_attributes.Count / 2); int count = _attributes.Count; for (int i = 0; i < count; i += 2) { hashtable.Add(_attributes[i], _attributes[i + 1]); } return hashtable; } set { if (value == null || value.Count == 0) { _attributes = null; return; } ArrayList arrayList = new ArrayList(value.Count); IDictionaryEnumerator enumerator = value.GetEnumerator(); while (enumerator.MoveNext()) { string text = (string)enumerator.Key; string text2 = (string)enumerator.Value; if (!IsValidAttributeName(text)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidElementName, text)); } if (!IsValidAttributeValue(text2)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidElementValue, text2)); } arrayList.Add(text); arrayList.Add(text2); } _attributes = arrayList; } } public string? Text { get { return Unescape(_text); } set { if (value == null) { _text = null; return; } if (!IsValidText(value)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidElementTag, value)); } _text = value; } } public ArrayList? Children { get { return _children; } set { if (value != null && value.Contains(null)) { throw new ArgumentException(SR.ArgumentNull_Child); } _children = value; } } public SecurityElement(string tag) { if (tag == null) { throw new ArgumentNullException("tag"); } if (!IsValidTag(tag)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidElementTag, tag)); } _tag = tag; } public SecurityElement(string tag, string? text) { if (tag == null) { throw new ArgumentNullException("tag"); } if (!IsValidTag(tag)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidElementTag, tag)); } if (text != null && !IsValidText(text)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidElementText, text)); } _tag = tag; _text = text; } internal void AddAttributeSafe(string name, string value) { if (_attributes == null) { _attributes = new ArrayList(8); } else { int count = _attributes.Count; for (int i = 0; i < count; i += 2) { string a = (string)_attributes[i]; if (string.Equals(a, name)) { throw new ArgumentException(SR.Argument_AttributeNamesMustBeUnique); } } } _attributes.Add(name); _attributes.Add(value); } public void AddAttribute(string name, string value) { if (name == null) { throw new ArgumentNullException("name"); } if (value == null) { throw new ArgumentNullException("value"); } if (!IsValidAttributeName(name)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidElementName, name)); } if (!IsValidAttributeValue(value)) { throw new ArgumentException(SR.Format(SR.Argument_InvalidElementValue, value)); } AddAttributeSafe(name, value); } public void AddChild(SecurityElement child) { if (child == null) { throw new ArgumentNullException("child"); } if (_children == null) { _children = new ArrayList(1); } _children.Add(child); } public bool Equal([NotNullWhen(true)] SecurityElement? other) { if (other == null) { return false; } if (!string.Equals(_tag, other._tag)) { return false; } if (!string.Equals(_text, other._text)) { return false; } if (_attributes == null || other._attributes == null) { if (_attributes != other._attributes) { return false; } } else { int count = _attributes.Count; if (count != other._attributes.Count) { return false; } for (int i = 0; i < count; i++) { string a = (string)_attributes[i]; string b = (string)other._attributes[i]; if (!string.Equals(a, b)) { return false; } } } if (_children == null || other._children == null) { if (_children != other._children) { return false; } } else { if (_children.Count != other._children.Count) { return false; } System.Collections.IEnumerator enumerator = _children.GetEnumerator(); System.Collections.IEnumerator enumerator2 = other._children.GetEnumerator(); while (enumerator.MoveNext()) { enumerator2.MoveNext(); SecurityElement securityElement = (SecurityElement)enumerator.Current; SecurityElement other2 = (SecurityElement)enumerator2.Current; if (securityElement == null || !securityElement.Equal(other2)) { return false; } } } return true; } public SecurityElement Copy() { SecurityElement securityElement = new SecurityElement(_tag, _text); securityElement._children = ((_children == null) ? null : new ArrayList(_children)); securityElement._attributes = ((_attributes == null) ? null : new ArrayList(_attributes)); return securityElement; } public static bool IsValidTag([NotNullWhen(true)] string? tag) { if (tag == null) { return false; } return tag.IndexOfAny(s_tagIllegalCharacters) == -1; } public static bool IsValidText([NotNullWhen(true)] string? text) { if (text == null) { return false; } return text.IndexOfAny(s_textIllegalCharacters) == -1; } public static bool IsValidAttributeName([NotNullWhen(true)] string? name) { return IsValidTag(name); } public static bool IsValidAttributeValue([NotNullWhen(true)] string? value) { if (value == null) { return false; } return value.IndexOfAny(s_valueIllegalCharacters) == -1; } private static string GetEscapeSequence(char c) { int num = s_escapeStringPairs.Length; for (int i = 0; i < num; i += 2) { string text = s_escapeStringPairs[i]; string result = s_escapeStringPairs[i + 1]; if (text[0] == c) { return result; } } return c.ToString(); } [return: NotNullIfNotNull("str")] public static string? Escape(string? str) { if (str == null) { return null; } StringBuilder stringBuilder = null; int length = str.Length; int num = 0; while (true) { int num2 = str.IndexOfAny(s_escapeChars, num); if (num2 == -1) { break; } if (stringBuilder == null) { stringBuilder = new StringBuilder(); } stringBuilder.Append(str, num, num2 - num); stringBuilder.Append(GetEscapeSequence(str[num2])); num = num2 + 1; } if (stringBuilder == null) { return str; } stringBuilder.Append(str, num, length - num); return stringBuilder.ToString(); } private static string GetUnescapeSequence(string str, int index, out int newIndex) { int num = str.Length - index; int num2 = s_escapeStringPairs.Length; for (int i = 0; i < num2; i += 2) { string result = s_escapeStringPairs[i]; string text = s_escapeStringPairs[i + 1]; int length = text.Length; if (length <= num && string.Compare(text, 0, str, index, length, StringComparison.Ordinal) == 0) { newIndex = index + text.Length; return result; } } newIndex = index + 1; return str[index].ToString(); } private static string Unescape(string str) { if (str == null) { return null; } StringBuilder stringBuilder = null; int length = str.Length; int newIndex = 0; while (true) { int num = str.IndexOf('&', newIndex); if (num == -1) { break; } if (stringBuilder == null) { stringBuilder = new StringBuilder(); } stringBuilder.Append(str, newIndex, num - newIndex); stringBuilder.Append(GetUnescapeSequence(str, num, out newIndex)); } if (stringBuilder == null) { return str; } stringBuilder.Append(str, newIndex, length - newIndex); return stringBuilder.ToString(); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); ToString(stringBuilder, delegate(object obj, string str) { ((StringBuilder)obj).Append(str); }); return stringBuilder.ToString(); } private void ToString(object obj, Action write) { write(obj, "<"); write(obj, _tag); if (_attributes != null && _attributes.Count > 0) { write(obj, " "); int count = _attributes.Count; for (int i = 0; i < count; i += 2) { string arg = (string)_attributes[i]; string arg2 = (string)_attributes[i + 1]; write(obj, arg); write(obj, "=\""); write(obj, arg2); write(obj, "\""); if (i != _attributes.Count - 2) { write(obj, "\r\n"); } } } if (_text == null && (_children == null || _children.Count == 0)) { write(obj, "/>"); write(obj, "\r\n"); return; } write(obj, ">"); write(obj, _text); if (_children != null) { write(obj, "\r\n"); for (int j = 0; j < _children.Count; j++) { ((SecurityElement)_children[j]).ToString(obj, write); } } write(obj, ""); write(obj, "\r\n"); } public string? Attribute(string name) { if (name == null) { throw new ArgumentNullException("name"); } if (_attributes == null) { return null; } int count = _attributes.Count; for (int i = 0; i < count; i += 2) { string a = (string)_attributes[i]; if (string.Equals(a, name)) { string str = (string)_attributes[i + 1]; return Unescape(str); } } return null; } public SecurityElement? SearchForChildByTag(string tag) { if (tag == null) { throw new ArgumentNullException("tag"); } if (_children == null) { return null; } foreach (SecurityElement child in _children) { if (child != null && string.Equals(child.Tag, tag)) { return child; } } return null; } public string? SearchForTextOfTag(string tag) { if (tag == null) { throw new ArgumentNullException("tag"); } if (string.Equals(_tag, tag)) { return Unescape(_text); } if (_children == null) { return null; } foreach (SecurityElement child in Children) { string text = child?.SearchForTextOfTag(tag); if (text != null) { return text; } } return null; } public static SecurityElement? FromString(string xml) { if (xml == null) { throw new ArgumentNullException("xml"); } return null; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SecurityException : SystemException { public object? Demanded { get; set; } public object? DenySetInstance { get; set; } public AssemblyName? FailedAssemblyInfo { get; set; } public string? GrantedSet { get; set; } public MethodInfo? Method { get; set; } public string? PermissionState { get; set; } public Type? PermissionType { get; set; } public object? PermitOnlySetInstance { get; set; } public string? RefusedSet { get; set; } public string? Url { get; set; } public SecurityException() : base(SR.Arg_SecurityException) { base.HResult = -2146233078; } public SecurityException(string? message) : base(message) { base.HResult = -2146233078; } public SecurityException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233078; } public SecurityException(string? message, Type? type) : base(message) { base.HResult = -2146233078; PermissionType = type; } public SecurityException(string? message, Type? type, string? state) : base(message) { base.HResult = -2146233078; PermissionType = type; PermissionState = state; } protected SecurityException(SerializationInfo info, StreamingContext context) : base(info, context) { Demanded = (string)info.GetValueNoThrow("Demanded", typeof(string)); GrantedSet = (string)info.GetValueNoThrow("GrantedSet", typeof(string)); RefusedSet = (string)info.GetValueNoThrow("RefusedSet", typeof(string)); DenySetInstance = (string)info.GetValueNoThrow("Denied", typeof(string)); PermitOnlySetInstance = (string)info.GetValueNoThrow("PermitOnly", typeof(string)); Url = (string)info.GetValueNoThrow("Url", typeof(string)); } public override string ToString() { return base.ToString(); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Demanded", Demanded, typeof(string)); info.AddValue("GrantedSet", GrantedSet, typeof(string)); info.AddValue("RefusedSet", RefusedSet, typeof(string)); info.AddValue("Denied", DenySetInstance, typeof(string)); info.AddValue("PermitOnly", PermitOnlySetInstance, typeof(string)); info.AddValue("Url", Url, typeof(string)); } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public sealed class SecurityRulesAttribute : Attribute { public bool SkipVerificationInFullTrust { get; set; } public SecurityRuleSet RuleSet { get; } public SecurityRulesAttribute(SecurityRuleSet ruleSet) { RuleSet = ruleSet; } } public enum SecurityRuleSet : byte { None, Level1, Level2 } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class SecuritySafeCriticalAttribute : Attribute { } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] public sealed class SecurityTransparentAttribute : Attribute { } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [Obsolete("SecurityTreatAsSafe is only used for .NET 2.0 transparency compatibility. Use the SecuritySafeCriticalAttribute instead.")] public sealed class SecurityTreatAsSafeAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false)] public sealed class SuppressUnmanagedCodeSecurityAttribute : Attribute { } [AttributeUsage(AttributeTargets.Module, AllowMultiple = true, Inherited = false)] public sealed class UnverifiableCodeAttribute : Attribute { } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class VerificationException : SystemException { public VerificationException() : base(SR.Verification_Exception) { base.HResult = -2146233075; } public VerificationException(string? message) : base(message) { base.HResult = -2146233075; } public VerificationException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233075; } protected VerificationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } namespace System.Security.Principal { public interface IIdentity { string? Name { get; } string? AuthenticationType { get; } bool IsAuthenticated { get; } } public interface IPrincipal { IIdentity? Identity { get; } bool IsInRole(string role); } public enum PrincipalPolicy { UnauthenticatedPrincipal, NoPrincipal, WindowsPrincipal } public enum TokenImpersonationLevel { None, Anonymous, Identification, Impersonation, Delegation } } namespace System.Security.Permissions { [Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId = "SYSLIB0003", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public abstract class CodeAccessSecurityAttribute : SecurityAttribute { protected CodeAccessSecurityAttribute(SecurityAction action) : base((SecurityAction)0) { } } [Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId = "SYSLIB0003", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public enum PermissionState { None, Unrestricted } [Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId = "SYSLIB0003", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public enum SecurityAction { Assert = 3, Demand = 2, Deny = 4, InheritanceDemand = 7, LinkDemand = 6, PermitOnly = 5, RequestMinimum = 8, RequestOptional = 9, RequestRefuse = 10 } [Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId = "SYSLIB0003", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public abstract class SecurityAttribute : Attribute { public SecurityAction Action { get; set; } public bool Unrestricted { get; set; } protected SecurityAttribute(SecurityAction action) { } public abstract IPermission? CreatePermission(); } [Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId = "SYSLIB0003", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = true, Inherited = false)] public sealed class SecurityPermissionAttribute : CodeAccessSecurityAttribute { public bool Assertion { get; set; } public bool BindingRedirects { get; set; } public bool ControlAppDomain { get; set; } public bool ControlDomainPolicy { get; set; } public bool ControlEvidence { get; set; } public bool ControlPolicy { get; set; } public bool ControlPrincipal { get; set; } public bool ControlThread { get; set; } public bool Execution { get; set; } public SecurityPermissionFlag Flags { get; set; } public bool Infrastructure { get; set; } public bool RemotingConfiguration { get; set; } public bool SerializationFormatter { get; set; } public bool SkipVerification { get; set; } public bool UnmanagedCode { get; set; } public SecurityPermissionAttribute(SecurityAction action) : base((SecurityAction)0) { } public override IPermission? CreatePermission() { return null; } } [Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId = "SYSLIB0003", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] [Flags] public enum SecurityPermissionFlag { AllFlags = 0x3FFF, Assertion = 1, BindingRedirects = 0x2000, ControlAppDomain = 0x400, ControlDomainPolicy = 0x100, ControlEvidence = 0x20, ControlPolicy = 0x40, ControlPrincipal = 0x200, ControlThread = 0x10, Execution = 8, Infrastructure = 0x1000, NoFlags = 0, RemotingConfiguration = 0x800, SerializationFormatter = 0x80, SkipVerification = 4, UnmanagedCode = 2 } } namespace System.Security.Cryptography { [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class CryptographicException : SystemException { public CryptographicException() : base(SR.Arg_CryptographyException) { } public CryptographicException(int hr) : base(SR.Arg_CryptographyException) { base.HResult = hr; } public CryptographicException(string? message) : base(message) { } public CryptographicException(string? message, Exception? inner) : base(message, inner) { } public CryptographicException(string format, string? insert) : base(string.Format(format, insert)) { } protected CryptographicException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } namespace System.Runtime { public struct DependentHandle : IDisposable { private IntPtr _handle; public bool IsAllocated => _handle != (IntPtr)0; public object? Target { get { IntPtr handle = _handle; if (handle == (IntPtr)0) { ThrowHelper.ThrowInvalidOperationException(); } return InternalGetTarget(handle); } set { IntPtr handle = _handle; if (handle == (IntPtr)0 || value != null) { ThrowHelper.ThrowInvalidOperationException(); } InternalSetTargetToNull(handle); } } public object? Dependent { get { IntPtr handle = _handle; if (handle == (IntPtr)0) { ThrowHelper.ThrowInvalidOperationException(); } return InternalGetDependent(handle); } set { IntPtr handle = _handle; if (handle == (IntPtr)0) { ThrowHelper.ThrowInvalidOperationException(); } InternalSetDependent(handle, value); } } public (object? Target, object? Dependent) TargetAndDependent { get { IntPtr handle = _handle; if (handle == (IntPtr)0) { ThrowHelper.ThrowInvalidOperationException(); } object dependent; object item = InternalGetTargetAndDependent(handle, out dependent); return (item, dependent); } } public DependentHandle(object? target, object? dependent) { _handle = InternalInitialize(target, dependent); } internal object UnsafeGetTarget() { return InternalGetTarget(_handle); } internal object UnsafeGetTargetAndDependent(out object dependent) { return InternalGetTargetAndDependent(_handle, out dependent); } internal void UnsafeSetTargetToNull() { InternalSetTargetToNull(_handle); } internal void UnsafeSetDependent(object dependent) { InternalSetDependent(_handle, dependent); } public void Dispose() { IntPtr handle = _handle; if (handle != (IntPtr)0) { _handle = IntPtr.Zero; InternalFree(handle); } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr InternalInitialize(object target, object dependent); private unsafe static object InternalGetTarget(IntPtr dependentHandle) { return Unsafe.As(ref *(IntPtr*)dependentHandle); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern object InternalGetDependent(IntPtr dependentHandle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern object InternalGetTargetAndDependent(IntPtr dependentHandle, out object dependent); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void InternalSetDependent(IntPtr dependentHandle, object dependent); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void InternalSetTargetToNull(IntPtr dependentHandle); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void InternalFree(IntPtr dependentHandle); } public static class GCSettings { private enum SetLatencyModeStatus { Succeeded, NoGCInProgress } public static extern bool IsServerGC { [MethodImpl(MethodImplOptions.InternalCall)] get; } public static GCLatencyMode LatencyMode { get { return GetGCLatencyMode(); } set { if (value < GCLatencyMode.Batch || value > GCLatencyMode.SustainedLowLatency) { ThrowHelper.ArgumentOutOfRangeException_Enum_Value(); } SetLatencyModeStatus setLatencyModeStatus = SetGCLatencyMode(value); if (setLatencyModeStatus == SetLatencyModeStatus.NoGCInProgress) { throw new InvalidOperationException(SR.InvalidOperation_SetLatencyModeNoGC); } } } public static GCLargeObjectHeapCompactionMode LargeObjectHeapCompactionMode { get { return GetLOHCompactionMode(); } set { if (value < GCLargeObjectHeapCompactionMode.Default || value > GCLargeObjectHeapCompactionMode.CompactOnce) { ThrowHelper.ArgumentOutOfRangeException_Enum_Value(); } SetLOHCompactionMode(value); } } [MethodImpl(MethodImplOptions.InternalCall)] private static extern GCLatencyMode GetGCLatencyMode(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern SetLatencyModeStatus SetGCLatencyMode(GCLatencyMode newLatencyMode); [MethodImpl(MethodImplOptions.InternalCall)] private static extern GCLargeObjectHeapCompactionMode GetLOHCompactionMode(); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void SetLOHCompactionMode(GCLargeObjectHeapCompactionMode newLOHCompactionMode); } public static class JitInfo { [MethodImpl(MethodImplOptions.InternalCall)] public static extern long GetCompiledILBytes(bool currentThread = false); [MethodImpl(MethodImplOptions.InternalCall)] public static extern long GetCompiledMethodCount(bool currentThread = false); [MethodImpl(MethodImplOptions.InternalCall)] private static extern long GetCompilationTimeInTicks(bool currentThread = false); public static TimeSpan GetCompilationTime(bool currentThread = false) { return TimeSpan.FromTicks(GetCompilationTimeInTicks(currentThread)); } } [Serializable] [TypeForwardedFrom("System.Runtime, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public sealed class AmbiguousImplementationException : Exception { public AmbiguousImplementationException() : base(SR.AmbiguousImplementationException_NullMessage) { base.HResult = -2146234262; } public AmbiguousImplementationException(string? message) : base(message) { base.HResult = -2146234262; } public AmbiguousImplementationException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146234262; } private AmbiguousImplementationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public enum GCLargeObjectHeapCompactionMode { Default = 1, CompactOnce } public enum GCLatencyMode { Batch, Interactive, LowLatency, SustainedLowLatency, NoGCRegion } public sealed class MemoryFailPoint : CriticalFinalizerObject, IDisposable { private static readonly ulong s_topOfMemory = GetTopOfMemory(); private static long s_hiddenLastKnownFreeAddressSpace; private static long s_hiddenLastTimeCheckingAddressSpace; private static readonly ulong s_GCSegmentSize = GC.GetSegmentSize(); private static long s_failPointReservedMemory; private readonly ulong _reservedMemory; private bool _mustSubtractReservation; private static long LastKnownFreeAddressSpace { get { return Volatile.Read(ref s_hiddenLastKnownFreeAddressSpace); } set { Volatile.Write(ref s_hiddenLastKnownFreeAddressSpace, value); } } private static long LastTimeCheckingAddressSpace { get { return Volatile.Read(ref s_hiddenLastTimeCheckingAddressSpace); } set { Volatile.Write(ref s_hiddenLastTimeCheckingAddressSpace, value); } } internal static ulong MemoryFailPointReservedMemory => (ulong)Volatile.Read(ref s_failPointReservedMemory); private static void AddToLastKnownFreeAddressSpace(long addend) { Interlocked.Add(ref s_hiddenLastKnownFreeAddressSpace, addend); } public MemoryFailPoint(int sizeInMegabytes) { if (sizeInMegabytes <= 0) { throw new ArgumentOutOfRangeException("sizeInMegabytes", SR.ArgumentOutOfRange_NeedNonNegNum); } ulong num = (_reservedMemory = (ulong)((long)sizeInMegabytes << 20)); ulong num2 = (ulong)(Math.Ceiling((double)num / (double)s_GCSegmentSize) * (double)s_GCSegmentSize); if (num2 >= s_topOfMemory) { throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_TooBig); } ulong num3 = (ulong)(Math.Ceiling((double)sizeInMegabytes / 16.0) * 16.0); num3 <<= 20; for (int i = 0; i < 3; i++) { if (!CheckForAvailableMemory(out var availPageFile, out var totalAddressSpaceFree)) { return; } ulong memoryFailPointReservedMemory = MemoryFailPointReservedMemory; ulong num4 = num2 + memoryFailPointReservedMemory; bool flag = num4 < num2 || num4 < memoryFailPointReservedMemory; bool flag2 = availPageFile < num3 + memoryFailPointReservedMemory + 16777216 || flag; bool flag3 = totalAddressSpaceFree < num4 || flag; long num5 = Environment.TickCount; if (num5 > LastTimeCheckingAddressSpace + 10000 || num5 < LastTimeCheckingAddressSpace || LastKnownFreeAddressSpace < (long)num2) { CheckForFreeAddressSpace(num2, shouldThrow: false); } bool flag4 = (ulong)LastKnownFreeAddressSpace < num2; if (!flag2 && !flag3 && !flag4) { break; } switch (i) { case 0: GC.Collect(); break; case 1: if (flag2) { UIntPtr numBytes = new UIntPtr(num2); GrowPageFileIfNecessaryAndPossible(numBytes); } break; case 2: if (flag2 || flag3) { InsufficientMemoryException ex = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint); throw ex; } if (flag4) { InsufficientMemoryException ex2 = new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag); throw ex2; } break; } } AddToLastKnownFreeAddressSpace((long)(0L - num)); if (LastKnownFreeAddressSpace < 0) { CheckForFreeAddressSpace(num2, shouldThrow: true); } AddMemoryFailPointReservation((long)num); _mustSubtractReservation = true; } ~MemoryFailPoint() { Dispose(disposing: false); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (_mustSubtractReservation) { AddMemoryFailPointReservation((long)(0L - _reservedMemory)); _mustSubtractReservation = false; } } internal static long AddMemoryFailPointReservation(long size) { return Interlocked.Add(ref s_failPointReservedMemory, size); } private static ulong GetTopOfMemory() { Interop.Kernel32.GetSystemInfo(out var lpSystemInfo); return (ulong)(long)lpSystemInfo.lpMaximumApplicationAddress; } private unsafe static bool CheckForAvailableMemory(out ulong availPageFile, out ulong totalAddressSpaceFree) { Interop.Kernel32.MEMORYSTATUSEX mEMORYSTATUSEX = default(Interop.Kernel32.MEMORYSTATUSEX); mEMORYSTATUSEX.dwLength = (uint)sizeof(Interop.Kernel32.MEMORYSTATUSEX); if (Interop.Kernel32.GlobalMemoryStatusEx(&mEMORYSTATUSEX) == Interop.BOOL.FALSE) { availPageFile = 0uL; totalAddressSpaceFree = 0uL; return false; } availPageFile = mEMORYSTATUSEX.ullAvailPageFile; totalAddressSpaceFree = mEMORYSTATUSEX.ullAvailVirtual; return true; } private unsafe static void CheckForFreeAddressSpace(ulong size, bool shouldThrow) { ulong num2 = (ulong)(LastKnownFreeAddressSpace = (long)MemFreeAfterAddress(null, size)); LastTimeCheckingAddressSpace = Environment.TickCount; if (num2 < size && shouldThrow) { throw new InsufficientMemoryException(SR.InsufficientMemory_MemFailPoint_VAFrag); } } private unsafe static ulong MemFreeAfterAddress(void* address, ulong size) { if (size >= s_topOfMemory) { return 0uL; } ulong num = 0uL; Interop.Kernel32.MEMORY_BASIC_INFORMATION lpBuffer = default(Interop.Kernel32.MEMORY_BASIC_INFORMATION); UIntPtr dwLength = (UIntPtr)(ulong)sizeof(Interop.Kernel32.MEMORY_BASIC_INFORMATION); while ((ulong)((long)address + (long)size) < s_topOfMemory) { UIntPtr uIntPtr = Interop.Kernel32.VirtualQuery(address, ref lpBuffer, dwLength); if (uIntPtr == UIntPtr.Zero) { throw Win32Marshal.GetExceptionForLastWin32Error(); } ulong num2 = lpBuffer.RegionSize.ToUInt64(); if (lpBuffer.State == 65536) { if (num2 >= size) { return num2; } num = Math.Max(num, num2); } address = (void*)((ulong)address + num2); } return num; } private unsafe static void GrowPageFileIfNecessaryAndPossible(UIntPtr numBytes) { void* ptr = Interop.Kernel32.VirtualAlloc(null, numBytes, 4096, 4); if (ptr != null && !Interop.Kernel32.VirtualFree(ptr, UIntPtr.Zero, 32768)) { throw Win32Marshal.GetExceptionForLastWin32Error(); } } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyTargetedPatchBandAttribute : Attribute { public string TargetedPatchBand { get; } public AssemblyTargetedPatchBandAttribute(string targetedPatchBand) { TargetedPatchBand = targetedPatchBand; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class TargetedPatchingOptOutAttribute : Attribute { public string Reason { get; } public TargetedPatchingOptOutAttribute(string reason) { Reason = reason; } } public static class ProfileOptimization { public static void SetProfileRoot(string directoryPath) { AssemblyLoadContext.Default.SetProfileOptimizationRoot(directoryPath); } public static void StartProfile(string? profile) { AssemblyLoadContext.Default.StartProfileOptimization(profile); } } } namespace System.Runtime.Serialization { public readonly struct DeserializationToken : IDisposable { private readonly DeserializationTracker _tracker; internal DeserializationToken(DeserializationTracker tracker) { _tracker = tracker; } public void Dispose() { if (_tracker == null || !_tracker.DeserializationInProgress) { return; } lock (_tracker) { if (_tracker.DeserializationInProgress) { _tracker.DeserializationInProgress = false; SerializationInfo.AsyncDeserializationInProgress.Value = false; } } } } internal sealed class DeserializationTracker { internal bool DeserializationInProgress { get; set; } } public interface IDeserializationCallback { void OnDeserialization(object? sender); } [CLSCompliant(false)] public interface IFormatterConverter { object Convert(object value, Type type); object Convert(object value, TypeCode typeCode); bool ToBoolean(object value); char ToChar(object value); sbyte ToSByte(object value); byte ToByte(object value); short ToInt16(object value); ushort ToUInt16(object value); int ToInt32(object value); uint ToUInt32(object value); long ToInt64(object value); ulong ToUInt64(object value); float ToSingle(object value); double ToDouble(object value); decimal ToDecimal(object value); DateTime ToDateTime(object value); string? ToString(object value); } public interface IObjectReference { object GetRealObject(StreamingContext context); } public interface ISafeSerializationData { void CompleteDeserialization(object deserialized); } public interface ISerializable { void GetObjectData(SerializationInfo info, StreamingContext context); } [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class OnDeserializedAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class OnDeserializingAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class OnSerializedAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class OnSerializingAttribute : Attribute { } [AttributeUsage(AttributeTargets.Field, Inherited = false)] public sealed class OptionalFieldAttribute : Attribute { private int _versionAdded = 1; public int VersionAdded { get { return _versionAdded; } set { if (value < 1) { throw new ArgumentException(SR.Serialization_OptionalFieldVersionValue); } _versionAdded = value; } } } public sealed class SafeSerializationEventArgs : EventArgs { public StreamingContext StreamingContext { get; } public void AddSerializedState(ISafeSerializationData serializedState) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SerializationException : SystemException { public SerializationException() : base(SR.SerializationException) { base.HResult = -2146233076; } public SerializationException(string? message) : base(message) { base.HResult = -2146233076; } public SerializationException(string? message, Exception? innerException) : base(message, innerException) { base.HResult = -2146233076; } protected SerializationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public sealed class SerializationInfo { private string[] _names; private object[] _values; private Type[] _types; private int _count; private readonly Dictionary _nameToIndex; private readonly IFormatterConverter _converter; private string _rootTypeName; private string _rootTypeAssemblyName; private Type _rootType; [ThreadStatic] private static DeserializationTracker t_deserializationTracker; public string FullTypeName { get { return _rootTypeName; } set { if (value == null) { throw new ArgumentNullException("value"); } _rootTypeName = value; IsFullTypeNameSetExplicit = true; } } public string AssemblyName { get { return _rootTypeAssemblyName; } set { if (value == null) { throw new ArgumentNullException("value"); } _rootTypeAssemblyName = value; IsAssemblyNameSetExplicit = true; } } public bool IsFullTypeNameSetExplicit { get; private set; } public bool IsAssemblyNameSetExplicit { get; private set; } public int MemberCount => _count; public Type ObjectType => _rootType; internal static AsyncLocal AsyncDeserializationInProgress { get; } = new AsyncLocal(); public static bool DeserializationInProgress { get { if (AsyncDeserializationInProgress.Value) { return true; } DeserializationTracker threadDeserializationTracker = GetThreadDeserializationTracker(); return threadDeserializationTracker.DeserializationInProgress; } } [CLSCompliant(false)] public SerializationInfo(Type type, IFormatterConverter converter) { if ((object)type == null) { throw new ArgumentNullException("type"); } if (converter == null) { throw new ArgumentNullException("converter"); } _rootType = type; _rootTypeName = type.FullName; _rootTypeAssemblyName = type.Module.Assembly.FullName; _names = new string[4]; _values = new object[4]; _types = new Type[4]; _nameToIndex = new Dictionary(); _converter = converter; } [CLSCompliant(false)] public SerializationInfo(Type type, IFormatterConverter converter, bool requireSameTokenInPartialTrust) : this(type, converter) { } public void SetType(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } if ((object)_rootType != type) { _rootType = type; _rootTypeName = type.FullName; _rootTypeAssemblyName = type.Module.Assembly.FullName; IsFullTypeNameSetExplicit = false; IsAssemblyNameSetExplicit = false; } } public SerializationInfoEnumerator GetEnumerator() { return new SerializationInfoEnumerator(_names, _values, _types, _count); } private void ExpandArrays() { int num = _count * 2; if (num < _count && int.MaxValue > _count) { num = int.MaxValue; } string[] array = new string[num]; object[] array2 = new object[num]; Type[] array3 = new Type[num]; Array.Copy(_names, array, _count); Array.Copy(_values, array2, _count); Array.Copy(_types, array3, _count); _names = array; _values = array2; _types = array3; } public void AddValue(string name, object? value, Type type) { if (name == null) { throw new ArgumentNullException("name"); } if ((object)type == null) { throw new ArgumentNullException("type"); } AddValueInternal(name, value, type); } public void AddValue(string name, object? value) { if (value == null) { AddValue(name, value, typeof(object)); } else { AddValue(name, value, value.GetType()); } } public void AddValue(string name, bool value) { AddValue(name, value, typeof(bool)); } public void AddValue(string name, char value) { AddValue(name, value, typeof(char)); } [CLSCompliant(false)] public void AddValue(string name, sbyte value) { AddValue(name, value, typeof(sbyte)); } public void AddValue(string name, byte value) { AddValue(name, value, typeof(byte)); } public void AddValue(string name, short value) { AddValue(name, value, typeof(short)); } [CLSCompliant(false)] public void AddValue(string name, ushort value) { AddValue(name, value, typeof(ushort)); } public void AddValue(string name, int value) { AddValue(name, value, typeof(int)); } [CLSCompliant(false)] public void AddValue(string name, uint value) { AddValue(name, value, typeof(uint)); } public void AddValue(string name, long value) { AddValue(name, value, typeof(long)); } [CLSCompliant(false)] public void AddValue(string name, ulong value) { AddValue(name, value, typeof(ulong)); } public void AddValue(string name, float value) { AddValue(name, value, typeof(float)); } public void AddValue(string name, double value) { AddValue(name, value, typeof(double)); } public void AddValue(string name, decimal value) { AddValue(name, value, typeof(decimal)); } public void AddValue(string name, DateTime value) { AddValue(name, value, typeof(DateTime)); } internal void AddValueInternal(string name, object value, Type type) { if (!_nameToIndex.TryAdd(name, _count)) { throw new SerializationException(SR.Serialization_SameNameTwice); } if (_count >= _names.Length) { ExpandArrays(); } _names[_count] = name; _values[_count] = value; _types[_count] = type; _count++; } public void UpdateValue(string name, object value, Type type) { int num = FindElement(name); if (num < 0) { AddValueInternal(name, value, type); return; } _values[num] = value; _types[num] = type; } private int FindElement(string name) { if (name == null) { throw new ArgumentNullException("name"); } if (_nameToIndex.TryGetValue(name, out var value)) { return value; } return -1; } private object GetElement(string name, out Type foundType) { int num = FindElement(name); if (num == -1) { throw new SerializationException(SR.Format(SR.Serialization_NotFound, name)); } foundType = _types[num]; return _values[num]; } private object GetElementNoThrow(string name, out Type foundType) { int num = FindElement(name); if (num == -1) { foundType = null; return null; } foundType = _types[num]; return _values[num]; } public object? GetValue(string name, Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } if (!type.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeType); } Type foundType; object element = GetElement(name, out foundType); if ((object)foundType == type || type.IsAssignableFrom(foundType) || element == null) { return element; } return _converter.Convert(element, type); } internal object GetValueNoThrow(string name, Type type) { Type foundType; object elementNoThrow = GetElementNoThrow(name, out foundType); if (elementNoThrow == null) { return null; } if ((object)foundType == type || type.IsAssignableFrom(foundType)) { return elementNoThrow; } return _converter.Convert(elementNoThrow, type); } public bool GetBoolean(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(bool)) { return _converter.ToBoolean(element); } return (bool)element; } public char GetChar(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(char)) { return _converter.ToChar(element); } return (char)element; } [CLSCompliant(false)] public sbyte GetSByte(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(sbyte)) { return _converter.ToSByte(element); } return (sbyte)element; } public byte GetByte(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(byte)) { return _converter.ToByte(element); } return (byte)element; } public short GetInt16(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(short)) { return _converter.ToInt16(element); } return (short)element; } [CLSCompliant(false)] public ushort GetUInt16(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(ushort)) { return _converter.ToUInt16(element); } return (ushort)element; } public int GetInt32(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(int)) { return _converter.ToInt32(element); } return (int)element; } [CLSCompliant(false)] public uint GetUInt32(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(uint)) { return _converter.ToUInt32(element); } return (uint)element; } public long GetInt64(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(long)) { return _converter.ToInt64(element); } return (long)element; } [CLSCompliant(false)] public ulong GetUInt64(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(ulong)) { return _converter.ToUInt64(element); } return (ulong)element; } public float GetSingle(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(float)) { return _converter.ToSingle(element); } return (float)element; } public double GetDouble(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(double)) { return _converter.ToDouble(element); } return (double)element; } public decimal GetDecimal(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(decimal)) { return _converter.ToDecimal(element); } return (decimal)element; } public DateTime GetDateTime(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(DateTime)) { return _converter.ToDateTime(element); } return (DateTime)element; } public string? GetString(string name) { Type foundType; object element = GetElement(name, out foundType); if ((object)foundType != typeof(string) && element != null) { return _converter.ToString(element); } return (string)element; } private static DeserializationTracker GetThreadDeserializationTracker() { return t_deserializationTracker ?? (t_deserializationTracker = new DeserializationTracker()); } public static void ThrowIfDeserializationInProgress() { if (DeserializationInProgress) { throw new SerializationException(SR.Serialization_DangerousDeserialization); } } public static void ThrowIfDeserializationInProgress(string switchSuffix, ref int cachedValue) { if (cachedValue == 0) { if (AppContext.TryGetSwitch("Switch.System.Runtime.Serialization.SerializationGuard." + switchSuffix, out var isEnabled) && isEnabled) { cachedValue = 1; } else { cachedValue = -1; } } if (cachedValue != 1) { if (cachedValue != -1) { throw new ArgumentOutOfRangeException("cachedValue"); } if (DeserializationInProgress) { throw new SerializationException(SR.Format(SR.Serialization_DangerousDeserialization_Switch, "Switch.System.Runtime.Serialization.SerializationGuard." + switchSuffix)); } } } public static DeserializationToken StartDeserialization() { if (LocalAppContextSwitches.SerializationGuard) { DeserializationTracker threadDeserializationTracker = GetThreadDeserializationTracker(); if (!threadDeserializationTracker.DeserializationInProgress) { lock (threadDeserializationTracker) { if (!threadDeserializationTracker.DeserializationInProgress) { AsyncDeserializationInProgress.Value = true; threadDeserializationTracker.DeserializationInProgress = true; return new DeserializationToken(threadDeserializationTracker); } } } } return new DeserializationToken(null); } } public readonly struct SerializationEntry { private readonly string _name; private readonly object _value; private readonly Type _type; public object? Value => _value; public string Name => _name; public Type ObjectType => _type; internal SerializationEntry(string entryName, object entryValue, Type entryType) { _name = entryName; _value = entryValue; _type = entryType; } } public sealed class SerializationInfoEnumerator : System.Collections.IEnumerator { private readonly string[] _members; private readonly object[] _data; private readonly Type[] _types; private readonly int _numItems; private int _currItem; private bool _current; object? System.Collections.IEnumerator.Current => Current; public SerializationEntry Current { get { if (!_current) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return new SerializationEntry(_members[_currItem], _data[_currItem], _types[_currItem]); } } public string Name { get { if (!_current) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _members[_currItem]; } } public object? Value { get { if (!_current) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _data[_currItem]; } } public Type ObjectType { get { if (!_current) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _types[_currItem]; } } internal SerializationInfoEnumerator(string[] members, object[] info, Type[] types, int numItems) { _members = members; _data = info; _types = types; _numItems = numItems - 1; _currItem = -1; } public bool MoveNext() { if (_currItem < _numItems) { _currItem++; _current = true; } else { _current = false; } return _current; } public void Reset() { _currItem = -1; _current = false; } } public readonly struct StreamingContext { private readonly object _additionalContext; private readonly StreamingContextStates _state; public StreamingContextStates State => _state; public object? Context => _additionalContext; public StreamingContext(StreamingContextStates state) : this(state, null) { } public StreamingContext(StreamingContextStates state, object? additional) { _state = state; _additionalContext = additional; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is StreamingContext streamingContext)) { return false; } if (streamingContext._additionalContext == _additionalContext) { return streamingContext._state == _state; } return false; } public override int GetHashCode() { return (int)_state; } } [Flags] public enum StreamingContextStates { CrossProcess = 1, CrossMachine = 2, File = 4, Persistence = 8, Remoting = 0x10, Other = 0x20, Clone = 0x40, CrossAppDomain = 0x80, All = 0xFF } } namespace System.Runtime.Remoting { public class ObjectHandle : MarshalByRefObject { private readonly object _wrappedObject; public ObjectHandle(object? o) { _wrappedObject = o; } public object? Unwrap() { return _wrappedObject; } } } namespace System.Runtime.ExceptionServices { public sealed class ExceptionDispatchInfo { private readonly Exception _exception; private readonly Exception.DispatchState _dispatchState; public Exception SourceException => _exception; private ExceptionDispatchInfo(Exception exception) { _exception = exception; _dispatchState = exception.CaptureDispatchState(); } public static ExceptionDispatchInfo Capture(Exception source) { if (source == null) { throw new ArgumentNullException("source"); } return new ExceptionDispatchInfo(source); } [DoesNotReturn] [StackTraceHidden] public void Throw() { _exception.RestoreDispatchState(in _dispatchState); throw _exception; } [DoesNotReturn] [StackTraceHidden] public static void Throw(Exception source) { Capture(source).Throw(); } [StackTraceHidden] public static Exception SetCurrentStackTrace(Exception source) { if (source == null) { throw new ArgumentNullException("source"); } source.SetCurrentStackTrace(); return source; } public static Exception SetRemoteStackTrace(Exception source, string stackTrace) { if (source == null) { throw new ArgumentNullException("source"); } if (stackTrace == null) { throw new ArgumentNullException("stackTrace"); } source.SetRemoteStackTrace(stackTrace); return source; } } public class FirstChanceExceptionEventArgs : EventArgs { public Exception Exception { get; } public FirstChanceExceptionEventArgs(Exception exception) { Exception = exception; } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] [Obsolete("Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored.", DiagnosticId = "SYSLIB0032", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public sealed class HandleProcessCorruptedStateExceptionsAttribute : Attribute { } } namespace System.Runtime.ConstrainedExecution { [Obsolete("The Constrained Execution Region (CER) feature is not supported.", DiagnosticId = "SYSLIB0004", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public enum Cer { None, MayFail, Success } [Obsolete("The Constrained Execution Region (CER) feature is not supported.", DiagnosticId = "SYSLIB0004", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public enum Consistency { MayCorruptProcess, MayCorruptAppDomain, MayCorruptInstance, WillNotCorruptState } public abstract class CriticalFinalizerObject { ~CriticalFinalizerObject() { } } [Obsolete("The Constrained Execution Region (CER) feature is not supported.", DiagnosticId = "SYSLIB0004", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] public sealed class PrePrepareMethodAttribute : Attribute { } [Obsolete("The Constrained Execution Region (CER) feature is not supported.", DiagnosticId = "SYSLIB0004", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Interface, Inherited = false)] public sealed class ReliabilityContractAttribute : Attribute { public Consistency ConsistencyGuarantee { get; } public Cer Cer { get; } public ReliabilityContractAttribute(Consistency consistencyGuarantee, Cer cer) { ConsistencyGuarantee = consistencyGuarantee; Cer = cer; } } } namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class ComponentGuaranteesAttribute : Attribute { public ComponentGuaranteesOptions Guarantees { get; } public ComponentGuaranteesAttribute(ComponentGuaranteesOptions guarantees) { Guarantees = guarantees; } } [Flags] public enum ComponentGuaranteesOptions { None = 0, Exchange = 1, Stable = 2, SideBySide = 4 } public sealed class FrameworkName : IEquatable { private readonly string _identifier; private readonly Version _version; private readonly string _profile; private string _fullName; public string Identifier => _identifier; public Version Version => _version; public string Profile => _profile; public string FullName { get { if (_fullName == null) { _fullName = (string.IsNullOrEmpty(Profile) ? $"{Identifier}{",Version=v"}{Version}" : $"{Identifier}{",Version=v"}{Version}{",Profile="}{Profile}"); } return _fullName; } } public override bool Equals([NotNullWhen(true)] object? obj) { return Equals(obj as FrameworkName); } public bool Equals([NotNullWhen(true)] FrameworkName? other) { if ((object)other == null) { return false; } if (Identifier == other.Identifier && Version == other.Version) { return Profile == other.Profile; } return false; } public override int GetHashCode() { return Identifier.GetHashCode() ^ Version.GetHashCode() ^ Profile.GetHashCode(); } public override string ToString() { return FullName; } public FrameworkName(string identifier, Version version) : this(identifier, version, null) { } public FrameworkName(string identifier, Version version, string? profile) { if (identifier == null) { throw new ArgumentNullException("identifier"); } identifier = identifier.Trim(); if (identifier.Length == 0) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, "identifier"), "identifier"); } if (version == null) { throw new ArgumentNullException("version"); } _identifier = identifier; _version = version; _profile = ((profile == null) ? string.Empty : profile.Trim()); } public FrameworkName(string frameworkName) { if (frameworkName == null) { throw new ArgumentNullException("frameworkName"); } if (frameworkName.Length == 0) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, "frameworkName"), "frameworkName"); } string[] array = frameworkName.Split(','); if (array.Length < 2 || array.Length > 3) { throw new ArgumentException(SR.Argument_FrameworkNameTooShort, "frameworkName"); } _identifier = array[0].Trim(); if (_identifier.Length == 0) { throw new ArgumentException(SR.Argument_FrameworkNameInvalid, "frameworkName"); } bool flag = false; _profile = string.Empty; for (int i = 1; i < array.Length; i++) { string text = array[i]; int num = text.IndexOf('='); if (num == -1 || num != text.LastIndexOf('=')) { throw new ArgumentException(SR.Argument_FrameworkNameInvalid, "frameworkName"); } ReadOnlySpan span = text.AsSpan(0, num).Trim(); ReadOnlySpan input = text.AsSpan(num + 1).Trim(); if (MemoryExtensions.Equals(span, "Version", StringComparison.OrdinalIgnoreCase)) { flag = true; if (input.Length > 0 && (input[0] == 'v' || input[0] == 'V')) { input = input.Slice(1); } try { _version = System.Version.Parse(input); } catch (Exception innerException) { throw new ArgumentException(SR.Argument_FrameworkNameInvalidVersion, "frameworkName", innerException); } } else { if (!MemoryExtensions.Equals(span, "Profile", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException(SR.Argument_FrameworkNameInvalid, "frameworkName"); } if (input.Length > 0) { _profile = input.ToString(); } } } if (!flag) { throw new ArgumentException(SR.Argument_FrameworkNameMissingVersion, "frameworkName"); } } public static bool operator ==(FrameworkName? left, FrameworkName? right) { return left?.Equals(right) ?? ((object)right == null); } public static bool operator !=(FrameworkName? left, FrameworkName? right) { return !(left == right); } } public abstract class OSPlatformAttribute : Attribute { public string PlatformName { get; } private protected OSPlatformAttribute(string platformName) { PlatformName = platformName; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] public sealed class TargetPlatformAttribute : OSPlatformAttribute { public TargetPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] public sealed class SupportedOSPlatformAttribute : OSPlatformAttribute { public SupportedOSPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] public sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute { public UnsupportedOSPlatformAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] public sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute { public SupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)] public sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute { public UnsupportedOSPlatformGuardAttribute(string platformName) : base(platformName) { } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] public sealed class RequiresPreviewFeaturesAttribute : Attribute { public string? Message { get; } public string? Url { get; set; } public RequiresPreviewFeaturesAttribute() { } public RequiresPreviewFeaturesAttribute(string? message) { Message = message; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property, Inherited = false)] [Conditional("RESOURCE_ANNOTATION_WORK")] public sealed class ResourceConsumptionAttribute : Attribute { public ResourceScope ResourceScope { get; } public ResourceScope ConsumptionScope { get; } public ResourceConsumptionAttribute(ResourceScope resourceScope) { ResourceScope = resourceScope; ConsumptionScope = resourceScope; } public ResourceConsumptionAttribute(ResourceScope resourceScope, ResourceScope consumptionScope) { ResourceScope = resourceScope; ConsumptionScope = consumptionScope; } } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, Inherited = false)] [Conditional("RESOURCE_ANNOTATION_WORK")] public sealed class ResourceExposureAttribute : Attribute { public ResourceScope ResourceExposureLevel { get; } public ResourceExposureAttribute(ResourceScope exposureLevel) { ResourceExposureLevel = exposureLevel; } } [Flags] public enum ResourceScope { None = 0, Machine = 1, Process = 2, AppDomain = 4, Library = 8, Private = 0x10, Assembly = 0x20 } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] public sealed class TargetFrameworkAttribute : Attribute { private readonly string _frameworkName; private string _frameworkDisplayName; public string FrameworkName => _frameworkName; public string? FrameworkDisplayName { get { return _frameworkDisplayName; } set { _frameworkDisplayName = value; } } public TargetFrameworkAttribute(string frameworkName) { if (frameworkName == null) { throw new ArgumentNullException("frameworkName"); } _frameworkName = frameworkName; } } [Flags] internal enum SxSRequirements { None = 0, AppDomainID = 1, ProcessID = 2, CLRInstanceID = 4, AssemblyName = 8, TypeName = 0x10 } public static class VersioningHelper { public static string MakeVersionSafeName(string? name, ResourceScope from, ResourceScope to) { return MakeVersionSafeName(name, from, to, null); } public static string MakeVersionSafeName(string? name, ResourceScope from, ResourceScope to, Type? type) { ResourceScope resourceScope = from & (ResourceScope.Machine | ResourceScope.Process | ResourceScope.AppDomain | ResourceScope.Library); ResourceScope resourceScope2 = to & (ResourceScope.Machine | ResourceScope.Process | ResourceScope.AppDomain | ResourceScope.Library); if (resourceScope > resourceScope2) { throw new ArgumentException(SR.Format(SR.Argument_ResourceScopeWrongDirection, resourceScope, resourceScope2), "from"); } SxSRequirements requirements = GetRequirements(to, from); if ((requirements & (SxSRequirements.AssemblyName | SxSRequirements.TypeName)) != 0 && type == null) { throw new ArgumentNullException("type", SR.ArgumentNull_TypeRequiredByResourceScope); } StringBuilder stringBuilder = new StringBuilder(name); char value = '_'; if ((requirements & SxSRequirements.ProcessID) != 0) { stringBuilder.Append(value); stringBuilder.Append('p'); stringBuilder.Append(Environment.ProcessId); } if ((requirements & SxSRequirements.CLRInstanceID) != 0) { string cLRInstanceString = GetCLRInstanceString(); stringBuilder.Append(value); stringBuilder.Append('r'); stringBuilder.Append(cLRInstanceString); } if ((requirements & SxSRequirements.AppDomainID) != 0) { stringBuilder.Append(value); stringBuilder.Append("ad"); stringBuilder.Append(AppDomain.CurrentDomain.Id); } if ((requirements & SxSRequirements.TypeName) != 0) { stringBuilder.Append(value); stringBuilder.Append(type.Name); } if ((requirements & SxSRequirements.AssemblyName) != 0) { stringBuilder.Append(value); stringBuilder.Append(type.Assembly.FullName); } return stringBuilder.ToString(); } private static string GetCLRInstanceString() { return "3"; } private static SxSRequirements GetRequirements(ResourceScope consumeAsScope, ResourceScope calleeScope) { SxSRequirements sxSRequirements = SxSRequirements.None; switch (calleeScope & (ResourceScope.Machine | ResourceScope.Process | ResourceScope.AppDomain | ResourceScope.Library)) { case ResourceScope.Machine: switch (consumeAsScope & (ResourceScope.Machine | ResourceScope.Process | ResourceScope.AppDomain | ResourceScope.Library)) { case ResourceScope.Process: sxSRequirements |= SxSRequirements.ProcessID; break; case ResourceScope.AppDomain: sxSRequirements |= SxSRequirements.AppDomainID | SxSRequirements.ProcessID | SxSRequirements.CLRInstanceID; break; default: throw new ArgumentException(SR.Format(SR.Argument_BadResourceScopeTypeBits, consumeAsScope), "consumeAsScope"); case ResourceScope.Machine: break; } break; case ResourceScope.Process: if ((consumeAsScope & ResourceScope.AppDomain) != 0) { sxSRequirements |= SxSRequirements.AppDomainID | SxSRequirements.CLRInstanceID; } break; default: throw new ArgumentException(SR.Format(SR.Argument_BadResourceScopeTypeBits, calleeScope), "calleeScope"); case ResourceScope.AppDomain: break; } switch (calleeScope & (ResourceScope.Private | ResourceScope.Assembly)) { case ResourceScope.None: switch (consumeAsScope & (ResourceScope.Private | ResourceScope.Assembly)) { case ResourceScope.Assembly: sxSRequirements |= SxSRequirements.AssemblyName; break; case ResourceScope.Private: sxSRequirements |= SxSRequirements.AssemblyName | SxSRequirements.TypeName; break; default: throw new ArgumentException(SR.Format(SR.Argument_BadResourceScopeVisibilityBits, consumeAsScope), "consumeAsScope"); case ResourceScope.None: break; } break; case ResourceScope.Assembly: if ((consumeAsScope & ResourceScope.Private) != 0) { sxSRequirements |= SxSRequirements.TypeName; } break; default: throw new ArgumentException(SR.Format(SR.Argument_BadResourceScopeVisibilityBits, calleeScope), "calleeScope"); case ResourceScope.Private: break; } return sxSRequirements; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)] internal sealed class NonVersionableAttribute : Attribute { } } namespace System.Runtime.Loader { public class AssemblyLoadContext { private enum InternalState { Alive, Unloading } [EditorBrowsable(EditorBrowsableState.Never)] public struct ContextualReflectionScope : IDisposable { private readonly AssemblyLoadContext _activated; private readonly AssemblyLoadContext _predecessor; private readonly bool _initialized; internal ContextualReflectionScope(AssemblyLoadContext activating) { _predecessor = CurrentContextualReflectionContext; SetCurrentContextualReflectionContext(activating); _activated = activating; _initialized = true; } public void Dispose() { if (_initialized) { SetCurrentContextualReflectionContext(_predecessor); } } } private const string AssemblyLoadName = "AssemblyLoad"; private static volatile Dictionary> s_allContexts; private static long s_nextId; private readonly IntPtr _nativeAssemblyLoadContext; private readonly object _unloadLock; private readonly string _name; private readonly long _id; private InternalState _state; private readonly bool _isCollectible; private static AsyncLocal s_asyncLocalCurrent; [MemberNotNull("s_allContexts")] private static Dictionary> AllContexts { [MemberNotNull("s_allContexts")] get { return s_allContexts ?? Interlocked.CompareExchange(ref s_allContexts, new Dictionary>(), null) ?? s_allContexts; } } public IEnumerable Assemblies { get { Assembly[] loadedAssemblies = GetLoadedAssemblies(); foreach (Assembly assembly in loadedAssemblies) { AssemblyLoadContext loadContext = GetLoadContext(assembly); if (loadContext == this) { yield return assembly; } } } } public static AssemblyLoadContext Default => DefaultAssemblyLoadContext.s_loadContext; public bool IsCollectible => _isCollectible; public string? Name => _name; public static IEnumerable All { get { _ = Default; Dictionary> dictionary = s_allContexts; WeakReference[] array; lock (dictionary) { array = new WeakReference[dictionary.Count]; int num = 0; foreach (KeyValuePair> item in dictionary) { array[num++] = item.Value; } } WeakReference[] array2 = array; foreach (WeakReference weakReference in array2) { if (weakReference.TryGetTarget(out var target)) { yield return target; } } } } public static AssemblyLoadContext? CurrentContextualReflectionContext => s_asyncLocalCurrent?.Value; private event Func? _resolvingUnmanagedDll; private event Func? _resolving; private event Action? _unloading; public event Func? ResolvingUnmanagedDll { add { _resolvingUnmanagedDll += value; } remove { _resolvingUnmanagedDll -= value; } } public event Func? Resolving { add { _resolving += value; } remove { _resolving -= value; } } public event Action? Unloading { add { _unloading += value; } remove { _unloading -= value; } } internal static event AssemblyLoadEventHandler? AssemblyLoad; internal static event ResolveEventHandler? TypeResolve; internal static event ResolveEventHandler? ResourceResolve; internal static event ResolveEventHandler? AssemblyResolve; [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext, bool fRepresentsTPALoadContext, bool isCollectible); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void PrepareForAssemblyLoadContextRelease(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyLoadContextStrong); [DllImport("QCall", CharSet = CharSet.Unicode)] [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] private static extern void LoadFromStream(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyArray, int iAssemblyArrayLen, IntPtr ptrSymbols, int iSymbolArrayLen, ObjectHandleOnStack retAssembly); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern void InternalSetProfileRoot(string directoryPath); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext); [DllImport("QCall", CharSet = CharSet.Unicode)] [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string ilPath, string niPath, ObjectHandleOnStack retAssembly); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Assembly[] GetLoadedAssemblies(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsTracingEnabled(); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern bool TraceResolvingHandlerInvoked(string assemblyName, string handlerName, string alcName, string resultAssemblyName, string resultAssemblyPath); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern bool TraceAssemblyResolveHandlerInvoked(string assemblyName, string handlerName, string resultAssemblyName, string resultAssemblyPath); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern bool TraceAssemblyLoadFromResolveHandlerInvoked(string assemblyName, bool isTrackedAssembly, string requestingAssemblyPath, string requestedAssemblyPath); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern bool TraceSatelliteSubdirectoryPathProbed(string filePath, int hResult); [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] private Assembly InternalLoadFromPath(string assemblyPath, string nativeImagePath) { RuntimeAssembly o = null; LoadFromPath(_nativeAssemblyLoadContext, assemblyPath, nativeImagePath, ObjectHandleOnStack.Create(ref o)); return o; } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] internal unsafe Assembly InternalLoad(ReadOnlySpan arrAssembly, ReadOnlySpan arrSymbols) { RuntimeAssembly o = null; fixed (byte* value = arrAssembly) { fixed (byte* value2 = arrSymbols) { LoadFromStream(_nativeAssemblyLoadContext, new IntPtr(value), arrAssembly.Length, new IntPtr(value2), arrSymbols.Length, ObjectHandleOnStack.Create(ref o)); } } return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern IntPtr LoadFromInMemoryModuleInternal(IntPtr ptrNativeAssemblyLoadContext, IntPtr hModule, ObjectHandleOnStack retAssembly); internal Assembly LoadFromInMemoryModule(IntPtr moduleHandle) { if (moduleHandle == IntPtr.Zero) { throw new ArgumentNullException("moduleHandle"); } lock (_unloadLock) { VerifyIsAlive(); RuntimeAssembly o = null; LoadFromInMemoryModuleInternal(_nativeAssemblyLoadContext, moduleHandle, ObjectHandleOnStack.Create(ref o)); return o; } } private static Assembly ResolveSatelliteAssembly(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) { AssemblyLoadContext assemblyLoadContext = (AssemblyLoadContext)GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target; return assemblyLoadContext.ResolveSatelliteAssembly(assemblyName); } private static IntPtr ResolveUnmanagedDll(string unmanagedDllName, IntPtr gchManagedAssemblyLoadContext) { AssemblyLoadContext assemblyLoadContext = (AssemblyLoadContext)GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target; return assemblyLoadContext.LoadUnmanagedDll(unmanagedDllName); } private static IntPtr ResolveUnmanagedDllUsingEvent(string unmanagedDllName, Assembly assembly, IntPtr gchManagedAssemblyLoadContext) { AssemblyLoadContext assemblyLoadContext = (AssemblyLoadContext)GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target; return assemblyLoadContext.GetResolvedUnmanagedDll(assembly, unmanagedDllName); } private static Assembly ResolveUsingResolvingEvent(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) { AssemblyLoadContext assemblyLoadContext = (AssemblyLoadContext)GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target; return assemblyLoadContext.ResolveUsingEvent(assemblyName); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern IntPtr GetLoadContextForAssembly(QCallAssembly assembly); public static AssemblyLoadContext? GetLoadContext(Assembly assembly) { if (assembly == null) { throw new ArgumentNullException("assembly"); } AssemblyLoadContext result = null; RuntimeAssembly runtimeAssembly = GetRuntimeAssembly(assembly); if (runtimeAssembly != null) { RuntimeAssembly assembly2 = runtimeAssembly; IntPtr loadContextForAssembly = GetLoadContextForAssembly(new QCallAssembly(ref assembly2)); result = ((!(loadContextForAssembly == IntPtr.Zero)) ? ((AssemblyLoadContext)GCHandle.FromIntPtr(loadContextForAssembly).Target) : Default); } return result; } public void SetProfileOptimizationRoot(string directoryPath) { InternalSetProfileRoot(directoryPath); } public void StartProfileOptimization(string? profile) { InternalStartProfile(profile, _nativeAssemblyLoadContext); } private static RuntimeAssembly GetRuntimeAssembly(Assembly asm) { if (!(asm == null)) { if (!(asm is RuntimeAssembly result)) { if (!(asm is AssemblyBuilder assemblyBuilder)) { return null; } return assemblyBuilder.InternalAssembly; } return result; } return null; } private static void StartAssemblyLoad(ref Guid activityId, ref Guid relatedActivityId) { ActivityTracker.Instance.Enable(); ActivityTracker.Instance.OnStart(NativeRuntimeEventSource.Log.Name, "AssemblyLoad", 0, ref activityId, ref relatedActivityId, EventActivityOptions.Recursive, useTplSource: false); } private static void StopAssemblyLoad(ref Guid activityId) { ActivityTracker.Instance.OnStop(NativeRuntimeEventSource.Log.Name, "AssemblyLoad", 0, ref activityId, useTplSource: false); } private static void InitializeDefaultContext() { _ = Default; } protected AssemblyLoadContext() : this(representsTPALoadContext: false, isCollectible: false, null) { } protected AssemblyLoadContext(bool isCollectible) : this(representsTPALoadContext: false, isCollectible, null) { } public AssemblyLoadContext(string? name, bool isCollectible = false) : this(representsTPALoadContext: false, isCollectible, name) { } private protected AssemblyLoadContext(bool representsTPALoadContext, bool isCollectible, string name) { _isCollectible = isCollectible; _name = name; _unloadLock = new object(); if (!isCollectible) { GC.SuppressFinalize(this); } _nativeAssemblyLoadContext = InitializeAssemblyLoadContext(GCHandle.ToIntPtr(GCHandle.Alloc(this, IsCollectible ? GCHandleType.WeakTrackResurrection : GCHandleType.Normal)), representsTPALoadContext, isCollectible); Dictionary> allContexts = AllContexts; lock (allContexts) { _id = s_nextId++; allContexts.Add(_id, new WeakReference(this, trackResurrection: true)); } } ~AssemblyLoadContext() { if (_unloadLock != null) { InitiateUnload(); } } private void RaiseUnloadEvent() { Interlocked.Exchange(ref this._unloading, null)?.Invoke(this); } private void InitiateUnload() { RaiseUnloadEvent(); lock (_unloadLock) { GCHandle value = GCHandle.Alloc(this, GCHandleType.Normal); IntPtr ptrAssemblyLoadContextStrong = GCHandle.ToIntPtr(value); PrepareForAssemblyLoadContextRelease(_nativeAssemblyLoadContext, ptrAssemblyLoadContextStrong); _state = InternalState.Unloading; } Dictionary> allContexts = AllContexts; lock (allContexts) { allContexts.Remove(_id); } } public override string ToString() { return $"\"{Name}\" {GetType()} #{_id}"; } public static AssemblyName GetAssemblyName(string assemblyPath) { if (assemblyPath == null) { throw new ArgumentNullException("assemblyPath"); } return AssemblyName.GetAssemblyName(assemblyPath); } protected virtual Assembly? Load(AssemblyName assemblyName) { return null; } public Assembly LoadFromAssemblyName(AssemblyName assemblyName) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeAssembly.InternalLoad(assemblyName, ref stackMark, this); } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public Assembly LoadFromAssemblyPath(string assemblyPath) { if (assemblyPath == null) { throw new ArgumentNullException("assemblyPath"); } if (PathInternal.IsPartiallyQualified(assemblyPath)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, assemblyPath), "assemblyPath"); } lock (_unloadLock) { VerifyIsAlive(); return InternalLoadFromPath(assemblyPath, null); } } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public Assembly LoadFromNativeImagePath(string nativeImagePath, string? assemblyPath) { if (nativeImagePath == null) { throw new ArgumentNullException("nativeImagePath"); } if (PathInternal.IsPartiallyQualified(nativeImagePath)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, nativeImagePath), "nativeImagePath"); } if (assemblyPath != null && PathInternal.IsPartiallyQualified(assemblyPath)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, assemblyPath), "assemblyPath"); } lock (_unloadLock) { VerifyIsAlive(); return InternalLoadFromPath(assemblyPath, nativeImagePath); } } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public Assembly LoadFromStream(Stream assembly) { return LoadFromStream(assembly, null); } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public Assembly LoadFromStream(Stream assembly, Stream? assemblySymbols) { if (assembly == null) { throw new ArgumentNullException("assembly"); } int num = (int)assembly.Length; if (num <= 0) { throw new BadImageFormatException(SR.BadImageFormat_BadILFormat); } byte[] array = new byte[num]; assembly.Read(array, 0, num); byte[] array2 = null; if (assemblySymbols != null) { int num2 = (int)assemblySymbols.Length; array2 = new byte[num2]; assemblySymbols.Read(array2, 0, num2); } lock (_unloadLock) { VerifyIsAlive(); return InternalLoad(array, array2); } } protected IntPtr LoadUnmanagedDllFromPath(string unmanagedDllPath) { if (unmanagedDllPath == null) { throw new ArgumentNullException("unmanagedDllPath"); } if (unmanagedDllPath.Length == 0) { throw new ArgumentException(SR.Argument_EmptyPath, "unmanagedDllPath"); } if (PathInternal.IsPartiallyQualified(unmanagedDllPath)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, unmanagedDllPath), "unmanagedDllPath"); } return NativeLibrary.Load(unmanagedDllPath); } protected virtual IntPtr LoadUnmanagedDll(string unmanagedDllName) { return IntPtr.Zero; } public void Unload() { if (!IsCollectible) { throw new InvalidOperationException(SR.AssemblyLoadContext_Unload_CannotUnloadIfNotCollectible); } GC.SuppressFinalize(this); InitiateUnload(); } internal static void OnProcessExit() { Dictionary> dictionary = s_allContexts; if (dictionary == null) { return; } lock (dictionary) { foreach (KeyValuePair> item in dictionary) { if (item.Value.TryGetTarget(out var target)) { target.RaiseUnloadEvent(); } } } } private void VerifyIsAlive() { if (_state != 0) { throw new InvalidOperationException(SR.AssemblyLoadContext_Verify_NotUnloading); } } private static void SetCurrentContextualReflectionContext(AssemblyLoadContext value) { if (s_asyncLocalCurrent == null) { Interlocked.CompareExchange(ref s_asyncLocalCurrent, new AsyncLocal(), null); } s_asyncLocalCurrent.Value = value; } public ContextualReflectionScope EnterContextualReflection() { return new ContextualReflectionScope(this); } public static ContextualReflectionScope EnterContextualReflection(Assembly? activating) { if (activating == null) { return new ContextualReflectionScope(null); } AssemblyLoadContext loadContext = GetLoadContext(activating); if (loadContext == null) { throw new ArgumentException(SR.Arg_MustBeRuntimeAssembly, "activating"); } return loadContext.EnterContextualReflection(); } private static Assembly Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName) { AssemblyLoadContext assemblyLoadContext = (AssemblyLoadContext)GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target; return assemblyLoadContext.ResolveUsingLoad(assemblyName); } [UnconditionalSuppressMessage("SingleFile", "IL3000: Avoid accessing Assembly file path when publishing as a single file", Justification = "The code handles the Assembly.Location equals null")] private Assembly GetFirstResolvedAssemblyFromResolvingEvent(AssemblyName assemblyName) { Assembly assembly = null; Func resolving = this._resolving; if (resolving != null) { Delegate[] invocationList = resolving.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { Func func = (Func)invocationList[i]; assembly = func(this, assemblyName); if (IsTracingEnabled()) { TraceResolvingHandlerInvoked(assemblyName.FullName, func.Method.Name, (this != Default) ? ToString() : Name, assembly?.FullName, (assembly != null && !assembly.IsDynamic) ? assembly.Location : null); } if (assembly != null) { return assembly; } } } return null; } private static Assembly ValidateAssemblyNameWithSimpleName(Assembly assembly, string requestedSimpleName) { if (string.IsNullOrEmpty(requestedSimpleName)) { throw new ArgumentException(SR.ArgumentNull_AssemblyNameName); } string value = null; RuntimeAssembly runtimeAssembly = GetRuntimeAssembly(assembly); if (runtimeAssembly != null) { value = runtimeAssembly.GetSimpleName(); } if (string.IsNullOrEmpty(value) || !requestedSimpleName.Equals(value, StringComparison.InvariantCultureIgnoreCase)) { throw new InvalidOperationException(SR.Argument_CustomAssemblyLoadContextRequestedNameMismatch); } return assembly; } private Assembly ResolveUsingLoad(AssemblyName assemblyName) { string name = assemblyName.Name; Assembly assembly = Load(assemblyName); if (assembly != null) { assembly = ValidateAssemblyNameWithSimpleName(assembly, name); } return assembly; } private Assembly ResolveUsingEvent(AssemblyName assemblyName) { string name = assemblyName.Name; Assembly assembly = GetFirstResolvedAssemblyFromResolvingEvent(assemblyName); if (assembly != null) { assembly = ValidateAssemblyNameWithSimpleName(assembly, name); } return assembly; } private static void OnAssemblyLoad(RuntimeAssembly assembly) { AssemblyLoadContext.AssemblyLoad?.Invoke(AppDomain.CurrentDomain, new AssemblyLoadEventArgs(assembly)); } private static RuntimeAssembly OnResourceResolve(RuntimeAssembly assembly, string resourceName) { return InvokeResolveEvent(AssemblyLoadContext.ResourceResolve, assembly, resourceName); } private static RuntimeAssembly OnTypeResolve(RuntimeAssembly assembly, string typeName) { return InvokeResolveEvent(AssemblyLoadContext.TypeResolve, assembly, typeName); } private static RuntimeAssembly OnAssemblyResolve(RuntimeAssembly assembly, string assemblyFullName) { return InvokeResolveEvent(AssemblyLoadContext.AssemblyResolve, assembly, assemblyFullName); } [UnconditionalSuppressMessage("SingleFile", "IL3000: Avoid accessing Assembly file path when publishing as a single file", Justification = "The code handles the Assembly.Location equals null")] private static RuntimeAssembly InvokeResolveEvent(ResolveEventHandler eventHandler, RuntimeAssembly assembly, string name) { if (eventHandler == null) { return null; } ResolveEventArgs args = new ResolveEventArgs(name, assembly); Delegate[] invocationList = eventHandler.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { ResolveEventHandler resolveEventHandler = (ResolveEventHandler)invocationList[i]; Assembly assembly2 = resolveEventHandler(AppDomain.CurrentDomain, args); if (eventHandler == AssemblyLoadContext.AssemblyResolve && IsTracingEnabled()) { TraceAssemblyResolveHandlerInvoked(name, resolveEventHandler.Method.Name, assembly2?.FullName, (assembly2 != null && !assembly2.IsDynamic) ? assembly2.Location : null); } RuntimeAssembly runtimeAssembly = GetRuntimeAssembly(assembly2); if (runtimeAssembly != null) { return runtimeAssembly; } } return null; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Satellite assemblies have no code in them and loading is not a problem")] [UnconditionalSuppressMessage("SingleFile", "IL3000: Avoid accessing Assembly file path when publishing as a single file", Justification = "This call is fine because native call runs before this and checks BindSatelliteResourceFromBundle")] private Assembly ResolveSatelliteAssembly(AssemblyName assemblyName) { if (assemblyName.Name == null || !assemblyName.Name.EndsWith(".resources", StringComparison.Ordinal)) { return null; } string assemblyName2 = assemblyName.Name.Substring(0, assemblyName.Name.Length - ".resources".Length); Assembly assembly = LoadFromAssemblyName(new AssemblyName(assemblyName2)); AssemblyLoadContext loadContext = GetLoadContext(assembly); string directoryName = Path.GetDirectoryName(assembly.Location); if (directoryName == null) { return null; } string text = Path.Combine(directoryName, assemblyName.CultureName, assemblyName.Name + ".dll"); bool flag = FileSystem.FileExists(text); if (flag || PathInternal.IsCaseSensitive) { } Assembly result = (flag ? loadContext.LoadFromAssemblyPath(text) : null); if (IsTracingEnabled()) { TraceSatelliteSubdirectoryPathProbed(text, (!flag) ? (-2147024894) : 0); } return result; } internal IntPtr GetResolvedUnmanagedDll(Assembly assembly, string unmanagedDllName) { IntPtr zero = IntPtr.Zero; Func resolvingUnmanagedDll = this._resolvingUnmanagedDll; if (resolvingUnmanagedDll != null) { Delegate[] invocationList = resolvingUnmanagedDll.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { Func func = (Func)invocationList[i]; zero = func(assembly, unmanagedDllName); if (zero != IntPtr.Zero) { return zero; } } } return IntPtr.Zero; } } internal sealed class DefaultAssemblyLoadContext : AssemblyLoadContext { internal static readonly AssemblyLoadContext s_loadContext = new DefaultAssemblyLoadContext(); internal DefaultAssemblyLoadContext() : base(representsTPALoadContext: true, isCollectible: false, "Default") { } } internal sealed class IndividualAssemblyLoadContext : AssemblyLoadContext { internal IndividualAssemblyLoadContext(string name) : base(representsTPALoadContext: false, isCollectible: false, name) { } } internal struct LibraryNameVariation { public string Prefix; public string Suffix; public LibraryNameVariation(string prefix, string suffix) { Prefix = prefix; Suffix = suffix; } internal static IEnumerable DetermineLibraryNameVariations(string libName, bool isRelativePath, bool forOSLoader = false) { yield return new LibraryNameVariation(string.Empty, string.Empty); if (isRelativePath && (!forOSLoader || (libName.Contains('.') && !libName.EndsWith('.'))) && !libName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && !libName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) { yield return new LibraryNameVariation(string.Empty, ".dll"); } } } [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] public sealed class AssemblyDependencyResolver { private readonly Dictionary _assemblyPaths; private readonly string[] _nativeSearchPaths; private readonly string[] _resourceSearchPaths; private readonly string[] _assemblyDirectorySearchPaths; public AssemblyDependencyResolver(string componentAssemblyPath) { if (componentAssemblyPath == null) { throw new ArgumentNullException("componentAssemblyPath"); } string assemblyPathsList = null; string nativeSearchPathsList = null; string resourceSearchPathsList = null; int num = 0; StringBuilder errorMessage = new StringBuilder(); try { Interop.HostPolicy.corehost_error_writer_fn corehost_error_writer_fn = delegate(string message) { errorMessage.AppendLine(message); }; IntPtr functionPointerForDelegate = Marshal.GetFunctionPointerForDelegate(corehost_error_writer_fn); IntPtr errorWriter = Interop.HostPolicy.corehost_set_error_writer(functionPointerForDelegate); try { num = Interop.HostPolicy.corehost_resolve_component_dependencies(componentAssemblyPath, delegate(string assemblyPaths, string nativeSearchPaths, string resourceSearchPaths) { assemblyPathsList = assemblyPaths; nativeSearchPathsList = nativeSearchPaths; resourceSearchPathsList = resourceSearchPaths; }); } finally { Interop.HostPolicy.corehost_set_error_writer(errorWriter); GC.KeepAlive(corehost_error_writer_fn); } } catch (EntryPointNotFoundException innerException) { throw new InvalidOperationException(SR.AssemblyDependencyResolver_FailedToLoadHostpolicy, innerException); } catch (DllNotFoundException innerException2) { throw new InvalidOperationException(SR.AssemblyDependencyResolver_FailedToLoadHostpolicy, innerException2); } if (num != 0) { throw new InvalidOperationException(SR.Format(SR.AssemblyDependencyResolver_FailedToResolveDependencies, componentAssemblyPath, num, errorMessage)); } string[] array = SplitPathsList(assemblyPathsList); _assemblyPaths = new Dictionary(StringComparer.OrdinalIgnoreCase); string[] array2 = array; foreach (string text in array2) { _assemblyPaths.TryAdd(Path.GetFileNameWithoutExtension(text), text); } _nativeSearchPaths = SplitPathsList(nativeSearchPathsList); _resourceSearchPaths = SplitPathsList(resourceSearchPathsList); _assemblyDirectorySearchPaths = new string[1] { Path.GetDirectoryName(componentAssemblyPath) }; } public string? ResolveAssemblyToPath(AssemblyName assemblyName) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } string value; if (!string.IsNullOrEmpty(assemblyName.CultureName) && !string.Equals(assemblyName.CultureName, "neutral", StringComparison.OrdinalIgnoreCase)) { string[] resourceSearchPaths = _resourceSearchPaths; foreach (string path in resourceSearchPaths) { string text = Path.Combine(path, assemblyName.CultureName, assemblyName.Name + ".dll"); if (File.Exists(text)) { return text; } } } else if (assemblyName.Name != null && _assemblyPaths.TryGetValue(assemblyName.Name, out value) && File.Exists(value)) { return value; } return null; } public string? ResolveUnmanagedDllToPath(string unmanagedDllName) { if (unmanagedDllName == null) { throw new ArgumentNullException("unmanagedDllName"); } string[] array = ((!unmanagedDllName.Contains(Path.DirectorySeparatorChar)) ? _nativeSearchPaths : _assemblyDirectorySearchPaths); bool isRelativePath = !Path.IsPathFullyQualified(unmanagedDllName); foreach (LibraryNameVariation item in LibraryNameVariation.DetermineLibraryNameVariations(unmanagedDllName, isRelativePath)) { string path = item.Prefix + unmanagedDllName + item.Suffix; string[] array2 = array; foreach (string path2 in array2) { string text = Path.Combine(path2, path); if (File.Exists(text)) { return text; } } } return null; } private static string[] SplitPathsList(string pathsList) { if (pathsList == null) { return Array.Empty(); } return pathsList.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries); } } } namespace System.Runtime.Intrinsics { public static class Vector128 { [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector128 As(this Vector128 vector) where T : struct where U : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return Unsafe.As, Vector128>(ref vector); } [Intrinsic] public static Vector128 AsByte(this Vector128 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector128 AsDouble(this Vector128 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector128 AsInt16(this Vector128 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector128 AsInt32(this Vector128 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector128 AsInt64(this Vector128 vector) where T : struct { return vector.As(); } [Intrinsic] [CLSCompliant(false)] public static Vector128 AsSByte(this Vector128 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector128 AsSingle(this Vector128 vector) where T : struct { return vector.As(); } [Intrinsic] [CLSCompliant(false)] public static Vector128 AsUInt16(this Vector128 vector) where T : struct { return vector.As(); } [Intrinsic] [CLSCompliant(false)] public static Vector128 AsUInt32(this Vector128 vector) where T : struct { return vector.As(); } [Intrinsic] [CLSCompliant(false)] public static Vector128 AsUInt64(this Vector128 vector) where T : struct { return vector.As(); } public static Vector128 AsVector128(this Vector2 value) { return new Vector4(value, 0f, 0f).AsVector128(); } public static Vector128 AsVector128(this Vector3 value) { return new Vector4(value, 0f).AsVector128(); } [Intrinsic] public static Vector128 AsVector128(this Vector4 value) { return Unsafe.As>(ref value); } [Intrinsic] public static Vector128 AsVector128(this Vector value) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return Unsafe.As, Vector128>(ref value); } public static Vector2 AsVector2(this Vector128 value) { return Unsafe.As, Vector2>(ref value); } public static Vector3 AsVector3(this Vector128 value) { return Unsafe.As, Vector3>(ref value); } [Intrinsic] public static Vector4 AsVector4(this Vector128 value) { return Unsafe.As, Vector4>(ref value); } [Intrinsic] public static Vector AsVector(this Vector128 value) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); Vector source = default(Vector); Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } [Intrinsic] public static Vector128 Create(byte value) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector128 SoftwareFallback(byte value) { byte* source = stackalloc byte[16] { value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector128 Create(double value) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector128 SoftwareFallback(double value) { double* source = stackalloc double[2] { value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector128 Create(short value) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector128 SoftwareFallback(short value) { short* source = stackalloc short[8] { value, value, value, value, value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector128 Create(int value) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector128 SoftwareFallback(int value) { int* source = stackalloc int[4] { value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector128 Create(long value) { if (Sse2.X64.IsSupported || AdvSimd.Arm64.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector128 SoftwareFallback(long value) { long* source = stackalloc long[2] { value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector128 Create(sbyte value) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector128 SoftwareFallback(sbyte value) { sbyte* source = stackalloc sbyte[16] { value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector128 Create(float value) { if (Sse.IsSupported || AdvSimd.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector128 SoftwareFallback(float value) { float* source = stackalloc float[4] { value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector128 Create(ushort value) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector128 SoftwareFallback(ushort value) { ushort* source = stackalloc ushort[8] { value, value, value, value, value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector128 Create(uint value) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector128 SoftwareFallback(uint value) { uint* source = stackalloc uint[4] { value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector128 Create(ulong value) { if (Sse2.X64.IsSupported || AdvSimd.Arm64.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector128 SoftwareFallback(ulong value) { ulong* source = stackalloc ulong[2] { value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector128 Create(byte e0, byte e1, byte e2, byte e3, byte e4, byte e5, byte e6, byte e7, byte e8, byte e9, byte e10, byte e11, byte e12, byte e13, byte e14, byte e15) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return Create(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15); } return SoftwareFallback(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15); unsafe static Vector128 SoftwareFallback(byte e0, byte e1, byte e2, byte e3, byte e4, byte e5, byte e6, byte e7, byte e8, byte e9, byte e10, byte e11, byte e12, byte e13, byte e14, byte e15) { byte* source = stackalloc byte[16] { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15 }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector128 Create(double e0, double e1) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return Create(e0, e1); } return SoftwareFallback(e0, e1); unsafe static Vector128 SoftwareFallback(double e0, double e1) { double* source = stackalloc double[2] { e0, e1 }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector128 Create(short e0, short e1, short e2, short e3, short e4, short e5, short e6, short e7) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return Create(e0, e1, e2, e3, e4, e5, e6, e7); } return SoftwareFallback(e0, e1, e2, e3, e4, e5, e6, e7); unsafe static Vector128 SoftwareFallback(short e0, short e1, short e2, short e3, short e4, short e5, short e6, short e7) { short* source = stackalloc short[8] { e0, e1, e2, e3, e4, e5, e6, e7 }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector128 Create(int e0, int e1, int e2, int e3) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return Create(e0, e1, e2, e3); } return SoftwareFallback(e0, e1, e2, e3); unsafe static Vector128 SoftwareFallback(int e0, int e1, int e2, int e3) { int* source = stackalloc int[4] { e0, e1, e2, e3 }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector128 Create(long e0, long e1) { if (Sse2.X64.IsSupported || AdvSimd.Arm64.IsSupported) { return Create(e0, e1); } return SoftwareFallback(e0, e1); unsafe static Vector128 SoftwareFallback(long e0, long e1) { long* source = stackalloc long[2] { e0, e1 }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector128 Create(sbyte e0, sbyte e1, sbyte e2, sbyte e3, sbyte e4, sbyte e5, sbyte e6, sbyte e7, sbyte e8, sbyte e9, sbyte e10, sbyte e11, sbyte e12, sbyte e13, sbyte e14, sbyte e15) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return Create(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15); } return SoftwareFallback(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15); unsafe static Vector128 SoftwareFallback(sbyte e0, sbyte e1, sbyte e2, sbyte e3, sbyte e4, sbyte e5, sbyte e6, sbyte e7, sbyte e8, sbyte e9, sbyte e10, sbyte e11, sbyte e12, sbyte e13, sbyte e14, sbyte e15) { sbyte* source = stackalloc sbyte[16] { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15 }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector128 Create(float e0, float e1, float e2, float e3) { if (Sse.IsSupported || AdvSimd.IsSupported) { return Create(e0, e1, e2, e3); } return SoftwareFallback(e0, e1, e2, e3); unsafe static Vector128 SoftwareFallback(float e0, float e1, float e2, float e3) { float* source = stackalloc float[4] { e0, e1, e2, e3 }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector128 Create(ushort e0, ushort e1, ushort e2, ushort e3, ushort e4, ushort e5, ushort e6, ushort e7) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return Create(e0, e1, e2, e3, e4, e5, e6, e7); } return SoftwareFallback(e0, e1, e2, e3, e4, e5, e6, e7); unsafe static Vector128 SoftwareFallback(ushort e0, ushort e1, ushort e2, ushort e3, ushort e4, ushort e5, ushort e6, ushort e7) { ushort* source = stackalloc ushort[8] { e0, e1, e2, e3, e4, e5, e6, e7 }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector128 Create(uint e0, uint e1, uint e2, uint e3) { if (Sse2.IsSupported || AdvSimd.IsSupported) { return Create(e0, e1, e2, e3); } return SoftwareFallback(e0, e1, e2, e3); unsafe static Vector128 SoftwareFallback(uint e0, uint e1, uint e2, uint e3) { uint* source = stackalloc uint[4] { e0, e1, e2, e3 }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector128 Create(ulong e0, ulong e1) { if (Sse2.X64.IsSupported || AdvSimd.Arm64.IsSupported) { return Create(e0, e1); } return SoftwareFallback(e0, e1); unsafe static Vector128 SoftwareFallback(ulong e0, ulong e1) { ulong* source = stackalloc ulong[2] { e0, e1 }; return Unsafe.AsRef>(source); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 Create(Vector64 lower, Vector64 upper) { if (AdvSimd.IsSupported) { } return SoftwareFallback(lower, upper); static Vector128 SoftwareFallback(Vector64 lower, Vector64 upper) { Vector128 source = Vector128.Zero; ref Vector64 reference = ref Unsafe.As, Vector64>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 Create(Vector64 lower, Vector64 upper) { if (AdvSimd.IsSupported) { } return SoftwareFallback(lower, upper); static Vector128 SoftwareFallback(Vector64 lower, Vector64 upper) { Vector128 source = Vector128.Zero; ref Vector64 reference = ref Unsafe.As, Vector64>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 Create(Vector64 lower, Vector64 upper) { if (AdvSimd.IsSupported) { } return SoftwareFallback(lower, upper); static Vector128 SoftwareFallback(Vector64 lower, Vector64 upper) { Vector128 source = Vector128.Zero; ref Vector64 reference = ref Unsafe.As, Vector64>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 Create(Vector64 lower, Vector64 upper) { if (AdvSimd.IsSupported) { } return SoftwareFallback(lower, upper); static Vector128 SoftwareFallback(Vector64 lower, Vector64 upper) { Vector128 source = Vector128.Zero; ref Vector64 reference = ref Unsafe.As, Vector64>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 Create(Vector64 lower, Vector64 upper) { if (AdvSimd.IsSupported) { } return SoftwareFallback(lower, upper); static Vector128 SoftwareFallback(Vector64 lower, Vector64 upper) { Vector128 source = Vector128.Zero; ref Vector64 reference = ref Unsafe.As, Vector64>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector128 Create(Vector64 lower, Vector64 upper) { if (AdvSimd.IsSupported) { } return SoftwareFallback(lower, upper); static Vector128 SoftwareFallback(Vector64 lower, Vector64 upper) { Vector128 source = Vector128.Zero; ref Vector64 reference = ref Unsafe.As, Vector64>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 Create(Vector64 lower, Vector64 upper) { if (AdvSimd.IsSupported) { } return SoftwareFallback(lower, upper); static Vector128 SoftwareFallback(Vector64 lower, Vector64 upper) { Vector128 source = Vector128.Zero; ref Vector64 reference = ref Unsafe.As, Vector64>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector128 Create(Vector64 lower, Vector64 upper) { if (AdvSimd.IsSupported) { } return SoftwareFallback(lower, upper); static Vector128 SoftwareFallback(Vector64 lower, Vector64 upper) { Vector128 source = Vector128.Zero; ref Vector64 reference = ref Unsafe.As, Vector64>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector128 Create(Vector64 lower, Vector64 upper) { if (AdvSimd.IsSupported) { } return SoftwareFallback(lower, upper); static Vector128 SoftwareFallback(Vector64 lower, Vector64 upper) { Vector128 source = Vector128.Zero; ref Vector64 reference = ref Unsafe.As, Vector64>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector128 Create(Vector64 lower, Vector64 upper) { if (AdvSimd.IsSupported) { } return SoftwareFallback(lower, upper); static Vector128 SoftwareFallback(Vector64 lower, Vector64 upper) { Vector128 source = Vector128.Zero; ref Vector64 reference = ref Unsafe.As, Vector64>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 CreateScalar(byte value) { if (AdvSimd.IsSupported) { } if (Sse2.IsSupported) { return Sse2.ConvertScalarToVector128UInt32(value).AsByte(); } return SoftwareFallback(value); static Vector128 SoftwareFallback(byte value) { Vector128 source = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 CreateScalar(double value) { if (AdvSimd.IsSupported) { } if (Sse2.IsSupported) { return Sse2.MoveScalar(Vector128.Zero, CreateScalarUnsafe(value)); } return SoftwareFallback(value); static Vector128 SoftwareFallback(double value) { Vector128 source = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 CreateScalar(short value) { if (AdvSimd.IsSupported) { } if (Sse2.IsSupported) { return Sse2.ConvertScalarToVector128UInt32((ushort)value).AsInt16(); } return SoftwareFallback(value); static Vector128 SoftwareFallback(short value) { Vector128 source = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 CreateScalar(int value) { if (AdvSimd.IsSupported) { } if (Sse2.IsSupported) { return Sse2.ConvertScalarToVector128Int32(value); } return SoftwareFallback(value); static Vector128 SoftwareFallback(int value) { Vector128 source = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } public static Vector128 CreateScalar(long value) { if (AdvSimd.IsSupported) { } if (Sse2.X64.IsSupported) { return Sse2.X64.ConvertScalarToVector128Int64(value); } return SoftwareFallback(value); static Vector128 SoftwareFallback(long value) { Vector128 source = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector128 CreateScalar(sbyte value) { if (AdvSimd.IsSupported) { } if (Sse2.IsSupported) { return Sse2.ConvertScalarToVector128UInt32((byte)value).AsSByte(); } return SoftwareFallback(value); static Vector128 SoftwareFallback(sbyte value) { Vector128 source = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 CreateScalar(float value) { if (AdvSimd.IsSupported) { } if (Sse.IsSupported) { return Sse.MoveScalar(Vector128.Zero, CreateScalarUnsafe(value)); } return SoftwareFallback(value); static Vector128 SoftwareFallback(float value) { Vector128 source = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector128 CreateScalar(ushort value) { if (AdvSimd.IsSupported) { } if (Sse2.IsSupported) { return Sse2.ConvertScalarToVector128UInt32(value).AsUInt16(); } return SoftwareFallback(value); static Vector128 SoftwareFallback(ushort value) { Vector128 source = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector128 CreateScalar(uint value) { if (AdvSimd.IsSupported) { } if (Sse2.IsSupported) { return Sse2.ConvertScalarToVector128UInt32(value); } return SoftwareFallback(value); static Vector128 SoftwareFallback(uint value) { Vector128 source = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector128 CreateScalar(ulong value) { if (AdvSimd.IsSupported) { } if (Sse2.X64.IsSupported) { return Sse2.X64.ConvertScalarToVector128UInt64(value); } return SoftwareFallback(value); static Vector128 SoftwareFallback(ulong value) { Vector128 source = Vector128.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [Intrinsic] public unsafe static Vector128 CreateScalarUnsafe(byte value) { byte* ptr = stackalloc byte[16]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public unsafe static Vector128 CreateScalarUnsafe(double value) { double* ptr = stackalloc double[2]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public unsafe static Vector128 CreateScalarUnsafe(short value) { short* ptr = stackalloc short[8]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public unsafe static Vector128 CreateScalarUnsafe(int value) { int* ptr = stackalloc int[4]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public unsafe static Vector128 CreateScalarUnsafe(long value) { long* ptr = stackalloc long[2]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] [CLSCompliant(false)] public unsafe static Vector128 CreateScalarUnsafe(sbyte value) { sbyte* ptr = stackalloc sbyte[16]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public unsafe static Vector128 CreateScalarUnsafe(float value) { float* ptr = stackalloc float[4]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] [CLSCompliant(false)] public unsafe static Vector128 CreateScalarUnsafe(ushort value) { ushort* ptr = stackalloc ushort[8]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] [CLSCompliant(false)] public unsafe static Vector128 CreateScalarUnsafe(uint value) { uint* ptr = stackalloc uint[4]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] [CLSCompliant(false)] public unsafe static Vector128 CreateScalarUnsafe(ulong value) { ulong* ptr = stackalloc ulong[2]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public static T GetElement(this Vector128 vector, int index) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); if ((uint)index >= (uint)Vector128.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return Unsafe.Add(ref Unsafe.As, T>(ref vector), index); } [Intrinsic] public static Vector128 WithElement(this Vector128 vector, int index, T value) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); if ((uint)index >= (uint)Vector128.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } Vector128 source = vector; Unsafe.Add(ref Unsafe.As, T>(ref source), index) = value; return source; } [Intrinsic] public static Vector64 GetLower(this Vector128 vector) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return Unsafe.As, Vector64>(ref vector); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 WithLower(this Vector128 vector, Vector64 value) where T : struct { if (AdvSimd.IsSupported) { } return SoftwareFallback(vector, value); static Vector128 SoftwareFallback(Vector128 vector, Vector64 value) { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); Vector128 source = vector; Unsafe.As, Vector64>(ref source) = value; return source; } } [Intrinsic] public static Vector64 GetUpper(this Vector128 vector) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return Unsafe.Add(ref Unsafe.As, Vector64>(ref vector), 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 WithUpper(this Vector128 vector, Vector64 value) where T : struct { if (AdvSimd.IsSupported) { } return SoftwareFallback(vector, value); static Vector128 SoftwareFallback(Vector128 vector, Vector64 value) { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); Vector128 source = vector; Unsafe.Add(ref Unsafe.As, Vector64>(ref source), 1) = value; return source; } } [Intrinsic] public static T ToScalar(this Vector128 vector) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return Unsafe.As, T>(ref vector); } [Intrinsic] public static Vector256 ToVector256(this Vector128 vector) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); Vector256 source = Vector256.Zero; Unsafe.As, Vector128>(ref source) = vector; return source; } [Intrinsic] public unsafe static Vector256 ToVector256Unsafe(this Vector128 vector) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); byte* source = stackalloc byte[32]; Unsafe.AsRef>(source) = vector; return Unsafe.AsRef>(source); } } [StructLayout(LayoutKind.Sequential, Size = 16)] [Intrinsic] [DebuggerDisplay("{DisplayString,nq}")] [DebuggerTypeProxy(typeof(Vector128DebugView<>))] public readonly struct Vector128 : IEquatable> where T : struct { private readonly ulong _00; private readonly ulong _01; public static int Count { [Intrinsic] get { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return 16 / Unsafe.SizeOf(); } } public static Vector128 Zero { [Intrinsic] get { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return default(Vector128); } } public static Vector128 AllBitsSet { [Intrinsic] get { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return Vector128.Create(uint.MaxValue).As(); } } internal string DisplayString { get { if (IsSupported) { return ToString(); } return SR.NotSupported_Type; } } internal static bool IsSupported { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (!(typeof(T) == typeof(byte)) && !(typeof(T) == typeof(sbyte)) && !(typeof(T) == typeof(short)) && !(typeof(T) == typeof(ushort)) && !(typeof(T) == typeof(int)) && !(typeof(T) == typeof(uint)) && !(typeof(T) == typeof(long)) && !(typeof(T) == typeof(ulong)) && !(typeof(T) == typeof(float))) { return typeof(T) == typeof(double); } return true; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Vector128 other) { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); if (Sse.IsSupported && typeof(T) == typeof(float)) { Vector128 value = Sse.CompareEqual(this.AsSingle(), other.AsSingle()); return Sse.MoveMask(value) == 15; } if (Sse2.IsSupported) { if (typeof(T) == typeof(double)) { Vector128 value2 = Sse2.CompareEqual(this.AsDouble(), other.AsDouble()); return Sse2.MoveMask(value2) == 3; } Vector128 value3 = Sse2.CompareEqual(this.AsByte(), other.AsByte()); return Sse2.MoveMask(value3) == 65535; } return SoftwareFallback(in this, other); static bool SoftwareFallback(in Vector128 vector, Vector128 other) { for (int i = 0; i < Count; i++) { if (!((IEquatable)(object)vector.GetElement(i)).Equals(other.GetElement(i))) { return false; } } return true; } } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is Vector128) { return Equals((Vector128)obj); } return false; } public override int GetHashCode() { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); HashCode hashCode = default(HashCode); for (int i = 0; i < Count; i++) { hashCode.Add(this.GetElement(i).GetHashCode()); } return hashCode.ToHashCode(); } public override string ToString() { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); int num = Count - 1; Span initialBuffer = stackalloc char[64]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); CultureInfo invariantCulture = CultureInfo.InvariantCulture; valueStringBuilder.Append('<'); for (int i = 0; i < num; i++) { valueStringBuilder.Append(((IFormattable)(object)this.GetElement(i)).ToString("G", invariantCulture)); valueStringBuilder.Append(','); valueStringBuilder.Append(' '); } valueStringBuilder.Append(((IFormattable)(object)this.GetElement(num)).ToString("G", invariantCulture)); valueStringBuilder.Append('>'); return valueStringBuilder.ToString(); } } internal readonly struct Vector128DebugView where T : struct { private readonly Vector128 _value; public byte[] ByteView { get { byte[] array = new byte[16]; Unsafe.WriteUnaligned(ref array[0], _value); return array; } } public double[] DoubleView { get { double[] array = new double[2]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public short[] Int16View { get { short[] array = new short[8]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public int[] Int32View { get { int[] array = new int[4]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public long[] Int64View { get { long[] array = new long[2]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public sbyte[] SByteView { get { sbyte[] array = new sbyte[16]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public float[] SingleView { get { float[] array = new float[4]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public ushort[] UInt16View { get { ushort[] array = new ushort[8]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public uint[] UInt32View { get { uint[] array = new uint[4]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public ulong[] UInt64View { get { ulong[] array = new ulong[2]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public Vector128DebugView(Vector128 value) { _value = value; } } public static class Vector256 { [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector256 As(this Vector256 vector) where T : struct where U : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return Unsafe.As, Vector256>(ref vector); } [Intrinsic] public static Vector256 AsByte(this Vector256 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector256 AsDouble(this Vector256 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector256 AsInt16(this Vector256 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector256 AsInt32(this Vector256 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector256 AsInt64(this Vector256 vector) where T : struct { return vector.As(); } [Intrinsic] [CLSCompliant(false)] public static Vector256 AsSByte(this Vector256 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector256 AsSingle(this Vector256 vector) where T : struct { return vector.As(); } [Intrinsic] [CLSCompliant(false)] public static Vector256 AsUInt16(this Vector256 vector) where T : struct { return vector.As(); } [Intrinsic] [CLSCompliant(false)] public static Vector256 AsUInt32(this Vector256 vector) where T : struct { return vector.As(); } [Intrinsic] [CLSCompliant(false)] public static Vector256 AsUInt64(this Vector256 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector256 AsVector256(this Vector value) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); Vector256 source = default(Vector256); Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } [Intrinsic] public static Vector AsVector(this Vector256 value) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return Unsafe.As, Vector>(ref value); } [Intrinsic] public static Vector256 Create(byte value) { if (Avx.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector256 SoftwareFallback(byte value) { byte* source = stackalloc byte[32] { value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector256 Create(double value) { if (Avx.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector256 SoftwareFallback(double value) { double* source = stackalloc double[4] { value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector256 Create(short value) { if (Avx.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector256 SoftwareFallback(short value) { short* source = stackalloc short[16] { value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector256 Create(int value) { if (Avx.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector256 SoftwareFallback(int value) { int* source = stackalloc int[8] { value, value, value, value, value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector256 Create(long value) { if (Sse2.X64.IsSupported && Avx.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector256 SoftwareFallback(long value) { long* source = stackalloc long[4] { value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector256 Create(sbyte value) { if (Avx.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector256 SoftwareFallback(sbyte value) { sbyte* source = stackalloc sbyte[32] { value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector256 Create(float value) { if (Avx.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector256 SoftwareFallback(float value) { float* source = stackalloc float[8] { value, value, value, value, value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector256 Create(ushort value) { if (Avx.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector256 SoftwareFallback(ushort value) { ushort* source = stackalloc ushort[16] { value, value, value, value, value, value, value, value, value, value, value, value, value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector256 Create(uint value) { if (Avx.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector256 SoftwareFallback(uint value) { uint* source = stackalloc uint[8] { value, value, value, value, value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector256 Create(ulong value) { if (Sse2.X64.IsSupported && Avx.IsSupported) { return Create(value); } return SoftwareFallback(value); unsafe static Vector256 SoftwareFallback(ulong value) { ulong* source = stackalloc ulong[4] { value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector256 Create(byte e0, byte e1, byte e2, byte e3, byte e4, byte e5, byte e6, byte e7, byte e8, byte e9, byte e10, byte e11, byte e12, byte e13, byte e14, byte e15, byte e16, byte e17, byte e18, byte e19, byte e20, byte e21, byte e22, byte e23, byte e24, byte e25, byte e26, byte e27, byte e28, byte e29, byte e30, byte e31) { if (Avx.IsSupported) { return Create(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31); } return SoftwareFallback(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31); unsafe static Vector256 SoftwareFallback(byte e0, byte e1, byte e2, byte e3, byte e4, byte e5, byte e6, byte e7, byte e8, byte e9, byte e10, byte e11, byte e12, byte e13, byte e14, byte e15, byte e16, byte e17, byte e18, byte e19, byte e20, byte e21, byte e22, byte e23, byte e24, byte e25, byte e26, byte e27, byte e28, byte e29, byte e30, byte e31) { byte* source = stackalloc byte[32] { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31 }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector256 Create(double e0, double e1, double e2, double e3) { if (Avx.IsSupported) { return Create(e0, e1, e2, e3); } return SoftwareFallback(e0, e1, e2, e3); unsafe static Vector256 SoftwareFallback(double e0, double e1, double e2, double e3) { double* source = stackalloc double[4] { e0, e1, e2, e3 }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector256 Create(short e0, short e1, short e2, short e3, short e4, short e5, short e6, short e7, short e8, short e9, short e10, short e11, short e12, short e13, short e14, short e15) { if (Avx.IsSupported) { return Create(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15); } return SoftwareFallback(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15); unsafe static Vector256 SoftwareFallback(short e0, short e1, short e2, short e3, short e4, short e5, short e6, short e7, short e8, short e9, short e10, short e11, short e12, short e13, short e14, short e15) { short* source = stackalloc short[16] { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15 }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector256 Create(int e0, int e1, int e2, int e3, int e4, int e5, int e6, int e7) { if (Avx.IsSupported) { return Create(e0, e1, e2, e3, e4, e5, e6, e7); } return SoftwareFallback(e0, e1, e2, e3, e4, e5, e6, e7); unsafe static Vector256 SoftwareFallback(int e0, int e1, int e2, int e3, int e4, int e5, int e6, int e7) { int* source = stackalloc int[8] { e0, e1, e2, e3, e4, e5, e6, e7 }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector256 Create(long e0, long e1, long e2, long e3) { if (Sse2.X64.IsSupported && Avx.IsSupported) { return Create(e0, e1, e2, e3); } return SoftwareFallback(e0, e1, e2, e3); unsafe static Vector256 SoftwareFallback(long e0, long e1, long e2, long e3) { long* source = stackalloc long[4] { e0, e1, e2, e3 }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector256 Create(sbyte e0, sbyte e1, sbyte e2, sbyte e3, sbyte e4, sbyte e5, sbyte e6, sbyte e7, sbyte e8, sbyte e9, sbyte e10, sbyte e11, sbyte e12, sbyte e13, sbyte e14, sbyte e15, sbyte e16, sbyte e17, sbyte e18, sbyte e19, sbyte e20, sbyte e21, sbyte e22, sbyte e23, sbyte e24, sbyte e25, sbyte e26, sbyte e27, sbyte e28, sbyte e29, sbyte e30, sbyte e31) { if (Avx.IsSupported) { return Create(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31); } return SoftwareFallback(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31); unsafe static Vector256 SoftwareFallback(sbyte e0, sbyte e1, sbyte e2, sbyte e3, sbyte e4, sbyte e5, sbyte e6, sbyte e7, sbyte e8, sbyte e9, sbyte e10, sbyte e11, sbyte e12, sbyte e13, sbyte e14, sbyte e15, sbyte e16, sbyte e17, sbyte e18, sbyte e19, sbyte e20, sbyte e21, sbyte e22, sbyte e23, sbyte e24, sbyte e25, sbyte e26, sbyte e27, sbyte e28, sbyte e29, sbyte e30, sbyte e31) { sbyte* source = stackalloc sbyte[32] { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16, e17, e18, e19, e20, e21, e22, e23, e24, e25, e26, e27, e28, e29, e30, e31 }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector256 Create(float e0, float e1, float e2, float e3, float e4, float e5, float e6, float e7) { if (Avx.IsSupported) { return Create(e0, e1, e2, e3, e4, e5, e6, e7); } return SoftwareFallback(e0, e1, e2, e3, e4, e5, e6, e7); unsafe static Vector256 SoftwareFallback(float e0, float e1, float e2, float e3, float e4, float e5, float e6, float e7) { float* source = stackalloc float[8] { e0, e1, e2, e3, e4, e5, e6, e7 }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector256 Create(ushort e0, ushort e1, ushort e2, ushort e3, ushort e4, ushort e5, ushort e6, ushort e7, ushort e8, ushort e9, ushort e10, ushort e11, ushort e12, ushort e13, ushort e14, ushort e15) { if (Avx.IsSupported) { return Create(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15); } return SoftwareFallback(e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15); unsafe static Vector256 SoftwareFallback(ushort e0, ushort e1, ushort e2, ushort e3, ushort e4, ushort e5, ushort e6, ushort e7, ushort e8, ushort e9, ushort e10, ushort e11, ushort e12, ushort e13, ushort e14, ushort e15) { ushort* source = stackalloc ushort[16] { e0, e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15 }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector256 Create(uint e0, uint e1, uint e2, uint e3, uint e4, uint e5, uint e6, uint e7) { if (Avx.IsSupported) { return Create(e0, e1, e2, e3, e4, e5, e6, e7); } return SoftwareFallback(e0, e1, e2, e3, e4, e5, e6, e7); unsafe static Vector256 SoftwareFallback(uint e0, uint e1, uint e2, uint e3, uint e4, uint e5, uint e6, uint e7) { uint* source = stackalloc uint[8] { e0, e1, e2, e3, e4, e5, e6, e7 }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector256 Create(ulong e0, ulong e1, ulong e2, ulong e3) { if (Sse2.X64.IsSupported && Avx.IsSupported) { return Create(e0, e1, e2, e3); } return SoftwareFallback(e0, e1, e2, e3); unsafe static Vector256 SoftwareFallback(ulong e0, ulong e1, ulong e2, ulong e3) { ulong* source = stackalloc ulong[4] { e0, e1, e2, e3 }; return Unsafe.AsRef>(source); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector256 Create(Vector128 lower, Vector128 upper) { if (Avx.IsSupported) { Vector256 vector = lower.ToVector256Unsafe(); return vector.WithUpper(upper); } return SoftwareFallback(lower, upper); static Vector256 SoftwareFallback(Vector128 lower, Vector128 upper) { Vector256 source = Vector256.Zero; ref Vector128 reference = ref Unsafe.As, Vector128>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector256 Create(Vector128 lower, Vector128 upper) { if (Avx.IsSupported) { Vector256 vector = lower.ToVector256Unsafe(); return vector.WithUpper(upper); } return SoftwareFallback(lower, upper); static Vector256 SoftwareFallback(Vector128 lower, Vector128 upper) { Vector256 source = Vector256.Zero; ref Vector128 reference = ref Unsafe.As, Vector128>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector256 Create(Vector128 lower, Vector128 upper) { if (Avx.IsSupported) { Vector256 vector = lower.ToVector256Unsafe(); return vector.WithUpper(upper); } return SoftwareFallback(lower, upper); static Vector256 SoftwareFallback(Vector128 lower, Vector128 upper) { Vector256 source = Vector256.Zero; ref Vector128 reference = ref Unsafe.As, Vector128>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector256 Create(Vector128 lower, Vector128 upper) { if (Avx.IsSupported) { Vector256 vector = lower.ToVector256Unsafe(); return vector.WithUpper(upper); } return SoftwareFallback(lower, upper); static Vector256 SoftwareFallback(Vector128 lower, Vector128 upper) { Vector256 source = Vector256.Zero; ref Vector128 reference = ref Unsafe.As, Vector128>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector256 Create(Vector128 lower, Vector128 upper) { if (Avx.IsSupported) { Vector256 vector = lower.ToVector256Unsafe(); return vector.WithUpper(upper); } return SoftwareFallback(lower, upper); static Vector256 SoftwareFallback(Vector128 lower, Vector128 upper) { Vector256 source = Vector256.Zero; ref Vector128 reference = ref Unsafe.As, Vector128>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector256 Create(Vector128 lower, Vector128 upper) { if (Avx.IsSupported) { Vector256 vector = lower.ToVector256Unsafe(); return vector.WithUpper(upper); } return SoftwareFallback(lower, upper); static Vector256 SoftwareFallback(Vector128 lower, Vector128 upper) { Vector256 source = Vector256.Zero; ref Vector128 reference = ref Unsafe.As, Vector128>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector256 Create(Vector128 lower, Vector128 upper) { if (Avx.IsSupported) { Vector256 vector = lower.ToVector256Unsafe(); return vector.WithUpper(upper); } return SoftwareFallback(lower, upper); static Vector256 SoftwareFallback(Vector128 lower, Vector128 upper) { Vector256 source = Vector256.Zero; ref Vector128 reference = ref Unsafe.As, Vector128>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector256 Create(Vector128 lower, Vector128 upper) { if (Avx.IsSupported) { Vector256 vector = lower.ToVector256Unsafe(); return vector.WithUpper(upper); } return SoftwareFallback(lower, upper); static Vector256 SoftwareFallback(Vector128 lower, Vector128 upper) { Vector256 source = Vector256.Zero; ref Vector128 reference = ref Unsafe.As, Vector128>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector256 Create(Vector128 lower, Vector128 upper) { if (Avx.IsSupported) { Vector256 vector = lower.ToVector256Unsafe(); return vector.WithUpper(upper); } return SoftwareFallback(lower, upper); static Vector256 SoftwareFallback(Vector128 lower, Vector128 upper) { Vector256 source = Vector256.Zero; ref Vector128 reference = ref Unsafe.As, Vector128>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector256 Create(Vector128 lower, Vector128 upper) { if (Avx.IsSupported) { Vector256 vector = lower.ToVector256Unsafe(); return vector.WithUpper(upper); } return SoftwareFallback(lower, upper); static Vector256 SoftwareFallback(Vector128 lower, Vector128 upper) { Vector256 source = Vector256.Zero; ref Vector128 reference = ref Unsafe.As, Vector128>(ref source); reference = lower; Unsafe.Add(ref reference, 1) = upper; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector256 CreateScalar(byte value) { if (Avx.IsSupported) { return Vector128.CreateScalar(value).ToVector256(); } return SoftwareFallback(value); static Vector256 SoftwareFallback(byte value) { Vector256 source = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector256 CreateScalar(double value) { if (Avx.IsSupported) { return Vector128.CreateScalar(value).ToVector256(); } return SoftwareFallback(value); static Vector256 SoftwareFallback(double value) { Vector256 source = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector256 CreateScalar(short value) { if (Avx.IsSupported) { return Vector128.CreateScalar(value).ToVector256(); } return SoftwareFallback(value); static Vector256 SoftwareFallback(short value) { Vector256 source = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector256 CreateScalar(int value) { if (Avx.IsSupported) { return Vector128.CreateScalar(value).ToVector256(); } return SoftwareFallback(value); static Vector256 SoftwareFallback(int value) { Vector256 source = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector256 CreateScalar(long value) { if (Sse2.X64.IsSupported && Avx.IsSupported) { return Vector128.CreateScalar(value).ToVector256(); } return SoftwareFallback(value); static Vector256 SoftwareFallback(long value) { Vector256 source = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector256 CreateScalar(sbyte value) { if (Avx.IsSupported) { return Vector128.CreateScalar(value).ToVector256(); } return SoftwareFallback(value); static Vector256 SoftwareFallback(sbyte value) { Vector256 source = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector256 CreateScalar(float value) { if (Avx.IsSupported) { return Vector128.CreateScalar(value).ToVector256(); } return SoftwareFallback(value); static Vector256 SoftwareFallback(float value) { Vector256 source = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector256 CreateScalar(ushort value) { if (Avx.IsSupported) { return Vector128.CreateScalar(value).ToVector256(); } return SoftwareFallback(value); static Vector256 SoftwareFallback(ushort value) { Vector256 source = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector256 CreateScalar(uint value) { if (Avx.IsSupported) { return Vector128.CreateScalar(value).ToVector256(); } return SoftwareFallback(value); static Vector256 SoftwareFallback(uint value) { Vector256 source = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] [CLSCompliant(false)] public static Vector256 CreateScalar(ulong value) { if (Sse2.X64.IsSupported && Avx.IsSupported) { return Vector128.CreateScalar(value).ToVector256(); } return SoftwareFallback(value); static Vector256 SoftwareFallback(ulong value) { Vector256 source = Vector256.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [Intrinsic] public unsafe static Vector256 CreateScalarUnsafe(byte value) { byte* ptr = stackalloc byte[32]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public unsafe static Vector256 CreateScalarUnsafe(double value) { double* ptr = stackalloc double[4]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public unsafe static Vector256 CreateScalarUnsafe(short value) { short* ptr = stackalloc short[16]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public unsafe static Vector256 CreateScalarUnsafe(int value) { int* ptr = stackalloc int[8]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public unsafe static Vector256 CreateScalarUnsafe(long value) { long* ptr = stackalloc long[4]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] [CLSCompliant(false)] public unsafe static Vector256 CreateScalarUnsafe(sbyte value) { sbyte* ptr = stackalloc sbyte[32]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public unsafe static Vector256 CreateScalarUnsafe(float value) { float* ptr = stackalloc float[8]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] [CLSCompliant(false)] public unsafe static Vector256 CreateScalarUnsafe(ushort value) { ushort* ptr = stackalloc ushort[16]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] [CLSCompliant(false)] public unsafe static Vector256 CreateScalarUnsafe(uint value) { uint* ptr = stackalloc uint[8]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] [CLSCompliant(false)] public unsafe static Vector256 CreateScalarUnsafe(ulong value) { ulong* ptr = stackalloc ulong[4]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public static T GetElement(this Vector256 vector, int index) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); if ((uint)index >= (uint)Vector256.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return Unsafe.Add(ref Unsafe.As, T>(ref vector), index); } [Intrinsic] public static Vector256 WithElement(this Vector256 vector, int index, T value) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); if ((uint)index >= (uint)Vector256.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } Vector256 source = vector; Unsafe.Add(ref Unsafe.As, T>(ref source), index) = value; return source; } [Intrinsic] public static Vector128 GetLower(this Vector256 vector) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return Unsafe.As, Vector128>(ref vector); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector256 WithLower(this Vector256 vector, Vector128 value) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); if (Avx2.IsSupported && typeof(T) != typeof(float) && typeof(T) != typeof(double)) { return Avx2.InsertVector128(vector.AsByte(), value.AsByte(), 0).As(); } if (Avx.IsSupported) { return Avx.InsertVector128(vector.AsSingle(), value.AsSingle(), 0).As(); } return SoftwareFallback(vector, value); static Vector256 SoftwareFallback(Vector256 vector, Vector128 value) { Vector256 source = vector; Unsafe.As, Vector128>(ref source) = value; return source; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector128 GetUpper(this Vector256 vector) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); if (Avx2.IsSupported && typeof(T) != typeof(float) && typeof(T) != typeof(double)) { return Avx2.ExtractVector128(vector.AsByte(), 1).As(); } if (Avx.IsSupported) { return Avx.ExtractVector128(vector.AsSingle(), 1).As(); } return SoftwareFallback(vector); static Vector128 SoftwareFallback(Vector256 vector) { return Unsafe.Add(ref Unsafe.As, Vector128>(ref vector), 1); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector256 WithUpper(this Vector256 vector, Vector128 value) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); if (Avx2.IsSupported && typeof(T) != typeof(float) && typeof(T) != typeof(double)) { return Avx2.InsertVector128(vector.AsByte(), value.AsByte(), 1).As(); } if (Avx.IsSupported) { return Avx.InsertVector128(vector.AsSingle(), value.AsSingle(), 1).As(); } return SoftwareFallback(vector, value); static Vector256 SoftwareFallback(Vector256 vector, Vector128 value) { Vector256 source = vector; Unsafe.Add(ref Unsafe.As, Vector128>(ref source), 1) = value; return source; } } [Intrinsic] public static T ToScalar(this Vector256 vector) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return Unsafe.As, T>(ref vector); } } [StructLayout(LayoutKind.Sequential, Size = 32)] [Intrinsic] [DebuggerDisplay("{DisplayString,nq}")] [DebuggerTypeProxy(typeof(Vector256DebugView<>))] public readonly struct Vector256 : IEquatable> where T : struct { private readonly ulong _00; private readonly ulong _01; private readonly ulong _02; private readonly ulong _03; public static int Count { [Intrinsic] get { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return 32 / Unsafe.SizeOf(); } } public static Vector256 Zero { [Intrinsic] get { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return default(Vector256); } } public static Vector256 AllBitsSet { [Intrinsic] get { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return Vector256.Create(uint.MaxValue).As(); } } internal string DisplayString { get { if (IsSupported) { return ToString(); } return SR.NotSupported_Type; } } internal static bool IsSupported { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (!(typeof(T) == typeof(byte)) && !(typeof(T) == typeof(sbyte)) && !(typeof(T) == typeof(short)) && !(typeof(T) == typeof(ushort)) && !(typeof(T) == typeof(int)) && !(typeof(T) == typeof(uint)) && !(typeof(T) == typeof(long)) && !(typeof(T) == typeof(ulong)) && !(typeof(T) == typeof(float))) { return typeof(T) == typeof(double); } return true; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Equals(Vector256 other) { if (Avx.IsSupported) { if (typeof(T) == typeof(float)) { Vector256 value = Avx.Compare(this.AsSingle(), other.AsSingle(), FloatComparisonMode.OrderedEqualNonSignaling); return Avx.MoveMask(value) == 255; } if (typeof(T) == typeof(double)) { Vector256 value2 = Avx.Compare(this.AsDouble(), other.AsDouble(), FloatComparisonMode.OrderedEqualNonSignaling); return Avx.MoveMask(value2) == 15; } } if (Avx2.IsSupported) { Vector256 value3 = Avx2.CompareEqual(this.AsByte(), other.AsByte()); return Avx2.MoveMask(value3) == -1; } return SoftwareFallback(in this, other); static bool SoftwareFallback(in Vector256 vector, Vector256 other) { for (int i = 0; i < Count; i++) { if (!((IEquatable)(object)vector.GetElement(i)).Equals(other.GetElement(i))) { return false; } } return true; } } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is Vector256) { return Equals((Vector256)obj); } return false; } public override int GetHashCode() { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); HashCode hashCode = default(HashCode); for (int i = 0; i < Count; i++) { hashCode.Add(this.GetElement(i).GetHashCode()); } return hashCode.ToHashCode(); } public override string ToString() { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); int num = Count - 1; Span initialBuffer = stackalloc char[64]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); CultureInfo invariantCulture = CultureInfo.InvariantCulture; valueStringBuilder.Append('<'); for (int i = 0; i < num; i++) { valueStringBuilder.Append(((IFormattable)(object)this.GetElement(i)).ToString("G", invariantCulture)); valueStringBuilder.Append(','); valueStringBuilder.Append(' '); } valueStringBuilder.Append(((IFormattable)(object)this.GetElement(num)).ToString("G", invariantCulture)); valueStringBuilder.Append('>'); return valueStringBuilder.ToString(); } } internal readonly struct Vector256DebugView where T : struct { private readonly Vector256 _value; public byte[] ByteView { get { byte[] array = new byte[32]; Unsafe.WriteUnaligned(ref array[0], _value); return array; } } public double[] DoubleView { get { double[] array = new double[4]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public short[] Int16View { get { short[] array = new short[16]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public int[] Int32View { get { int[] array = new int[8]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public long[] Int64View { get { long[] array = new long[4]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public sbyte[] SByteView { get { sbyte[] array = new sbyte[32]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public float[] SingleView { get { float[] array = new float[8]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public ushort[] UInt16View { get { ushort[] array = new ushort[16]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public uint[] UInt32View { get { uint[] array = new uint[8]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public ulong[] UInt64View { get { ulong[] array = new ulong[4]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public Vector256DebugView(Vector256 value) { _value = value; } } public static class Vector64 { [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] public static Vector64 As(this Vector64 vector) where T : struct where U : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return Unsafe.As, Vector64>(ref vector); } [Intrinsic] public static Vector64 AsByte(this Vector64 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector64 AsDouble(this Vector64 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector64 AsInt16(this Vector64 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector64 AsInt32(this Vector64 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector64 AsInt64(this Vector64 vector) where T : struct { return vector.As(); } [Intrinsic] [CLSCompliant(false)] public static Vector64 AsSByte(this Vector64 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector64 AsSingle(this Vector64 vector) where T : struct { return vector.As(); } [Intrinsic] [CLSCompliant(false)] public static Vector64 AsUInt16(this Vector64 vector) where T : struct { return vector.As(); } [Intrinsic] [CLSCompliant(false)] public static Vector64 AsUInt32(this Vector64 vector) where T : struct { return vector.As(); } [Intrinsic] [CLSCompliant(false)] public static Vector64 AsUInt64(this Vector64 vector) where T : struct { return vector.As(); } [Intrinsic] public static Vector64 Create(byte value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); unsafe static Vector64 SoftwareFallback(byte value) { byte* source = stackalloc byte[8] { value, value, value, value, value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector64 Create(double value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); static Vector64 SoftwareFallback(double value) { return Unsafe.As>(ref value); } } [Intrinsic] public static Vector64 Create(short value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); unsafe static Vector64 SoftwareFallback(short value) { short* source = stackalloc short[4] { value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector64 Create(int value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); unsafe static Vector64 SoftwareFallback(int value) { int* source = stackalloc int[2] { value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector64 Create(long value) { if (AdvSimd.Arm64.IsSupported) { } return SoftwareFallback(value); static Vector64 SoftwareFallback(long value) { return Unsafe.As>(ref value); } } [Intrinsic] [CLSCompliant(false)] public static Vector64 Create(sbyte value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); unsafe static Vector64 SoftwareFallback(sbyte value) { sbyte* source = stackalloc sbyte[8] { value, value, value, value, value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector64 Create(float value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); unsafe static Vector64 SoftwareFallback(float value) { float* source = stackalloc float[2] { value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector64 Create(ushort value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); unsafe static Vector64 SoftwareFallback(ushort value) { ushort* source = stackalloc ushort[4] { value, value, value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector64 Create(uint value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); unsafe static Vector64 SoftwareFallback(uint value) { uint* source = stackalloc uint[2] { value, value }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector64 Create(ulong value) { if (AdvSimd.Arm64.IsSupported) { } return SoftwareFallback(value); static Vector64 SoftwareFallback(ulong value) { return Unsafe.As>(ref value); } } [Intrinsic] public static Vector64 Create(byte e0, byte e1, byte e2, byte e3, byte e4, byte e5, byte e6, byte e7) { if (AdvSimd.IsSupported) { } return SoftwareFallback(e0, e1, e2, e3, e4, e5, e6, e7); unsafe static Vector64 SoftwareFallback(byte e0, byte e1, byte e2, byte e3, byte e4, byte e5, byte e6, byte e7) { byte* source = stackalloc byte[8] { e0, e1, e2, e3, e4, e5, e6, e7 }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector64 Create(short e0, short e1, short e2, short e3) { if (AdvSimd.IsSupported) { } return SoftwareFallback(e0, e1, e2, e3); unsafe static Vector64 SoftwareFallback(short e0, short e1, short e2, short e3) { short* source = stackalloc short[4] { e0, e1, e2, e3 }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector64 Create(int e0, int e1) { if (AdvSimd.IsSupported) { } return SoftwareFallback(e0, e1); unsafe static Vector64 SoftwareFallback(int e0, int e1) { int* source = stackalloc int[2] { e0, e1 }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector64 Create(sbyte e0, sbyte e1, sbyte e2, sbyte e3, sbyte e4, sbyte e5, sbyte e6, sbyte e7) { if (AdvSimd.IsSupported) { } return SoftwareFallback(e0, e1, e2, e3, e4, e5, e6, e7); unsafe static Vector64 SoftwareFallback(sbyte e0, sbyte e1, sbyte e2, sbyte e3, sbyte e4, sbyte e5, sbyte e6, sbyte e7) { sbyte* source = stackalloc sbyte[8] { e0, e1, e2, e3, e4, e5, e6, e7 }; return Unsafe.AsRef>(source); } } [Intrinsic] public static Vector64 Create(float e0, float e1) { if (AdvSimd.IsSupported) { } return SoftwareFallback(e0, e1); unsafe static Vector64 SoftwareFallback(float e0, float e1) { float* source = stackalloc float[2] { e0, e1 }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector64 Create(ushort e0, ushort e1, ushort e2, ushort e3) { if (AdvSimd.IsSupported) { } return SoftwareFallback(e0, e1, e2, e3); unsafe static Vector64 SoftwareFallback(ushort e0, ushort e1, ushort e2, ushort e3) { ushort* source = stackalloc ushort[4] { e0, e1, e2, e3 }; return Unsafe.AsRef>(source); } } [Intrinsic] [CLSCompliant(false)] public static Vector64 Create(uint e0, uint e1) { if (AdvSimd.IsSupported) { } return SoftwareFallback(e0, e1); unsafe static Vector64 SoftwareFallback(uint e0, uint e1) { uint* source = stackalloc uint[2] { e0, e1 }; return Unsafe.AsRef>(source); } } public static Vector64 CreateScalar(byte value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); static Vector64 SoftwareFallback(byte value) { Vector64 source = Vector64.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } public static Vector64 CreateScalar(double value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); static Vector64 SoftwareFallback(double value) { return Unsafe.As>(ref value); } } public static Vector64 CreateScalar(short value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); static Vector64 SoftwareFallback(short value) { Vector64 source = Vector64.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } public static Vector64 CreateScalar(int value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); static Vector64 SoftwareFallback(int value) { Vector64 source = Vector64.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } public static Vector64 CreateScalar(long value) { if (AdvSimd.Arm64.IsSupported) { } return SoftwareFallback(value); static Vector64 SoftwareFallback(long value) { return Unsafe.As>(ref value); } } [CLSCompliant(false)] public static Vector64 CreateScalar(sbyte value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); static Vector64 SoftwareFallback(sbyte value) { Vector64 source = Vector64.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } public static Vector64 CreateScalar(float value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); static Vector64 SoftwareFallback(float value) { Vector64 source = Vector64.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [CLSCompliant(false)] public static Vector64 CreateScalar(ushort value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); static Vector64 SoftwareFallback(ushort value) { Vector64 source = Vector64.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [CLSCompliant(false)] public static Vector64 CreateScalar(uint value) { if (AdvSimd.IsSupported) { } return SoftwareFallback(value); static Vector64 SoftwareFallback(uint value) { Vector64 source = Vector64.Zero; Unsafe.WriteUnaligned(ref Unsafe.As, byte>(ref source), value); return source; } } [CLSCompliant(false)] public static Vector64 CreateScalar(ulong value) { if (AdvSimd.Arm64.IsSupported) { } return SoftwareFallback(value); static Vector64 SoftwareFallback(ulong value) { return Unsafe.As>(ref value); } } [Intrinsic] public unsafe static Vector64 CreateScalarUnsafe(byte value) { byte* ptr = stackalloc byte[8]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public unsafe static Vector64 CreateScalarUnsafe(short value) { short* ptr = stackalloc short[4]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public unsafe static Vector64 CreateScalarUnsafe(int value) { int* ptr = stackalloc int[2]; *ptr = value; return Unsafe.AsRef>(ptr); } [CLSCompliant(false)] [Intrinsic] public unsafe static Vector64 CreateScalarUnsafe(sbyte value) { sbyte* ptr = stackalloc sbyte[8]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public unsafe static Vector64 CreateScalarUnsafe(float value) { float* ptr = stackalloc float[2]; *ptr = value; return Unsafe.AsRef>(ptr); } [CLSCompliant(false)] [Intrinsic] public unsafe static Vector64 CreateScalarUnsafe(ushort value) { ushort* ptr = stackalloc ushort[4]; *ptr = value; return Unsafe.AsRef>(ptr); } [CLSCompliant(false)] [Intrinsic] public unsafe static Vector64 CreateScalarUnsafe(uint value) { uint* ptr = stackalloc uint[2]; *ptr = value; return Unsafe.AsRef>(ptr); } [Intrinsic] public static T GetElement(this Vector64 vector, int index) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); if ((uint)index >= (uint)Vector64.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } return Unsafe.Add(ref Unsafe.As, T>(ref vector), index); } [Intrinsic] public static Vector64 WithElement(this Vector64 vector, int index, T value) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); if ((uint)index >= (uint)Vector64.Count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index); } Vector64 source = vector; Unsafe.Add(ref Unsafe.As, T>(ref source), index) = value; return source; } [Intrinsic] public static T ToScalar(this Vector64 vector) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return Unsafe.As, T>(ref vector); } [Intrinsic] public static Vector128 ToVector128(this Vector64 vector) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); Vector128 source = Vector128.Zero; Unsafe.As, Vector64>(ref source) = vector; return source; } [Intrinsic] public unsafe static Vector128 ToVector128Unsafe(this Vector64 vector) where T : struct { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); byte* source = stackalloc byte[16]; Unsafe.AsRef>(source) = vector; return Unsafe.AsRef>(source); } } [StructLayout(LayoutKind.Sequential, Size = 8)] [Intrinsic] [DebuggerDisplay("{DisplayString,nq}")] [DebuggerTypeProxy(typeof(Vector64DebugView<>))] public readonly struct Vector64 : IEquatable> where T : struct { private readonly ulong _00; public static int Count { [Intrinsic] get { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return 8 / Unsafe.SizeOf(); } } public static Vector64 Zero { [Intrinsic] get { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return default(Vector64); } } public static Vector64 AllBitsSet { [Intrinsic] get { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); return Vector64.Create(uint.MaxValue).As(); } } internal string DisplayString { get { if (IsSupported) { return ToString(); } return SR.NotSupported_Type; } } internal static bool IsSupported { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if (!(typeof(T) == typeof(byte)) && !(typeof(T) == typeof(sbyte)) && !(typeof(T) == typeof(short)) && !(typeof(T) == typeof(ushort)) && !(typeof(T) == typeof(int)) && !(typeof(T) == typeof(uint)) && !(typeof(T) == typeof(long)) && !(typeof(T) == typeof(ulong)) && !(typeof(T) == typeof(float))) { return typeof(T) == typeof(double); } return true; } } public bool Equals(Vector64 other) { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); for (int i = 0; i < Count; i++) { if (!((IEquatable)(object)this.GetElement(i)).Equals(other.GetElement(i))) { return false; } } return true; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is Vector64) { return Equals((Vector64)obj); } return false; } public override int GetHashCode() { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); HashCode hashCode = default(HashCode); for (int i = 0; i < Count; i++) { hashCode.Add(this.GetElement(i).GetHashCode()); } return hashCode.ToHashCode(); } public override string ToString() { ThrowHelper.ThrowForUnsupportedIntrinsicsVectorBaseType(); int num = Count - 1; Span initialBuffer = stackalloc char[64]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); CultureInfo invariantCulture = CultureInfo.InvariantCulture; valueStringBuilder.Append('<'); for (int i = 0; i < num; i++) { valueStringBuilder.Append(((IFormattable)(object)this.GetElement(i)).ToString("G", invariantCulture)); valueStringBuilder.Append(','); valueStringBuilder.Append(' '); } valueStringBuilder.Append(((IFormattable)(object)this.GetElement(num)).ToString("G", invariantCulture)); valueStringBuilder.Append('>'); return valueStringBuilder.ToString(); } } internal readonly struct Vector64DebugView where T : struct { private readonly Vector64 _value; public byte[] ByteView { get { byte[] array = new byte[8]; Unsafe.WriteUnaligned(ref array[0], _value); return array; } } public double[] DoubleView { get { double[] array = new double[1]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public short[] Int16View { get { short[] array = new short[4]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public int[] Int32View { get { int[] array = new int[2]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public long[] Int64View { get { long[] array = new long[1]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public sbyte[] SByteView { get { sbyte[] array = new sbyte[8]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public float[] SingleView { get { float[] array = new float[2]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public ushort[] UInt16View { get { ushort[] array = new ushort[4]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public uint[] UInt32View { get { uint[] array = new uint[2]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public ulong[] UInt64View { get { ulong[] array = new ulong[1]; Unsafe.WriteUnaligned(ref Unsafe.As(ref array[0]), _value); return array; } } public Vector64DebugView(Vector64 value) { _value = value; } } } namespace System.Runtime.Intrinsics.Arm { [CLSCompliant(false)] public abstract class AdvSimd : ArmBase { public new abstract class Arm64 : ArmBase.Arm64 { public new static bool IsSupported { [Intrinsic] get { return false; } } public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 AbsSaturate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AbsSaturateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AbsSaturateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AbsSaturateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AbsSaturateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AbsScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteCompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteCompareGreaterThanScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteCompareGreaterThanScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteCompareGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteCompareGreaterThanOrEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteCompareGreaterThanOrEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteCompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteCompareLessThanScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteCompareLessThanScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteCompareLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteCompareLessThanOrEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteCompareLessThanOrEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifference(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifferenceScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifferenceScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcross(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcross(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcross(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcross(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcrossWidening(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcrossWidening(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcrossWidening(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcrossWidening(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcrossWidening(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcrossWidening(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcrossWidening(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcrossWidening(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcrossWidening(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddAcrossWidening(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseScalar(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseScalar(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseScalar(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 Ceiling(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanOrEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanOrEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanOrEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanOrEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanOrEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanOrEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanOrEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanOrEqualScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareTest(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareTest(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareTest(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareTestScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareTestScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareTestScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToDouble(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToDouble(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToDouble(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToDoubleScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToDoubleScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToDoubleUpper(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToInt64RoundAwayFromZero(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt64RoundAwayFromZeroScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToInt64RoundToEven(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt64RoundToEvenScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToInt64RoundToNegativeInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt64RoundToNegativeInfinityScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToInt64RoundToPositiveInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt64RoundToPositiveInfinityScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToInt64RoundToZero(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt64RoundToZeroScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToSingleLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToSingleRoundToOddLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToSingleRoundToOddUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToSingleUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToUInt64RoundAwayFromZero(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt64RoundAwayFromZeroScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToUInt64RoundToEven(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt64RoundToEvenScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToUInt64RoundToNegativeInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt64RoundToNegativeInfinityScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToUInt64RoundToPositiveInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt64RoundToPositiveInfinityScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToUInt64RoundToZero(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt64RoundToZeroScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Divide(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 Divide(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Divide(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateToVector128(double value) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateToVector128(long value) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateToVector128(ulong value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateUnsignedScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateUnsignedScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateUnsignedScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 Floor(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 FusedMultiplyAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplyAddByScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedMultiplyAddByScalar(Vector128 addend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedMultiplyAddByScalar(Vector128 addend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplyAddBySelectedScalar(Vector64 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplyAddBySelectedScalar(Vector64 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 FusedMultiplyAddBySelectedScalar(Vector128 addend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 FusedMultiplyAddBySelectedScalar(Vector128 addend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 FusedMultiplyAddBySelectedScalar(Vector128 addend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplyAddScalarBySelectedScalar(Vector64 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplyAddScalarBySelectedScalar(Vector64 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplyAddScalarBySelectedScalar(Vector64 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 FusedMultiplySubtract(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplySubtractByScalar(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedMultiplySubtractByScalar(Vector128 minuend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedMultiplySubtractByScalar(Vector128 minuend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplySubtractBySelectedScalar(Vector64 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplySubtractBySelectedScalar(Vector64 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 FusedMultiplySubtractBySelectedScalar(Vector128 minuend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 FusedMultiplySubtractBySelectedScalar(Vector128 minuend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 FusedMultiplySubtractBySelectedScalar(Vector128 minuend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplySubtractScalarBySelectedScalar(Vector64 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplySubtractScalarBySelectedScalar(Vector64 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplySubtractScalarBySelectedScalar(Vector64 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 InsertSelectedScalar(Vector64 result, byte resultIndex, Vector64 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector64 InsertSelectedScalar(Vector64 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector64 InsertSelectedScalar(Vector64 result, byte resultIndex, Vector64 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector64 InsertSelectedScalar(Vector64 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector64 InsertSelectedScalar(Vector64 result, byte resultIndex, Vector64 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector64 InsertSelectedScalar(Vector64 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector64 InsertSelectedScalar(Vector64 result, byte resultIndex, Vector64 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector64 InsertSelectedScalar(Vector64 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector64 InsertSelectedScalar(Vector64 result, byte resultIndex, Vector64 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector64 InsertSelectedScalar(Vector64 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector64 InsertSelectedScalar(Vector64 result, byte resultIndex, Vector64 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector64 InsertSelectedScalar(Vector64 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector64 InsertSelectedScalar(Vector64 result, byte resultIndex, Vector64 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector64 InsertSelectedScalar(Vector64 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector64 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector64 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector64 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector64 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector64 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector64 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector64 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public static Vector128 InsertSelectedScalar(Vector128 result, byte resultIndex, Vector128 value, byte valueIndex) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndReplicateToVector128(double* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndReplicateToVector128(long* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndReplicateToVector128(ulong* address) { throw new PlatformNotSupportedException(); } public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxAcross(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 MaxAcross(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 MaxAcross(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 MaxAcross(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 MaxAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MaxAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MaxAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MaxAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MaxAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MaxAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MaxAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 MaxNumber(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxNumberAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MaxNumberPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MaxNumberPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MaxNumberPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxNumberPairwiseScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 MaxNumberPairwiseScalar(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 MaxPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MaxPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MaxPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MaxPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MaxPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MaxPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MaxPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MaxPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxPairwiseScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 MaxPairwiseScalar(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MaxScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinAcross(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 MinAcross(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 MinAcross(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 MinAcross(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 MinAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MinAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MinAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MinAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MinAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MinAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MinAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 MinNumber(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinNumberAcross(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MinNumberPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MinNumberPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MinNumberPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinNumberPairwiseScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 MinNumberPairwiseScalar(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 MinPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MinPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MinPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MinPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MinPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MinPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MinPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MinPairwise(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinPairwiseScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 MinPairwiseScalar(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 MinScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyByScalar(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalar(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingSaturateHighScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingSaturateHighScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingScalarBySelectedScalarSaturateHigh(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingScalarBySelectedScalarSaturateHigh(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingScalarBySelectedScalarSaturateHigh(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingScalarBySelectedScalarSaturateHigh(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningAndAddSaturateScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningAndAddSaturateScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningAndSubtractSaturateScalar(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningAndSubtractSaturateScalar(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningSaturateScalarBySelectedScalar(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningSaturateScalarBySelectedScalar(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningSaturateScalarBySelectedScalar(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningSaturateScalarBySelectedScalar(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningScalarBySelectedScalarAndAddSaturate(Vector64 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningScalarBySelectedScalarAndAddSaturate(Vector64 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningScalarBySelectedScalarAndAddSaturate(Vector64 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningScalarBySelectedScalarAndAddSaturate(Vector64 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningScalarBySelectedScalarAndSubtractSaturate(Vector64 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningScalarBySelectedScalarAndSubtractSaturate(Vector64 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningScalarBySelectedScalarAndSubtractSaturate(Vector64 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingWideningScalarBySelectedScalarAndSubtractSaturate(Vector64 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyExtended(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyExtended(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyExtended(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyExtendedByScalar(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyExtendedBySelectedScalar(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyExtendedBySelectedScalar(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyExtendedBySelectedScalar(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyExtendedBySelectedScalar(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyExtendedBySelectedScalar(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyExtendedScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyExtendedScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyExtendedScalarBySelectedScalar(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyExtendedScalarBySelectedScalar(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyExtendedScalarBySelectedScalar(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingSaturateHighScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingSaturateHighScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingScalarBySelectedScalarSaturateHigh(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyScalarBySelectedScalar(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 Negate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Negate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 NegateSaturate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 NegateSaturateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 NegateSaturateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 NegateSaturateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 NegateSaturateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 NegateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReciprocalEstimate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalEstimateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalEstimateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalExponentScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalExponentScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReciprocalSquareRootEstimate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalSquareRootEstimateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalSquareRootEstimateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReciprocalSquareRootStep(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalSquareRootStepScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalSquareRootStepScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 ReciprocalStep(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalStepScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalStepScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 RoundAwayFromZero(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 RoundToNearest(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 RoundToNegativeInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 RoundToPositiveInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 RoundToZero(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticRoundedSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticRoundedSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticRoundedSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateUnsignedScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateUnsignedScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateUnsignedScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticNarrowingSaturateUnsignedScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticNarrowingSaturateUnsignedScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticNarrowingSaturateUnsignedScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedNarrowingSaturateUnsignedScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedNarrowingSaturateUnsignedScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedNarrowingSaturateUnsignedScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 Sqrt(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 Sqrt(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Sqrt(Vector128 value) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(byte* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(double* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(short* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(int* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(long* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(sbyte* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(float* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(ushort* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(uint* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(ulong* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(byte* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(double* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(short* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(int* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(long* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(sbyte* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(float* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(ushort* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(uint* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePair(ulong* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(byte* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(double* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(short* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(int* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(long* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(sbyte* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(float* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(ushort* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(uint* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(ulong* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(byte* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(double* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(short* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(int* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(long* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(sbyte* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(float* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(ushort* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(uint* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairNonTemporal(ulong* address, Vector128 value1, Vector128 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairScalar(int* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairScalar(float* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairScalar(uint* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairScalarNonTemporal(int* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairScalarNonTemporal(float* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public unsafe static void StorePairScalarNonTemporal(uint* address, Vector64 value1, Vector64 value2) { throw new PlatformNotSupportedException(); } public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ReverseElementBits(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReverseElementBits(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReverseElementBits(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReverseElementBits(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 TransposeEven(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 TransposeEven(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 TransposeEven(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 TransposeEven(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 TransposeEven(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 TransposeEven(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 TransposeEven(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 TransposeOdd(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 TransposeOdd(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 TransposeOdd(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 TransposeOdd(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 TransposeOdd(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 TransposeOdd(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 TransposeOdd(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 TransposeOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 UnzipEven(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 UnzipEven(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 UnzipEven(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 UnzipEven(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 UnzipEven(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 UnzipEven(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 UnzipEven(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipEven(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 UnzipOdd(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 UnzipOdd(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 UnzipOdd(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 UnzipOdd(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 UnzipOdd(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 UnzipOdd(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 UnzipOdd(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 UnzipOdd(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 VectorTableLookup(Vector128 table, Vector128 byteIndexes) { throw new PlatformNotSupportedException(); } public static Vector128 VectorTableLookup(Vector128 table, Vector128 byteIndexes) { throw new PlatformNotSupportedException(); } public static Vector128 VectorTableLookupExtension(Vector128 defaultValues, Vector128 table, Vector128 byteIndexes) { throw new PlatformNotSupportedException(); } public static Vector128 VectorTableLookupExtension(Vector128 defaultValues, Vector128 table, Vector128 byteIndexes) { throw new PlatformNotSupportedException(); } public static Vector64 ZipHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ZipHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ZipHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ZipHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ZipHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ZipHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ZipHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 ZipLow(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ZipLow(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ZipLow(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ZipLow(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ZipLow(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ZipLow(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 ZipLow(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZipLow(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } } public new static bool IsSupported { [Intrinsic] get { return false; } } public static Vector64 Abs(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Abs(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Abs(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Abs(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Abs(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AbsSaturate(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AbsSaturate(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AbsSaturate(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 AbsSaturate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 AbsSaturate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 AbsSaturate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AbsScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AbsScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteCompareGreaterThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteCompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteCompareGreaterThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteCompareGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteCompareLessThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteCompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteCompareLessThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteCompareLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifference(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifference(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifference(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifference(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifference(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifference(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifference(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifference(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifference(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifference(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifference(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifference(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifference(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifference(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifferenceAdd(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifferenceAdd(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifferenceAdd(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifferenceAdd(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifferenceAdd(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AbsoluteDifferenceAdd(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AbsoluteDifferenceWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 Add(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Add(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Add(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Add(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Add(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Add(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Add(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Add(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseWidening(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseWidening(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseWidening(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseWidening(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwiseWidening(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwiseWidening(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwiseWidening(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwiseWidening(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwiseWidening(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwiseWidening(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseWideningAndAdd(Vector64 addend, Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseWideningAndAdd(Vector64 addend, Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseWideningAndAdd(Vector64 addend, Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseWideningAndAdd(Vector64 addend, Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwiseWideningAndAdd(Vector128 addend, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwiseWideningAndAdd(Vector128 addend, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwiseWideningAndAdd(Vector128 addend, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwiseWideningAndAdd(Vector128 addend, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwiseWideningAndAdd(Vector128 addend, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 AddPairwiseWideningAndAdd(Vector128 addend, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseWideningAndAddScalar(Vector64 addend, Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseWideningAndAddScalar(Vector64 addend, Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseWideningScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddPairwiseWideningScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 AddRoundedHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddRoundedHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddRoundedHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddRoundedHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddRoundedHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddRoundedHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddRoundedHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddRoundedHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddRoundedHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddRoundedHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddRoundedHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddRoundedHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 AddScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningLower(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningLower(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningLower(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningLower(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningLower(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningLower(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 AddWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 And(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 And(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 And(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 And(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 And(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 And(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 And(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 And(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 And(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 And(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 And(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseClear(Vector64 value, Vector64 mask) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseClear(Vector64 value, Vector64 mask) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseClear(Vector64 value, Vector64 mask) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseClear(Vector64 value, Vector64 mask) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseClear(Vector64 value, Vector64 mask) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseClear(Vector64 value, Vector64 mask) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseClear(Vector64 value, Vector64 mask) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseClear(Vector64 value, Vector64 mask) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseClear(Vector64 value, Vector64 mask) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseClear(Vector64 value, Vector64 mask) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseClear(Vector128 value, Vector128 mask) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseClear(Vector128 value, Vector128 mask) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseClear(Vector128 value, Vector128 mask) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseClear(Vector128 value, Vector128 mask) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseClear(Vector128 value, Vector128 mask) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseClear(Vector128 value, Vector128 mask) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseClear(Vector128 value, Vector128 mask) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseClear(Vector128 value, Vector128 mask) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseClear(Vector128 value, Vector128 mask) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseClear(Vector128 value, Vector128 mask) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseSelect(Vector64 select, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseSelect(Vector64 select, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseSelect(Vector64 select, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseSelect(Vector64 select, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseSelect(Vector64 select, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseSelect(Vector64 select, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseSelect(Vector64 select, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseSelect(Vector64 select, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseSelect(Vector64 select, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 BitwiseSelect(Vector64 select, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseSelect(Vector128 select, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseSelect(Vector128 select, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseSelect(Vector128 select, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseSelect(Vector128 select, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseSelect(Vector128 select, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseSelect(Vector128 select, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseSelect(Vector128 select, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseSelect(Vector128 select, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseSelect(Vector128 select, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 BitwiseSelect(Vector128 select, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 Ceiling(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 Ceiling(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 CeilingScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 CeilingScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 CompareEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareGreaterThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThan(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareLessThanOrEqual(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareTest(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareTest(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareTest(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareTest(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareTest(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareTest(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 CompareTest(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareTest(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareTest(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareTest(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareTest(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareTest(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareTest(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 CompareTest(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt32RoundAwayFromZero(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToInt32RoundAwayFromZero(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt32RoundAwayFromZeroScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt32RoundToEven(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToInt32RoundToEven(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt32RoundToEvenScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt32RoundToNegativeInfinity(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToInt32RoundToNegativeInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt32RoundToNegativeInfinityScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt32RoundToPositiveInfinity(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToInt32RoundToPositiveInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt32RoundToPositiveInfinityScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt32RoundToZero(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToInt32RoundToZero(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToInt32RoundToZeroScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToSingle(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToSingle(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToSingle(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToSingle(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToSingleScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToSingleScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt32RoundAwayFromZero(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToUInt32RoundAwayFromZero(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt32RoundAwayFromZeroScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt32RoundToEven(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToUInt32RoundToEven(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt32RoundToEvenScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt32RoundToNegativeInfinity(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToUInt32RoundToNegativeInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt32RoundToNegativeInfinityScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt32RoundToPositiveInfinity(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToUInt32RoundToPositiveInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt32RoundToPositiveInfinityScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt32RoundToZero(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ConvertToUInt32RoundToZero(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ConvertToUInt32RoundToZeroScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 DivideScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 DivideScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateSelectedScalarToVector64(Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateSelectedScalarToVector64(Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateSelectedScalarToVector64(Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateSelectedScalarToVector64(Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateSelectedScalarToVector64(Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateSelectedScalarToVector64(Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateSelectedScalarToVector64(Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateSelectedScalarToVector64(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateSelectedScalarToVector64(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateSelectedScalarToVector64(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateSelectedScalarToVector64(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateSelectedScalarToVector64(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateSelectedScalarToVector64(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateSelectedScalarToVector64(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateSelectedScalarToVector128(Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateToVector64(byte value) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateToVector64(short value) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateToVector64(int value) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateToVector64(sbyte value) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateToVector64(float value) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateToVector64(ushort value) { throw new PlatformNotSupportedException(); } public static Vector64 DuplicateToVector64(uint value) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateToVector128(byte value) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateToVector128(short value) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateToVector128(int value) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateToVector128(sbyte value) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateToVector128(float value) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateToVector128(ushort value) { throw new PlatformNotSupportedException(); } public static Vector128 DuplicateToVector128(uint value) { throw new PlatformNotSupportedException(); } public static byte Extract(Vector64 vector, byte index) { throw new PlatformNotSupportedException(); } public static short Extract(Vector64 vector, byte index) { throw new PlatformNotSupportedException(); } public static int Extract(Vector64 vector, byte index) { throw new PlatformNotSupportedException(); } public static sbyte Extract(Vector64 vector, byte index) { throw new PlatformNotSupportedException(); } public static float Extract(Vector64 vector, byte index) { throw new PlatformNotSupportedException(); } public static ushort Extract(Vector64 vector, byte index) { throw new PlatformNotSupportedException(); } public static uint Extract(Vector64 vector, byte index) { throw new PlatformNotSupportedException(); } public static byte Extract(Vector128 vector, byte index) { throw new PlatformNotSupportedException(); } public static double Extract(Vector128 vector, byte index) { throw new PlatformNotSupportedException(); } public static short Extract(Vector128 vector, byte index) { throw new PlatformNotSupportedException(); } public static int Extract(Vector128 vector, byte index) { throw new PlatformNotSupportedException(); } public static long Extract(Vector128 vector, byte index) { throw new PlatformNotSupportedException(); } public static sbyte Extract(Vector128 vector, byte index) { throw new PlatformNotSupportedException(); } public static float Extract(Vector128 vector, byte index) { throw new PlatformNotSupportedException(); } public static ushort Extract(Vector128 vector, byte index) { throw new PlatformNotSupportedException(); } public static uint Extract(Vector128 vector, byte index) { throw new PlatformNotSupportedException(); } public static ulong Extract(Vector128 vector, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateUnsignedLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateUnsignedLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractNarrowingSaturateUnsignedLower(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingSaturateUnsignedUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingSaturateUnsignedUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingSaturateUnsignedUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingSaturateUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingSaturateUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingSaturateUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingSaturateUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingSaturateUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingSaturateUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractNarrowingUpper(Vector64 lower, Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractVector64(Vector64 upper, Vector64 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractVector64(Vector64 upper, Vector64 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractVector64(Vector64 upper, Vector64 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractVector64(Vector64 upper, Vector64 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractVector64(Vector64 upper, Vector64 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractVector64(Vector64 upper, Vector64 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 ExtractVector64(Vector64 upper, Vector64 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractVector128(Vector128 upper, Vector128 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractVector128(Vector128 upper, Vector128 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractVector128(Vector128 upper, Vector128 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractVector128(Vector128 upper, Vector128 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractVector128(Vector128 upper, Vector128 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractVector128(Vector128 upper, Vector128 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractVector128(Vector128 upper, Vector128 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractVector128(Vector128 upper, Vector128 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractVector128(Vector128 upper, Vector128 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector128 ExtractVector128(Vector128 upper, Vector128 lower, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 Floor(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 Floor(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 FloorScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 FloorScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 FusedAddHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedAddHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedAddHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedAddHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedAddHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedAddHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedAddHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedAddHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedAddHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedAddHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedAddHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedAddHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedAddRoundedHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedAddRoundedHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedAddRoundedHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedAddRoundedHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedAddRoundedHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedAddRoundedHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedAddRoundedHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedAddRoundedHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedAddRoundedHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedAddRoundedHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedAddRoundedHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedAddRoundedHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplyAdd(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedMultiplyAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplyAddNegatedScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplyAddNegatedScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplyAddScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplyAddScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplySubtract(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedMultiplySubtract(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplySubtractNegatedScalar(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplySubtractNegatedScalar(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplySubtractScalar(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedMultiplySubtractScalar(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedSubtractHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedSubtractHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedSubtractHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedSubtractHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedSubtractHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 FusedSubtractHalving(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedSubtractHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedSubtractHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedSubtractHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedSubtractHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedSubtractHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 FusedSubtractHalving(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 Insert(Vector64 vector, byte index, byte data) { throw new PlatformNotSupportedException(); } public static Vector64 Insert(Vector64 vector, byte index, short data) { throw new PlatformNotSupportedException(); } public static Vector64 Insert(Vector64 vector, byte index, int data) { throw new PlatformNotSupportedException(); } public static Vector64 Insert(Vector64 vector, byte index, sbyte data) { throw new PlatformNotSupportedException(); } public static Vector64 Insert(Vector64 vector, byte index, float data) { throw new PlatformNotSupportedException(); } public static Vector64 Insert(Vector64 vector, byte index, ushort data) { throw new PlatformNotSupportedException(); } public static Vector64 Insert(Vector64 vector, byte index, uint data) { throw new PlatformNotSupportedException(); } public static Vector128 Insert(Vector128 vector, byte index, byte data) { throw new PlatformNotSupportedException(); } public static Vector128 Insert(Vector128 vector, byte index, double data) { throw new PlatformNotSupportedException(); } public static Vector128 Insert(Vector128 vector, byte index, short data) { throw new PlatformNotSupportedException(); } public static Vector128 Insert(Vector128 vector, byte index, int data) { throw new PlatformNotSupportedException(); } public static Vector128 Insert(Vector128 vector, byte index, long data) { throw new PlatformNotSupportedException(); } public static Vector128 Insert(Vector128 vector, byte index, sbyte data) { throw new PlatformNotSupportedException(); } public static Vector128 Insert(Vector128 vector, byte index, float data) { throw new PlatformNotSupportedException(); } public static Vector128 Insert(Vector128 vector, byte index, ushort data) { throw new PlatformNotSupportedException(); } public static Vector128 Insert(Vector128 vector, byte index, uint data) { throw new PlatformNotSupportedException(); } public static Vector128 Insert(Vector128 vector, byte index, ulong data) { throw new PlatformNotSupportedException(); } public static Vector128 InsertScalar(Vector128 result, byte resultIndex, Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 InsertScalar(Vector128 result, byte resultIndex, Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 InsertScalar(Vector128 result, byte resultIndex, Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 LeadingSignCount(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 LeadingSignCount(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 LeadingSignCount(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 LeadingSignCount(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 LeadingSignCount(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 LeadingSignCount(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 LeadingZeroCount(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 LeadingZeroCount(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 LeadingZeroCount(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 LeadingZeroCount(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 LeadingZeroCount(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 LeadingZeroCount(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 LeadingZeroCount(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 LeadingZeroCount(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 LeadingZeroCount(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 LeadingZeroCount(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 LeadingZeroCount(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 LeadingZeroCount(Vector128 value) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadAndInsertScalar(Vector64 value, byte index, byte* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadAndInsertScalar(Vector64 value, byte index, short* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadAndInsertScalar(Vector64 value, byte index, int* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadAndInsertScalar(Vector64 value, byte index, sbyte* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadAndInsertScalar(Vector64 value, byte index, float* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadAndInsertScalar(Vector64 value, byte index, ushort* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadAndInsertScalar(Vector64 value, byte index, uint* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndInsertScalar(Vector128 value, byte index, byte* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndInsertScalar(Vector128 value, byte index, double* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndInsertScalar(Vector128 value, byte index, short* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndInsertScalar(Vector128 value, byte index, int* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndInsertScalar(Vector128 value, byte index, long* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndInsertScalar(Vector128 value, byte index, sbyte* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndInsertScalar(Vector128 value, byte index, float* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndInsertScalar(Vector128 value, byte index, ushort* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndInsertScalar(Vector128 value, byte index, uint* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndInsertScalar(Vector128 value, byte index, ulong* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadAndReplicateToVector64(byte* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadAndReplicateToVector64(short* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadAndReplicateToVector64(int* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadAndReplicateToVector64(sbyte* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadAndReplicateToVector64(float* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadAndReplicateToVector64(ushort* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadAndReplicateToVector64(uint* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndReplicateToVector128(byte* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndReplicateToVector128(short* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndReplicateToVector128(int* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndReplicateToVector128(sbyte* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndReplicateToVector128(float* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndReplicateToVector128(ushort* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadAndReplicateToVector128(uint* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadVector64(byte* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadVector64(double* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadVector64(short* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadVector64(int* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadVector64(long* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadVector64(sbyte* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadVector64(float* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadVector64(ushort* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadVector64(uint* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector64 LoadVector64(ulong* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadVector128(byte* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadVector128(double* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadVector128(short* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadVector128(int* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadVector128(long* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadVector128(sbyte* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadVector128(float* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadVector128(ushort* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadVector128(uint* address) { throw new PlatformNotSupportedException(); } public unsafe static Vector128 LoadVector128(ulong* address) { throw new PlatformNotSupportedException(); } public static Vector64 Max(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Max(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Max(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Max(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Max(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Max(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Max(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Max(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxNumber(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MaxNumber(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxNumberScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxNumberScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MaxPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Min(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Min(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Min(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Min(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Min(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Min(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Min(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Min(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinNumber(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MinNumber(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinNumberScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinNumberScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MinPairwise(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Multiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Multiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Multiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Multiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Multiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Multiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Multiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Multiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAdd(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAdd(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAdd(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAdd(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAdd(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAdd(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAddByScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAddByScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAddByScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAddByScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAddByScalar(Vector128 addend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAddByScalar(Vector128 addend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAddByScalar(Vector128 addend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAddByScalar(Vector128 addend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAddBySelectedScalar(Vector64 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAddBySelectedScalar(Vector64 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAddBySelectedScalar(Vector64 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAddBySelectedScalar(Vector64 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAddBySelectedScalar(Vector64 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAddBySelectedScalar(Vector64 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAddBySelectedScalar(Vector64 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyAddBySelectedScalar(Vector64 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAddBySelectedScalar(Vector128 addend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAddBySelectedScalar(Vector128 addend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAddBySelectedScalar(Vector128 addend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAddBySelectedScalar(Vector128 addend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAddBySelectedScalar(Vector128 addend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAddBySelectedScalar(Vector128 addend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAddBySelectedScalar(Vector128 addend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyAddBySelectedScalar(Vector128 addend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyByScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyByScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyByScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyByScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyByScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyByScalar(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyByScalar(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyByScalar(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyByScalar(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyByScalar(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyBySelectedScalar(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyBySelectedScalar(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyBySelectedScalar(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyBySelectedScalar(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyBySelectedScalar(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyBySelectedScalar(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyBySelectedScalar(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyBySelectedScalar(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyBySelectedScalar(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyBySelectedScalar(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalar(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalar(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalar(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalar(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalar(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalar(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalar(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalar(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalar(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalar(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLower(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLower(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLower(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLower(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLower(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLower(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLower(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLower(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndSubtract(Vector128 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndSubtract(Vector128 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndSubtract(Vector128 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndSubtract(Vector128 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndSubtract(Vector128 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndSubtract(Vector128 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndSubtract(Vector128 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningLowerAndSubtract(Vector128 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpper(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpper(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpper(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpper(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpper(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpper(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpper(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpper(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndSubtract(Vector128 minuend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndSubtract(Vector128 minuend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndSubtract(Vector128 minuend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndSubtract(Vector128 minuend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndSubtract(Vector128 minuend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndSubtract(Vector128 minuend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndSubtract(Vector128 minuend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyBySelectedScalarWideningUpperAndSubtract(Vector128 minuend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingByScalarSaturateHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingByScalarSaturateHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingByScalarSaturateHigh(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingByScalarSaturateHigh(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingBySelectedScalarSaturateHigh(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingBySelectedScalarSaturateHigh(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingBySelectedScalarSaturateHigh(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingBySelectedScalarSaturateHigh(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingBySelectedScalarSaturateHigh(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingBySelectedScalarSaturateHigh(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingBySelectedScalarSaturateHigh(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingBySelectedScalarSaturateHigh(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingSaturateHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyDoublingSaturateHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingSaturateHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingSaturateHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerAndAddSaturate(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerAndAddSaturate(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerAndSubtractSaturate(Vector128 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerAndSubtractSaturate(Vector128 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerByScalarAndAddSaturate(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerByScalarAndAddSaturate(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerByScalarAndSubtractSaturate(Vector128 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerByScalarAndSubtractSaturate(Vector128 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerBySelectedScalarAndAddSaturate(Vector128 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerBySelectedScalarAndAddSaturate(Vector128 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerBySelectedScalarAndAddSaturate(Vector128 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerBySelectedScalarAndAddSaturate(Vector128 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerBySelectedScalarAndSubtractSaturate(Vector128 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerBySelectedScalarAndSubtractSaturate(Vector128 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerBySelectedScalarAndSubtractSaturate(Vector128 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningLowerBySelectedScalarAndSubtractSaturate(Vector128 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateLowerByScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateLowerByScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateLowerBySelectedScalar(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateLowerBySelectedScalar(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateLowerBySelectedScalar(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateLowerBySelectedScalar(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateUpperByScalar(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateUpperByScalar(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateUpperBySelectedScalar(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateUpperBySelectedScalar(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateUpperBySelectedScalar(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningSaturateUpperBySelectedScalar(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperAndAddSaturate(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperAndAddSaturate(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperAndSubtractSaturate(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperAndSubtractSaturate(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperByScalarAndAddSaturate(Vector128 addend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperByScalarAndAddSaturate(Vector128 addend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperByScalarAndSubtractSaturate(Vector128 minuend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperByScalarAndSubtractSaturate(Vector128 minuend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperBySelectedScalarAndAddSaturate(Vector128 addend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperBySelectedScalarAndAddSaturate(Vector128 addend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperBySelectedScalarAndAddSaturate(Vector128 addend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperBySelectedScalarAndAddSaturate(Vector128 addend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(Vector128 minuend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(Vector128 minuend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(Vector128 minuend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyDoublingWideningUpperBySelectedScalarAndSubtractSaturate(Vector128 minuend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingByScalarSaturateHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingByScalarSaturateHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingByScalarSaturateHigh(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingByScalarSaturateHigh(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingBySelectedScalarSaturateHigh(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingBySelectedScalarSaturateHigh(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingBySelectedScalarSaturateHigh(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingBySelectedScalarSaturateHigh(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingBySelectedScalarSaturateHigh(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingBySelectedScalarSaturateHigh(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingBySelectedScalarSaturateHigh(Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingBySelectedScalarSaturateHigh(Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingSaturateHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingSaturateHigh(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingSaturateHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingSaturateHigh(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyScalarBySelectedScalar(Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyScalarBySelectedScalar(Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtract(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtract(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtract(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtract(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtract(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtract(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtract(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtract(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtract(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtract(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtract(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtract(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtractByScalar(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtractByScalar(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtractByScalar(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtractByScalar(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtractByScalar(Vector128 minuend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtractByScalar(Vector128 minuend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtractByScalar(Vector128 minuend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtractByScalar(Vector128 minuend, Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtractBySelectedScalar(Vector64 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtractBySelectedScalar(Vector64 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtractBySelectedScalar(Vector64 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtractBySelectedScalar(Vector64 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtractBySelectedScalar(Vector64 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtractBySelectedScalar(Vector64 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtractBySelectedScalar(Vector64 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplySubtractBySelectedScalar(Vector64 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtractBySelectedScalar(Vector128 minuend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtractBySelectedScalar(Vector128 minuend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtractBySelectedScalar(Vector128 minuend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtractBySelectedScalar(Vector128 minuend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtractBySelectedScalar(Vector128 minuend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtractBySelectedScalar(Vector128 minuend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtractBySelectedScalar(Vector128 minuend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplySubtractBySelectedScalar(Vector128 minuend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLowerAndAdd(Vector128 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLowerAndSubtract(Vector128 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLowerAndSubtract(Vector128 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLowerAndSubtract(Vector128 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLowerAndSubtract(Vector128 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLowerAndSubtract(Vector128 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningLowerAndSubtract(Vector128 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpperAndAdd(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpperAndSubtract(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpperAndSubtract(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpperAndSubtract(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpperAndSubtract(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpperAndSubtract(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyWideningUpperAndSubtract(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 Negate(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Negate(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Negate(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Negate(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 Negate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Negate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Negate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Negate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 NegateSaturate(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 NegateSaturate(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 NegateSaturate(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 NegateSaturate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 NegateSaturate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 NegateSaturate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 NegateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 NegateScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Not(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Not(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Not(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Not(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Not(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Not(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Not(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Not(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Not(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 Not(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 Not(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Not(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Not(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Not(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Not(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Not(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Not(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Not(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Not(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 Not(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 Or(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Or(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Or(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Or(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Or(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Or(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Or(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Or(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Or(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Or(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Or(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 OrNot(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 OrNot(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 OrNot(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 OrNot(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 OrNot(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 OrNot(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 OrNot(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 OrNot(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 OrNot(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 OrNot(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 OrNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 OrNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 OrNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 OrNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 OrNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 OrNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 OrNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 OrNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 OrNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 OrNot(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 PolynomialMultiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 PolynomialMultiply(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 PolynomialMultiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 PolynomialMultiply(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 PolynomialMultiplyWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 PolynomialMultiplyWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 PolynomialMultiplyWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 PolynomialMultiplyWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 PopCount(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 PopCount(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 PopCount(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 PopCount(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalEstimate(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalEstimate(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReciprocalEstimate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReciprocalEstimate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalSquareRootEstimate(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalSquareRootEstimate(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReciprocalSquareRootEstimate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReciprocalSquareRootEstimate(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalSquareRootStep(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 ReciprocalSquareRootStep(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 ReciprocalStep(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 ReciprocalStep(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 ReverseElement16(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReverseElement16(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReverseElement16(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReverseElement16(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReverseElement16(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReverseElement16(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReverseElement16(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReverseElement16(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReverseElement32(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReverseElement32(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReverseElement32(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReverseElement32(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReverseElement8(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReverseElement8(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReverseElement8(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReverseElement8(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReverseElement8(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ReverseElement8(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReverseElement8(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReverseElement8(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReverseElement8(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReverseElement8(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReverseElement8(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ReverseElement8(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundAwayFromZero(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 RoundAwayFromZero(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundAwayFromZeroScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundAwayFromZeroScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundToNearest(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 RoundToNearest(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundToNearestScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundToNearestScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundToNegativeInfinity(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 RoundToNegativeInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundToNegativeInfinityScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundToNegativeInfinityScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundToPositiveInfinity(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 RoundToPositiveInfinity(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundToPositiveInfinityScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundToPositiveInfinityScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundToZero(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 RoundToZero(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundToZeroScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 RoundToZeroScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmetic(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmetic(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmetic(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmetic(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmetic(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmetic(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmetic(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticRounded(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticRounded(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticRounded(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmeticRounded(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmeticRounded(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmeticRounded(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmeticRounded(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticRoundedSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticRoundedSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticRoundedSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmeticRoundedSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmeticRoundedSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmeticRoundedSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmeticRoundedSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticRoundedSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticRoundedScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmeticSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmeticSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmeticSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftArithmeticSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftArithmeticScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftAndInsert(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftAndInsert(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftAndInsert(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftAndInsert(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftAndInsert(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftAndInsert(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftAndInsertScalar(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftAndInsertScalar(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogical(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogical(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogical(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogical(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogical(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogical(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturate(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturate(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturate(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturate(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturate(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturate(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalSaturate(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalSaturate(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalSaturate(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalSaturate(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalSaturate(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalSaturate(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalSaturate(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalSaturate(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateUnsigned(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateUnsigned(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateUnsigned(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalSaturateUnsigned(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalSaturateUnsigned(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalSaturateUnsigned(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalSaturateUnsigned(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalSaturateUnsignedScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLeftLogicalScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalWideningLower(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalWideningLower(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalWideningLower(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalWideningLower(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalWideningLower(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalWideningLower(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalWideningUpper(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalWideningUpper(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalWideningUpper(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalWideningUpper(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalWideningUpper(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLeftLogicalWideningUpper(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogical(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogical(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogical(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogical(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogical(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogical(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogical(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRounded(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRounded(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRounded(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRounded(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRounded(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRounded(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRounded(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRounded(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRounded(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRounded(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRounded(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRounded(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRounded(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRounded(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRoundedSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRoundedSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRoundedSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRoundedSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRoundedSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRoundedSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRoundedSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalRoundedSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalRoundedScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalSaturate(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftLogicalSaturate(Vector128 value, Vector128 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalSaturateScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftLogicalScalar(Vector64 value, Vector64 count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightAndInsert(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightAndInsert(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightAndInsert(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightAndInsert(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightAndInsert(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightAndInsert(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightAndInsert(Vector128 left, Vector128 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightAndInsertScalar(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightAndInsertScalar(Vector64 left, Vector64 right, byte shift) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmetic(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmetic(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmetic(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmetic(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmetic(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmetic(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmetic(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticAddScalar(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticNarrowingSaturateUnsignedLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticNarrowingSaturateUnsignedLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticNarrowingSaturateUnsignedLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticNarrowingSaturateUnsignedUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticNarrowingSaturateUnsignedUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticNarrowingSaturateUnsignedUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRounded(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRounded(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRounded(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticRounded(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticRounded(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticRounded(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticRounded(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticRoundedAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticRoundedAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticRoundedAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticRoundedAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedAddScalar(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedNarrowingSaturateUnsignedLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedNarrowingSaturateUnsignedLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedNarrowingSaturateUnsignedLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticRoundedNarrowingSaturateUnsignedUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticRoundedNarrowingSaturateUnsignedUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticRoundedNarrowingSaturateUnsignedUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticRoundedNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticRoundedNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightArithmeticRoundedNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticRoundedScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightArithmeticScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogical(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogical(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogical(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogical(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogical(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogical(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogical(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalAddScalar(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalAddScalar(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalNarrowingUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalNarrowingUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalNarrowingUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalNarrowingUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalNarrowingUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalNarrowingUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRounded(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRounded(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRounded(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRounded(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRounded(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRounded(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRounded(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRounded(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRounded(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRounded(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRounded(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRounded(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRounded(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRounded(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedAdd(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedAdd(Vector128 addend, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedAddScalar(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedAddScalar(Vector64 addend, Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedNarrowingSaturateLower(Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedNarrowingSaturateUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedNarrowingUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedNarrowingUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedNarrowingUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedNarrowingUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedNarrowingUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 ShiftRightLogicalRoundedNarrowingUpper(Vector64 lower, Vector128 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalRoundedScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector64 ShiftRightLogicalScalar(Vector64 value, byte count) { throw new PlatformNotSupportedException(); } public static Vector128 SignExtendWideningLower(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 SignExtendWideningLower(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 SignExtendWideningLower(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 SignExtendWideningUpper(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 SignExtendWideningUpper(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 SignExtendWideningUpper(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector64 SqrtScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector64 SqrtScalar(Vector64 value) { throw new PlatformNotSupportedException(); } public unsafe static void Store(byte* address, Vector64 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(double* address, Vector64 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(short* address, Vector64 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(int* address, Vector64 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(long* address, Vector64 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(sbyte* address, Vector64 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(float* address, Vector64 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(ushort* address, Vector64 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(uint* address, Vector64 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(ulong* address, Vector64 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(byte* address, Vector128 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(double* address, Vector128 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(short* address, Vector128 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(int* address, Vector128 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(long* address, Vector128 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(sbyte* address, Vector128 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(float* address, Vector128 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(ushort* address, Vector128 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(uint* address, Vector128 source) { throw new PlatformNotSupportedException(); } public unsafe static void Store(ulong* address, Vector128 source) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(byte* address, Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(short* address, Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(int* address, Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(sbyte* address, Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(float* address, Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(ushort* address, Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(uint* address, Vector64 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(byte* address, Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(double* address, Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(short* address, Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(int* address, Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(long* address, Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(sbyte* address, Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(float* address, Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(ushort* address, Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(uint* address, Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public unsafe static void StoreSelectedScalar(ulong* address, Vector128 value, byte index) { throw new PlatformNotSupportedException(); } public static Vector64 Subtract(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Subtract(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Subtract(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Subtract(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Subtract(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Subtract(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Subtract(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Subtract(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractRoundedHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractRoundedHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractRoundedHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractRoundedHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractRoundedHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractRoundedHighNarrowingLower(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractRoundedHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractRoundedHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractRoundedHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractRoundedHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractRoundedHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractRoundedHighNarrowingUpper(Vector64 lower, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractSaturate(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractSaturateScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 SubtractScalar(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningLower(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningLower(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningLower(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningLower(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningLower(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningLower(Vector128 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 SubtractWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 VectorTableLookup(Vector128 table, Vector64 byteIndexes) { throw new PlatformNotSupportedException(); } public static Vector64 VectorTableLookup(Vector128 table, Vector64 byteIndexes) { throw new PlatformNotSupportedException(); } public static Vector64 VectorTableLookupExtension(Vector64 defaultValues, Vector128 table, Vector64 byteIndexes) { throw new PlatformNotSupportedException(); } public static Vector64 VectorTableLookupExtension(Vector64 defaultValues, Vector128 table, Vector64 byteIndexes) { throw new PlatformNotSupportedException(); } public static Vector64 Xor(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Xor(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Xor(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Xor(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Xor(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Xor(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Xor(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Xor(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Xor(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 Xor(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 Xor(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 ZeroExtendWideningLower(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ZeroExtendWideningLower(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ZeroExtendWideningLower(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ZeroExtendWideningLower(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ZeroExtendWideningLower(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ZeroExtendWideningLower(Vector64 value) { throw new PlatformNotSupportedException(); } public static Vector128 ZeroExtendWideningUpper(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ZeroExtendWideningUpper(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ZeroExtendWideningUpper(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ZeroExtendWideningUpper(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ZeroExtendWideningUpper(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 ZeroExtendWideningUpper(Vector128 value) { throw new PlatformNotSupportedException(); } } [CLSCompliant(false)] public abstract class Aes : ArmBase { public new abstract class Arm64 : ArmBase.Arm64 { public new static bool IsSupported { [Intrinsic] get { return false; } } } public new static bool IsSupported { [Intrinsic] get { return false; } } public static Vector128 Decrypt(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } public static Vector128 Encrypt(Vector128 value, Vector128 roundKey) { throw new PlatformNotSupportedException(); } public static Vector128 InverseMixColumns(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 MixColumns(Vector128 value) { throw new PlatformNotSupportedException(); } public static Vector128 PolynomialMultiplyWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 PolynomialMultiplyWideningLower(Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 PolynomialMultiplyWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 PolynomialMultiplyWideningUpper(Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } } [CLSCompliant(false)] public abstract class ArmBase { public abstract class Arm64 { public static bool IsSupported { [Intrinsic] get { return false; } } public static int LeadingSignCount(int value) { throw new PlatformNotSupportedException(); } public static int LeadingSignCount(long value) { throw new PlatformNotSupportedException(); } public static int LeadingZeroCount(long value) { throw new PlatformNotSupportedException(); } public static int LeadingZeroCount(ulong value) { throw new PlatformNotSupportedException(); } public static long MultiplyHigh(long left, long right) { throw new PlatformNotSupportedException(); } public static ulong MultiplyHigh(ulong left, ulong right) { throw new PlatformNotSupportedException(); } public static long ReverseElementBits(long value) { throw new PlatformNotSupportedException(); } public static ulong ReverseElementBits(ulong value) { throw new PlatformNotSupportedException(); } } public static bool IsSupported { [Intrinsic] get { return false; } } public static int LeadingZeroCount(int value) { throw new PlatformNotSupportedException(); } public static int LeadingZeroCount(uint value) { throw new PlatformNotSupportedException(); } public static int ReverseElementBits(int value) { throw new PlatformNotSupportedException(); } public static uint ReverseElementBits(uint value) { throw new PlatformNotSupportedException(); } } [Intrinsic] [CLSCompliant(false)] public abstract class Crc32 : ArmBase { [Intrinsic] public new abstract class Arm64 : ArmBase.Arm64 { public new static bool IsSupported { [Intrinsic] get { return false; } } public static uint ComputeCrc32(uint crc, ulong data) { throw new PlatformNotSupportedException(); } public static uint ComputeCrc32C(uint crc, ulong data) { throw new PlatformNotSupportedException(); } } public new static bool IsSupported { [Intrinsic] get { return false; } } public static uint ComputeCrc32(uint crc, byte data) { throw new PlatformNotSupportedException(); } public static uint ComputeCrc32(uint crc, ushort data) { throw new PlatformNotSupportedException(); } public static uint ComputeCrc32(uint crc, uint data) { throw new PlatformNotSupportedException(); } public static uint ComputeCrc32C(uint crc, byte data) { throw new PlatformNotSupportedException(); } public static uint ComputeCrc32C(uint crc, ushort data) { throw new PlatformNotSupportedException(); } public static uint ComputeCrc32C(uint crc, uint data) { throw new PlatformNotSupportedException(); } } [CLSCompliant(false)] public abstract class Dp : AdvSimd { public new abstract class Arm64 : AdvSimd.Arm64 { public new static bool IsSupported { [Intrinsic] get { return false; } } } public new static bool IsSupported { [Intrinsic] get { return false; } } public static Vector64 DotProduct(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 DotProduct(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 DotProduct(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 DotProduct(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 DotProductBySelectedQuadruplet(Vector64 addend, Vector64 left, Vector64 right, byte rightScaledIndex) { throw new PlatformNotSupportedException(); } public static Vector64 DotProductBySelectedQuadruplet(Vector64 addend, Vector64 left, Vector128 right, byte rightScaledIndex) { throw new PlatformNotSupportedException(); } public static Vector64 DotProductBySelectedQuadruplet(Vector64 addend, Vector64 left, Vector64 right, byte rightScaledIndex) { throw new PlatformNotSupportedException(); } public static Vector64 DotProductBySelectedQuadruplet(Vector64 addend, Vector64 left, Vector128 right, byte rightScaledIndex) { throw new PlatformNotSupportedException(); } public static Vector128 DotProductBySelectedQuadruplet(Vector128 addend, Vector128 left, Vector128 right, byte rightScaledIndex) { throw new PlatformNotSupportedException(); } public static Vector128 DotProductBySelectedQuadruplet(Vector128 addend, Vector128 left, Vector64 right, byte rightScaledIndex) { throw new PlatformNotSupportedException(); } public static Vector128 DotProductBySelectedQuadruplet(Vector128 addend, Vector128 left, Vector128 right, byte rightScaledIndex) { throw new PlatformNotSupportedException(); } public static Vector128 DotProductBySelectedQuadruplet(Vector128 addend, Vector128 left, Vector64 right, byte rightScaledIndex) { throw new PlatformNotSupportedException(); } } [CLSCompliant(false)] public abstract class Rdm : AdvSimd { public new abstract class Arm64 : AdvSimd.Arm64 { public new static bool IsSupported { [Intrinsic] get { return false; } } public static Vector64 MultiplyRoundedDoublingAndAddSaturateHighScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingAndAddSaturateHighScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingAndSubtractSaturateHighScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingAndSubtractSaturateHighScalar(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingScalarBySelectedScalarAndAddSaturateHigh(Vector64 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingScalarBySelectedScalarAndAddSaturateHigh(Vector64 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingScalarBySelectedScalarAndAddSaturateHigh(Vector64 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingScalarBySelectedScalarAndAddSaturateHigh(Vector64 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingScalarBySelectedScalarAndSubtractSaturateHigh(Vector64 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingScalarBySelectedScalarAndSubtractSaturateHigh(Vector64 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingScalarBySelectedScalarAndSubtractSaturateHigh(Vector64 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingScalarBySelectedScalarAndSubtractSaturateHigh(Vector64 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } } public new static bool IsSupported { [Intrinsic] get { return false; } } public static Vector64 MultiplyRoundedDoublingAndAddSaturateHigh(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingAndAddSaturateHigh(Vector64 addend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingAndAddSaturateHigh(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingAndAddSaturateHigh(Vector128 addend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingAndSubtractSaturateHigh(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingAndSubtractSaturateHigh(Vector64 minuend, Vector64 left, Vector64 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingAndSubtractSaturateHigh(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingAndSubtractSaturateHigh(Vector128 minuend, Vector128 left, Vector128 right) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingBySelectedScalarAndAddSaturateHigh(Vector64 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingBySelectedScalarAndAddSaturateHigh(Vector64 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingBySelectedScalarAndAddSaturateHigh(Vector64 addend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingBySelectedScalarAndAddSaturateHigh(Vector64 addend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingBySelectedScalarAndAddSaturateHigh(Vector128 addend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingBySelectedScalarAndAddSaturateHigh(Vector128 addend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingBySelectedScalarAndAddSaturateHigh(Vector128 addend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingBySelectedScalarAndAddSaturateHigh(Vector128 addend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingBySelectedScalarAndSubtractSaturateHigh(Vector64 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingBySelectedScalarAndSubtractSaturateHigh(Vector64 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingBySelectedScalarAndSubtractSaturateHigh(Vector64 minuend, Vector64 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector64 MultiplyRoundedDoublingBySelectedScalarAndSubtractSaturateHigh(Vector64 minuend, Vector64 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingBySelectedScalarAndSubtractSaturateHigh(Vector128 minuend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingBySelectedScalarAndSubtractSaturateHigh(Vector128 minuend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingBySelectedScalarAndSubtractSaturateHigh(Vector128 minuend, Vector128 left, Vector64 right, byte rightIndex) { throw new PlatformNotSupportedException(); } public static Vector128 MultiplyRoundedDoublingBySelectedScalarAndSubtractSaturateHigh(Vector128 minuend, Vector128 left, Vector128 right, byte rightIndex) { throw new PlatformNotSupportedException(); } } [CLSCompliant(false)] public abstract class Sha1 : ArmBase { public new abstract class Arm64 : ArmBase.Arm64 { public new static bool IsSupported { [Intrinsic] get { return false; } } } public new static bool IsSupported { [Intrinsic] get { return false; } } public static Vector64 FixedRotate(Vector64 hash_e) { throw new PlatformNotSupportedException(); } public static Vector128 HashUpdateChoose(Vector128 hash_abcd, Vector64 hash_e, Vector128 wk) { throw new PlatformNotSupportedException(); } public static Vector128 HashUpdateMajority(Vector128 hash_abcd, Vector64 hash_e, Vector128 wk) { throw new PlatformNotSupportedException(); } public static Vector128 HashUpdateParity(Vector128 hash_abcd, Vector64 hash_e, Vector128 wk) { throw new PlatformNotSupportedException(); } public static Vector128 ScheduleUpdate0(Vector128 w0_3, Vector128 w4_7, Vector128 w8_11) { throw new PlatformNotSupportedException(); } public static Vector128 ScheduleUpdate1(Vector128 tw0_3, Vector128 w12_15) { throw new PlatformNotSupportedException(); } } [CLSCompliant(false)] public abstract class Sha256 : ArmBase { public new abstract class Arm64 : ArmBase.Arm64 { public new static bool IsSupported { [Intrinsic] get { return false; } } } public new static bool IsSupported { [Intrinsic] get { return false; } } public static Vector128 HashUpdate1(Vector128 hash_abcd, Vector128 hash_efgh, Vector128 wk) { throw new PlatformNotSupportedException(); } public static Vector128 HashUpdate2(Vector128 hash_efgh, Vector128 hash_abcd, Vector128 wk) { throw new PlatformNotSupportedException(); } public static Vector128 ScheduleUpdate0(Vector128 w0_3, Vector128 w4_7) { throw new PlatformNotSupportedException(); } public static Vector128 ScheduleUpdate1(Vector128 w0_3, Vector128 w8_11, Vector128 w12_15) { throw new PlatformNotSupportedException(); } } } namespace System.Runtime.Intrinsics.X86 { [Intrinsic] public abstract class X86Base { [Intrinsic] public abstract class X64 { public static bool IsSupported => IsSupported; internal static ulong BitScanForward(ulong value) { return BitScanForward(value); } internal static ulong BitScanReverse(ulong value) { return BitScanReverse(value); } } public static bool IsSupported => IsSupported; [DllImport("QCall")] private unsafe static extern void __cpuidex(int* cpuInfo, int functionId, int subFunctionId); internal static uint BitScanForward(uint value) { return BitScanForward(value); } internal static uint BitScanReverse(uint value) { return BitScanReverse(value); } public unsafe static (int Eax, int Ebx, int Ecx, int Edx) CpuId(int functionId, int subFunctionId) { int* ptr = stackalloc int[4]; __cpuidex(ptr, functionId, subFunctionId); return (*ptr, ptr[1], ptr[2], ptr[3]); } } public enum FloatComparisonMode : byte { OrderedEqualNonSignaling, OrderedLessThanSignaling, OrderedLessThanOrEqualSignaling, UnorderedNonSignaling, UnorderedNotEqualNonSignaling, UnorderedNotLessThanSignaling, UnorderedNotLessThanOrEqualSignaling, OrderedNonSignaling, UnorderedEqualNonSignaling, UnorderedNotGreaterThanOrEqualSignaling, UnorderedNotGreaterThanSignaling, OrderedFalseNonSignaling, OrderedNotEqualNonSignaling, OrderedGreaterThanOrEqualSignaling, OrderedGreaterThanSignaling, UnorderedTrueNonSignaling, OrderedEqualSignaling, OrderedLessThanNonSignaling, OrderedLessThanOrEqualNonSignaling, UnorderedSignaling, UnorderedNotEqualSignaling, UnorderedNotLessThanNonSignaling, UnorderedNotLessThanOrEqualNonSignaling, OrderedSignaling, UnorderedEqualSignaling, UnorderedNotGreaterThanOrEqualNonSignaling, UnorderedNotGreaterThanNonSignaling, OrderedFalseSignaling, OrderedNotEqualSignaling, OrderedGreaterThanOrEqualNonSignaling, OrderedGreaterThanNonSignaling, UnorderedTrueSignaling } [Intrinsic] [CLSCompliant(false)] public abstract class Aes : Sse2 { [Intrinsic] public new abstract class X64 : Sse2.X64 { public new static bool IsSupported => IsSupported; } public new static bool IsSupported => IsSupported; public static Vector128 Decrypt(Vector128 value, Vector128 roundKey) { return Decrypt(value, roundKey); } public static Vector128 DecryptLast(Vector128 value, Vector128 roundKey) { return DecryptLast(value, roundKey); } public static Vector128 Encrypt(Vector128 value, Vector128 roundKey) { return Encrypt(value, roundKey); } public static Vector128 EncryptLast(Vector128 value, Vector128 roundKey) { return EncryptLast(value, roundKey); } public static Vector128 InverseMixColumns(Vector128 value) { return InverseMixColumns(value); } public static Vector128 KeygenAssist(Vector128 value, byte control) { return KeygenAssist(value, control); } } [Intrinsic] [CLSCompliant(false)] public abstract class Avx : Sse42 { [Intrinsic] public new abstract class X64 : Sse42.X64 { public new static bool IsSupported => IsSupported; } public new static bool IsSupported => IsSupported; public static Vector256 Add(Vector256 left, Vector256 right) { return Add(left, right); } public static Vector256 Add(Vector256 left, Vector256 right) { return Add(left, right); } public static Vector256 AddSubtract(Vector256 left, Vector256 right) { return AddSubtract(left, right); } public static Vector256 AddSubtract(Vector256 left, Vector256 right) { return AddSubtract(left, right); } public static Vector256 And(Vector256 left, Vector256 right) { return And(left, right); } public static Vector256 And(Vector256 left, Vector256 right) { return And(left, right); } public static Vector256 AndNot(Vector256 left, Vector256 right) { return AndNot(left, right); } public static Vector256 AndNot(Vector256 left, Vector256 right) { return AndNot(left, right); } public static Vector256 Blend(Vector256 left, Vector256 right, byte control) { return Blend(left, right, control); } public static Vector256 Blend(Vector256 left, Vector256 right, byte control) { return Blend(left, right, control); } public static Vector256 BlendVariable(Vector256 left, Vector256 right, Vector256 mask) { return BlendVariable(left, right, mask); } public static Vector256 BlendVariable(Vector256 left, Vector256 right, Vector256 mask) { return BlendVariable(left, right, mask); } public unsafe static Vector128 BroadcastScalarToVector128(float* source) { return BroadcastScalarToVector128(source); } public unsafe static Vector256 BroadcastScalarToVector256(float* source) { return BroadcastScalarToVector256(source); } public unsafe static Vector256 BroadcastScalarToVector256(double* source) { return BroadcastScalarToVector256(source); } public unsafe static Vector256 BroadcastVector128ToVector256(float* address) { return BroadcastVector128ToVector256(address); } public unsafe static Vector256 BroadcastVector128ToVector256(double* address) { return BroadcastVector128ToVector256(address); } public static Vector256 Ceiling(Vector256 value) { return Ceiling(value); } public static Vector256 Ceiling(Vector256 value) { return Ceiling(value); } public static Vector128 Compare(Vector128 left, Vector128 right, FloatComparisonMode mode) { return Compare(left, right, mode); } public static Vector128 Compare(Vector128 left, Vector128 right, FloatComparisonMode mode) { return Compare(left, right, mode); } public static Vector256 Compare(Vector256 left, Vector256 right, FloatComparisonMode mode) { return Compare(left, right, mode); } public static Vector256 Compare(Vector256 left, Vector256 right, FloatComparisonMode mode) { return Compare(left, right, mode); } public static Vector256 CompareEqual(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.OrderedEqualNonSignaling); } public static Vector256 CompareEqual(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.OrderedEqualNonSignaling); } public static Vector256 CompareGreaterThan(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.OrderedGreaterThanSignaling); } public static Vector256 CompareGreaterThan(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.OrderedGreaterThanSignaling); } public static Vector256 CompareGreaterThanOrEqual(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.OrderedGreaterThanOrEqualSignaling); } public static Vector256 CompareGreaterThanOrEqual(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.OrderedGreaterThanOrEqualSignaling); } public static Vector256 CompareLessThan(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.OrderedLessThanSignaling); } public static Vector256 CompareLessThan(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.OrderedLessThanSignaling); } public static Vector256 CompareLessThanOrEqual(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.OrderedLessThanOrEqualSignaling); } public static Vector256 CompareLessThanOrEqual(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.OrderedLessThanOrEqualSignaling); } public static Vector256 CompareNotEqual(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.UnorderedNotEqualNonSignaling); } public static Vector256 CompareNotEqual(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.UnorderedNotEqualNonSignaling); } public static Vector256 CompareNotGreaterThan(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.UnorderedNotGreaterThanSignaling); } public static Vector256 CompareNotGreaterThan(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.UnorderedNotGreaterThanSignaling); } public static Vector256 CompareNotGreaterThanOrEqual(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.UnorderedNotGreaterThanOrEqualSignaling); } public static Vector256 CompareNotGreaterThanOrEqual(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.UnorderedNotGreaterThanOrEqualSignaling); } public static Vector256 CompareNotLessThan(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.UnorderedNotLessThanSignaling); } public static Vector256 CompareNotLessThan(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.UnorderedNotLessThanSignaling); } public static Vector256 CompareNotLessThanOrEqual(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.UnorderedNotLessThanOrEqualSignaling); } public static Vector256 CompareNotLessThanOrEqual(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.UnorderedNotLessThanOrEqualSignaling); } public static Vector256 CompareOrdered(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.OrderedNonSignaling); } public static Vector256 CompareOrdered(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.OrderedNonSignaling); } public static Vector128 CompareScalar(Vector128 left, Vector128 right, FloatComparisonMode mode) { return CompareScalar(left, right, mode); } public static Vector128 CompareScalar(Vector128 left, Vector128 right, FloatComparisonMode mode) { return CompareScalar(left, right, mode); } public static Vector256 CompareUnordered(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.UnorderedNonSignaling); } public static Vector256 CompareUnordered(Vector256 left, Vector256 right) { return Compare(left, right, FloatComparisonMode.UnorderedNonSignaling); } public static Vector128 ConvertToVector128Int32(Vector256 value) { return ConvertToVector128Int32(value); } public static Vector128 ConvertToVector128Single(Vector256 value) { return ConvertToVector128Single(value); } public static Vector256 ConvertToVector256Int32(Vector256 value) { return ConvertToVector256Int32(value); } public static Vector256 ConvertToVector256Single(Vector256 value) { return ConvertToVector256Single(value); } public static Vector256 ConvertToVector256Double(Vector128 value) { return ConvertToVector256Double(value); } public static Vector256 ConvertToVector256Double(Vector128 value) { return ConvertToVector256Double(value); } public static Vector128 ConvertToVector128Int32WithTruncation(Vector256 value) { return ConvertToVector128Int32WithTruncation(value); } public static Vector256 ConvertToVector256Int32WithTruncation(Vector256 value) { return ConvertToVector256Int32WithTruncation(value); } public static Vector256 Divide(Vector256 left, Vector256 right) { return Divide(left, right); } public static Vector256 Divide(Vector256 left, Vector256 right) { return Divide(left, right); } public static Vector256 DotProduct(Vector256 left, Vector256 right, byte control) { return DotProduct(left, right, control); } public static Vector256 DuplicateEvenIndexed(Vector256 value) { return DuplicateEvenIndexed(value); } public static Vector256 DuplicateEvenIndexed(Vector256 value) { return DuplicateEvenIndexed(value); } public static Vector256 DuplicateOddIndexed(Vector256 value) { return DuplicateOddIndexed(value); } public static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public static Vector256 Floor(Vector256 value) { return Floor(value); } public static Vector256 Floor(Vector256 value) { return Floor(value); } public static Vector256 HorizontalAdd(Vector256 left, Vector256 right) { return HorizontalAdd(left, right); } public static Vector256 HorizontalAdd(Vector256 left, Vector256 right) { return HorizontalAdd(left, right); } public static Vector256 HorizontalSubtract(Vector256 left, Vector256 right) { return HorizontalSubtract(left, right); } public static Vector256 HorizontalSubtract(Vector256 left, Vector256 right) { return HorizontalSubtract(left, right); } public static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public unsafe static Vector256 LoadVector256(sbyte* address) { return LoadVector256(address); } public unsafe static Vector256 LoadVector256(byte* address) { return LoadVector256(address); } public unsafe static Vector256 LoadVector256(short* address) { return LoadVector256(address); } public unsafe static Vector256 LoadVector256(ushort* address) { return LoadVector256(address); } public unsafe static Vector256 LoadVector256(int* address) { return LoadVector256(address); } public unsafe static Vector256 LoadVector256(uint* address) { return LoadVector256(address); } public unsafe static Vector256 LoadVector256(long* address) { return LoadVector256(address); } public unsafe static Vector256 LoadVector256(ulong* address) { return LoadVector256(address); } public unsafe static Vector256 LoadVector256(float* address) { return LoadVector256(address); } public unsafe static Vector256 LoadVector256(double* address) { return LoadVector256(address); } public unsafe static Vector256 LoadAlignedVector256(sbyte* address) { return LoadAlignedVector256(address); } public unsafe static Vector256 LoadAlignedVector256(byte* address) { return LoadAlignedVector256(address); } public unsafe static Vector256 LoadAlignedVector256(short* address) { return LoadAlignedVector256(address); } public unsafe static Vector256 LoadAlignedVector256(ushort* address) { return LoadAlignedVector256(address); } public unsafe static Vector256 LoadAlignedVector256(int* address) { return LoadAlignedVector256(address); } public unsafe static Vector256 LoadAlignedVector256(uint* address) { return LoadAlignedVector256(address); } public unsafe static Vector256 LoadAlignedVector256(long* address) { return LoadAlignedVector256(address); } public unsafe static Vector256 LoadAlignedVector256(ulong* address) { return LoadAlignedVector256(address); } public unsafe static Vector256 LoadAlignedVector256(float* address) { return LoadAlignedVector256(address); } public unsafe static Vector256 LoadAlignedVector256(double* address) { return LoadAlignedVector256(address); } public unsafe static Vector256 LoadDquVector256(sbyte* address) { return LoadDquVector256(address); } public unsafe static Vector256 LoadDquVector256(byte* address) { return LoadDquVector256(address); } public unsafe static Vector256 LoadDquVector256(short* address) { return LoadDquVector256(address); } public unsafe static Vector256 LoadDquVector256(ushort* address) { return LoadDquVector256(address); } public unsafe static Vector256 LoadDquVector256(int* address) { return LoadDquVector256(address); } public unsafe static Vector256 LoadDquVector256(uint* address) { return LoadDquVector256(address); } public unsafe static Vector256 LoadDquVector256(long* address) { return LoadDquVector256(address); } public unsafe static Vector256 LoadDquVector256(ulong* address) { return LoadDquVector256(address); } public unsafe static Vector128 MaskLoad(float* address, Vector128 mask) { return MaskLoad(address, mask); } public unsafe static Vector128 MaskLoad(double* address, Vector128 mask) { return MaskLoad(address, mask); } public unsafe static Vector256 MaskLoad(float* address, Vector256 mask) { return MaskLoad(address, mask); } public unsafe static Vector256 MaskLoad(double* address, Vector256 mask) { return MaskLoad(address, mask); } public unsafe static void MaskStore(float* address, Vector128 mask, Vector128 source) { MaskStore(address, mask, source); } public unsafe static void MaskStore(double* address, Vector128 mask, Vector128 source) { MaskStore(address, mask, source); } public unsafe static void MaskStore(float* address, Vector256 mask, Vector256 source) { MaskStore(address, mask, source); } public unsafe static void MaskStore(double* address, Vector256 mask, Vector256 source) { MaskStore(address, mask, source); } public static Vector256 Max(Vector256 left, Vector256 right) { return Max(left, right); } public static Vector256 Max(Vector256 left, Vector256 right) { return Max(left, right); } public static Vector256 Min(Vector256 left, Vector256 right) { return Min(left, right); } public static Vector256 Min(Vector256 left, Vector256 right) { return Min(left, right); } public static int MoveMask(Vector256 value) { return MoveMask(value); } public static int MoveMask(Vector256 value) { return MoveMask(value); } public static Vector256 Multiply(Vector256 left, Vector256 right) { return Multiply(left, right); } public static Vector256 Multiply(Vector256 left, Vector256 right) { return Multiply(left, right); } public static Vector256 Or(Vector256 left, Vector256 right) { return Or(left, right); } public static Vector256 Or(Vector256 left, Vector256 right) { return Or(left, right); } public static Vector128 Permute(Vector128 value, byte control) { return Permute(value, control); } public static Vector128 Permute(Vector128 value, byte control) { return Permute(value, control); } public static Vector256 Permute(Vector256 value, byte control) { return Permute(value, control); } public static Vector256 Permute(Vector256 value, byte control) { return Permute(value, control); } public static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public static Vector128 PermuteVar(Vector128 left, Vector128 control) { return PermuteVar(left, control); } public static Vector128 PermuteVar(Vector128 left, Vector128 control) { return PermuteVar(left, control); } public static Vector256 PermuteVar(Vector256 left, Vector256 control) { return PermuteVar(left, control); } public static Vector256 PermuteVar(Vector256 left, Vector256 control) { return PermuteVar(left, control); } public static Vector256 Reciprocal(Vector256 value) { return Reciprocal(value); } public static Vector256 ReciprocalSqrt(Vector256 value) { return ReciprocalSqrt(value); } public static Vector256 RoundToNearestInteger(Vector256 value) { return RoundToNearestInteger(value); } public static Vector256 RoundToNegativeInfinity(Vector256 value) { return RoundToNegativeInfinity(value); } public static Vector256 RoundToPositiveInfinity(Vector256 value) { return RoundToPositiveInfinity(value); } public static Vector256 RoundToZero(Vector256 value) { return RoundToZero(value); } public static Vector256 RoundCurrentDirection(Vector256 value) { return RoundCurrentDirection(value); } public static Vector256 RoundToNearestInteger(Vector256 value) { return RoundToNearestInteger(value); } public static Vector256 RoundToNegativeInfinity(Vector256 value) { return RoundToNegativeInfinity(value); } public static Vector256 RoundToPositiveInfinity(Vector256 value) { return RoundToPositiveInfinity(value); } public static Vector256 RoundToZero(Vector256 value) { return RoundToZero(value); } public static Vector256 RoundCurrentDirection(Vector256 value) { return RoundCurrentDirection(value); } public static Vector256 Shuffle(Vector256 value, Vector256 right, byte control) { return Shuffle(value, right, control); } public static Vector256 Shuffle(Vector256 value, Vector256 right, byte control) { return Shuffle(value, right, control); } public static Vector256 Sqrt(Vector256 value) { return Sqrt(value); } public static Vector256 Sqrt(Vector256 value) { return Sqrt(value); } public unsafe static void StoreAligned(sbyte* address, Vector256 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(byte* address, Vector256 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(short* address, Vector256 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(ushort* address, Vector256 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(int* address, Vector256 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(uint* address, Vector256 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(long* address, Vector256 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(ulong* address, Vector256 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(float* address, Vector256 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(double* address, Vector256 source) { StoreAligned(address, source); } public unsafe static void StoreAlignedNonTemporal(sbyte* address, Vector256 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(byte* address, Vector256 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(short* address, Vector256 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(ushort* address, Vector256 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(int* address, Vector256 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(uint* address, Vector256 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(long* address, Vector256 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(ulong* address, Vector256 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(float* address, Vector256 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(double* address, Vector256 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void Store(sbyte* address, Vector256 source) { Store(address, source); } public unsafe static void Store(byte* address, Vector256 source) { Store(address, source); } public unsafe static void Store(short* address, Vector256 source) { Store(address, source); } public unsafe static void Store(ushort* address, Vector256 source) { Store(address, source); } public unsafe static void Store(int* address, Vector256 source) { Store(address, source); } public unsafe static void Store(uint* address, Vector256 source) { Store(address, source); } public unsafe static void Store(long* address, Vector256 source) { Store(address, source); } public unsafe static void Store(ulong* address, Vector256 source) { Store(address, source); } public unsafe static void Store(float* address, Vector256 source) { Store(address, source); } public unsafe static void Store(double* address, Vector256 source) { Store(address, source); } public static Vector256 Subtract(Vector256 left, Vector256 right) { return Subtract(left, right); } public static Vector256 Subtract(Vector256 left, Vector256 right) { return Subtract(left, right); } public static bool TestC(Vector128 left, Vector128 right) { return TestC(left, right); } public static bool TestC(Vector128 left, Vector128 right) { return TestC(left, right); } public static bool TestC(Vector256 left, Vector256 right) { return TestC(left, right); } public static bool TestC(Vector256 left, Vector256 right) { return TestC(left, right); } public static bool TestC(Vector256 left, Vector256 right) { return TestC(left, right); } public static bool TestC(Vector256 left, Vector256 right) { return TestC(left, right); } public static bool TestC(Vector256 left, Vector256 right) { return TestC(left, right); } public static bool TestC(Vector256 left, Vector256 right) { return TestC(left, right); } public static bool TestC(Vector256 left, Vector256 right) { return TestC(left, right); } public static bool TestC(Vector256 left, Vector256 right) { return TestC(left, right); } public static bool TestC(Vector256 left, Vector256 right) { return TestC(left, right); } public static bool TestC(Vector256 left, Vector256 right) { return TestC(left, right); } public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector256 left, Vector256 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector256 left, Vector256 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector256 left, Vector256 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector256 left, Vector256 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector256 left, Vector256 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector256 left, Vector256 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector256 left, Vector256 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector256 left, Vector256 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector256 left, Vector256 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector256 left, Vector256 right) { return TestNotZAndNotC(left, right); } public static bool TestZ(Vector128 left, Vector128 right) { return TestZ(left, right); } public static bool TestZ(Vector128 left, Vector128 right) { return TestZ(left, right); } public static bool TestZ(Vector256 left, Vector256 right) { return TestZ(left, right); } public static bool TestZ(Vector256 left, Vector256 right) { return TestZ(left, right); } public static bool TestZ(Vector256 left, Vector256 right) { return TestZ(left, right); } public static bool TestZ(Vector256 left, Vector256 right) { return TestZ(left, right); } public static bool TestZ(Vector256 left, Vector256 right) { return TestZ(left, right); } public static bool TestZ(Vector256 left, Vector256 right) { return TestZ(left, right); } public static bool TestZ(Vector256 left, Vector256 right) { return TestZ(left, right); } public static bool TestZ(Vector256 left, Vector256 right) { return TestZ(left, right); } public static bool TestZ(Vector256 left, Vector256 right) { return TestZ(left, right); } public static bool TestZ(Vector256 left, Vector256 right) { return TestZ(left, right); } public static Vector256 UnpackHigh(Vector256 left, Vector256 right) { return UnpackHigh(left, right); } public static Vector256 UnpackHigh(Vector256 left, Vector256 right) { return UnpackHigh(left, right); } public static Vector256 UnpackLow(Vector256 left, Vector256 right) { return UnpackLow(left, right); } public static Vector256 UnpackLow(Vector256 left, Vector256 right) { return UnpackLow(left, right); } public static Vector256 Xor(Vector256 left, Vector256 right) { return Xor(left, right); } public static Vector256 Xor(Vector256 left, Vector256 right) { return Xor(left, right); } } [Intrinsic] [CLSCompliant(false)] public abstract class Avx2 : Avx { [Intrinsic] public new abstract class X64 : Avx.X64 { public new static bool IsSupported => IsSupported; } public new static bool IsSupported => IsSupported; public static Vector256 Abs(Vector256 value) { return Abs(value); } public static Vector256 Abs(Vector256 value) { return Abs(value); } public static Vector256 Abs(Vector256 value) { return Abs(value); } public static Vector256 Add(Vector256 left, Vector256 right) { return Add(left, right); } public static Vector256 Add(Vector256 left, Vector256 right) { return Add(left, right); } public static Vector256 Add(Vector256 left, Vector256 right) { return Add(left, right); } public static Vector256 Add(Vector256 left, Vector256 right) { return Add(left, right); } public static Vector256 Add(Vector256 left, Vector256 right) { return Add(left, right); } public static Vector256 Add(Vector256 left, Vector256 right) { return Add(left, right); } public static Vector256 Add(Vector256 left, Vector256 right) { return Add(left, right); } public static Vector256 Add(Vector256 left, Vector256 right) { return Add(left, right); } public static Vector256 AddSaturate(Vector256 left, Vector256 right) { return AddSaturate(left, right); } public static Vector256 AddSaturate(Vector256 left, Vector256 right) { return AddSaturate(left, right); } public static Vector256 AddSaturate(Vector256 left, Vector256 right) { return AddSaturate(left, right); } public static Vector256 AddSaturate(Vector256 left, Vector256 right) { return AddSaturate(left, right); } public static Vector256 AlignRight(Vector256 left, Vector256 right, byte mask) { return AlignRight(left, right, mask); } public static Vector256 AlignRight(Vector256 left, Vector256 right, byte mask) { return AlignRight(left, right, mask); } public static Vector256 AlignRight(Vector256 left, Vector256 right, byte mask) { return AlignRight(left, right, mask); } public static Vector256 AlignRight(Vector256 left, Vector256 right, byte mask) { return AlignRight(left, right, mask); } public static Vector256 AlignRight(Vector256 left, Vector256 right, byte mask) { return AlignRight(left, right, mask); } public static Vector256 AlignRight(Vector256 left, Vector256 right, byte mask) { return AlignRight(left, right, mask); } public static Vector256 AlignRight(Vector256 left, Vector256 right, byte mask) { return AlignRight(left, right, mask); } public static Vector256 AlignRight(Vector256 left, Vector256 right, byte mask) { return AlignRight(left, right, mask); } public static Vector256 And(Vector256 left, Vector256 right) { return And(left, right); } public static Vector256 And(Vector256 left, Vector256 right) { return And(left, right); } public static Vector256 And(Vector256 left, Vector256 right) { return And(left, right); } public static Vector256 And(Vector256 left, Vector256 right) { return And(left, right); } public static Vector256 And(Vector256 left, Vector256 right) { return And(left, right); } public static Vector256 And(Vector256 left, Vector256 right) { return And(left, right); } public static Vector256 And(Vector256 left, Vector256 right) { return And(left, right); } public static Vector256 And(Vector256 left, Vector256 right) { return And(left, right); } public static Vector256 AndNot(Vector256 left, Vector256 right) { return AndNot(left, right); } public static Vector256 AndNot(Vector256 left, Vector256 right) { return AndNot(left, right); } public static Vector256 AndNot(Vector256 left, Vector256 right) { return AndNot(left, right); } public static Vector256 AndNot(Vector256 left, Vector256 right) { return AndNot(left, right); } public static Vector256 AndNot(Vector256 left, Vector256 right) { return AndNot(left, right); } public static Vector256 AndNot(Vector256 left, Vector256 right) { return AndNot(left, right); } public static Vector256 AndNot(Vector256 left, Vector256 right) { return AndNot(left, right); } public static Vector256 AndNot(Vector256 left, Vector256 right) { return AndNot(left, right); } public static Vector256 Average(Vector256 left, Vector256 right) { return Average(left, right); } public static Vector256 Average(Vector256 left, Vector256 right) { return Average(left, right); } public static Vector128 Blend(Vector128 left, Vector128 right, byte control) { return Blend(left, right, control); } public static Vector128 Blend(Vector128 left, Vector128 right, byte control) { return Blend(left, right, control); } public static Vector256 Blend(Vector256 left, Vector256 right, byte control) { return Blend(left, right, control); } public static Vector256 Blend(Vector256 left, Vector256 right, byte control) { return Blend(left, right, control); } public static Vector256 Blend(Vector256 left, Vector256 right, byte control) { return Blend(left, right, control); } public static Vector256 Blend(Vector256 left, Vector256 right, byte control) { return Blend(left, right, control); } public static Vector256 BlendVariable(Vector256 left, Vector256 right, Vector256 mask) { return BlendVariable(left, right, mask); } public static Vector256 BlendVariable(Vector256 left, Vector256 right, Vector256 mask) { return BlendVariable(left, right, mask); } public static Vector256 BlendVariable(Vector256 left, Vector256 right, Vector256 mask) { return BlendVariable(left, right, mask); } public static Vector256 BlendVariable(Vector256 left, Vector256 right, Vector256 mask) { return BlendVariable(left, right, mask); } public static Vector256 BlendVariable(Vector256 left, Vector256 right, Vector256 mask) { return BlendVariable(left, right, mask); } public static Vector256 BlendVariable(Vector256 left, Vector256 right, Vector256 mask) { return BlendVariable(left, right, mask); } public static Vector256 BlendVariable(Vector256 left, Vector256 right, Vector256 mask) { return BlendVariable(left, right, mask); } public static Vector256 BlendVariable(Vector256 left, Vector256 right, Vector256 mask) { return BlendVariable(left, right, mask); } public static Vector128 BroadcastScalarToVector128(Vector128 value) { return BroadcastScalarToVector128(value); } public static Vector128 BroadcastScalarToVector128(Vector128 value) { return BroadcastScalarToVector128(value); } public static Vector128 BroadcastScalarToVector128(Vector128 value) { return BroadcastScalarToVector128(value); } public static Vector128 BroadcastScalarToVector128(Vector128 value) { return BroadcastScalarToVector128(value); } public static Vector128 BroadcastScalarToVector128(Vector128 value) { return BroadcastScalarToVector128(value); } public static Vector128 BroadcastScalarToVector128(Vector128 value) { return BroadcastScalarToVector128(value); } public static Vector128 BroadcastScalarToVector128(Vector128 value) { return BroadcastScalarToVector128(value); } public static Vector128 BroadcastScalarToVector128(Vector128 value) { return BroadcastScalarToVector128(value); } public static Vector128 BroadcastScalarToVector128(Vector128 value) { return BroadcastScalarToVector128(value); } public static Vector128 BroadcastScalarToVector128(Vector128 value) { return BroadcastScalarToVector128(value); } public unsafe static Vector128 BroadcastScalarToVector128(byte* source) { return BroadcastScalarToVector128(source); } public unsafe static Vector128 BroadcastScalarToVector128(sbyte* source) { return BroadcastScalarToVector128(source); } public unsafe static Vector128 BroadcastScalarToVector128(short* source) { return BroadcastScalarToVector128(source); } public unsafe static Vector128 BroadcastScalarToVector128(ushort* source) { return BroadcastScalarToVector128(source); } public unsafe static Vector128 BroadcastScalarToVector128(int* source) { return BroadcastScalarToVector128(source); } public unsafe static Vector128 BroadcastScalarToVector128(uint* source) { return BroadcastScalarToVector128(source); } public unsafe static Vector128 BroadcastScalarToVector128(long* source) { return BroadcastScalarToVector128(source); } public unsafe static Vector128 BroadcastScalarToVector128(ulong* source) { return BroadcastScalarToVector128(source); } public static Vector256 BroadcastScalarToVector256(Vector128 value) { return BroadcastScalarToVector256(value); } public static Vector256 BroadcastScalarToVector256(Vector128 value) { return BroadcastScalarToVector256(value); } public static Vector256 BroadcastScalarToVector256(Vector128 value) { return BroadcastScalarToVector256(value); } public static Vector256 BroadcastScalarToVector256(Vector128 value) { return BroadcastScalarToVector256(value); } public static Vector256 BroadcastScalarToVector256(Vector128 value) { return BroadcastScalarToVector256(value); } public static Vector256 BroadcastScalarToVector256(Vector128 value) { return BroadcastScalarToVector256(value); } public static Vector256 BroadcastScalarToVector256(Vector128 value) { return BroadcastScalarToVector256(value); } public static Vector256 BroadcastScalarToVector256(Vector128 value) { return BroadcastScalarToVector256(value); } public static Vector256 BroadcastScalarToVector256(Vector128 value) { return BroadcastScalarToVector256(value); } public static Vector256 BroadcastScalarToVector256(Vector128 value) { return BroadcastScalarToVector256(value); } public unsafe static Vector256 BroadcastScalarToVector256(byte* source) { return BroadcastScalarToVector256(source); } public unsafe static Vector256 BroadcastScalarToVector256(sbyte* source) { return BroadcastScalarToVector256(source); } public unsafe static Vector256 BroadcastScalarToVector256(short* source) { return BroadcastScalarToVector256(source); } public unsafe static Vector256 BroadcastScalarToVector256(ushort* source) { return BroadcastScalarToVector256(source); } public unsafe static Vector256 BroadcastScalarToVector256(int* source) { return BroadcastScalarToVector256(source); } public unsafe static Vector256 BroadcastScalarToVector256(uint* source) { return BroadcastScalarToVector256(source); } public unsafe static Vector256 BroadcastScalarToVector256(long* source) { return BroadcastScalarToVector256(source); } public unsafe static Vector256 BroadcastScalarToVector256(ulong* source) { return BroadcastScalarToVector256(source); } public unsafe static Vector256 BroadcastVector128ToVector256(sbyte* address) { return BroadcastVector128ToVector256(address); } public unsafe static Vector256 BroadcastVector128ToVector256(byte* address) { return BroadcastVector128ToVector256(address); } public unsafe static Vector256 BroadcastVector128ToVector256(short* address) { return BroadcastVector128ToVector256(address); } public unsafe static Vector256 BroadcastVector128ToVector256(ushort* address) { return BroadcastVector128ToVector256(address); } public unsafe static Vector256 BroadcastVector128ToVector256(int* address) { return BroadcastVector128ToVector256(address); } public unsafe static Vector256 BroadcastVector128ToVector256(uint* address) { return BroadcastVector128ToVector256(address); } public unsafe static Vector256 BroadcastVector128ToVector256(long* address) { return BroadcastVector128ToVector256(address); } public unsafe static Vector256 BroadcastVector128ToVector256(ulong* address) { return BroadcastVector128ToVector256(address); } public static Vector256 CompareEqual(Vector256 left, Vector256 right) { return CompareEqual(left, right); } public static Vector256 CompareEqual(Vector256 left, Vector256 right) { return CompareEqual(left, right); } public static Vector256 CompareEqual(Vector256 left, Vector256 right) { return CompareEqual(left, right); } public static Vector256 CompareEqual(Vector256 left, Vector256 right) { return CompareEqual(left, right); } public static Vector256 CompareEqual(Vector256 left, Vector256 right) { return CompareEqual(left, right); } public static Vector256 CompareEqual(Vector256 left, Vector256 right) { return CompareEqual(left, right); } public static Vector256 CompareEqual(Vector256 left, Vector256 right) { return CompareEqual(left, right); } public static Vector256 CompareEqual(Vector256 left, Vector256 right) { return CompareEqual(left, right); } public static Vector256 CompareGreaterThan(Vector256 left, Vector256 right) { return CompareGreaterThan(left, right); } public static Vector256 CompareGreaterThan(Vector256 left, Vector256 right) { return CompareGreaterThan(left, right); } public static Vector256 CompareGreaterThan(Vector256 left, Vector256 right) { return CompareGreaterThan(left, right); } public static Vector256 CompareGreaterThan(Vector256 left, Vector256 right) { return CompareGreaterThan(left, right); } public static int ConvertToInt32(Vector256 value) { return ConvertToInt32(value); } public static uint ConvertToUInt32(Vector256 value) { return ConvertToUInt32(value); } public static Vector256 ConvertToVector256Int16(Vector128 value) { return ConvertToVector256Int16(value); } public static Vector256 ConvertToVector256Int16(Vector128 value) { return ConvertToVector256Int16(value); } public static Vector256 ConvertToVector256Int32(Vector128 value) { return ConvertToVector256Int32(value); } public static Vector256 ConvertToVector256Int32(Vector128 value) { return ConvertToVector256Int32(value); } public static Vector256 ConvertToVector256Int32(Vector128 value) { return ConvertToVector256Int32(value); } public static Vector256 ConvertToVector256Int32(Vector128 value) { return ConvertToVector256Int32(value); } public static Vector256 ConvertToVector256Int64(Vector128 value) { return ConvertToVector256Int64(value); } public static Vector256 ConvertToVector256Int64(Vector128 value) { return ConvertToVector256Int64(value); } public static Vector256 ConvertToVector256Int64(Vector128 value) { return ConvertToVector256Int64(value); } public static Vector256 ConvertToVector256Int64(Vector128 value) { return ConvertToVector256Int64(value); } public static Vector256 ConvertToVector256Int64(Vector128 value) { return ConvertToVector256Int64(value); } public static Vector256 ConvertToVector256Int64(Vector128 value) { return ConvertToVector256Int64(value); } public unsafe static Vector256 ConvertToVector256Int16(sbyte* address) { return ConvertToVector256Int16(address); } public unsafe static Vector256 ConvertToVector256Int16(byte* address) { return ConvertToVector256Int16(address); } public unsafe static Vector256 ConvertToVector256Int32(sbyte* address) { return ConvertToVector256Int32(address); } public unsafe static Vector256 ConvertToVector256Int32(byte* address) { return ConvertToVector256Int32(address); } public unsafe static Vector256 ConvertToVector256Int32(short* address) { return ConvertToVector256Int32(address); } public unsafe static Vector256 ConvertToVector256Int32(ushort* address) { return ConvertToVector256Int32(address); } public unsafe static Vector256 ConvertToVector256Int64(sbyte* address) { return ConvertToVector256Int64(address); } public unsafe static Vector256 ConvertToVector256Int64(byte* address) { return ConvertToVector256Int64(address); } public unsafe static Vector256 ConvertToVector256Int64(short* address) { return ConvertToVector256Int64(address); } public unsafe static Vector256 ConvertToVector256Int64(ushort* address) { return ConvertToVector256Int64(address); } public unsafe static Vector256 ConvertToVector256Int64(int* address) { return ConvertToVector256Int64(address); } public unsafe static Vector256 ConvertToVector256Int64(uint* address) { return ConvertToVector256Int64(address); } public new static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public new static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public new static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public new static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public new static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public new static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public new static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public new static Vector128 ExtractVector128(Vector256 value, byte index) { return ExtractVector128(value, index); } public unsafe static Vector128 GatherVector128(int* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherVector128(uint* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherVector128(long* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherVector128(ulong* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherVector128(float* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherVector128(double* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherVector128(int* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherVector128(uint* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherVector128(long* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherVector128(ulong* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherVector128(float* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherVector128(double* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherVector256(int* baseAddress, Vector256 index, byte scale) { return scale switch { 1 => GatherVector256(baseAddress, index, 1), 2 => GatherVector256(baseAddress, index, 2), 4 => GatherVector256(baseAddress, index, 4), 8 => GatherVector256(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherVector256(uint* baseAddress, Vector256 index, byte scale) { return scale switch { 1 => GatherVector256(baseAddress, index, 1), 2 => GatherVector256(baseAddress, index, 2), 4 => GatherVector256(baseAddress, index, 4), 8 => GatherVector256(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherVector256(long* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector256(baseAddress, index, 1), 2 => GatherVector256(baseAddress, index, 2), 4 => GatherVector256(baseAddress, index, 4), 8 => GatherVector256(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherVector256(ulong* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector256(baseAddress, index, 1), 2 => GatherVector256(baseAddress, index, 2), 4 => GatherVector256(baseAddress, index, 4), 8 => GatherVector256(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherVector256(float* baseAddress, Vector256 index, byte scale) { return scale switch { 1 => GatherVector256(baseAddress, index, 1), 2 => GatherVector256(baseAddress, index, 2), 4 => GatherVector256(baseAddress, index, 4), 8 => GatherVector256(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherVector256(double* baseAddress, Vector128 index, byte scale) { return scale switch { 1 => GatherVector256(baseAddress, index, 1), 2 => GatherVector256(baseAddress, index, 2), 4 => GatherVector256(baseAddress, index, 4), 8 => GatherVector256(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherVector128(int* baseAddress, Vector256 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherVector128(uint* baseAddress, Vector256 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherVector256(long* baseAddress, Vector256 index, byte scale) { return scale switch { 1 => GatherVector256(baseAddress, index, 1), 2 => GatherVector256(baseAddress, index, 2), 4 => GatherVector256(baseAddress, index, 4), 8 => GatherVector256(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherVector256(ulong* baseAddress, Vector256 index, byte scale) { return scale switch { 1 => GatherVector256(baseAddress, index, 1), 2 => GatherVector256(baseAddress, index, 2), 4 => GatherVector256(baseAddress, index, 4), 8 => GatherVector256(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherVector128(float* baseAddress, Vector256 index, byte scale) { return scale switch { 1 => GatherVector128(baseAddress, index, 1), 2 => GatherVector128(baseAddress, index, 2), 4 => GatherVector128(baseAddress, index, 4), 8 => GatherVector128(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherVector256(double* baseAddress, Vector256 index, byte scale) { return scale switch { 1 => GatherVector256(baseAddress, index, 1), 2 => GatherVector256(baseAddress, index, 2), 4 => GatherVector256(baseAddress, index, 4), 8 => GatherVector256(baseAddress, index, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, int* baseAddress, Vector128 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, uint* baseAddress, Vector128 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, long* baseAddress, Vector128 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, ulong* baseAddress, Vector128 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, float* baseAddress, Vector128 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, double* baseAddress, Vector128 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, int* baseAddress, Vector128 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, uint* baseAddress, Vector128 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, long* baseAddress, Vector128 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, ulong* baseAddress, Vector128 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, float* baseAddress, Vector128 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, double* baseAddress, Vector128 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherMaskVector256(Vector256 source, int* baseAddress, Vector256 index, Vector256 mask, byte scale) { return scale switch { 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherMaskVector256(Vector256 source, uint* baseAddress, Vector256 index, Vector256 mask, byte scale) { return scale switch { 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherMaskVector256(Vector256 source, long* baseAddress, Vector128 index, Vector256 mask, byte scale) { return scale switch { 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherMaskVector256(Vector256 source, ulong* baseAddress, Vector128 index, Vector256 mask, byte scale) { return scale switch { 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherMaskVector256(Vector256 source, float* baseAddress, Vector256 index, Vector256 mask, byte scale) { return scale switch { 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherMaskVector256(Vector256 source, double* baseAddress, Vector128 index, Vector256 mask, byte scale) { return scale switch { 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, int* baseAddress, Vector256 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, uint* baseAddress, Vector256 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherMaskVector256(Vector256 source, long* baseAddress, Vector256 index, Vector256 mask, byte scale) { return scale switch { 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherMaskVector256(Vector256 source, ulong* baseAddress, Vector256 index, Vector256 mask, byte scale) { return scale switch { 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector128 GatherMaskVector128(Vector128 source, float* baseAddress, Vector256 index, Vector128 mask, byte scale) { return scale switch { 1 => GatherMaskVector128(source, baseAddress, index, mask, 1), 2 => GatherMaskVector128(source, baseAddress, index, mask, 2), 4 => GatherMaskVector128(source, baseAddress, index, mask, 4), 8 => GatherMaskVector128(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public unsafe static Vector256 GatherMaskVector256(Vector256 source, double* baseAddress, Vector256 index, Vector256 mask, byte scale) { return scale switch { 1 => GatherMaskVector256(source, baseAddress, index, mask, 1), 2 => GatherMaskVector256(source, baseAddress, index, mask, 2), 4 => GatherMaskVector256(source, baseAddress, index, mask, 4), 8 => GatherMaskVector256(source, baseAddress, index, mask, 8), _ => throw new ArgumentOutOfRangeException("scale"), }; } public static Vector256 HorizontalAdd(Vector256 left, Vector256 right) { return HorizontalAdd(left, right); } public static Vector256 HorizontalAdd(Vector256 left, Vector256 right) { return HorizontalAdd(left, right); } public static Vector256 HorizontalAddSaturate(Vector256 left, Vector256 right) { return HorizontalAddSaturate(left, right); } public static Vector256 HorizontalSubtract(Vector256 left, Vector256 right) { return HorizontalSubtract(left, right); } public static Vector256 HorizontalSubtract(Vector256 left, Vector256 right) { return HorizontalSubtract(left, right); } public static Vector256 HorizontalSubtractSaturate(Vector256 left, Vector256 right) { return HorizontalSubtractSaturate(left, right); } public new static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public new static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public new static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public new static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public new static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public new static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public new static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public new static Vector256 InsertVector128(Vector256 value, Vector128 data, byte index) { return InsertVector128(value, data, index); } public unsafe static Vector256 LoadAlignedVector256NonTemporal(sbyte* address) { return LoadAlignedVector256NonTemporal(address); } public unsafe static Vector256 LoadAlignedVector256NonTemporal(byte* address) { return LoadAlignedVector256NonTemporal(address); } public unsafe static Vector256 LoadAlignedVector256NonTemporal(short* address) { return LoadAlignedVector256NonTemporal(address); } public unsafe static Vector256 LoadAlignedVector256NonTemporal(ushort* address) { return LoadAlignedVector256NonTemporal(address); } public unsafe static Vector256 LoadAlignedVector256NonTemporal(int* address) { return LoadAlignedVector256NonTemporal(address); } public unsafe static Vector256 LoadAlignedVector256NonTemporal(uint* address) { return LoadAlignedVector256NonTemporal(address); } public unsafe static Vector256 LoadAlignedVector256NonTemporal(long* address) { return LoadAlignedVector256NonTemporal(address); } public unsafe static Vector256 LoadAlignedVector256NonTemporal(ulong* address) { return LoadAlignedVector256NonTemporal(address); } public unsafe static Vector128 MaskLoad(int* address, Vector128 mask) { return MaskLoad(address, mask); } public unsafe static Vector128 MaskLoad(uint* address, Vector128 mask) { return MaskLoad(address, mask); } public unsafe static Vector128 MaskLoad(long* address, Vector128 mask) { return MaskLoad(address, mask); } public unsafe static Vector128 MaskLoad(ulong* address, Vector128 mask) { return MaskLoad(address, mask); } public unsafe static Vector256 MaskLoad(int* address, Vector256 mask) { return MaskLoad(address, mask); } public unsafe static Vector256 MaskLoad(uint* address, Vector256 mask) { return MaskLoad(address, mask); } public unsafe static Vector256 MaskLoad(long* address, Vector256 mask) { return MaskLoad(address, mask); } public unsafe static Vector256 MaskLoad(ulong* address, Vector256 mask) { return MaskLoad(address, mask); } public unsafe static void MaskStore(int* address, Vector128 mask, Vector128 source) { MaskStore(address, mask, source); } public unsafe static void MaskStore(uint* address, Vector128 mask, Vector128 source) { MaskStore(address, mask, source); } public unsafe static void MaskStore(long* address, Vector128 mask, Vector128 source) { MaskStore(address, mask, source); } public unsafe static void MaskStore(ulong* address, Vector128 mask, Vector128 source) { MaskStore(address, mask, source); } public unsafe static void MaskStore(int* address, Vector256 mask, Vector256 source) { MaskStore(address, mask, source); } public unsafe static void MaskStore(uint* address, Vector256 mask, Vector256 source) { MaskStore(address, mask, source); } public unsafe static void MaskStore(long* address, Vector256 mask, Vector256 source) { MaskStore(address, mask, source); } public unsafe static void MaskStore(ulong* address, Vector256 mask, Vector256 source) { MaskStore(address, mask, source); } public static Vector256 MultiplyAddAdjacent(Vector256 left, Vector256 right) { return MultiplyAddAdjacent(left, right); } public static Vector256 MultiplyAddAdjacent(Vector256 left, Vector256 right) { return MultiplyAddAdjacent(left, right); } public static Vector256 Max(Vector256 left, Vector256 right) { return Max(left, right); } public static Vector256 Max(Vector256 left, Vector256 right) { return Max(left, right); } public static Vector256 Max(Vector256 left, Vector256 right) { return Max(left, right); } public static Vector256 Max(Vector256 left, Vector256 right) { return Max(left, right); } public static Vector256 Max(Vector256 left, Vector256 right) { return Max(left, right); } public static Vector256 Max(Vector256 left, Vector256 right) { return Max(left, right); } public static Vector256 Min(Vector256 left, Vector256 right) { return Min(left, right); } public static Vector256 Min(Vector256 left, Vector256 right) { return Min(left, right); } public static Vector256 Min(Vector256 left, Vector256 right) { return Min(left, right); } public static Vector256 Min(Vector256 left, Vector256 right) { return Min(left, right); } public static Vector256 Min(Vector256 left, Vector256 right) { return Min(left, right); } public static Vector256 Min(Vector256 left, Vector256 right) { return Min(left, right); } public static int MoveMask(Vector256 value) { return MoveMask(value); } public static int MoveMask(Vector256 value) { return MoveMask(value); } public static Vector256 MultipleSumAbsoluteDifferences(Vector256 left, Vector256 right, byte mask) { return MultipleSumAbsoluteDifferences(left, right, mask); } public static Vector256 Multiply(Vector256 left, Vector256 right) { return Multiply(left, right); } public static Vector256 Multiply(Vector256 left, Vector256 right) { return Multiply(left, right); } public static Vector256 MultiplyHigh(Vector256 left, Vector256 right) { return MultiplyHigh(left, right); } public static Vector256 MultiplyHigh(Vector256 left, Vector256 right) { return MultiplyHigh(left, right); } public static Vector256 MultiplyHighRoundScale(Vector256 left, Vector256 right) { return MultiplyHighRoundScale(left, right); } public static Vector256 MultiplyLow(Vector256 left, Vector256 right) { return MultiplyLow(left, right); } public static Vector256 MultiplyLow(Vector256 left, Vector256 right) { return MultiplyLow(left, right); } public static Vector256 MultiplyLow(Vector256 left, Vector256 right) { return MultiplyLow(left, right); } public static Vector256 MultiplyLow(Vector256 left, Vector256 right) { return MultiplyLow(left, right); } public static Vector256 Or(Vector256 left, Vector256 right) { return Or(left, right); } public static Vector256 Or(Vector256 left, Vector256 right) { return Or(left, right); } public static Vector256 Or(Vector256 left, Vector256 right) { return Or(left, right); } public static Vector256 Or(Vector256 left, Vector256 right) { return Or(left, right); } public static Vector256 Or(Vector256 left, Vector256 right) { return Or(left, right); } public static Vector256 Or(Vector256 left, Vector256 right) { return Or(left, right); } public static Vector256 Or(Vector256 left, Vector256 right) { return Or(left, right); } public static Vector256 Or(Vector256 left, Vector256 right) { return Or(left, right); } public static Vector256 PackSignedSaturate(Vector256 left, Vector256 right) { return PackSignedSaturate(left, right); } public static Vector256 PackSignedSaturate(Vector256 left, Vector256 right) { return PackSignedSaturate(left, right); } public static Vector256 PackUnsignedSaturate(Vector256 left, Vector256 right) { return PackUnsignedSaturate(left, right); } public static Vector256 PackUnsignedSaturate(Vector256 left, Vector256 right) { return PackUnsignedSaturate(left, right); } public new static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public new static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public new static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public new static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public new static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public new static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public new static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public new static Vector256 Permute2x128(Vector256 left, Vector256 right, byte control) { return Permute2x128(left, right, control); } public static Vector256 Permute4x64(Vector256 value, byte control) { return Permute4x64(value, control); } public static Vector256 Permute4x64(Vector256 value, byte control) { return Permute4x64(value, control); } public static Vector256 Permute4x64(Vector256 value, byte control) { return Permute4x64(value, control); } public static Vector256 PermuteVar8x32(Vector256 left, Vector256 control) { return PermuteVar8x32(left, control); } public static Vector256 PermuteVar8x32(Vector256 left, Vector256 control) { return PermuteVar8x32(left, control); } public static Vector256 PermuteVar8x32(Vector256 left, Vector256 control) { return PermuteVar8x32(left, control); } public static Vector256 ShiftLeftLogical(Vector256 value, Vector128 count) { return ShiftLeftLogical(value, count); } public static Vector256 ShiftLeftLogical(Vector256 value, Vector128 count) { return ShiftLeftLogical(value, count); } public static Vector256 ShiftLeftLogical(Vector256 value, Vector128 count) { return ShiftLeftLogical(value, count); } public static Vector256 ShiftLeftLogical(Vector256 value, Vector128 count) { return ShiftLeftLogical(value, count); } public static Vector256 ShiftLeftLogical(Vector256 value, Vector128 count) { return ShiftLeftLogical(value, count); } public static Vector256 ShiftLeftLogical(Vector256 value, Vector128 count) { return ShiftLeftLogical(value, count); } public static Vector256 ShiftLeftLogical(Vector256 value, byte count) { return ShiftLeftLogical(value, count); } public static Vector256 ShiftLeftLogical(Vector256 value, byte count) { return ShiftLeftLogical(value, count); } public static Vector256 ShiftLeftLogical(Vector256 value, byte count) { return ShiftLeftLogical(value, count); } public static Vector256 ShiftLeftLogical(Vector256 value, byte count) { return ShiftLeftLogical(value, count); } public static Vector256 ShiftLeftLogical(Vector256 value, byte count) { return ShiftLeftLogical(value, count); } public static Vector256 ShiftLeftLogical(Vector256 value, byte count) { return ShiftLeftLogical(value, count); } public static Vector256 ShiftLeftLogical128BitLane(Vector256 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector256 ShiftLeftLogical128BitLane(Vector256 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector256 ShiftLeftLogical128BitLane(Vector256 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector256 ShiftLeftLogical128BitLane(Vector256 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector256 ShiftLeftLogical128BitLane(Vector256 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector256 ShiftLeftLogical128BitLane(Vector256 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector256 ShiftLeftLogical128BitLane(Vector256 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector256 ShiftLeftLogical128BitLane(Vector256 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector256 ShiftLeftLogicalVariable(Vector256 value, Vector256 count) { return ShiftLeftLogicalVariable(value, count); } public static Vector256 ShiftLeftLogicalVariable(Vector256 value, Vector256 count) { return ShiftLeftLogicalVariable(value, count); } public static Vector256 ShiftLeftLogicalVariable(Vector256 value, Vector256 count) { return ShiftLeftLogicalVariable(value, count); } public static Vector256 ShiftLeftLogicalVariable(Vector256 value, Vector256 count) { return ShiftLeftLogicalVariable(value, count); } public static Vector128 ShiftLeftLogicalVariable(Vector128 value, Vector128 count) { return ShiftLeftLogicalVariable(value, count); } public static Vector128 ShiftLeftLogicalVariable(Vector128 value, Vector128 count) { return ShiftLeftLogicalVariable(value, count); } public static Vector128 ShiftLeftLogicalVariable(Vector128 value, Vector128 count) { return ShiftLeftLogicalVariable(value, count); } public static Vector128 ShiftLeftLogicalVariable(Vector128 value, Vector128 count) { return ShiftLeftLogicalVariable(value, count); } public static Vector256 ShiftRightArithmetic(Vector256 value, Vector128 count) { return ShiftRightArithmetic(value, count); } public static Vector256 ShiftRightArithmetic(Vector256 value, Vector128 count) { return ShiftRightArithmetic(value, count); } public static Vector256 ShiftRightArithmetic(Vector256 value, byte count) { return ShiftRightArithmetic(value, count); } public static Vector256 ShiftRightArithmetic(Vector256 value, byte count) { return ShiftRightArithmetic(value, count); } public static Vector256 ShiftRightArithmeticVariable(Vector256 value, Vector256 count) { return ShiftRightArithmeticVariable(value, count); } public static Vector128 ShiftRightArithmeticVariable(Vector128 value, Vector128 count) { return ShiftRightArithmeticVariable(value, count); } public static Vector256 ShiftRightLogical(Vector256 value, Vector128 count) { return ShiftRightLogical(value, count); } public static Vector256 ShiftRightLogical(Vector256 value, Vector128 count) { return ShiftRightLogical(value, count); } public static Vector256 ShiftRightLogical(Vector256 value, Vector128 count) { return ShiftRightLogical(value, count); } public static Vector256 ShiftRightLogical(Vector256 value, Vector128 count) { return ShiftRightLogical(value, count); } public static Vector256 ShiftRightLogical(Vector256 value, Vector128 count) { return ShiftRightLogical(value, count); } public static Vector256 ShiftRightLogical(Vector256 value, Vector128 count) { return ShiftRightLogical(value, count); } public static Vector256 ShiftRightLogical(Vector256 value, byte count) { return ShiftRightLogical(value, count); } public static Vector256 ShiftRightLogical(Vector256 value, byte count) { return ShiftRightLogical(value, count); } public static Vector256 ShiftRightLogical(Vector256 value, byte count) { return ShiftRightLogical(value, count); } public static Vector256 ShiftRightLogical(Vector256 value, byte count) { return ShiftRightLogical(value, count); } public static Vector256 ShiftRightLogical(Vector256 value, byte count) { return ShiftRightLogical(value, count); } public static Vector256 ShiftRightLogical(Vector256 value, byte count) { return ShiftRightLogical(value, count); } public static Vector256 ShiftRightLogical128BitLane(Vector256 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector256 ShiftRightLogical128BitLane(Vector256 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector256 ShiftRightLogical128BitLane(Vector256 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector256 ShiftRightLogical128BitLane(Vector256 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector256 ShiftRightLogical128BitLane(Vector256 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector256 ShiftRightLogical128BitLane(Vector256 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector256 ShiftRightLogical128BitLane(Vector256 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector256 ShiftRightLogical128BitLane(Vector256 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector256 ShiftRightLogicalVariable(Vector256 value, Vector256 count) { return ShiftRightLogicalVariable(value, count); } public static Vector256 ShiftRightLogicalVariable(Vector256 value, Vector256 count) { return ShiftRightLogicalVariable(value, count); } public static Vector256 ShiftRightLogicalVariable(Vector256 value, Vector256 count) { return ShiftRightLogicalVariable(value, count); } public static Vector256 ShiftRightLogicalVariable(Vector256 value, Vector256 count) { return ShiftRightLogicalVariable(value, count); } public static Vector128 ShiftRightLogicalVariable(Vector128 value, Vector128 count) { return ShiftRightLogicalVariable(value, count); } public static Vector128 ShiftRightLogicalVariable(Vector128 value, Vector128 count) { return ShiftRightLogicalVariable(value, count); } public static Vector128 ShiftRightLogicalVariable(Vector128 value, Vector128 count) { return ShiftRightLogicalVariable(value, count); } public static Vector128 ShiftRightLogicalVariable(Vector128 value, Vector128 count) { return ShiftRightLogicalVariable(value, count); } public static Vector256 Shuffle(Vector256 value, Vector256 mask) { return Shuffle(value, mask); } public static Vector256 Shuffle(Vector256 value, Vector256 mask) { return Shuffle(value, mask); } public static Vector256 Shuffle(Vector256 value, byte control) { return Shuffle(value, control); } public static Vector256 Shuffle(Vector256 value, byte control) { return Shuffle(value, control); } public static Vector256 ShuffleHigh(Vector256 value, byte control) { return ShuffleHigh(value, control); } public static Vector256 ShuffleHigh(Vector256 value, byte control) { return ShuffleHigh(value, control); } public static Vector256 ShuffleLow(Vector256 value, byte control) { return ShuffleLow(value, control); } public static Vector256 ShuffleLow(Vector256 value, byte control) { return ShuffleLow(value, control); } public static Vector256 Sign(Vector256 left, Vector256 right) { return Sign(left, right); } public static Vector256 Sign(Vector256 left, Vector256 right) { return Sign(left, right); } public static Vector256 Sign(Vector256 left, Vector256 right) { return Sign(left, right); } public static Vector256 Subtract(Vector256 left, Vector256 right) { return Subtract(left, right); } public static Vector256 Subtract(Vector256 left, Vector256 right) { return Subtract(left, right); } public static Vector256 Subtract(Vector256 left, Vector256 right) { return Subtract(left, right); } public static Vector256 Subtract(Vector256 left, Vector256 right) { return Subtract(left, right); } public static Vector256 Subtract(Vector256 left, Vector256 right) { return Subtract(left, right); } public static Vector256 Subtract(Vector256 left, Vector256 right) { return Subtract(left, right); } public static Vector256 Subtract(Vector256 left, Vector256 right) { return Subtract(left, right); } public static Vector256 Subtract(Vector256 left, Vector256 right) { return Subtract(left, right); } public static Vector256 SubtractSaturate(Vector256 left, Vector256 right) { return SubtractSaturate(left, right); } public static Vector256 SubtractSaturate(Vector256 left, Vector256 right) { return SubtractSaturate(left, right); } public static Vector256 SubtractSaturate(Vector256 left, Vector256 right) { return SubtractSaturate(left, right); } public static Vector256 SubtractSaturate(Vector256 left, Vector256 right) { return SubtractSaturate(left, right); } public static Vector256 SumAbsoluteDifferences(Vector256 left, Vector256 right) { return SumAbsoluteDifferences(left, right); } public static Vector256 UnpackHigh(Vector256 left, Vector256 right) { return UnpackHigh(left, right); } public static Vector256 UnpackHigh(Vector256 left, Vector256 right) { return UnpackHigh(left, right); } public static Vector256 UnpackHigh(Vector256 left, Vector256 right) { return UnpackHigh(left, right); } public static Vector256 UnpackHigh(Vector256 left, Vector256 right) { return UnpackHigh(left, right); } public static Vector256 UnpackHigh(Vector256 left, Vector256 right) { return UnpackHigh(left, right); } public static Vector256 UnpackHigh(Vector256 left, Vector256 right) { return UnpackHigh(left, right); } public static Vector256 UnpackHigh(Vector256 left, Vector256 right) { return UnpackHigh(left, right); } public static Vector256 UnpackHigh(Vector256 left, Vector256 right) { return UnpackHigh(left, right); } public static Vector256 UnpackLow(Vector256 left, Vector256 right) { return UnpackLow(left, right); } public static Vector256 UnpackLow(Vector256 left, Vector256 right) { return UnpackLow(left, right); } public static Vector256 UnpackLow(Vector256 left, Vector256 right) { return UnpackLow(left, right); } public static Vector256 UnpackLow(Vector256 left, Vector256 right) { return UnpackLow(left, right); } public static Vector256 UnpackLow(Vector256 left, Vector256 right) { return UnpackLow(left, right); } public static Vector256 UnpackLow(Vector256 left, Vector256 right) { return UnpackLow(left, right); } public static Vector256 UnpackLow(Vector256 left, Vector256 right) { return UnpackLow(left, right); } public static Vector256 UnpackLow(Vector256 left, Vector256 right) { return UnpackLow(left, right); } public static Vector256 Xor(Vector256 left, Vector256 right) { return Xor(left, right); } public static Vector256 Xor(Vector256 left, Vector256 right) { return Xor(left, right); } public static Vector256 Xor(Vector256 left, Vector256 right) { return Xor(left, right); } public static Vector256 Xor(Vector256 left, Vector256 right) { return Xor(left, right); } public static Vector256 Xor(Vector256 left, Vector256 right) { return Xor(left, right); } public static Vector256 Xor(Vector256 left, Vector256 right) { return Xor(left, right); } public static Vector256 Xor(Vector256 left, Vector256 right) { return Xor(left, right); } public static Vector256 Xor(Vector256 left, Vector256 right) { return Xor(left, right); } } [Intrinsic] [CLSCompliant(false)] [RequiresPreviewFeatures("AvxVnni is in preview.")] public abstract class AvxVnni : Avx2 { [Intrinsic] public new abstract class X64 : Avx2.X64 { public new static bool IsSupported => IsSupported; } public new static bool IsSupported => IsSupported; public static Vector128 MultiplyWideningAndAdd(Vector128 addend, Vector128 left, Vector128 right) { return MultiplyWideningAndAdd(addend, left, right); } public static Vector128 MultiplyWideningAndAdd(Vector128 addend, Vector128 left, Vector128 right) { return MultiplyWideningAndAdd(addend, left, right); } public static Vector256 MultiplyWideningAndAdd(Vector256 addend, Vector256 left, Vector256 right) { return MultiplyWideningAndAdd(addend, left, right); } public static Vector256 MultiplyWideningAndAdd(Vector256 addend, Vector256 left, Vector256 right) { return MultiplyWideningAndAdd(addend, left, right); } public static Vector128 MultiplyWideningAndAddSaturate(Vector128 addend, Vector128 left, Vector128 right) { return MultiplyWideningAndAddSaturate(addend, left, right); } public static Vector128 MultiplyWideningAndAddSaturate(Vector128 addend, Vector128 left, Vector128 right) { return MultiplyWideningAndAddSaturate(addend, left, right); } public static Vector256 MultiplyWideningAndAddSaturate(Vector256 addend, Vector256 left, Vector256 right) { return MultiplyWideningAndAddSaturate(addend, left, right); } public static Vector256 MultiplyWideningAndAddSaturate(Vector256 addend, Vector256 left, Vector256 right) { return MultiplyWideningAndAddSaturate(addend, left, right); } } [Intrinsic] [CLSCompliant(false)] public abstract class Bmi1 : X86Base { [Intrinsic] public new abstract class X64 : X86Base.X64 { public new static bool IsSupported => IsSupported; public static ulong AndNot(ulong left, ulong right) { return AndNot(left, right); } public static ulong BitFieldExtract(ulong value, byte start, byte length) { return BitFieldExtract(value, (ushort)(start | (length << 8))); } public static ulong BitFieldExtract(ulong value, ushort control) { return BitFieldExtract(value, control); } public static ulong ExtractLowestSetBit(ulong value) { return ExtractLowestSetBit(value); } public static ulong GetMaskUpToLowestSetBit(ulong value) { return GetMaskUpToLowestSetBit(value); } public static ulong ResetLowestSetBit(ulong value) { return ResetLowestSetBit(value); } public static ulong TrailingZeroCount(ulong value) { return TrailingZeroCount(value); } } public new static bool IsSupported => IsSupported; public static uint AndNot(uint left, uint right) { return AndNot(left, right); } public static uint BitFieldExtract(uint value, byte start, byte length) { return BitFieldExtract(value, (ushort)(start | (length << 8))); } public static uint BitFieldExtract(uint value, ushort control) { return BitFieldExtract(value, control); } public static uint ExtractLowestSetBit(uint value) { return ExtractLowestSetBit(value); } public static uint GetMaskUpToLowestSetBit(uint value) { return GetMaskUpToLowestSetBit(value); } public static uint ResetLowestSetBit(uint value) { return ResetLowestSetBit(value); } public static uint TrailingZeroCount(uint value) { return TrailingZeroCount(value); } } [Intrinsic] [CLSCompliant(false)] public abstract class Bmi2 : X86Base { [Intrinsic] public new abstract class X64 : X86Base.X64 { public new static bool IsSupported => IsSupported; public static ulong ZeroHighBits(ulong value, ulong index) { return ZeroHighBits(value, index); } public static ulong MultiplyNoFlags(ulong left, ulong right) { return MultiplyNoFlags(left, right); } public unsafe static ulong MultiplyNoFlags(ulong left, ulong right, ulong* low) { return MultiplyNoFlags(left, right, low); } public static ulong ParallelBitDeposit(ulong value, ulong mask) { return ParallelBitDeposit(value, mask); } public static ulong ParallelBitExtract(ulong value, ulong mask) { return ParallelBitExtract(value, mask); } } public new static bool IsSupported => IsSupported; public static uint ZeroHighBits(uint value, uint index) { return ZeroHighBits(value, index); } public static uint MultiplyNoFlags(uint left, uint right) { return MultiplyNoFlags(left, right); } public unsafe static uint MultiplyNoFlags(uint left, uint right, uint* low) { return MultiplyNoFlags(left, right, low); } public static uint ParallelBitDeposit(uint value, uint mask) { return ParallelBitDeposit(value, mask); } public static uint ParallelBitExtract(uint value, uint mask) { return ParallelBitExtract(value, mask); } } [Intrinsic] [CLSCompliant(false)] public abstract class Fma : Avx { [Intrinsic] public new abstract class X64 : Avx.X64 { public new static bool IsSupported => IsSupported; } public new static bool IsSupported => IsSupported; public static Vector128 MultiplyAdd(Vector128 a, Vector128 b, Vector128 c) { return MultiplyAdd(a, b, c); } public static Vector128 MultiplyAdd(Vector128 a, Vector128 b, Vector128 c) { return MultiplyAdd(a, b, c); } public static Vector256 MultiplyAdd(Vector256 a, Vector256 b, Vector256 c) { return MultiplyAdd(a, b, c); } public static Vector256 MultiplyAdd(Vector256 a, Vector256 b, Vector256 c) { return MultiplyAdd(a, b, c); } public static Vector128 MultiplyAddScalar(Vector128 a, Vector128 b, Vector128 c) { return MultiplyAddScalar(a, b, c); } public static Vector128 MultiplyAddScalar(Vector128 a, Vector128 b, Vector128 c) { return MultiplyAddScalar(a, b, c); } public static Vector128 MultiplyAddSubtract(Vector128 a, Vector128 b, Vector128 c) { return MultiplyAddSubtract(a, b, c); } public static Vector128 MultiplyAddSubtract(Vector128 a, Vector128 b, Vector128 c) { return MultiplyAddSubtract(a, b, c); } public static Vector256 MultiplyAddSubtract(Vector256 a, Vector256 b, Vector256 c) { return MultiplyAddSubtract(a, b, c); } public static Vector256 MultiplyAddSubtract(Vector256 a, Vector256 b, Vector256 c) { return MultiplyAddSubtract(a, b, c); } public static Vector128 MultiplySubtract(Vector128 a, Vector128 b, Vector128 c) { return MultiplySubtract(a, b, c); } public static Vector128 MultiplySubtract(Vector128 a, Vector128 b, Vector128 c) { return MultiplySubtract(a, b, c); } public static Vector256 MultiplySubtract(Vector256 a, Vector256 b, Vector256 c) { return MultiplySubtract(a, b, c); } public static Vector256 MultiplySubtract(Vector256 a, Vector256 b, Vector256 c) { return MultiplySubtract(a, b, c); } public static Vector128 MultiplySubtractScalar(Vector128 a, Vector128 b, Vector128 c) { return MultiplySubtractScalar(a, b, c); } public static Vector128 MultiplySubtractScalar(Vector128 a, Vector128 b, Vector128 c) { return MultiplySubtractScalar(a, b, c); } public static Vector128 MultiplySubtractAdd(Vector128 a, Vector128 b, Vector128 c) { return MultiplySubtractAdd(a, b, c); } public static Vector128 MultiplySubtractAdd(Vector128 a, Vector128 b, Vector128 c) { return MultiplySubtractAdd(a, b, c); } public static Vector256 MultiplySubtractAdd(Vector256 a, Vector256 b, Vector256 c) { return MultiplySubtractAdd(a, b, c); } public static Vector256 MultiplySubtractAdd(Vector256 a, Vector256 b, Vector256 c) { return MultiplySubtractAdd(a, b, c); } public static Vector128 MultiplyAddNegated(Vector128 a, Vector128 b, Vector128 c) { return MultiplyAddNegated(a, b, c); } public static Vector128 MultiplyAddNegated(Vector128 a, Vector128 b, Vector128 c) { return MultiplyAddNegated(a, b, c); } public static Vector256 MultiplyAddNegated(Vector256 a, Vector256 b, Vector256 c) { return MultiplyAddNegated(a, b, c); } public static Vector256 MultiplyAddNegated(Vector256 a, Vector256 b, Vector256 c) { return MultiplyAddNegated(a, b, c); } public static Vector128 MultiplyAddNegatedScalar(Vector128 a, Vector128 b, Vector128 c) { return MultiplyAddNegatedScalar(a, b, c); } public static Vector128 MultiplyAddNegatedScalar(Vector128 a, Vector128 b, Vector128 c) { return MultiplyAddNegatedScalar(a, b, c); } public static Vector128 MultiplySubtractNegated(Vector128 a, Vector128 b, Vector128 c) { return MultiplySubtractNegated(a, b, c); } public static Vector128 MultiplySubtractNegated(Vector128 a, Vector128 b, Vector128 c) { return MultiplySubtractNegated(a, b, c); } public static Vector256 MultiplySubtractNegated(Vector256 a, Vector256 b, Vector256 c) { return MultiplySubtractNegated(a, b, c); } public static Vector256 MultiplySubtractNegated(Vector256 a, Vector256 b, Vector256 c) { return MultiplySubtractNegated(a, b, c); } public static Vector128 MultiplySubtractNegatedScalar(Vector128 a, Vector128 b, Vector128 c) { return MultiplySubtractNegatedScalar(a, b, c); } public static Vector128 MultiplySubtractNegatedScalar(Vector128 a, Vector128 b, Vector128 c) { return MultiplySubtractNegatedScalar(a, b, c); } } [Intrinsic] [CLSCompliant(false)] public abstract class Lzcnt : X86Base { [Intrinsic] public new abstract class X64 : X86Base.X64 { public new static bool IsSupported => IsSupported; public static ulong LeadingZeroCount(ulong value) { return LeadingZeroCount(value); } } public new static bool IsSupported => IsSupported; public static uint LeadingZeroCount(uint value) { return LeadingZeroCount(value); } } [Intrinsic] [CLSCompliant(false)] public abstract class Pclmulqdq : Sse2 { [Intrinsic] public new abstract class X64 : Sse2.X64 { public new static bool IsSupported => IsSupported; } public new static bool IsSupported => IsSupported; public static Vector128 CarrylessMultiply(Vector128 left, Vector128 right, byte control) { return CarrylessMultiply(left, right, control); } public static Vector128 CarrylessMultiply(Vector128 left, Vector128 right, byte control) { return CarrylessMultiply(left, right, control); } } [Intrinsic] [CLSCompliant(false)] public abstract class Popcnt : Sse42 { [Intrinsic] public new abstract class X64 : Sse42.X64 { public new static bool IsSupported => IsSupported; public static ulong PopCount(ulong value) { return PopCount(value); } } public new static bool IsSupported => IsSupported; public static uint PopCount(uint value) { return PopCount(value); } } [Intrinsic] [CLSCompliant(false)] public abstract class Sse : X86Base { [Intrinsic] public new abstract class X64 : X86Base.X64 { public new static bool IsSupported => IsSupported; public static long ConvertToInt64(Vector128 value) { return ConvertToInt64(value); } public static Vector128 ConvertScalarToVector128Single(Vector128 upper, long value) { return ConvertScalarToVector128Single(upper, value); } public static long ConvertToInt64WithTruncation(Vector128 value) { return ConvertToInt64WithTruncation(value); } } public new static bool IsSupported => IsSupported; public static Vector128 Add(Vector128 left, Vector128 right) { return Add(left, right); } public static Vector128 AddScalar(Vector128 left, Vector128 right) { return AddScalar(left, right); } public static Vector128 And(Vector128 left, Vector128 right) { return And(left, right); } public static Vector128 AndNot(Vector128 left, Vector128 right) { return AndNot(left, right); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { return CompareEqual(left, right); } public static bool CompareScalarOrderedEqual(Vector128 left, Vector128 right) { return CompareScalarOrderedEqual(left, right); } public static bool CompareScalarUnorderedEqual(Vector128 left, Vector128 right) { return CompareScalarUnorderedEqual(left, right); } public static Vector128 CompareScalarEqual(Vector128 left, Vector128 right) { return CompareScalarEqual(left, right); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { return CompareGreaterThan(left, right); } public static bool CompareScalarOrderedGreaterThan(Vector128 left, Vector128 right) { return CompareScalarOrderedGreaterThan(left, right); } public static bool CompareScalarUnorderedGreaterThan(Vector128 left, Vector128 right) { return CompareScalarUnorderedGreaterThan(left, right); } public static Vector128 CompareScalarGreaterThan(Vector128 left, Vector128 right) { return CompareScalarGreaterThan(left, right); } public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) { return CompareGreaterThanOrEqual(left, right); } public static bool CompareScalarOrderedGreaterThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarOrderedGreaterThanOrEqual(left, right); } public static bool CompareScalarUnorderedGreaterThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarUnorderedGreaterThanOrEqual(left, right); } public static Vector128 CompareScalarGreaterThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarGreaterThanOrEqual(left, right); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { return CompareLessThan(left, right); } public static bool CompareScalarOrderedLessThan(Vector128 left, Vector128 right) { return CompareScalarOrderedLessThan(left, right); } public static bool CompareScalarUnorderedLessThan(Vector128 left, Vector128 right) { return CompareScalarUnorderedLessThan(left, right); } public static Vector128 CompareScalarLessThan(Vector128 left, Vector128 right) { return CompareScalarLessThan(left, right); } public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) { return CompareLessThanOrEqual(left, right); } public static bool CompareScalarOrderedLessThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarOrderedLessThanOrEqual(left, right); } public static bool CompareScalarUnorderedLessThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarUnorderedLessThanOrEqual(left, right); } public static Vector128 CompareScalarLessThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarLessThanOrEqual(left, right); } public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { return CompareNotEqual(left, right); } public static bool CompareScalarOrderedNotEqual(Vector128 left, Vector128 right) { return CompareScalarOrderedNotEqual(left, right); } public static bool CompareScalarUnorderedNotEqual(Vector128 left, Vector128 right) { return CompareScalarUnorderedNotEqual(left, right); } public static Vector128 CompareScalarNotEqual(Vector128 left, Vector128 right) { return CompareScalarNotEqual(left, right); } public static Vector128 CompareNotGreaterThan(Vector128 left, Vector128 right) { return CompareNotGreaterThan(left, right); } public static Vector128 CompareScalarNotGreaterThan(Vector128 left, Vector128 right) { return CompareScalarNotGreaterThan(left, right); } public static Vector128 CompareNotGreaterThanOrEqual(Vector128 left, Vector128 right) { return CompareNotGreaterThanOrEqual(left, right); } public static Vector128 CompareScalarNotGreaterThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarNotGreaterThanOrEqual(left, right); } public static Vector128 CompareNotLessThan(Vector128 left, Vector128 right) { return CompareNotLessThan(left, right); } public static Vector128 CompareScalarNotLessThan(Vector128 left, Vector128 right) { return CompareScalarNotLessThan(left, right); } public static Vector128 CompareNotLessThanOrEqual(Vector128 left, Vector128 right) { return CompareNotLessThanOrEqual(left, right); } public static Vector128 CompareScalarNotLessThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarNotLessThanOrEqual(left, right); } public static Vector128 CompareOrdered(Vector128 left, Vector128 right) { return CompareOrdered(left, right); } public static Vector128 CompareScalarOrdered(Vector128 left, Vector128 right) { return CompareScalarOrdered(left, right); } public static Vector128 CompareUnordered(Vector128 left, Vector128 right) { return CompareUnordered(left, right); } public static Vector128 CompareScalarUnordered(Vector128 left, Vector128 right) { return CompareScalarUnordered(left, right); } public static int ConvertToInt32(Vector128 value) { return ConvertToInt32(value); } public static Vector128 ConvertScalarToVector128Single(Vector128 upper, int value) { return ConvertScalarToVector128Single(upper, value); } public static int ConvertToInt32WithTruncation(Vector128 value) { return ConvertToInt32WithTruncation(value); } public static Vector128 Divide(Vector128 left, Vector128 right) { return Divide(left, right); } public static Vector128 DivideScalar(Vector128 left, Vector128 right) { return DivideScalar(left, right); } public unsafe static Vector128 LoadVector128(float* address) { return LoadVector128(address); } public unsafe static Vector128 LoadScalarVector128(float* address) { return LoadScalarVector128(address); } public unsafe static Vector128 LoadAlignedVector128(float* address) { return LoadAlignedVector128(address); } public unsafe static Vector128 LoadHigh(Vector128 lower, float* address) { return LoadHigh(lower, address); } public unsafe static Vector128 LoadLow(Vector128 upper, float* address) { return LoadLow(upper, address); } public static Vector128 Max(Vector128 left, Vector128 right) { return Max(left, right); } public static Vector128 MaxScalar(Vector128 left, Vector128 right) { return MaxScalar(left, right); } public static Vector128 Min(Vector128 left, Vector128 right) { return Min(left, right); } public static Vector128 MinScalar(Vector128 left, Vector128 right) { return MinScalar(left, right); } public static Vector128 MoveScalar(Vector128 upper, Vector128 value) { return MoveScalar(upper, value); } public static Vector128 MoveHighToLow(Vector128 left, Vector128 right) { return MoveHighToLow(left, right); } public static Vector128 MoveLowToHigh(Vector128 left, Vector128 right) { return MoveLowToHigh(left, right); } public static int MoveMask(Vector128 value) { return MoveMask(value); } public static Vector128 Multiply(Vector128 left, Vector128 right) { return Multiply(left, right); } public static Vector128 MultiplyScalar(Vector128 left, Vector128 right) { return MultiplyScalar(left, right); } public static Vector128 Or(Vector128 left, Vector128 right) { return Or(left, right); } public unsafe static void Prefetch0(void* address) { Prefetch0(address); } public unsafe static void Prefetch1(void* address) { Prefetch1(address); } public unsafe static void Prefetch2(void* address) { Prefetch2(address); } public unsafe static void PrefetchNonTemporal(void* address) { PrefetchNonTemporal(address); } public static Vector128 Reciprocal(Vector128 value) { return Reciprocal(value); } public static Vector128 ReciprocalScalar(Vector128 value) { return ReciprocalScalar(value); } public static Vector128 ReciprocalScalar(Vector128 upper, Vector128 value) { return ReciprocalScalar(upper, value); } public static Vector128 ReciprocalSqrt(Vector128 value) { return ReciprocalSqrt(value); } public static Vector128 ReciprocalSqrtScalar(Vector128 value) { return ReciprocalSqrtScalar(value); } public static Vector128 ReciprocalSqrtScalar(Vector128 upper, Vector128 value) { return ReciprocalSqrtScalar(upper, value); } public static Vector128 Shuffle(Vector128 left, Vector128 right, byte control) { return Shuffle(left, right, control); } public static Vector128 Sqrt(Vector128 value) { return Sqrt(value); } public static Vector128 SqrtScalar(Vector128 value) { return SqrtScalar(value); } public static Vector128 SqrtScalar(Vector128 upper, Vector128 value) { return SqrtScalar(upper, value); } public unsafe static void StoreAligned(float* address, Vector128 source) { StoreAligned(address, source); } public unsafe static void StoreAlignedNonTemporal(float* address, Vector128 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void Store(float* address, Vector128 source) { Store(address, source); } public static void StoreFence() { StoreFence(); } public unsafe static void StoreScalar(float* address, Vector128 source) { StoreScalar(address, source); } public unsafe static void StoreHigh(float* address, Vector128 source) { StoreHigh(address, source); } public unsafe static void StoreLow(float* address, Vector128 source) { StoreLow(address, source); } public static Vector128 Subtract(Vector128 left, Vector128 right) { return Subtract(left, right); } public static Vector128 SubtractScalar(Vector128 left, Vector128 right) { return SubtractScalar(left, right); } public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { return UnpackHigh(left, right); } public static Vector128 UnpackLow(Vector128 left, Vector128 right) { return UnpackLow(left, right); } public static Vector128 Xor(Vector128 left, Vector128 right) { return Xor(left, right); } } [Intrinsic] [CLSCompliant(false)] public abstract class Sse2 : Sse { [Intrinsic] public new abstract class X64 : Sse.X64 { public new static bool IsSupported => IsSupported; public static long ConvertToInt64(Vector128 value) { return ConvertToInt64(value); } public static long ConvertToInt64(Vector128 value) { return ConvertToInt64(value); } public static ulong ConvertToUInt64(Vector128 value) { return ConvertToUInt64(value); } public static Vector128 ConvertScalarToVector128Double(Vector128 upper, long value) { return ConvertScalarToVector128Double(upper, value); } public static Vector128 ConvertScalarToVector128Int64(long value) { return ConvertScalarToVector128Int64(value); } public static Vector128 ConvertScalarToVector128UInt64(ulong value) { return ConvertScalarToVector128UInt64(value); } public static long ConvertToInt64WithTruncation(Vector128 value) { return ConvertToInt64WithTruncation(value); } public unsafe static void StoreNonTemporal(long* address, long value) { StoreNonTemporal(address, value); } public unsafe static void StoreNonTemporal(ulong* address, ulong value) { StoreNonTemporal(address, value); } } public new static bool IsSupported => IsSupported; public static Vector128 Add(Vector128 left, Vector128 right) { return Add(left, right); } public static Vector128 Add(Vector128 left, Vector128 right) { return Add(left, right); } public static Vector128 Add(Vector128 left, Vector128 right) { return Add(left, right); } public static Vector128 Add(Vector128 left, Vector128 right) { return Add(left, right); } public static Vector128 Add(Vector128 left, Vector128 right) { return Add(left, right); } public static Vector128 Add(Vector128 left, Vector128 right) { return Add(left, right); } public static Vector128 Add(Vector128 left, Vector128 right) { return Add(left, right); } public static Vector128 Add(Vector128 left, Vector128 right) { return Add(left, right); } public static Vector128 Add(Vector128 left, Vector128 right) { return Add(left, right); } public static Vector128 AddScalar(Vector128 left, Vector128 right) { return AddScalar(left, right); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { return AddSaturate(left, right); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { return AddSaturate(left, right); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { return AddSaturate(left, right); } public static Vector128 AddSaturate(Vector128 left, Vector128 right) { return AddSaturate(left, right); } public static Vector128 And(Vector128 left, Vector128 right) { return And(left, right); } public static Vector128 And(Vector128 left, Vector128 right) { return And(left, right); } public static Vector128 And(Vector128 left, Vector128 right) { return And(left, right); } public static Vector128 And(Vector128 left, Vector128 right) { return And(left, right); } public static Vector128 And(Vector128 left, Vector128 right) { return And(left, right); } public static Vector128 And(Vector128 left, Vector128 right) { return And(left, right); } public static Vector128 And(Vector128 left, Vector128 right) { return And(left, right); } public static Vector128 And(Vector128 left, Vector128 right) { return And(left, right); } public static Vector128 And(Vector128 left, Vector128 right) { return And(left, right); } public static Vector128 AndNot(Vector128 left, Vector128 right) { return AndNot(left, right); } public static Vector128 AndNot(Vector128 left, Vector128 right) { return AndNot(left, right); } public static Vector128 AndNot(Vector128 left, Vector128 right) { return AndNot(left, right); } public static Vector128 AndNot(Vector128 left, Vector128 right) { return AndNot(left, right); } public static Vector128 AndNot(Vector128 left, Vector128 right) { return AndNot(left, right); } public static Vector128 AndNot(Vector128 left, Vector128 right) { return AndNot(left, right); } public static Vector128 AndNot(Vector128 left, Vector128 right) { return AndNot(left, right); } public static Vector128 AndNot(Vector128 left, Vector128 right) { return AndNot(left, right); } public static Vector128 AndNot(Vector128 left, Vector128 right) { return AndNot(left, right); } public static Vector128 Average(Vector128 left, Vector128 right) { return Average(left, right); } public static Vector128 Average(Vector128 left, Vector128 right) { return Average(left, right); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { return CompareEqual(left, right); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { return CompareEqual(left, right); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { return CompareEqual(left, right); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { return CompareEqual(left, right); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { return CompareEqual(left, right); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { return CompareEqual(left, right); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { return CompareEqual(left, right); } public static bool CompareScalarOrderedEqual(Vector128 left, Vector128 right) { return CompareScalarOrderedEqual(left, right); } public static bool CompareScalarUnorderedEqual(Vector128 left, Vector128 right) { return CompareScalarUnorderedEqual(left, right); } public static Vector128 CompareScalarEqual(Vector128 left, Vector128 right) { return CompareScalarEqual(left, right); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { return CompareGreaterThan(left, right); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { return CompareGreaterThan(left, right); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { return CompareGreaterThan(left, right); } public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { return CompareGreaterThan(left, right); } public static bool CompareScalarOrderedGreaterThan(Vector128 left, Vector128 right) { return CompareScalarOrderedGreaterThan(left, right); } public static bool CompareScalarUnorderedGreaterThan(Vector128 left, Vector128 right) { return CompareScalarUnorderedGreaterThan(left, right); } public static Vector128 CompareScalarGreaterThan(Vector128 left, Vector128 right) { return CompareScalarGreaterThan(left, right); } public static Vector128 CompareGreaterThanOrEqual(Vector128 left, Vector128 right) { return CompareGreaterThanOrEqual(left, right); } public static bool CompareScalarOrderedGreaterThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarOrderedGreaterThanOrEqual(left, right); } public static bool CompareScalarUnorderedGreaterThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarUnorderedGreaterThanOrEqual(left, right); } public static Vector128 CompareScalarGreaterThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarGreaterThanOrEqual(left, right); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { return CompareLessThan(left, right); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { return CompareLessThan(left, right); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { return CompareLessThan(left, right); } public static Vector128 CompareLessThan(Vector128 left, Vector128 right) { return CompareLessThan(left, right); } public static bool CompareScalarOrderedLessThan(Vector128 left, Vector128 right) { return CompareScalarOrderedLessThan(left, right); } public static bool CompareScalarUnorderedLessThan(Vector128 left, Vector128 right) { return CompareScalarUnorderedLessThan(left, right); } public static Vector128 CompareScalarLessThan(Vector128 left, Vector128 right) { return CompareScalarLessThan(left, right); } public static Vector128 CompareLessThanOrEqual(Vector128 left, Vector128 right) { return CompareLessThanOrEqual(left, right); } public static bool CompareScalarOrderedLessThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarOrderedLessThanOrEqual(left, right); } public static bool CompareScalarUnorderedLessThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarUnorderedLessThanOrEqual(left, right); } public static Vector128 CompareScalarLessThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarLessThanOrEqual(left, right); } public static Vector128 CompareNotEqual(Vector128 left, Vector128 right) { return CompareNotEqual(left, right); } public static bool CompareScalarOrderedNotEqual(Vector128 left, Vector128 right) { return CompareScalarOrderedNotEqual(left, right); } public static bool CompareScalarUnorderedNotEqual(Vector128 left, Vector128 right) { return CompareScalarUnorderedNotEqual(left, right); } public static Vector128 CompareScalarNotEqual(Vector128 left, Vector128 right) { return CompareScalarNotEqual(left, right); } public static Vector128 CompareNotGreaterThan(Vector128 left, Vector128 right) { return CompareNotGreaterThan(left, right); } public static Vector128 CompareScalarNotGreaterThan(Vector128 left, Vector128 right) { return CompareScalarNotGreaterThan(left, right); } public static Vector128 CompareNotGreaterThanOrEqual(Vector128 left, Vector128 right) { return CompareNotGreaterThanOrEqual(left, right); } public static Vector128 CompareScalarNotGreaterThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarNotGreaterThanOrEqual(left, right); } public static Vector128 CompareNotLessThan(Vector128 left, Vector128 right) { return CompareNotLessThan(left, right); } public static Vector128 CompareScalarNotLessThan(Vector128 left, Vector128 right) { return CompareScalarNotLessThan(left, right); } public static Vector128 CompareNotLessThanOrEqual(Vector128 left, Vector128 right) { return CompareNotLessThanOrEqual(left, right); } public static Vector128 CompareScalarNotLessThanOrEqual(Vector128 left, Vector128 right) { return CompareScalarNotLessThanOrEqual(left, right); } public static Vector128 CompareOrdered(Vector128 left, Vector128 right) { return CompareOrdered(left, right); } public static Vector128 CompareScalarOrdered(Vector128 left, Vector128 right) { return CompareScalarOrdered(left, right); } public static Vector128 CompareUnordered(Vector128 left, Vector128 right) { return CompareUnordered(left, right); } public static Vector128 CompareScalarUnordered(Vector128 left, Vector128 right) { return CompareScalarUnordered(left, right); } public static Vector128 ConvertToVector128Int32(Vector128 value) { return ConvertToVector128Int32(value); } public static Vector128 ConvertToVector128Int32(Vector128 value) { return ConvertToVector128Int32(value); } public static Vector128 ConvertToVector128Single(Vector128 value) { return ConvertToVector128Single(value); } public static Vector128 ConvertToVector128Single(Vector128 value) { return ConvertToVector128Single(value); } public static Vector128 ConvertToVector128Double(Vector128 value) { return ConvertToVector128Double(value); } public static Vector128 ConvertToVector128Double(Vector128 value) { return ConvertToVector128Double(value); } public static int ConvertToInt32(Vector128 value) { return ConvertToInt32(value); } public static int ConvertToInt32(Vector128 value) { return ConvertToInt32(value); } public static uint ConvertToUInt32(Vector128 value) { return ConvertToUInt32(value); } public static Vector128 ConvertScalarToVector128Double(Vector128 upper, int value) { return ConvertScalarToVector128Double(upper, value); } public static Vector128 ConvertScalarToVector128Double(Vector128 upper, Vector128 value) { return ConvertScalarToVector128Double(upper, value); } public static Vector128 ConvertScalarToVector128Int32(int value) { return ConvertScalarToVector128Int32(value); } public static Vector128 ConvertScalarToVector128Single(Vector128 upper, Vector128 value) { return ConvertScalarToVector128Single(upper, value); } public static Vector128 ConvertScalarToVector128UInt32(uint value) { return ConvertScalarToVector128UInt32(value); } public static Vector128 ConvertToVector128Int32WithTruncation(Vector128 value) { return ConvertToVector128Int32WithTruncation(value); } public static Vector128 ConvertToVector128Int32WithTruncation(Vector128 value) { return ConvertToVector128Int32WithTruncation(value); } public static int ConvertToInt32WithTruncation(Vector128 value) { return ConvertToInt32WithTruncation(value); } public static Vector128 Divide(Vector128 left, Vector128 right) { return Divide(left, right); } public static Vector128 DivideScalar(Vector128 left, Vector128 right) { return DivideScalar(left, right); } public static ushort Extract(Vector128 value, byte index) { return Extract(value, index); } public static Vector128 Insert(Vector128 value, short data, byte index) { return Insert(value, data, index); } public static Vector128 Insert(Vector128 value, ushort data, byte index) { return Insert(value, data, index); } public unsafe static Vector128 LoadVector128(sbyte* address) { return LoadVector128(address); } public unsafe static Vector128 LoadVector128(byte* address) { return LoadVector128(address); } public unsafe static Vector128 LoadVector128(short* address) { return LoadVector128(address); } public unsafe static Vector128 LoadVector128(ushort* address) { return LoadVector128(address); } public unsafe static Vector128 LoadVector128(int* address) { return LoadVector128(address); } public unsafe static Vector128 LoadVector128(uint* address) { return LoadVector128(address); } public unsafe static Vector128 LoadVector128(long* address) { return LoadVector128(address); } public unsafe static Vector128 LoadVector128(ulong* address) { return LoadVector128(address); } public unsafe static Vector128 LoadVector128(double* address) { return LoadVector128(address); } public unsafe static Vector128 LoadScalarVector128(double* address) { return LoadScalarVector128(address); } public unsafe static Vector128 LoadAlignedVector128(sbyte* address) { return LoadAlignedVector128(address); } public unsafe static Vector128 LoadAlignedVector128(byte* address) { return LoadAlignedVector128(address); } public unsafe static Vector128 LoadAlignedVector128(short* address) { return LoadAlignedVector128(address); } public unsafe static Vector128 LoadAlignedVector128(ushort* address) { return LoadAlignedVector128(address); } public unsafe static Vector128 LoadAlignedVector128(int* address) { return LoadAlignedVector128(address); } public unsafe static Vector128 LoadAlignedVector128(uint* address) { return LoadAlignedVector128(address); } public unsafe static Vector128 LoadAlignedVector128(long* address) { return LoadAlignedVector128(address); } public unsafe static Vector128 LoadAlignedVector128(ulong* address) { return LoadAlignedVector128(address); } public unsafe static Vector128 LoadAlignedVector128(double* address) { return LoadAlignedVector128(address); } public static void LoadFence() { LoadFence(); } public unsafe static Vector128 LoadHigh(Vector128 lower, double* address) { return LoadHigh(lower, address); } public unsafe static Vector128 LoadLow(Vector128 upper, double* address) { return LoadLow(upper, address); } public unsafe static Vector128 LoadScalarVector128(int* address) { return LoadScalarVector128(address); } public unsafe static Vector128 LoadScalarVector128(uint* address) { return LoadScalarVector128(address); } public unsafe static Vector128 LoadScalarVector128(long* address) { return LoadScalarVector128(address); } public unsafe static Vector128 LoadScalarVector128(ulong* address) { return LoadScalarVector128(address); } public unsafe static void MaskMove(Vector128 source, Vector128 mask, sbyte* address) { MaskMove(source, mask, address); } public unsafe static void MaskMove(Vector128 source, Vector128 mask, byte* address) { MaskMove(source, mask, address); } public static Vector128 Max(Vector128 left, Vector128 right) { return Max(left, right); } public static Vector128 Max(Vector128 left, Vector128 right) { return Max(left, right); } public static Vector128 Max(Vector128 left, Vector128 right) { return Max(left, right); } public static Vector128 MaxScalar(Vector128 left, Vector128 right) { return MaxScalar(left, right); } public static void MemoryFence() { MemoryFence(); } public static Vector128 Min(Vector128 left, Vector128 right) { return Min(left, right); } public static Vector128 Min(Vector128 left, Vector128 right) { return Min(left, right); } public static Vector128 Min(Vector128 left, Vector128 right) { return Min(left, right); } public static Vector128 MinScalar(Vector128 left, Vector128 right) { return MinScalar(left, right); } public static Vector128 MoveScalar(Vector128 upper, Vector128 value) { return MoveScalar(upper, value); } public static int MoveMask(Vector128 value) { return MoveMask(value); } public static int MoveMask(Vector128 value) { return MoveMask(value); } public static int MoveMask(Vector128 value) { return MoveMask(value); } public static Vector128 MoveScalar(Vector128 value) { return MoveScalar(value); } public static Vector128 MoveScalar(Vector128 value) { return MoveScalar(value); } public static Vector128 Multiply(Vector128 left, Vector128 right) { return Multiply(left, right); } public static Vector128 Multiply(Vector128 left, Vector128 right) { return Multiply(left, right); } public static Vector128 MultiplyScalar(Vector128 left, Vector128 right) { return MultiplyScalar(left, right); } public static Vector128 MultiplyHigh(Vector128 left, Vector128 right) { return MultiplyHigh(left, right); } public static Vector128 MultiplyHigh(Vector128 left, Vector128 right) { return MultiplyHigh(left, right); } public static Vector128 MultiplyAddAdjacent(Vector128 left, Vector128 right) { return MultiplyAddAdjacent(left, right); } public static Vector128 MultiplyLow(Vector128 left, Vector128 right) { return MultiplyLow(left, right); } public static Vector128 MultiplyLow(Vector128 left, Vector128 right) { return MultiplyLow(left, right); } public static Vector128 Or(Vector128 left, Vector128 right) { return Or(left, right); } public static Vector128 Or(Vector128 left, Vector128 right) { return Or(left, right); } public static Vector128 Or(Vector128 left, Vector128 right) { return Or(left, right); } public static Vector128 Or(Vector128 left, Vector128 right) { return Or(left, right); } public static Vector128 Or(Vector128 left, Vector128 right) { return Or(left, right); } public static Vector128 Or(Vector128 left, Vector128 right) { return Or(left, right); } public static Vector128 Or(Vector128 left, Vector128 right) { return Or(left, right); } public static Vector128 Or(Vector128 left, Vector128 right) { return Or(left, right); } public static Vector128 Or(Vector128 left, Vector128 right) { return Or(left, right); } public static Vector128 PackSignedSaturate(Vector128 left, Vector128 right) { return PackSignedSaturate(left, right); } public static Vector128 PackSignedSaturate(Vector128 left, Vector128 right) { return PackSignedSaturate(left, right); } public static Vector128 PackUnsignedSaturate(Vector128 left, Vector128 right) { return PackUnsignedSaturate(left, right); } public static Vector128 SumAbsoluteDifferences(Vector128 left, Vector128 right) { return SumAbsoluteDifferences(left, right); } public static Vector128 Shuffle(Vector128 value, byte control) { return Shuffle(value, control); } public static Vector128 Shuffle(Vector128 value, byte control) { return Shuffle(value, control); } public static Vector128 Shuffle(Vector128 left, Vector128 right, byte control) { return Shuffle(left, right, control); } public static Vector128 ShuffleHigh(Vector128 value, byte control) { return ShuffleHigh(value, control); } public static Vector128 ShuffleHigh(Vector128 value, byte control) { return ShuffleHigh(value, control); } public static Vector128 ShuffleLow(Vector128 value, byte control) { return ShuffleLow(value, control); } public static Vector128 ShuffleLow(Vector128 value, byte control) { return ShuffleLow(value, control); } public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) { return ShiftLeftLogical(value, count); } public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) { return ShiftLeftLogical(value, count); } public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) { return ShiftLeftLogical(value, count); } public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) { return ShiftLeftLogical(value, count); } public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) { return ShiftLeftLogical(value, count); } public static Vector128 ShiftLeftLogical(Vector128 value, Vector128 count) { return ShiftLeftLogical(value, count); } public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { return ShiftLeftLogical(value, count); } public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { return ShiftLeftLogical(value, count); } public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { return ShiftLeftLogical(value, count); } public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { return ShiftLeftLogical(value, count); } public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { return ShiftLeftLogical(value, count); } public static Vector128 ShiftLeftLogical(Vector128 value, byte count) { return ShiftLeftLogical(value, count); } public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector128 ShiftLeftLogical128BitLane(Vector128 value, byte numBytes) { return ShiftLeftLogical128BitLane(value, numBytes); } public static Vector128 ShiftRightArithmetic(Vector128 value, Vector128 count) { return ShiftRightArithmetic(value, count); } public static Vector128 ShiftRightArithmetic(Vector128 value, Vector128 count) { return ShiftRightArithmetic(value, count); } public static Vector128 ShiftRightArithmetic(Vector128 value, byte count) { return ShiftRightArithmetic(value, count); } public static Vector128 ShiftRightArithmetic(Vector128 value, byte count) { return ShiftRightArithmetic(value, count); } public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) { return ShiftRightLogical(value, count); } public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) { return ShiftRightLogical(value, count); } public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) { return ShiftRightLogical(value, count); } public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) { return ShiftRightLogical(value, count); } public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) { return ShiftRightLogical(value, count); } public static Vector128 ShiftRightLogical(Vector128 value, Vector128 count) { return ShiftRightLogical(value, count); } public static Vector128 ShiftRightLogical(Vector128 value, byte count) { return ShiftRightLogical(value, count); } public static Vector128 ShiftRightLogical(Vector128 value, byte count) { return ShiftRightLogical(value, count); } public static Vector128 ShiftRightLogical(Vector128 value, byte count) { return ShiftRightLogical(value, count); } public static Vector128 ShiftRightLogical(Vector128 value, byte count) { return ShiftRightLogical(value, count); } public static Vector128 ShiftRightLogical(Vector128 value, byte count) { return ShiftRightLogical(value, count); } public static Vector128 ShiftRightLogical(Vector128 value, byte count) { return ShiftRightLogical(value, count); } public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector128 ShiftRightLogical128BitLane(Vector128 value, byte numBytes) { return ShiftRightLogical128BitLane(value, numBytes); } public static Vector128 Sqrt(Vector128 value) { return Sqrt(value); } public static Vector128 SqrtScalar(Vector128 value) { return SqrtScalar(value); } public static Vector128 SqrtScalar(Vector128 upper, Vector128 value) { return SqrtScalar(upper, value); } public unsafe static void StoreScalar(double* address, Vector128 source) { StoreScalar(address, source); } public unsafe static void StoreScalar(int* address, Vector128 source) { StoreScalar(address, source); } public unsafe static void StoreScalar(long* address, Vector128 source) { StoreScalar(address, source); } public unsafe static void StoreScalar(uint* address, Vector128 source) { StoreScalar(address, source); } public unsafe static void StoreScalar(ulong* address, Vector128 source) { StoreScalar(address, source); } public unsafe static void StoreAligned(sbyte* address, Vector128 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(byte* address, Vector128 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(short* address, Vector128 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(ushort* address, Vector128 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(int* address, Vector128 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(uint* address, Vector128 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(long* address, Vector128 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(ulong* address, Vector128 source) { StoreAligned(address, source); } public unsafe static void StoreAligned(double* address, Vector128 source) { StoreAligned(address, source); } public unsafe static void StoreAlignedNonTemporal(sbyte* address, Vector128 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(byte* address, Vector128 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(short* address, Vector128 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(ushort* address, Vector128 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(int* address, Vector128 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(uint* address, Vector128 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(long* address, Vector128 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(ulong* address, Vector128 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void StoreAlignedNonTemporal(double* address, Vector128 source) { StoreAlignedNonTemporal(address, source); } public unsafe static void Store(sbyte* address, Vector128 source) { Store(address, source); } public unsafe static void Store(byte* address, Vector128 source) { Store(address, source); } public unsafe static void Store(short* address, Vector128 source) { Store(address, source); } public unsafe static void Store(ushort* address, Vector128 source) { Store(address, source); } public unsafe static void Store(int* address, Vector128 source) { Store(address, source); } public unsafe static void Store(uint* address, Vector128 source) { Store(address, source); } public unsafe static void Store(long* address, Vector128 source) { Store(address, source); } public unsafe static void Store(ulong* address, Vector128 source) { Store(address, source); } public unsafe static void Store(double* address, Vector128 source) { Store(address, source); } public unsafe static void StoreHigh(double* address, Vector128 source) { StoreHigh(address, source); } public unsafe static void StoreLow(double* address, Vector128 source) { StoreLow(address, source); } public unsafe static void StoreNonTemporal(int* address, int value) { StoreNonTemporal(address, value); } public unsafe static void StoreNonTemporal(uint* address, uint value) { StoreNonTemporal(address, value); } public static Vector128 Subtract(Vector128 left, Vector128 right) { return Subtract(left, right); } public static Vector128 Subtract(Vector128 left, Vector128 right) { return Subtract(left, right); } public static Vector128 Subtract(Vector128 left, Vector128 right) { return Subtract(left, right); } public static Vector128 Subtract(Vector128 left, Vector128 right) { return Subtract(left, right); } public static Vector128 Subtract(Vector128 left, Vector128 right) { return Subtract(left, right); } public static Vector128 Subtract(Vector128 left, Vector128 right) { return Subtract(left, right); } public static Vector128 Subtract(Vector128 left, Vector128 right) { return Subtract(left, right); } public static Vector128 Subtract(Vector128 left, Vector128 right) { return Subtract(left, right); } public static Vector128 Subtract(Vector128 left, Vector128 right) { return Subtract(left, right); } public static Vector128 SubtractScalar(Vector128 left, Vector128 right) { return SubtractScalar(left, right); } public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { return SubtractSaturate(left, right); } public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { return SubtractSaturate(left, right); } public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { return SubtractSaturate(left, right); } public static Vector128 SubtractSaturate(Vector128 left, Vector128 right) { return SubtractSaturate(left, right); } public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { return UnpackHigh(left, right); } public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { return UnpackHigh(left, right); } public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { return UnpackHigh(left, right); } public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { return UnpackHigh(left, right); } public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { return UnpackHigh(left, right); } public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { return UnpackHigh(left, right); } public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { return UnpackHigh(left, right); } public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { return UnpackHigh(left, right); } public static Vector128 UnpackHigh(Vector128 left, Vector128 right) { return UnpackHigh(left, right); } public static Vector128 UnpackLow(Vector128 left, Vector128 right) { return UnpackLow(left, right); } public static Vector128 UnpackLow(Vector128 left, Vector128 right) { return UnpackLow(left, right); } public static Vector128 UnpackLow(Vector128 left, Vector128 right) { return UnpackLow(left, right); } public static Vector128 UnpackLow(Vector128 left, Vector128 right) { return UnpackLow(left, right); } public static Vector128 UnpackLow(Vector128 left, Vector128 right) { return UnpackLow(left, right); } public static Vector128 UnpackLow(Vector128 left, Vector128 right) { return UnpackLow(left, right); } public static Vector128 UnpackLow(Vector128 left, Vector128 right) { return UnpackLow(left, right); } public static Vector128 UnpackLow(Vector128 left, Vector128 right) { return UnpackLow(left, right); } public static Vector128 UnpackLow(Vector128 left, Vector128 right) { return UnpackLow(left, right); } public static Vector128 Xor(Vector128 left, Vector128 right) { return Xor(left, right); } public static Vector128 Xor(Vector128 left, Vector128 right) { return Xor(left, right); } public static Vector128 Xor(Vector128 left, Vector128 right) { return Xor(left, right); } public static Vector128 Xor(Vector128 left, Vector128 right) { return Xor(left, right); } public static Vector128 Xor(Vector128 left, Vector128 right) { return Xor(left, right); } public static Vector128 Xor(Vector128 left, Vector128 right) { return Xor(left, right); } public static Vector128 Xor(Vector128 left, Vector128 right) { return Xor(left, right); } public static Vector128 Xor(Vector128 left, Vector128 right) { return Xor(left, right); } public static Vector128 Xor(Vector128 left, Vector128 right) { return Xor(left, right); } } [Intrinsic] [CLSCompliant(false)] public abstract class Sse3 : Sse2 { [Intrinsic] public new abstract class X64 : Sse2.X64 { public new static bool IsSupported => IsSupported; } public new static bool IsSupported => IsSupported; public static Vector128 AddSubtract(Vector128 left, Vector128 right) { return AddSubtract(left, right); } public static Vector128 AddSubtract(Vector128 left, Vector128 right) { return AddSubtract(left, right); } public static Vector128 HorizontalAdd(Vector128 left, Vector128 right) { return HorizontalAdd(left, right); } public static Vector128 HorizontalAdd(Vector128 left, Vector128 right) { return HorizontalAdd(left, right); } public static Vector128 HorizontalSubtract(Vector128 left, Vector128 right) { return HorizontalSubtract(left, right); } public static Vector128 HorizontalSubtract(Vector128 left, Vector128 right) { return HorizontalSubtract(left, right); } public unsafe static Vector128 LoadAndDuplicateToVector128(double* address) { return LoadAndDuplicateToVector128(address); } public unsafe static Vector128 LoadDquVector128(sbyte* address) { return LoadDquVector128(address); } public unsafe static Vector128 LoadDquVector128(byte* address) { return LoadDquVector128(address); } public unsafe static Vector128 LoadDquVector128(short* address) { return LoadDquVector128(address); } public unsafe static Vector128 LoadDquVector128(ushort* address) { return LoadDquVector128(address); } public unsafe static Vector128 LoadDquVector128(int* address) { return LoadDquVector128(address); } public unsafe static Vector128 LoadDquVector128(uint* address) { return LoadDquVector128(address); } public unsafe static Vector128 LoadDquVector128(long* address) { return LoadDquVector128(address); } public unsafe static Vector128 LoadDquVector128(ulong* address) { return LoadDquVector128(address); } public static Vector128 MoveAndDuplicate(Vector128 source) { return MoveAndDuplicate(source); } public static Vector128 MoveHighAndDuplicate(Vector128 source) { return MoveHighAndDuplicate(source); } public static Vector128 MoveLowAndDuplicate(Vector128 source) { return MoveLowAndDuplicate(source); } } [Intrinsic] [CLSCompliant(false)] public abstract class Sse41 : Ssse3 { [Intrinsic] public new abstract class X64 : Ssse3.X64 { public new static bool IsSupported => IsSupported; public static long Extract(Vector128 value, byte index) { return Extract(value, index); } public static ulong Extract(Vector128 value, byte index) { return Extract(value, index); } public static Vector128 Insert(Vector128 value, long data, byte index) { return Insert(value, data, index); } public static Vector128 Insert(Vector128 value, ulong data, byte index) { return Insert(value, data, index); } } public new static bool IsSupported => IsSupported; public static Vector128 Blend(Vector128 left, Vector128 right, byte control) { return Blend(left, right, control); } public static Vector128 Blend(Vector128 left, Vector128 right, byte control) { return Blend(left, right, control); } public static Vector128 Blend(Vector128 left, Vector128 right, byte control) { return Blend(left, right, control); } public static Vector128 Blend(Vector128 left, Vector128 right, byte control) { return Blend(left, right, control); } public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) { return BlendVariable(left, right, mask); } public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) { return BlendVariable(left, right, mask); } public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) { return BlendVariable(left, right, mask); } public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) { return BlendVariable(left, right, mask); } public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) { return BlendVariable(left, right, mask); } public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) { return BlendVariable(left, right, mask); } public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) { return BlendVariable(left, right, mask); } public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) { return BlendVariable(left, right, mask); } public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) { return BlendVariable(left, right, mask); } public static Vector128 BlendVariable(Vector128 left, Vector128 right, Vector128 mask) { return BlendVariable(left, right, mask); } public static Vector128 Ceiling(Vector128 value) { return Ceiling(value); } public static Vector128 Ceiling(Vector128 value) { return Ceiling(value); } public static Vector128 CeilingScalar(Vector128 value) { return CeilingScalar(value); } public static Vector128 CeilingScalar(Vector128 value) { return CeilingScalar(value); } public static Vector128 CeilingScalar(Vector128 upper, Vector128 value) { return CeilingScalar(upper, value); } public static Vector128 CeilingScalar(Vector128 upper, Vector128 value) { return CeilingScalar(upper, value); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { return CompareEqual(left, right); } public static Vector128 CompareEqual(Vector128 left, Vector128 right) { return CompareEqual(left, right); } public static Vector128 ConvertToVector128Int16(Vector128 value) { return ConvertToVector128Int16(value); } public static Vector128 ConvertToVector128Int16(Vector128 value) { return ConvertToVector128Int16(value); } public static Vector128 ConvertToVector128Int32(Vector128 value) { return ConvertToVector128Int32(value); } public static Vector128 ConvertToVector128Int32(Vector128 value) { return ConvertToVector128Int32(value); } public static Vector128 ConvertToVector128Int32(Vector128 value) { return ConvertToVector128Int32(value); } public static Vector128 ConvertToVector128Int32(Vector128 value) { return ConvertToVector128Int32(value); } public static Vector128 ConvertToVector128Int64(Vector128 value) { return ConvertToVector128Int64(value); } public static Vector128 ConvertToVector128Int64(Vector128 value) { return ConvertToVector128Int64(value); } public static Vector128 ConvertToVector128Int64(Vector128 value) { return ConvertToVector128Int64(value); } public static Vector128 ConvertToVector128Int64(Vector128 value) { return ConvertToVector128Int64(value); } public static Vector128 ConvertToVector128Int64(Vector128 value) { return ConvertToVector128Int64(value); } public static Vector128 ConvertToVector128Int64(Vector128 value) { return ConvertToVector128Int64(value); } public unsafe static Vector128 ConvertToVector128Int16(sbyte* address) { return ConvertToVector128Int16(address); } public unsafe static Vector128 ConvertToVector128Int16(byte* address) { return ConvertToVector128Int16(address); } public unsafe static Vector128 ConvertToVector128Int32(sbyte* address) { return ConvertToVector128Int32(address); } public unsafe static Vector128 ConvertToVector128Int32(byte* address) { return ConvertToVector128Int32(address); } public unsafe static Vector128 ConvertToVector128Int32(short* address) { return ConvertToVector128Int32(address); } public unsafe static Vector128 ConvertToVector128Int32(ushort* address) { return ConvertToVector128Int32(address); } public unsafe static Vector128 ConvertToVector128Int64(sbyte* address) { return ConvertToVector128Int64(address); } public unsafe static Vector128 ConvertToVector128Int64(byte* address) { return ConvertToVector128Int64(address); } public unsafe static Vector128 ConvertToVector128Int64(short* address) { return ConvertToVector128Int64(address); } public unsafe static Vector128 ConvertToVector128Int64(ushort* address) { return ConvertToVector128Int64(address); } public unsafe static Vector128 ConvertToVector128Int64(int* address) { return ConvertToVector128Int64(address); } public unsafe static Vector128 ConvertToVector128Int64(uint* address) { return ConvertToVector128Int64(address); } public static Vector128 DotProduct(Vector128 left, Vector128 right, byte control) { return DotProduct(left, right, control); } public static Vector128 DotProduct(Vector128 left, Vector128 right, byte control) { return DotProduct(left, right, control); } public static byte Extract(Vector128 value, byte index) { return Extract(value, index); } public static int Extract(Vector128 value, byte index) { return Extract(value, index); } public static uint Extract(Vector128 value, byte index) { return Extract(value, index); } public static float Extract(Vector128 value, byte index) { return Extract(value, index); } public static Vector128 Floor(Vector128 value) { return Floor(value); } public static Vector128 Floor(Vector128 value) { return Floor(value); } public static Vector128 FloorScalar(Vector128 value) { return FloorScalar(value); } public static Vector128 FloorScalar(Vector128 value) { return FloorScalar(value); } public static Vector128 FloorScalar(Vector128 upper, Vector128 value) { return FloorScalar(upper, value); } public static Vector128 FloorScalar(Vector128 upper, Vector128 value) { return FloorScalar(upper, value); } public static Vector128 Insert(Vector128 value, sbyte data, byte index) { return Insert(value, data, index); } public static Vector128 Insert(Vector128 value, byte data, byte index) { return Insert(value, data, index); } public static Vector128 Insert(Vector128 value, int data, byte index) { return Insert(value, data, index); } public static Vector128 Insert(Vector128 value, uint data, byte index) { return Insert(value, data, index); } public static Vector128 Insert(Vector128 value, Vector128 data, byte index) { return Insert(value, data, index); } public static Vector128 Max(Vector128 left, Vector128 right) { return Max(left, right); } public static Vector128 Max(Vector128 left, Vector128 right) { return Max(left, right); } public static Vector128 Max(Vector128 left, Vector128 right) { return Max(left, right); } public static Vector128 Max(Vector128 left, Vector128 right) { return Max(left, right); } public static Vector128 Min(Vector128 left, Vector128 right) { return Min(left, right); } public static Vector128 Min(Vector128 left, Vector128 right) { return Min(left, right); } public static Vector128 Min(Vector128 left, Vector128 right) { return Min(left, right); } public static Vector128 Min(Vector128 left, Vector128 right) { return Min(left, right); } public static Vector128 MinHorizontal(Vector128 value) { return MinHorizontal(value); } public static Vector128 MultipleSumAbsoluteDifferences(Vector128 left, Vector128 right, byte mask) { return MultipleSumAbsoluteDifferences(left, right, mask); } public static Vector128 Multiply(Vector128 left, Vector128 right) { return Multiply(left, right); } public static Vector128 MultiplyLow(Vector128 left, Vector128 right) { return MultiplyLow(left, right); } public static Vector128 MultiplyLow(Vector128 left, Vector128 right) { return MultiplyLow(left, right); } public static Vector128 PackUnsignedSaturate(Vector128 left, Vector128 right) { return PackUnsignedSaturate(left, right); } public static Vector128 RoundToNearestInteger(Vector128 value) { return RoundToNearestInteger(value); } public static Vector128 RoundToNegativeInfinity(Vector128 value) { return RoundToNegativeInfinity(value); } public static Vector128 RoundToPositiveInfinity(Vector128 value) { return RoundToPositiveInfinity(value); } public static Vector128 RoundToZero(Vector128 value) { return RoundToZero(value); } public static Vector128 RoundCurrentDirection(Vector128 value) { return RoundCurrentDirection(value); } public static Vector128 RoundToNearestInteger(Vector128 value) { return RoundToNearestInteger(value); } public static Vector128 RoundToNegativeInfinity(Vector128 value) { return RoundToNegativeInfinity(value); } public static Vector128 RoundToPositiveInfinity(Vector128 value) { return RoundToPositiveInfinity(value); } public static Vector128 RoundToZero(Vector128 value) { return RoundToZero(value); } public static Vector128 RoundCurrentDirection(Vector128 value) { return RoundCurrentDirection(value); } public static Vector128 RoundCurrentDirectionScalar(Vector128 value) { return RoundCurrentDirectionScalar(value); } public static Vector128 RoundToNearestIntegerScalar(Vector128 value) { return RoundToNearestIntegerScalar(value); } public static Vector128 RoundToNegativeInfinityScalar(Vector128 value) { return RoundToNegativeInfinityScalar(value); } public static Vector128 RoundToPositiveInfinityScalar(Vector128 value) { return RoundToPositiveInfinityScalar(value); } public static Vector128 RoundToZeroScalar(Vector128 value) { return RoundToZeroScalar(value); } public static Vector128 RoundCurrentDirectionScalar(Vector128 upper, Vector128 value) { return RoundCurrentDirectionScalar(upper, value); } public static Vector128 RoundToNearestIntegerScalar(Vector128 upper, Vector128 value) { return RoundToNearestIntegerScalar(upper, value); } public static Vector128 RoundToNegativeInfinityScalar(Vector128 upper, Vector128 value) { return RoundToNegativeInfinityScalar(upper, value); } public static Vector128 RoundToPositiveInfinityScalar(Vector128 upper, Vector128 value) { return RoundToPositiveInfinityScalar(upper, value); } public static Vector128 RoundToZeroScalar(Vector128 upper, Vector128 value) { return RoundToZeroScalar(upper, value); } public static Vector128 RoundCurrentDirectionScalar(Vector128 value) { return RoundCurrentDirectionScalar(value); } public static Vector128 RoundToNearestIntegerScalar(Vector128 value) { return RoundToNearestIntegerScalar(value); } public static Vector128 RoundToNegativeInfinityScalar(Vector128 value) { return RoundToNegativeInfinityScalar(value); } public static Vector128 RoundToPositiveInfinityScalar(Vector128 value) { return RoundToPositiveInfinityScalar(value); } public static Vector128 RoundToZeroScalar(Vector128 value) { return RoundToZeroScalar(value); } public static Vector128 RoundCurrentDirectionScalar(Vector128 upper, Vector128 value) { return RoundCurrentDirectionScalar(upper, value); } public static Vector128 RoundToNearestIntegerScalar(Vector128 upper, Vector128 value) { return RoundToNearestIntegerScalar(upper, value); } public static Vector128 RoundToNegativeInfinityScalar(Vector128 upper, Vector128 value) { return RoundToNegativeInfinityScalar(upper, value); } public static Vector128 RoundToPositiveInfinityScalar(Vector128 upper, Vector128 value) { return RoundToPositiveInfinityScalar(upper, value); } public static Vector128 RoundToZeroScalar(Vector128 upper, Vector128 value) { return RoundToZeroScalar(upper, value); } public unsafe static Vector128 LoadAlignedVector128NonTemporal(sbyte* address) { return LoadAlignedVector128NonTemporal(address); } public unsafe static Vector128 LoadAlignedVector128NonTemporal(byte* address) { return LoadAlignedVector128NonTemporal(address); } public unsafe static Vector128 LoadAlignedVector128NonTemporal(short* address) { return LoadAlignedVector128NonTemporal(address); } public unsafe static Vector128 LoadAlignedVector128NonTemporal(ushort* address) { return LoadAlignedVector128NonTemporal(address); } public unsafe static Vector128 LoadAlignedVector128NonTemporal(int* address) { return LoadAlignedVector128NonTemporal(address); } public unsafe static Vector128 LoadAlignedVector128NonTemporal(uint* address) { return LoadAlignedVector128NonTemporal(address); } public unsafe static Vector128 LoadAlignedVector128NonTemporal(long* address) { return LoadAlignedVector128NonTemporal(address); } public unsafe static Vector128 LoadAlignedVector128NonTemporal(ulong* address) { return LoadAlignedVector128NonTemporal(address); } public static bool TestC(Vector128 left, Vector128 right) { return TestC(left, right); } public static bool TestC(Vector128 left, Vector128 right) { return TestC(left, right); } public static bool TestC(Vector128 left, Vector128 right) { return TestC(left, right); } public static bool TestC(Vector128 left, Vector128 right) { return TestC(left, right); } public static bool TestC(Vector128 left, Vector128 right) { return TestC(left, right); } public static bool TestC(Vector128 left, Vector128 right) { return TestC(left, right); } public static bool TestC(Vector128 left, Vector128 right) { return TestC(left, right); } public static bool TestC(Vector128 left, Vector128 right) { return TestC(left, right); } public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { return TestNotZAndNotC(left, right); } public static bool TestNotZAndNotC(Vector128 left, Vector128 right) { return TestNotZAndNotC(left, right); } public static bool TestZ(Vector128 left, Vector128 right) { return TestZ(left, right); } public static bool TestZ(Vector128 left, Vector128 right) { return TestZ(left, right); } public static bool TestZ(Vector128 left, Vector128 right) { return TestZ(left, right); } public static bool TestZ(Vector128 left, Vector128 right) { return TestZ(left, right); } public static bool TestZ(Vector128 left, Vector128 right) { return TestZ(left, right); } public static bool TestZ(Vector128 left, Vector128 right) { return TestZ(left, right); } public static bool TestZ(Vector128 left, Vector128 right) { return TestZ(left, right); } public static bool TestZ(Vector128 left, Vector128 right) { return TestZ(left, right); } } [Intrinsic] [CLSCompliant(false)] public abstract class Sse42 : Sse41 { [Intrinsic] public new abstract class X64 : Sse41.X64 { public new static bool IsSupported => IsSupported; public static ulong Crc32(ulong crc, ulong data) { return Crc32(crc, data); } } public new static bool IsSupported => IsSupported; public static Vector128 CompareGreaterThan(Vector128 left, Vector128 right) { return CompareGreaterThan(left, right); } public static uint Crc32(uint crc, byte data) { return Crc32(crc, data); } public static uint Crc32(uint crc, ushort data) { return Crc32(crc, data); } public static uint Crc32(uint crc, uint data) { return Crc32(crc, data); } } [Intrinsic] [CLSCompliant(false)] public abstract class Ssse3 : Sse3 { [Intrinsic] public new abstract class X64 : Sse3.X64 { public new static bool IsSupported => IsSupported; } public new static bool IsSupported => IsSupported; public static Vector128 Abs(Vector128 value) { return Abs(value); } public static Vector128 Abs(Vector128 value) { return Abs(value); } public static Vector128 Abs(Vector128 value) { return Abs(value); } public static Vector128 AlignRight(Vector128 left, Vector128 right, byte mask) { return AlignRight(left, right, mask); } public static Vector128 AlignRight(Vector128 left, Vector128 right, byte mask) { return AlignRight(left, right, mask); } public static Vector128 AlignRight(Vector128 left, Vector128 right, byte mask) { return AlignRight(left, right, mask); } public static Vector128 AlignRight(Vector128 left, Vector128 right, byte mask) { return AlignRight(left, right, mask); } public static Vector128 AlignRight(Vector128 left, Vector128 right, byte mask) { return AlignRight(left, right, mask); } public static Vector128 AlignRight(Vector128 left, Vector128 right, byte mask) { return AlignRight(left, right, mask); } public static Vector128 AlignRight(Vector128 left, Vector128 right, byte mask) { return AlignRight(left, right, mask); } public static Vector128 AlignRight(Vector128 left, Vector128 right, byte mask) { return AlignRight(left, right, mask); } public static Vector128 HorizontalAdd(Vector128 left, Vector128 right) { return HorizontalAdd(left, right); } public static Vector128 HorizontalAdd(Vector128 left, Vector128 right) { return HorizontalAdd(left, right); } public static Vector128 HorizontalAddSaturate(Vector128 left, Vector128 right) { return HorizontalAddSaturate(left, right); } public static Vector128 HorizontalSubtract(Vector128 left, Vector128 right) { return HorizontalSubtract(left, right); } public static Vector128 HorizontalSubtract(Vector128 left, Vector128 right) { return HorizontalSubtract(left, right); } public static Vector128 HorizontalSubtractSaturate(Vector128 left, Vector128 right) { return HorizontalSubtractSaturate(left, right); } public static Vector128 MultiplyAddAdjacent(Vector128 left, Vector128 right) { return MultiplyAddAdjacent(left, right); } public static Vector128 MultiplyHighRoundScale(Vector128 left, Vector128 right) { return MultiplyHighRoundScale(left, right); } public static Vector128 Shuffle(Vector128 value, Vector128 mask) { return Shuffle(value, mask); } public static Vector128 Shuffle(Vector128 value, Vector128 mask) { return Shuffle(value, mask); } public static Vector128 Sign(Vector128 left, Vector128 right) { return Sign(left, right); } public static Vector128 Sign(Vector128 left, Vector128 right) { return Sign(left, right); } public static Vector128 Sign(Vector128 left, Vector128 right) { return Sign(left, right); } } } namespace System.Runtime.InteropServices { internal static class DynamicInterfaceCastableHelpers { [StackTraceHidden] internal static bool IsInterfaceImplemented(IDynamicInterfaceCastable castable, RuntimeType interfaceType, bool throwIfNotImplemented) { bool flag = castable.IsInterfaceImplemented(new RuntimeTypeHandle(interfaceType), throwIfNotImplemented); if (!flag && throwIfNotImplemented) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, castable.GetType(), interfaceType)); } return flag; } [StackTraceHidden] internal static RuntimeType GetInterfaceImplementation(IDynamicInterfaceCastable castable, RuntimeType interfaceType) { RuntimeTypeHandle interfaceImplementation = castable.GetInterfaceImplementation(new RuntimeTypeHandle(interfaceType)); if (interfaceImplementation.Equals(default(RuntimeTypeHandle))) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, castable.GetType(), interfaceType)); } RuntimeType runtimeType = interfaceImplementation.GetRuntimeType(); if (!runtimeType.IsInterface) { throw new InvalidOperationException(SR.Format(SR.IDynamicInterfaceCastable_NotInterface, runtimeType.ToString())); } if (!runtimeType.IsDefined(typeof(DynamicInterfaceCastableImplementationAttribute), inherit: false)) { throw new InvalidOperationException(SR.Format(SR.IDynamicInterfaceCastable_MissingImplementationAttribute, runtimeType, "DynamicInterfaceCastableImplementationAttribute")); } if (!runtimeType.IsAssignableTo(interfaceType)) { throw new InvalidOperationException(SR.Format(SR.IDynamicInterfaceCastable_DoesNotImplementRequested, runtimeType, interfaceType)); } return runtimeType; } } public struct GCHandle { private IntPtr _handle; public object? Target { get { IntPtr handle = _handle; ThrowIfInvalid(handle); return InternalGet(GetHandleValue(handle)); } set { IntPtr handle = _handle; ThrowIfInvalid(handle); if (IsPinned(handle) && !Marshal.IsPinnable(value)) { throw new ArgumentException(SR.ArgumentException_NotIsomorphic, "value"); } InternalSet(GetHandleValue(handle), value); } } public bool IsAllocated => _handle != (IntPtr)0; [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr InternalAlloc(object value, GCHandleType type); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void InternalFree(IntPtr handle); internal unsafe static object InternalGet(IntPtr handle) { return Unsafe.As(ref *(IntPtr*)handle); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void InternalSet(IntPtr handle, object value); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern object InternalCompareExchange(IntPtr handle, object value, object oldValue); private GCHandle(object value, GCHandleType type) { switch (type) { default: throw new ArgumentOutOfRangeException("type", SR.ArgumentOutOfRange_Enum); case GCHandleType.Pinned: if (!Marshal.IsPinnable(value)) { throw new ArgumentException(SR.ArgumentException_NotIsomorphic, "value"); } break; case GCHandleType.Weak: case GCHandleType.WeakTrackResurrection: case GCHandleType.Normal: break; } nint num = InternalAlloc(value, type); if (type == GCHandleType.Pinned) { num |= 1; } _handle = num; } private GCHandle(IntPtr handle) { _handle = handle; } public static GCHandle Alloc(object? value) { return new GCHandle(value, GCHandleType.Normal); } public static GCHandle Alloc(object? value, GCHandleType type) { return new GCHandle(value, type); } public void Free() { IntPtr handle = Interlocked.Exchange(ref _handle, IntPtr.Zero); ThrowIfInvalid(handle); InternalFree(GetHandleValue(handle)); } public unsafe IntPtr AddrOfPinnedObject() { IntPtr handle = _handle; ThrowIfInvalid(handle); if (!IsPinned(handle)) { ThrowHelper.ThrowInvalidOperationException_HandleIsNotPinned(); } object obj = InternalGet(GetHandleValue(handle)); if (obj == null) { return (IntPtr)0; } if (RuntimeHelpers.ObjectHasComponentSize(obj)) { if (obj.GetType() == typeof(string)) { return (IntPtr)Unsafe.AsPointer(ref Unsafe.As(obj).GetRawStringData()); } return (IntPtr)Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(Unsafe.As(obj))); } return (IntPtr)Unsafe.AsPointer(ref obj.GetRawData()); } public static explicit operator GCHandle(IntPtr value) { return FromIntPtr(value); } public static GCHandle FromIntPtr(IntPtr value) { ThrowIfInvalid(value); return new GCHandle(value); } public static explicit operator IntPtr(GCHandle value) { return ToIntPtr(value); } public static IntPtr ToIntPtr(GCHandle value) { return value._handle; } public override int GetHashCode() { return _handle.GetHashCode(); } public override bool Equals([NotNullWhen(true)] object? o) { if (o is GCHandle) { return _handle == ((GCHandle)o)._handle; } return false; } public static bool operator ==(GCHandle a, GCHandle b) { return a._handle == b._handle; } public static bool operator !=(GCHandle a, GCHandle b) { return a._handle != b._handle; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static IntPtr GetHandleValue(IntPtr handle) { return new IntPtr((nint)handle & ~(nint)1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsPinned(IntPtr handle) { return ((nint)handle & 1) != 0; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void ThrowIfInvalid(IntPtr handle) { if (handle == (IntPtr)0) { ThrowHelper.ThrowInvalidOperationException_HandleIsNotInitialized(); } } } public static class Marshal { internal static Guid IID_IUnknown = new Guid(0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 70); public static readonly int SystemDefaultCharSize = 2; public static readonly int SystemMaxDBCSCharSize = GetSystemMaxDBCSCharSize(); internal static bool IsBuiltInComSupported { get; } = IsBuiltInComSupportedInternal(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int SizeOfHelper(Type t, bool throwIfNotMarshalable); [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "Trimming doesn't affect types eligible for marshalling. Different exception for invalid inputs doesn't matter.")] public static IntPtr OffsetOf(Type t, string fieldName) { if ((object)t == null) { throw new ArgumentNullException("t"); } FieldInfo field = t.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if ((object)field == null) { throw new ArgumentException(SR.Format(SR.Argument_OffsetOfFieldNotFound, t.FullName), "fieldName"); } if (!(field is RtFieldInfo f)) { throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, "fieldName"); } return OffsetOfHelper(f); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr OffsetOfHelper(IRuntimeFieldInfo f); public static byte ReadByte(object ptr, int ofs) { return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => ReadByte(nativeHome, offset)); } public static short ReadInt16(object ptr, int ofs) { return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => ReadInt16(nativeHome, offset)); } public static int ReadInt32(object ptr, int ofs) { return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => ReadInt32(nativeHome, offset)); } public static long ReadInt64([In][MarshalAs(UnmanagedType.AsAny)] object ptr, int ofs) { return ReadValueSlow(ptr, ofs, (IntPtr nativeHome, int offset) => ReadInt64(nativeHome, offset)); } private unsafe static T ReadValueSlow(object ptr, int ofs, Func readValueHelper) { if (ptr == null) { throw new AccessViolationException(); } MngdNativeArrayMarshaler.MarshalerState marshalerState = default(MngdNativeArrayMarshaler.MarshalerState); AsAnyMarshaler asAnyMarshaler = new AsAnyMarshaler(new IntPtr(&marshalerState)); IntPtr intPtr = IntPtr.Zero; try { intPtr = asAnyMarshaler.ConvertToNative(ptr, 285147391); return readValueHelper(intPtr, ofs); } finally { asAnyMarshaler.ClearNative(intPtr); } } public static void WriteByte(object ptr, int ofs, byte val) { WriteValueSlow(ptr, ofs, val, delegate(IntPtr nativeHome, int offset, byte value) { WriteByte(nativeHome, offset, value); }); } public static void WriteInt16(object ptr, int ofs, short val) { WriteValueSlow(ptr, ofs, val, delegate(IntPtr nativeHome, int offset, short value) { WriteInt16(nativeHome, offset, value); }); } public static void WriteInt32(object ptr, int ofs, int val) { WriteValueSlow(ptr, ofs, val, delegate(IntPtr nativeHome, int offset, int value) { WriteInt32(nativeHome, offset, value); }); } public static void WriteInt64(object ptr, int ofs, long val) { WriteValueSlow(ptr, ofs, val, delegate(IntPtr nativeHome, int offset, long value) { WriteInt64(nativeHome, offset, value); }); } private unsafe static void WriteValueSlow(object ptr, int ofs, T val, Action writeValueHelper) { if (ptr == null) { throw new AccessViolationException(); } MngdNativeArrayMarshaler.MarshalerState marshalerState = default(MngdNativeArrayMarshaler.MarshalerState); AsAnyMarshaler asAnyMarshaler = new AsAnyMarshaler(new IntPtr(&marshalerState)); IntPtr intPtr = IntPtr.Zero; try { intPtr = asAnyMarshaler.ConvertToNative(ptr, 822018303); writeValueHelper(intPtr, ofs, val); asAnyMarshaler.ConvertToManaged(ptr, intPtr); } finally { asAnyMarshaler.ClearNative(intPtr); } } [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetLastPInvokeError(); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void SetLastPInvokeError(int error); private static void PrelinkCore(MethodInfo m) { if (!(m is RuntimeMethodInfo runtimeMethodInfo)) { throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, "m"); } InternalPrelink(((IRuntimeMethodInfo)runtimeMethodInfo).Value); GC.KeepAlive(runtimeMethodInfo); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void InternalPrelink(RuntimeMethodHandleInternal m); [MethodImpl(MethodImplOptions.InternalCall)] public static extern IntPtr GetExceptionPointers(); [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetExceptionCode(); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void StructureToPtr(object structure, IntPtr ptr, bool fDeleteOld); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void PtrToStructureHelper(IntPtr ptr, object structure, bool allowValueClasses); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void DestroyStructure(IntPtr ptr, Type structuretype); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern bool IsPinnable(object obj); [DllImport("QCall")] private static extern bool IsBuiltInComSupportedInternal(); public static IntPtr GetHINSTANCE(Module m) { if ((object)m == null) { throw new ArgumentNullException("m"); } RuntimeModule module = m as RuntimeModule; if ((object)module != null) { return GetHINSTANCE(new QCallModule(ref module)); } return (IntPtr)(-1); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern IntPtr GetHINSTANCE(QCallModule m); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Exception GetExceptionForHRInternal(int errorCode, IntPtr errorInfo); [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetHRForException(Exception? e); [SupportedOSPlatform("windows")] public static string GetTypeInfoName(ITypeInfo typeInfo) { if (typeInfo == null) { throw new ArgumentNullException("typeInfo"); } typeInfo.GetDocumentation(-1, out string strName, out string _, out int _, out string _); return strName; } internal static Type GetTypeFromCLSID(Guid clsid, string server, bool throwOnError) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } Type o = null; GetTypeFromCLSID(in clsid, server, ObjectHandleOnStack.Create(ref o)); return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetTypeFromCLSID(in Guid clsid, string server, ObjectHandleOnStack retType); [SupportedOSPlatform("windows")] public static IntPtr GetIUnknownForObject(object o) { if (o == null) { throw new ArgumentNullException("o"); } return GetIUnknownForObjectNative(o); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr GetIUnknownForObjectNative(object o); [SupportedOSPlatform("windows")] public static IntPtr GetIDispatchForObject(object o) { if (o == null) { throw new ArgumentNullException("o"); } return GetIDispatchForObjectNative(o); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr GetIDispatchForObjectNative(object o); [SupportedOSPlatform("windows")] public static IntPtr GetComInterfaceForObject(object o, Type T) { if (o == null) { throw new ArgumentNullException("o"); } if ((object)T == null) { throw new ArgumentNullException("T"); } return GetComInterfaceForObjectNative(o, T, fEnableCustomizedQueryInterface: true); } [SupportedOSPlatform("windows")] public static IntPtr GetComInterfaceForObject([DisallowNull] T o) { return GetComInterfaceForObject(o, typeof(TInterface)); } [SupportedOSPlatform("windows")] public static IntPtr GetComInterfaceForObject(object o, Type T, CustomQueryInterfaceMode mode) { if (o == null) { throw new ArgumentNullException("o"); } if ((object)T == null) { throw new ArgumentNullException("T"); } bool fEnableCustomizedQueryInterface = mode == CustomQueryInterfaceMode.Allow; return GetComInterfaceForObjectNative(o, T, fEnableCustomizedQueryInterface); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr GetComInterfaceForObjectNative(object o, Type t, bool fEnableCustomizedQueryInterface); [SupportedOSPlatform("windows")] public static object GetObjectForIUnknown(IntPtr pUnk) { if (pUnk == IntPtr.Zero) { throw new ArgumentNullException("pUnk"); } return GetObjectForIUnknownNative(pUnk); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern object GetObjectForIUnknownNative(IntPtr pUnk); [SupportedOSPlatform("windows")] public static object GetUniqueObjectForIUnknown(IntPtr unknown) { if (unknown == IntPtr.Zero) { throw new ArgumentNullException("unknown"); } return GetUniqueObjectForIUnknownNative(unknown); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern object GetUniqueObjectForIUnknownNative(IntPtr unknown); [MethodImpl(MethodImplOptions.InternalCall)] [SupportedOSPlatform("windows")] public static extern object GetTypedObjectForIUnknown(IntPtr pUnk, Type t); [SupportedOSPlatform("windows")] public static IntPtr CreateAggregatedObject(IntPtr pOuter, object o) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } return CreateAggregatedObjectNative(pOuter, o); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr CreateAggregatedObjectNative(IntPtr pOuter, object o); [SupportedOSPlatform("windows")] public static IntPtr CreateAggregatedObject(IntPtr pOuter, T o) where T : notnull { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } return CreateAggregatedObject(pOuter, (object)o); } [MethodImpl(MethodImplOptions.InternalCall)] public static extern void CleanupUnusedObjectsInCurrentContext(); [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool AreComObjectsAvailableForCleanup(); public static bool IsComObject(object o) { if (o == null) { throw new ArgumentNullException("o"); } return o is __ComObject; } [SupportedOSPlatform("windows")] public static int ReleaseComObject(object o) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } if (o == null) { throw new NullReferenceException(); } if (!(o is __ComObject _ComObject)) { throw new ArgumentException(SR.Argument_ObjNotComObject, "o"); } return _ComObject.ReleaseSelf(); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int InternalReleaseComObject(object o); [SupportedOSPlatform("windows")] public static int FinalReleaseComObject(object o) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } if (o == null) { throw new ArgumentNullException("o"); } if (!(o is __ComObject _ComObject)) { throw new ArgumentException(SR.Argument_ObjNotComObject, "o"); } _ComObject.FinalReleaseSelf(); return 0; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern void InternalFinalReleaseComObject(object o); [SupportedOSPlatform("windows")] public static object? GetComObjectData(object obj, object key) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } if (obj == null) { throw new ArgumentNullException("obj"); } if (key == null) { throw new ArgumentNullException("key"); } if (!(obj is __ComObject _ComObject)) { throw new ArgumentException(SR.Argument_ObjNotComObject, "obj"); } return _ComObject.GetData(key); } [SupportedOSPlatform("windows")] public static bool SetComObjectData(object obj, object key, object? data) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } if (obj == null) { throw new ArgumentNullException("obj"); } if (key == null) { throw new ArgumentNullException("key"); } if (!(obj is __ComObject _ComObject)) { throw new ArgumentException(SR.Argument_ObjNotComObject, "obj"); } return _ComObject.SetData(key, data); } [SupportedOSPlatform("windows")] [return: NotNullIfNotNull("o")] public static object? CreateWrapperOfType(object? o, Type t) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } if ((object)t == null) { throw new ArgumentNullException("t"); } if (!t.IsCOMObject) { throw new ArgumentException(SR.Argument_TypeNotComObject, "t"); } if (t.IsGenericType) { throw new ArgumentException(SR.Argument_NeedNonGenericType, "t"); } if (o == null) { return null; } if (!o.GetType().IsCOMObject) { throw new ArgumentException(SR.Argument_ObjNotComObject, "o"); } if (o.GetType() == t) { return o; } object obj = GetComObjectData(o, t); if (obj == null) { obj = InternalCreateWrapperOfType(o, t); if (!SetComObjectData(o, t, obj)) { obj = GetComObjectData(o, t); } } return obj; } [SupportedOSPlatform("windows")] public static TWrapper CreateWrapperOfType(T? o) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } return (TWrapper)CreateWrapperOfType(o, typeof(TWrapper)); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern object InternalCreateWrapperOfType(object o, Type t); [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool IsTypeVisibleFromCom(Type t); [SupportedOSPlatform("windows")] public static void GetNativeVariantForObject(object? obj, IntPtr pDstNativeVariant) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } GetNativeVariantForObjectNative(obj, pDstNativeVariant); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void GetNativeVariantForObjectNative(object obj, IntPtr pDstNativeVariant); [SupportedOSPlatform("windows")] public static void GetNativeVariantForObject(T? obj, IntPtr pDstNativeVariant) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } GetNativeVariantForObject((object?)obj, pDstNativeVariant); } [SupportedOSPlatform("windows")] public static object? GetObjectForNativeVariant(IntPtr pSrcNativeVariant) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } return GetObjectForNativeVariantNative(pSrcNativeVariant); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern object GetObjectForNativeVariantNative(IntPtr pSrcNativeVariant); [SupportedOSPlatform("windows")] public static T? GetObjectForNativeVariant(IntPtr pSrcNativeVariant) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } return (T)GetObjectForNativeVariant(pSrcNativeVariant); } [SupportedOSPlatform("windows")] public static object?[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } return GetObjectsForNativeVariantsNative(aSrcNativeVariant, cVars); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern object[] GetObjectsForNativeVariantsNative(IntPtr aSrcNativeVariant, int cVars); [SupportedOSPlatform("windows")] public static T[] GetObjectsForNativeVariants(IntPtr aSrcNativeVariant, int cVars) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } object[] objectsForNativeVariants = GetObjectsForNativeVariants(aSrcNativeVariant, cVars); T[] array = new T[objectsForNativeVariants.Length]; Array.Copy(objectsForNativeVariants, array, objectsForNativeVariants.Length); return array; } [MethodImpl(MethodImplOptions.InternalCall)] [SupportedOSPlatform("windows")] public static extern int GetStartComSlot(Type t); [MethodImpl(MethodImplOptions.InternalCall)] [SupportedOSPlatform("windows")] public static extern int GetEndComSlot(Type t); [RequiresUnreferencedCode("Built-in COM support is not trim compatible", Url = "https://aka.ms/dotnet-illink/com")] [SupportedOSPlatform("windows")] public static object BindToMoniker(string monikerName) { if (!IsBuiltInComSupported) { throw new NotSupportedException(SR.NotSupported_COM); } CreateBindCtx(0u, out var ppbc); MkParseDisplayName(ppbc, monikerName, out var _, out var ppmk); BindMoniker(ppmk, 0u, ref IID_IUnknown, out var ppvResult); return ppvResult; } [DllImport("ole32.dll", PreserveSig = false)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2050:UnrecognizedReflectionPattern", Justification = "The calling method is annotated with RequiresUnreferencedCode")] private static extern void CreateBindCtx(uint reserved, out IBindCtx ppbc); [DllImport("ole32.dll", PreserveSig = false)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2050:UnrecognizedReflectionPattern", Justification = "The calling method is annotated with RequiresUnreferencedCode")] private static extern void MkParseDisplayName(IBindCtx pbc, [MarshalAs(UnmanagedType.LPWStr)] string szUserName, out uint pchEaten, out IMoniker ppmk); [DllImport("ole32.dll", PreserveSig = false)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2050:UnrecognizedReflectionPattern", Justification = "The calling method is annotated with RequiresUnreferencedCode")] private static extern void BindMoniker(IMoniker pmk, uint grfOpt, ref Guid iidResult, [MarshalAs(UnmanagedType.Interface)] out object ppvResult); [MethodImpl(MethodImplOptions.InternalCall)] [SupportedOSPlatform("windows")] public static extern void ChangeWrapperHandleStrength(object otp, bool fIsWeak); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern Delegate GetDelegateForFunctionPointerInternal(IntPtr ptr, Type t); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetFunctionPointerForDelegateInternal(Delegate d); public static IntPtr AllocHGlobal(int cb) { return AllocHGlobal((IntPtr)cb); } public unsafe static string? PtrToStringAnsi(IntPtr ptr) { if (IsNullOrWin32Atom(ptr)) { return null; } return new string((sbyte*)(void*)ptr); } public unsafe static string PtrToStringAnsi(IntPtr ptr, int len) { if (ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } if (len < 0) { throw new ArgumentOutOfRangeException("len", len, SR.ArgumentOutOfRange_NeedNonNegNum); } return new string((sbyte*)(void*)ptr, 0, len); } public unsafe static string? PtrToStringUni(IntPtr ptr) { if (IsNullOrWin32Atom(ptr)) { return null; } return new string((char*)(void*)ptr); } public unsafe static string PtrToStringUni(IntPtr ptr, int len) { if (ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } if (len < 0) { throw new ArgumentOutOfRangeException("len", len, SR.ArgumentOutOfRange_NeedNonNegNum); } return new string((char*)(void*)ptr, 0, len); } public unsafe static string? PtrToStringUTF8(IntPtr ptr) { if (IsNullOrWin32Atom(ptr)) { return null; } int byteLength = string.strlen((byte*)(void*)ptr); return string.CreateStringFromEncoding((byte*)(void*)ptr, byteLength, Encoding.UTF8); } public unsafe static string PtrToStringUTF8(IntPtr ptr, int byteLen) { if (ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } if (byteLen < 0) { throw new ArgumentOutOfRangeException("byteLen", byteLen, SR.ArgumentOutOfRange_NeedNonNegNum); } return string.CreateStringFromEncoding((byte*)(void*)ptr, byteLen, Encoding.UTF8); } public static int SizeOf(object structure) { if (structure == null) { throw new ArgumentNullException("structure"); } return SizeOfHelper(structure.GetType(), throwIfNotMarshalable: true); } public static int SizeOf(T structure) { if (structure == null) { throw new ArgumentNullException("structure"); } return SizeOfHelper(structure.GetType(), throwIfNotMarshalable: true); } public static int SizeOf(Type t) { if ((object)t == null) { throw new ArgumentNullException("t"); } if (!t.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, "t"); } if (t.IsGenericType) { throw new ArgumentException(SR.Argument_NeedNonGenericType, "t"); } return SizeOfHelper(t, throwIfNotMarshalable: true); } public static int SizeOf() { Type typeFromHandle = typeof(T); if (typeFromHandle.IsGenericType) { throw new ArgumentException(SR.Argument_NeedNonGenericType, "T"); } return SizeOfHelper(typeFromHandle, throwIfNotMarshalable: true); } public unsafe static int QueryInterface(IntPtr pUnk, ref Guid iid, out IntPtr ppv) { if (pUnk == IntPtr.Zero) { throw new ArgumentNullException("pUnk"); } fixed (Guid* ptr = &iid) { fixed (IntPtr* ptr2 = &ppv) { return ((delegate* unmanaged)(*(*(IntPtr**)(void*)pUnk)))(pUnk, ptr, ptr2); } } } public unsafe static int AddRef(IntPtr pUnk) { if (pUnk == IntPtr.Zero) { throw new ArgumentNullException("pUnk"); } return ((delegate* unmanaged)(*(IntPtr*)((nint)(*(IntPtr*)(void*)pUnk) + sizeof(void*))))(pUnk); } public unsafe static int Release(IntPtr pUnk) { if (pUnk == IntPtr.Zero) { throw new ArgumentNullException("pUnk"); } return ((delegate* unmanaged)(*(IntPtr*)((nint)(*(IntPtr*)(void*)pUnk) + (nint)2 * (nint)sizeof(void*))))(pUnk); } public unsafe static IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index) { if (arr == null) { throw new ArgumentNullException("arr"); } void* ptr = Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(arr)); return (IntPtr)((byte*)ptr + (nuint)((nint)(uint)index * (nint)arr.GetElementSize())); } public unsafe static IntPtr UnsafeAddrOfPinnedArrayElement(T[] arr, int index) { if (arr == null) { throw new ArgumentNullException("arr"); } void* ptr = Unsafe.AsPointer(ref MemoryMarshal.GetArrayDataReference(arr)); return (IntPtr)((byte*)ptr + (nuint)((nint)(uint)index * (nint)Unsafe.SizeOf())); } public static IntPtr OffsetOf(string fieldName) { return OffsetOf(typeof(T), fieldName); } public static void Copy(int[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(char[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(short[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(long[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(float[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(double[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(byte[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } public static void Copy(IntPtr[] source, int startIndex, IntPtr destination, int length) { CopyToNative(source, startIndex, destination, length); } private unsafe static void CopyToNative(T[] source, int startIndex, IntPtr destination, int length) { if (source == null) { throw new ArgumentNullException("source"); } if (destination == IntPtr.Zero) { throw new ArgumentNullException("destination"); } new Span(source, startIndex, length).CopyTo(new Span((void*)destination, length)); } public static void Copy(IntPtr source, int[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, char[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, short[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, long[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, float[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, double[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, byte[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } public static void Copy(IntPtr source, IntPtr[] destination, int startIndex, int length) { CopyToManaged(source, destination, startIndex, length); } private unsafe static void CopyToManaged(IntPtr source, T[] destination, int startIndex, int length) { if (source == IntPtr.Zero) { throw new ArgumentNullException("source"); } if (destination == null) { throw new ArgumentNullException("destination"); } if (startIndex < 0) { throw new ArgumentOutOfRangeException("startIndex", SR.ArgumentOutOfRange_StartIndex); } if (length < 0) { throw new ArgumentOutOfRangeException("length", SR.ArgumentOutOfRange_NeedNonNegNum); } new Span((void*)source, length).CopyTo(new Span(destination, startIndex, length)); } public unsafe static byte ReadByte(IntPtr ptr, int ofs) { try { byte* ptr2 = (byte*)(void*)ptr + ofs; return *ptr2; } catch (NullReferenceException) { throw new AccessViolationException(); } } public static byte ReadByte(IntPtr ptr) { return ReadByte(ptr, 0); } public unsafe static short ReadInt16(IntPtr ptr, int ofs) { try { byte* ptr2 = (byte*)(void*)ptr + ofs; if (((int)ptr2 & 1) == 0) { return *(short*)ptr2; } return Unsafe.ReadUnaligned(ptr2); } catch (NullReferenceException) { throw new AccessViolationException(); } } public static short ReadInt16(IntPtr ptr) { return ReadInt16(ptr, 0); } public unsafe static int ReadInt32(IntPtr ptr, int ofs) { try { byte* ptr2 = (byte*)(void*)ptr + ofs; if (((int)ptr2 & 3) == 0) { return *(int*)ptr2; } return Unsafe.ReadUnaligned(ptr2); } catch (NullReferenceException) { throw new AccessViolationException(); } } public static int ReadInt32(IntPtr ptr) { return ReadInt32(ptr, 0); } public static IntPtr ReadIntPtr(object ptr, int ofs) { return (IntPtr)ReadInt32(ptr, ofs); } public static IntPtr ReadIntPtr(IntPtr ptr, int ofs) { return (IntPtr)ReadInt32(ptr, ofs); } public static IntPtr ReadIntPtr(IntPtr ptr) { return ReadIntPtr(ptr, 0); } public unsafe static long ReadInt64(IntPtr ptr, int ofs) { try { byte* ptr2 = (byte*)(void*)ptr + ofs; if (((int)ptr2 & 7) == 0) { return *(long*)ptr2; } return Unsafe.ReadUnaligned(ptr2); } catch (NullReferenceException) { throw new AccessViolationException(); } } public static long ReadInt64(IntPtr ptr) { return ReadInt64(ptr, 0); } public unsafe static void WriteByte(IntPtr ptr, int ofs, byte val) { try { byte* ptr2 = (byte*)(void*)ptr + ofs; *ptr2 = val; } catch (NullReferenceException) { throw new AccessViolationException(); } } public static void WriteByte(IntPtr ptr, byte val) { WriteByte(ptr, 0, val); } public unsafe static void WriteInt16(IntPtr ptr, int ofs, short val) { try { byte* ptr2 = (byte*)(void*)ptr + ofs; if (((int)ptr2 & 1) == 0) { *(short*)ptr2 = val; } else { Unsafe.WriteUnaligned(ptr2, val); } } catch (NullReferenceException) { throw new AccessViolationException(); } } public static void WriteInt16(IntPtr ptr, short val) { WriteInt16(ptr, 0, val); } public static void WriteInt16(IntPtr ptr, int ofs, char val) { WriteInt16(ptr, ofs, (short)val); } public static void WriteInt16([In][Out] object ptr, int ofs, char val) { WriteInt16(ptr, ofs, (short)val); } public static void WriteInt16(IntPtr ptr, char val) { WriteInt16(ptr, 0, (short)val); } public unsafe static void WriteInt32(IntPtr ptr, int ofs, int val) { try { byte* ptr2 = (byte*)(void*)ptr + ofs; if (((int)ptr2 & 3) == 0) { *(int*)ptr2 = val; } else { Unsafe.WriteUnaligned(ptr2, val); } } catch (NullReferenceException) { throw new AccessViolationException(); } } public static void WriteInt32(IntPtr ptr, int val) { WriteInt32(ptr, 0, val); } public static void WriteIntPtr(IntPtr ptr, int ofs, IntPtr val) { WriteInt32(ptr, ofs, (int)val); } public static void WriteIntPtr(object ptr, int ofs, IntPtr val) { WriteInt32(ptr, ofs, (int)val); } public static void WriteIntPtr(IntPtr ptr, IntPtr val) { WriteIntPtr(ptr, 0, val); } public unsafe static void WriteInt64(IntPtr ptr, int ofs, long val) { try { byte* ptr2 = (byte*)(void*)ptr + ofs; if (((int)ptr2 & 7) == 0) { *(long*)ptr2 = val; } else { Unsafe.WriteUnaligned(ptr2, val); } } catch (NullReferenceException) { throw new AccessViolationException(); } } public static void WriteInt64(IntPtr ptr, long val) { WriteInt64(ptr, 0, val); } public static void Prelink(MethodInfo m) { if ((object)m == null) { throw new ArgumentNullException("m"); } PrelinkCore(m); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "This only needs to prelink methods that are actually used")] public static void PrelinkAll(Type c) { if ((object)c == null) { throw new ArgumentNullException("c"); } MethodInfo[] methods = c.GetMethods(); for (int i = 0; i < methods.Length; i++) { Prelink(methods[i]); } } public static void StructureToPtr([DisallowNull] T structure, IntPtr ptr, bool fDeleteOld) { StructureToPtr((object)structure, ptr, fDeleteOld); } public static object? PtrToStructure(IntPtr ptr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type structureType) { if (ptr == IntPtr.Zero) { return null; } if ((object)structureType == null) { throw new ArgumentNullException("structureType"); } if (structureType.IsGenericType) { throw new ArgumentException(SR.Argument_NeedNonGenericType, "structureType"); } if (!structureType.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, "structureType"); } object obj = Activator.CreateInstance(structureType, nonPublic: true); PtrToStructureHelper(ptr, obj, allowValueClasses: true); return obj; } public static void PtrToStructure(IntPtr ptr, object structure) { PtrToStructureHelper(ptr, structure, allowValueClasses: false); } public static void PtrToStructure(IntPtr ptr, [DisallowNull] T structure) { PtrToStructureHelper(ptr, structure, allowValueClasses: false); } public static T? PtrToStructure<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(IntPtr ptr) { if (ptr == IntPtr.Zero) { return (T)(object)null; } Type typeFromHandle = typeof(T); if (typeFromHandle.IsGenericType) { throw new ArgumentException(SR.Argument_NeedNonGenericType, "T"); } object obj = Activator.CreateInstance(typeFromHandle, nonPublic: true); PtrToStructureHelper(ptr, obj, allowValueClasses: true); return (T)obj; } public static void DestroyStructure(IntPtr ptr) { DestroyStructure(ptr, typeof(T)); } public static Exception? GetExceptionForHR(int errorCode) { return GetExceptionForHR(errorCode, IntPtr.Zero); } public static Exception? GetExceptionForHR(int errorCode, IntPtr errorInfo) { if (errorCode >= 0) { return null; } return GetExceptionForHRInternal(errorCode, errorInfo); } public static void ThrowExceptionForHR(int errorCode) { if (errorCode < 0) { throw GetExceptionForHR(errorCode); } } public static void ThrowExceptionForHR(int errorCode, IntPtr errorInfo) { if (errorCode < 0) { throw GetExceptionForHR(errorCode, errorInfo); } } public static IntPtr SecureStringToBSTR(SecureString s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return s.MarshalToBSTR(); } public static IntPtr SecureStringToCoTaskMemAnsi(SecureString s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return s.MarshalToString(globalAlloc: false, unicode: false); } public static IntPtr SecureStringToCoTaskMemUnicode(SecureString s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return s.MarshalToString(globalAlloc: false, unicode: true); } public static IntPtr SecureStringToGlobalAllocAnsi(SecureString s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return s.MarshalToString(globalAlloc: true, unicode: false); } public static IntPtr SecureStringToGlobalAllocUnicode(SecureString s) { if (s == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); } return s.MarshalToString(globalAlloc: true, unicode: true); } public unsafe static IntPtr StringToHGlobalAnsi(string? s) { if (s == null) { return IntPtr.Zero; } long num = (long)(s.Length + 1) * (long)SystemMaxDBCSCharSize; int num2 = (int)num; if (num2 != num) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.s); } IntPtr intPtr = AllocHGlobal((IntPtr)num2); StringToAnsiString(s, (byte*)(void*)intPtr, num2); return intPtr; } public unsafe static IntPtr StringToHGlobalUni(string? s) { if (s == null) { return IntPtr.Zero; } int num = (s.Length + 1) * 2; if (num < s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.s); } IntPtr intPtr = AllocHGlobal((IntPtr)num); s.CopyTo(new Span((void*)intPtr, s.Length)); *(short*)((byte*)(void*)intPtr + (nint)s.Length * (nint)2) = 0; return intPtr; } public unsafe static IntPtr StringToCoTaskMemUni(string? s) { if (s == null) { return IntPtr.Zero; } int num = (s.Length + 1) * 2; if (num < s.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.s); } IntPtr intPtr = AllocCoTaskMem(num); s.CopyTo(new Span((void*)intPtr, s.Length)); *(short*)((byte*)(void*)intPtr + (nint)s.Length * (nint)2) = 0; return intPtr; } public unsafe static IntPtr StringToCoTaskMemUTF8(string? s) { if (s == null) { return IntPtr.Zero; } int maxByteCount = Encoding.UTF8.GetMaxByteCount(s.Length); IntPtr intPtr = AllocCoTaskMem(maxByteCount + 1); byte* ptr = (byte*)(void*)intPtr; int bytes; fixed (char* chars = s) { bytes = Encoding.UTF8.GetBytes(chars, s.Length, ptr, maxByteCount); } ptr[bytes] = 0; return intPtr; } public unsafe static IntPtr StringToCoTaskMemAnsi(string? s) { if (s == null) { return IntPtr.Zero; } long num = (long)(s.Length + 1) * (long)SystemMaxDBCSCharSize; int num2 = (int)num; if (num2 != num) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.s); } IntPtr intPtr = AllocCoTaskMem(num2); StringToAnsiString(s, (byte*)(void*)intPtr, num2); return intPtr; } public static Guid GenerateGuidForType(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } if (!type.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, "type"); } return type.GUID; } public static string? GenerateProgIdForType(Type type) { if ((object)type == null) { throw new ArgumentNullException("type"); } if (type.IsImport) { throw new ArgumentException(SR.Argument_TypeMustNotBeComImport, "type"); } if (type.IsGenericType) { throw new ArgumentException(SR.Argument_NeedNonGenericType, "type"); } ProgIdAttribute customAttribute = type.GetCustomAttribute(); if (customAttribute != null) { return customAttribute.Value ?? string.Empty; } return type.FullName; } public static Delegate GetDelegateForFunctionPointer(IntPtr ptr, Type t) { if (ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } if ((object)t == null) { throw new ArgumentNullException("t"); } if (!t.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, "t"); } if (t.IsGenericType) { throw new ArgumentException(SR.Argument_NeedNonGenericType, "t"); } if (t.BaseType != typeof(MulticastDelegate) && t != typeof(MulticastDelegate)) { throw new ArgumentException(SR.Arg_MustBeDelegate, "t"); } return GetDelegateForFunctionPointerInternal(ptr, t); } public static TDelegate GetDelegateForFunctionPointer(IntPtr ptr) { if (ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } Type typeFromHandle = typeof(TDelegate); if (typeFromHandle.IsGenericType) { throw new ArgumentException(SR.Argument_NeedNonGenericType, "TDelegate"); } if (typeFromHandle.BaseType != typeof(MulticastDelegate) && typeFromHandle != typeof(MulticastDelegate)) { throw new ArgumentException(SR.Arg_MustBeDelegate, "TDelegate"); } return (TDelegate)(object)GetDelegateForFunctionPointerInternal(ptr, typeFromHandle); } public static IntPtr GetFunctionPointerForDelegate(Delegate d) { if ((object)d == null) { throw new ArgumentNullException("d"); } return GetFunctionPointerForDelegateInternal(d); } public static IntPtr GetFunctionPointerForDelegate(TDelegate d) where TDelegate : notnull { return GetFunctionPointerForDelegate((Delegate)(object)d); } public static int GetHRForLastWin32Error() { int lastPInvokeError = GetLastPInvokeError(); if ((lastPInvokeError & 0x80000000u) == 2147483648u) { return lastPInvokeError; } return (lastPInvokeError & 0xFFFF) | -2147024896; } public unsafe static void ZeroFreeBSTR(IntPtr s) { if (!(s == IntPtr.Zero)) { Buffer.ZeroMemory((byte*)(void*)s, SysStringByteLen(s)); FreeBSTR(s); } } public static void ZeroFreeCoTaskMemAnsi(IntPtr s) { ZeroFreeCoTaskMemUTF8(s); } public unsafe static void ZeroFreeCoTaskMemUnicode(IntPtr s) { if (!(s == IntPtr.Zero)) { Buffer.ZeroMemory((byte*)(void*)s, (nuint)string.wcslen((char*)(void*)s) * (nuint)2u); FreeCoTaskMem(s); } } public unsafe static void ZeroFreeCoTaskMemUTF8(IntPtr s) { if (!(s == IntPtr.Zero)) { Buffer.ZeroMemory((byte*)(void*)s, (nuint)string.strlen((byte*)(void*)s)); FreeCoTaskMem(s); } } public unsafe static void ZeroFreeGlobalAllocAnsi(IntPtr s) { if (!(s == IntPtr.Zero)) { Buffer.ZeroMemory((byte*)(void*)s, (nuint)string.strlen((byte*)(void*)s)); FreeHGlobal(s); } } public unsafe static void ZeroFreeGlobalAllocUnicode(IntPtr s) { if (!(s == IntPtr.Zero)) { Buffer.ZeroMemory((byte*)(void*)s, (nuint)string.wcslen((char*)(void*)s) * (nuint)2u); FreeHGlobal(s); } } public unsafe static IntPtr StringToBSTR(string? s) { if (s == null) { return IntPtr.Zero; } IntPtr intPtr = AllocBSTR(s.Length); s.CopyTo(new Span((void*)intPtr, s.Length)); return intPtr; } public static string PtrToStringBSTR(IntPtr ptr) { if (ptr == IntPtr.Zero) { throw new ArgumentNullException("ptr"); } return PtrToStringUni(ptr, (int)(SysStringByteLen(ptr) / 2)); } internal unsafe static uint SysStringByteLen(IntPtr s) { return *(uint*)((byte*)(void*)s - 4); } [SupportedOSPlatform("windows")] public static Type? GetTypeFromCLSID(Guid clsid) { return GetTypeFromCLSID(clsid, null, throwOnError: false); } public static void InitHandle(SafeHandle safeHandle, IntPtr handle) { safeHandle.SetHandle(handle); } public static int GetLastWin32Error() { return GetLastPInvokeError(); } public static string? PtrToStringAuto(IntPtr ptr, int len) { return PtrToStringUni(ptr, len); } public static string? PtrToStringAuto(IntPtr ptr) { return PtrToStringUni(ptr); } public static IntPtr StringToHGlobalAuto(string? s) { return StringToHGlobalUni(s); } public static IntPtr StringToCoTaskMemAuto(string? s) { return StringToCoTaskMemUni(s); } private unsafe static int GetSystemMaxDBCSCharSize() { Interop.Kernel32.CPINFO cPINFO = default(Interop.Kernel32.CPINFO); if (Interop.Kernel32.GetCPInfo(0u, &cPINFO) == Interop.BOOL.FALSE) { return 2; } return cPINFO.MaxCharSize; } private static bool IsNullOrWin32Atom(IntPtr ptr) { long num = (long)ptr; return (num & -65536) == 0; } internal unsafe static int StringToAnsiString(string s, byte* buffer, int bufferLength, bool bestFit = false, bool throwOnUnmappableChar = false) { uint dwFlags = ((!bestFit) ? 1024u : 0u); uint num = 0u; int num2; fixed (char* lpWideCharStr = s) { num2 = Interop.Kernel32.WideCharToMultiByte(0u, dwFlags, lpWideCharStr, s.Length, buffer, bufferLength, IntPtr.Zero, throwOnUnmappableChar ? new IntPtr(&num) : IntPtr.Zero); } if (num != 0) { throw new ArgumentException(SR.Interop_Marshal_Unmappable_Char); } buffer[num2] = 0; return num2; } internal unsafe static int GetAnsiStringByteCount(ReadOnlySpan chars) { int num; if (chars.Length == 0) { num = 0; } else { fixed (char* lpWideCharStr = chars) { num = Interop.Kernel32.WideCharToMultiByte(0u, 1024u, lpWideCharStr, chars.Length, null, 0, IntPtr.Zero, IntPtr.Zero); if (num <= 0) { throw new ArgumentException(); } } } return checked(num + 1); } internal unsafe static void GetAnsiStringBytes(ReadOnlySpan chars, Span bytes) { int num; if (chars.Length == 0) { num = 0; } else { fixed (char* lpWideCharStr = chars) { fixed (byte* lpMultiByteStr = bytes) { num = Interop.Kernel32.WideCharToMultiByte(0u, 1024u, lpWideCharStr, chars.Length, lpMultiByteStr, bytes.Length, IntPtr.Zero, IntPtr.Zero); if (num <= 0) { throw new ArgumentException(); } } } } bytes[num] = 0; } public static IntPtr AllocHGlobal(IntPtr cb) { IntPtr intPtr = Interop.Kernel32.LocalAlloc(0u, (nuint)(nint)cb); if (intPtr == IntPtr.Zero) { throw new OutOfMemoryException(); } return intPtr; } public static void FreeHGlobal(IntPtr hglobal) { if (!IsNullOrWin32Atom(hglobal)) { Interop.Kernel32.LocalFree(hglobal); } } public static IntPtr ReAllocHGlobal(IntPtr pv, IntPtr cb) { if (pv == IntPtr.Zero) { return AllocHGlobal(cb); } IntPtr intPtr = Interop.Kernel32.LocalReAlloc(pv, (nuint)(nint)cb, 2u); if (intPtr == IntPtr.Zero) { throw new OutOfMemoryException(); } return intPtr; } public static IntPtr AllocCoTaskMem(int cb) { IntPtr intPtr = Interop.Ole32.CoTaskMemAlloc((uint)cb); if (intPtr == IntPtr.Zero) { throw new OutOfMemoryException(); } return intPtr; } public static void FreeCoTaskMem(IntPtr ptr) { if (!IsNullOrWin32Atom(ptr)) { Interop.Ole32.CoTaskMemFree(ptr); } } public static IntPtr ReAllocCoTaskMem(IntPtr pv, int cb) { IntPtr intPtr = Interop.Ole32.CoTaskMemRealloc(pv, (uint)cb); if (intPtr == IntPtr.Zero && cb != 0) { throw new OutOfMemoryException(); } return intPtr; } internal static IntPtr AllocBSTR(int length) { IntPtr intPtr = Interop.OleAut32.SysAllocStringLen(IntPtr.Zero, (uint)length); if (intPtr == IntPtr.Zero) { throw new OutOfMemoryException(); } return intPtr; } internal static IntPtr AllocBSTRByteLen(uint length) { IntPtr intPtr = Interop.OleAut32.SysAllocStringByteLen(null, length); if (intPtr == IntPtr.Zero) { throw new OutOfMemoryException(); } return intPtr; } public static void FreeBSTR(IntPtr ptr) { if (!IsNullOrWin32Atom(ptr)) { Interop.OleAut32.SysFreeString(ptr); } } internal static Type GetTypeFromProgID(string progID, string server, bool throwOnError) { if (progID == null) { throw new ArgumentNullException("progID"); } Guid lpclsid; int num = Interop.Ole32.CLSIDFromProgID(progID, out lpclsid); if (num < 0) { if (throwOnError) { throw GetExceptionForHR(num, new IntPtr(-1)); } return null; } return GetTypeFromCLSID(lpclsid, server, throwOnError); } public static int GetLastSystemError() { return Interop.Kernel32.GetLastError(); } public static void SetLastSystemError(int error) { Interop.Kernel32.SetLastError(error); } } public static class MemoryMarshal { [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] [NonVersionable] public static ref T GetArrayDataReference(T[] array) { return ref Unsafe.As(ref Unsafe.As(array).Data); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static ref byte GetArrayDataReference(Array array) { return ref Unsafe.AddByteOffset(ref Unsafe.As(array).Data, (nuint)RuntimeHelpers.GetMethodTable(array)->BaseSize - (nuint)(2 * sizeof(IntPtr))); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span AsBytes(Span span) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); } return new Span(ref Unsafe.As(ref GetReference(span)), checked(span.Length * Unsafe.SizeOf())); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan AsBytes(ReadOnlySpan span) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); } return new ReadOnlySpan(ref Unsafe.As(ref GetReference(span)), checked(span.Length * Unsafe.SizeOf())); } public static Memory AsMemory(ReadOnlyMemory memory) { return Unsafe.As, Memory>(ref memory); } public static ref T GetReference(Span span) { return ref span._pointer.Value; } public static ref T GetReference(ReadOnlySpan span) { return ref span._pointer.Value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe static ref T GetNonNullPinnableReference(Span span) { if (span.Length == 0) { return ref Unsafe.AsRef((void*)1); } return ref span._pointer.Value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe static ref T GetNonNullPinnableReference(ReadOnlySpan span) { if (span.Length == 0) { return ref Unsafe.AsRef((void*)1); } return ref span._pointer.Value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span Cast(Span span) where TFrom : struct where TTo : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom)); } if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo)); } uint num = (uint)Unsafe.SizeOf(); uint num2 = (uint)Unsafe.SizeOf(); uint length = (uint)span.Length; int length2; if (num == num2) { length2 = (int)length; } else if (num == 1) { length2 = (int)(length / num2); } else { ulong num3 = (ulong)((long)length * (long)num) / (ulong)num2; length2 = checked((int)num3); } return new Span(ref Unsafe.As(ref span._pointer.Value), length2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan Cast(ReadOnlySpan span) where TFrom : struct where TTo : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TFrom)); } if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(TTo)); } uint num = (uint)Unsafe.SizeOf(); uint num2 = (uint)Unsafe.SizeOf(); uint length = (uint)span.Length; int length2; if (num == num2) { length2 = (int)length; } else if (num == 1) { length2 = (int)(length / num2); } else { ulong num3 = (ulong)((long)length * (long)num) / (ulong)num2; length2 = checked((int)num3); } return new ReadOnlySpan(ref Unsafe.As(ref GetReference(span)), length2); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span CreateSpan(ref T reference, int length) { return new Span(ref reference, length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan CreateReadOnlySpan(ref T reference, int length) { return new ReadOnlySpan(ref reference, length); } [CLSCompliant(false)] public unsafe static ReadOnlySpan CreateReadOnlySpanFromNullTerminated(char* value) { if (value == null) { return default(ReadOnlySpan); } return new ReadOnlySpan(value, string.wcslen(value)); } [CLSCompliant(false)] public unsafe static ReadOnlySpan CreateReadOnlySpanFromNullTerminated(byte* value) { if (value == null) { return default(ReadOnlySpan); } return new ReadOnlySpan(value, string.strlen(value)); } public static bool TryGetArray(ReadOnlyMemory memory, out ArraySegment segment) { int start; int length; object objectStartLength = memory.GetObjectStartLength(out start, out length); if (objectStartLength != null && (!(typeof(T) == typeof(char)) || !(objectStartLength.GetType() == typeof(string)))) { if (RuntimeHelpers.ObjectHasComponentSize(objectStartLength)) { segment = new ArraySegment(Unsafe.As(objectStartLength), start & 0x7FFFFFFF, length); return true; } if (Unsafe.As>(objectStartLength).TryGetArray(out var segment2)) { segment = new ArraySegment(segment2.Array, segment2.Offset + start, length); return true; } } if (length == 0) { segment = ArraySegment.Empty; return true; } segment = default(ArraySegment); return false; } public static bool TryGetMemoryManager(ReadOnlyMemory memory, [NotNullWhen(true)] out TManager? manager) where TManager : MemoryManager { int start; int length; return (manager = memory.GetObjectStartLength(out start, out length) as TManager) != null; } public static bool TryGetMemoryManager(ReadOnlyMemory memory, [NotNullWhen(true)] out TManager? manager, out int start, out int length) where TManager : MemoryManager { if ((manager = memory.GetObjectStartLength(out start, out length) as TManager) == null) { start = 0; length = 0; return false; } return true; } public static IEnumerable ToEnumerable(ReadOnlyMemory memory) { for (int i = 0; i < memory.Length; i++) { yield return memory.Span[i]; } } public static bool TryGetString(ReadOnlyMemory memory, [NotNullWhen(true)] out string? text, out int start, out int length) { if (memory.GetObjectStartLength(out var start2, out var length2) is string text2) { text = text2; start = start2; length = length2; return true; } text = null; start = 0; length = 0; return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static T Read(ReadOnlySpan source) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); } if (Unsafe.SizeOf() > source.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); } return Unsafe.ReadUnaligned(ref GetReference(source)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryRead(ReadOnlySpan source, out T value) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); } if (Unsafe.SizeOf() > (uint)source.Length) { value = default(T); return false; } value = Unsafe.ReadUnaligned(ref GetReference(source)); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Write(Span destination, ref T value) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); } if ((uint)Unsafe.SizeOf() > (uint)destination.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); } Unsafe.WriteUnaligned(ref GetReference(destination), value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryWrite(Span destination, ref T value) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); } if (Unsafe.SizeOf() > (uint)destination.Length) { return false; } Unsafe.WriteUnaligned(ref GetReference(destination), value); return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref T AsRef(Span span) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); } if (Unsafe.SizeOf() > (uint)span.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); } return ref Unsafe.As(ref GetReference(span)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ref readonly T AsRef(ReadOnlySpan span) where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { ThrowHelper.ThrowInvalidTypeWithPointersNotSupported(typeof(T)); } if (Unsafe.SizeOf() > (uint)span.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.length); } return ref Unsafe.As(ref GetReference(span)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Memory CreateFromPinnedArray(T[]? array, int start, int length) { if (array == null) { if (start != 0 || length != 0) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return default(Memory); } if (!typeof(T).IsValueType && array.GetType() != typeof(T[])) { ThrowHelper.ThrowArrayTypeMismatchException(); } if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start)) { ThrowHelper.ThrowArgumentOutOfRangeException(); } return new Memory((object)array, start | int.MinValue, length); } } public static class NativeLibrary { private static ConditionalWeakTable s_nativeDllResolveMap; internal static IntPtr LoadLibraryByName(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, bool throwOnError) { RuntimeAssembly assembly2 = (RuntimeAssembly)assembly; return LoadByName(libraryName, new QCallAssembly(ref assembly2), searchPath.HasValue, (uint)searchPath.GetValueOrDefault(), throwOnError); } [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern IntPtr LoadFromPath(string libraryName, bool throwOnError); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern IntPtr LoadByName(string libraryName, QCallAssembly callingAssembly, bool hasDllImportSearchPathFlag, uint dllImportSearchPathFlag, bool throwOnError); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern void FreeLib(IntPtr handle); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern IntPtr GetSymbol(IntPtr handle, string symbolName, bool throwOnError); public static IntPtr Load(string libraryPath) { if (libraryPath == null) { throw new ArgumentNullException("libraryPath"); } return LoadFromPath(libraryPath, throwOnError: true); } public static bool TryLoad(string libraryPath, out IntPtr handle) { if (libraryPath == null) { throw new ArgumentNullException("libraryPath"); } handle = LoadFromPath(libraryPath, throwOnError: false); return handle != IntPtr.Zero; } public static IntPtr Load(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) { if (libraryName == null) { throw new ArgumentNullException("libraryName"); } if (assembly == null) { throw new ArgumentNullException("assembly"); } if (!assembly.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); } return LoadLibraryByName(libraryName, assembly, searchPath, throwOnError: true); } public static bool TryLoad(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, out IntPtr handle) { if (libraryName == null) { throw new ArgumentNullException("libraryName"); } if (assembly == null) { throw new ArgumentNullException("assembly"); } if (!assembly.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); } handle = LoadLibraryByName(libraryName, assembly, searchPath, throwOnError: false); return handle != IntPtr.Zero; } public static void Free(IntPtr handle) { if (!(handle == IntPtr.Zero)) { FreeLib(handle); } } public static IntPtr GetExport(IntPtr handle, string name) { if (handle == IntPtr.Zero) { throw new ArgumentNullException("handle"); } if (name == null) { throw new ArgumentNullException("name"); } return GetSymbol(handle, name, throwOnError: true); } public static bool TryGetExport(IntPtr handle, string name, out IntPtr address) { if (handle == IntPtr.Zero) { throw new ArgumentNullException("handle"); } if (name == null) { throw new ArgumentNullException("name"); } address = GetSymbol(handle, name, throwOnError: false); return address != IntPtr.Zero; } public static void SetDllImportResolver(Assembly assembly, DllImportResolver resolver) { if (assembly == null) { throw new ArgumentNullException("assembly"); } if (resolver == null) { throw new ArgumentNullException("resolver"); } if (!assembly.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); } if (s_nativeDllResolveMap == null) { Interlocked.CompareExchange(ref s_nativeDllResolveMap, new ConditionalWeakTable(), null); } try { s_nativeDllResolveMap.Add(assembly, resolver); } catch (ArgumentException) { throw new InvalidOperationException(SR.InvalidOperation_CannotRegisterSecondResolver); } } internal static IntPtr LoadLibraryCallbackStub(string libraryName, Assembly assembly, bool hasDllImportSearchPathFlags, uint dllImportSearchPathFlags) { if (s_nativeDllResolveMap == null) { return IntPtr.Zero; } if (!s_nativeDllResolveMap.TryGetValue(assembly, out var value)) { return IntPtr.Zero; } return value(libraryName, assembly, hasDllImportSearchPathFlags ? new DllImportSearchPath?((DllImportSearchPath)dllImportSearchPathFlags) : null); } } internal enum ComWrappersScenario { Instance, TrackerSupportGlobalInstance, MarshallingGlobalInstance } [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] [CLSCompliant(false)] public abstract class ComWrappers { public struct ComInterfaceDispatch { private struct ComInterfaceInstance { public IntPtr GcHandle; } public IntPtr Vtable; public unsafe static T GetInstance(ComInterfaceDispatch* dispatchPtr) where T : class { ComInterfaceInstance* ptr = *(ComInterfaceInstance**)((ulong)dispatchPtr & 0xFFFFFFFFFFFFFFF0uL); return Unsafe.As(GCHandle.InternalGet(ptr->GcHandle)); } } public struct ComInterfaceEntry { public Guid IID; public IntPtr Vtable; } private static ComWrappers s_globalInstanceForTrackerSupport; private static ComWrappers s_globalInstanceForMarshalling; private static long s_instanceCounter; private readonly long id = Interlocked.Increment(ref s_instanceCounter); public IntPtr GetOrCreateComInterfaceForObject(object instance, CreateComInterfaceFlags flags) { if (!TryGetOrCreateComInterfaceForObjectInternal(this, instance, flags, out var retValue)) { throw new ArgumentException(null, "instance"); } return retValue; } private static bool TryGetOrCreateComInterfaceForObjectInternal(ComWrappers impl, object instance, CreateComInterfaceFlags flags, out IntPtr retValue) { if (instance == null) { throw new ArgumentNullException("instance"); } return TryGetOrCreateComInterfaceForObjectInternal(ObjectHandleOnStack.Create(ref impl), impl.id, ObjectHandleOnStack.Create(ref instance), flags, out retValue); } [DllImport("QCall")] private static extern bool TryGetOrCreateComInterfaceForObjectInternal(ObjectHandleOnStack comWrappersImpl, long wrapperId, ObjectHandleOnStack instance, CreateComInterfaceFlags flags, out IntPtr retValue); internal unsafe static void* CallComputeVtables(ComWrappersScenario scenario, ComWrappers comWrappersImpl, object obj, CreateComInterfaceFlags flags, out int count) { ComWrappers comWrappers = null; switch (scenario) { case ComWrappersScenario.Instance: comWrappers = comWrappersImpl; break; case ComWrappersScenario.TrackerSupportGlobalInstance: comWrappers = s_globalInstanceForTrackerSupport; break; case ComWrappersScenario.MarshallingGlobalInstance: comWrappers = s_globalInstanceForMarshalling; break; } if (comWrappers == null) { count = -1; return null; } return comWrappers.ComputeVtables(obj, flags, out count); } public object GetOrCreateObjectForComInstance(IntPtr externalComObject, CreateObjectFlags flags) { if (!TryGetOrCreateObjectForComInstanceInternal(this, externalComObject, IntPtr.Zero, flags, null, out var retValue)) { throw new ArgumentNullException("externalComObject"); } return retValue; } internal static object CallCreateObject(ComWrappersScenario scenario, ComWrappers comWrappersImpl, IntPtr externalComObject, CreateObjectFlags flags) { ComWrappers comWrappers = null; switch (scenario) { case ComWrappersScenario.Instance: comWrappers = comWrappersImpl; break; case ComWrappersScenario.TrackerSupportGlobalInstance: comWrappers = s_globalInstanceForTrackerSupport; break; case ComWrappersScenario.MarshallingGlobalInstance: comWrappers = s_globalInstanceForMarshalling; break; } return comWrappers?.CreateObject(externalComObject, flags); } public object GetOrRegisterObjectForComInstance(IntPtr externalComObject, CreateObjectFlags flags, object wrapper) { return GetOrRegisterObjectForComInstance(externalComObject, flags, wrapper, IntPtr.Zero); } public object GetOrRegisterObjectForComInstance(IntPtr externalComObject, CreateObjectFlags flags, object wrapper, IntPtr inner) { if (wrapper == null) { throw new ArgumentNullException("wrapper"); } if (!TryGetOrCreateObjectForComInstanceInternal(this, externalComObject, inner, flags, wrapper, out var retValue)) { throw new ArgumentNullException("externalComObject"); } return retValue; } private static bool TryGetOrCreateObjectForComInstanceInternal(ComWrappers impl, IntPtr externalComObject, IntPtr innerMaybe, CreateObjectFlags flags, object wrapperMaybe, out object retValue) { if (externalComObject == IntPtr.Zero) { throw new ArgumentNullException("externalComObject"); } if (innerMaybe != IntPtr.Zero && !flags.HasFlag(CreateObjectFlags.Aggregation)) { throw new InvalidOperationException(SR.InvalidOperation_SuppliedInnerMustBeMarkedAggregation); } object o = wrapperMaybe; retValue = null; return TryGetOrCreateObjectForComInstanceInternal(ObjectHandleOnStack.Create(ref impl), impl.id, externalComObject, innerMaybe, flags, ObjectHandleOnStack.Create(ref o), ObjectHandleOnStack.Create(ref retValue)); } [DllImport("QCall")] private static extern bool TryGetOrCreateObjectForComInstanceInternal(ObjectHandleOnStack comWrappersImpl, long wrapperId, IntPtr externalComObject, IntPtr innerMaybe, CreateObjectFlags flags, ObjectHandleOnStack wrapper, ObjectHandleOnStack retValue); internal static void CallReleaseObjects(ComWrappers comWrappersImpl, System.Collections.IEnumerable objects) { (comWrappersImpl ?? s_globalInstanceForTrackerSupport).ReleaseObjects(objects); } public static void RegisterForTrackerSupport(ComWrappers instance) { if (instance == null) { throw new ArgumentNullException("instance"); } if (Interlocked.CompareExchange(ref s_globalInstanceForTrackerSupport, instance, null) != null) { throw new InvalidOperationException(SR.InvalidOperation_ResetGlobalComWrappersInstance); } SetGlobalInstanceRegisteredForTrackerSupport(instance.id); } [DllImport("QCall")] [SuppressGCTransition] private static extern void SetGlobalInstanceRegisteredForTrackerSupport(long id); [SupportedOSPlatform("windows")] public static void RegisterForMarshalling(ComWrappers instance) { if (instance == null) { throw new ArgumentNullException("instance"); } if (Interlocked.CompareExchange(ref s_globalInstanceForMarshalling, instance, null) != null) { throw new InvalidOperationException(SR.InvalidOperation_ResetGlobalComWrappersInstance); } SetGlobalInstanceRegisteredForMarshalling(instance.id); } [DllImport("QCall")] [SuppressGCTransition] private static extern void SetGlobalInstanceRegisteredForMarshalling(long id); protected static void GetIUnknownImpl(out IntPtr fpQueryInterface, out IntPtr fpAddRef, out IntPtr fpRelease) { GetIUnknownImplInternal(out fpQueryInterface, out fpAddRef, out fpRelease); } [DllImport("QCall")] private static extern void GetIUnknownImplInternal(out IntPtr fpQueryInterface, out IntPtr fpAddRef, out IntPtr fpRelease); internal static int CallICustomQueryInterface(object customQueryInterfaceMaybe, ref Guid iid, out IntPtr ppObject) { if (!(customQueryInterfaceMaybe is ICustomQueryInterface customQueryInterface)) { ppObject = IntPtr.Zero; return -1; } return (int)customQueryInterface.GetInterface(ref iid, out ppObject); } protected unsafe abstract ComInterfaceEntry* ComputeVtables(object obj, CreateComInterfaceFlags flags, out int count); protected abstract object? CreateObject(IntPtr externalComObject, CreateObjectFlags flags); protected abstract void ReleaseObjects(System.Collections.IEnumerable objects); } [ComImport] [Guid("00020400-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IDispatch { int GetTypeInfoCount(); ITypeInfo GetTypeInfo(int iTInfo, int lcid); void GetIDsOfNames(ref Guid riid, [In][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 2)] string[] rgszNames, int cNames, int lcid, [Out] int[] rgDispId); void Invoke(int dispIdMember, ref Guid riid, int lcid, InvokeFlags wFlags, ref DISPPARAMS pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); } [Flags] internal enum InvokeFlags : short { DISPATCH_METHOD = 1, DISPATCH_PROPERTYGET = 2, DISPATCH_PROPERTYPUT = 4, DISPATCH_PROPERTYPUTREF = 8 } internal sealed class ComEventsMethod { public class DelegateWrapper { private bool _once; private int _expectedParamsCount; private Type[] _cachedTargetTypes; public Delegate Delegate { get; set; } public bool WrapArgs { get; } public DelegateWrapper(Delegate d, bool wrapArgs) { Delegate = d; WrapArgs = wrapArgs; } public object Invoke(object[] args) { if ((object)Delegate == null) { return null; } if (!_once) { PreProcessSignature(); _once = true; } if (_cachedTargetTypes != null && _expectedParamsCount == args.Length) { for (int i = 0; i < _expectedParamsCount; i++) { Type type = _cachedTargetTypes[i]; if ((object)type != null) { args[i] = Enum.ToObject(type, args[i]); } } } return Delegate.DynamicInvoke((!WrapArgs) ? args : new object[1] { args }); } private void PreProcessSignature() { ParameterInfo[] parameters = Delegate.Method.GetParameters(); _expectedParamsCount = parameters.Length; Type[] array = null; for (int i = 0; i < _expectedParamsCount; i++) { ParameterInfo parameterInfo = parameters[i]; if (parameterInfo.ParameterType.IsByRef && parameterInfo.ParameterType.HasElementType && parameterInfo.ParameterType.GetElementType().IsEnum) { if (array == null) { array = new Type[_expectedParamsCount]; } array[i] = parameterInfo.ParameterType.GetElementType(); } } if (array != null) { _cachedTargetTypes = array; } } } private readonly List _delegateWrappers = new List(); private readonly int _dispid; private ComEventsMethod _next; public bool Empty { get { lock (_delegateWrappers) { return _delegateWrappers.Count == 0; } } } public ComEventsMethod(int dispid) { _dispid = dispid; } public static ComEventsMethod Find(ComEventsMethod methods, int dispid) { while (methods != null && methods._dispid != dispid) { methods = methods._next; } return methods; } public static ComEventsMethod Add(ComEventsMethod methods, ComEventsMethod method) { method._next = methods; return method; } public static ComEventsMethod Remove(ComEventsMethod methods, ComEventsMethod method) { if (methods == method) { return methods._next; } ComEventsMethod comEventsMethod = methods; while (comEventsMethod != null && comEventsMethod._next != method) { comEventsMethod = comEventsMethod._next; } if (comEventsMethod != null) { comEventsMethod._next = method._next; } return methods; } public void AddDelegate(Delegate d, bool wrapArgs = false) { lock (_delegateWrappers) { foreach (DelegateWrapper delegateWrapper in _delegateWrappers) { if (delegateWrapper.Delegate.GetType() == d.GetType() && delegateWrapper.WrapArgs == wrapArgs) { delegateWrapper.Delegate = Delegate.Combine(delegateWrapper.Delegate, d); return; } } DelegateWrapper item = new DelegateWrapper(d, wrapArgs); _delegateWrappers.Add(item); } } public void RemoveDelegate(Delegate d, bool wrapArgs = false) { lock (_delegateWrappers) { int num = -1; DelegateWrapper delegateWrapper = null; for (int i = 0; i < _delegateWrappers.Count; i++) { DelegateWrapper delegateWrapper2 = _delegateWrappers[i]; if (delegateWrapper2.Delegate.GetType() == d.GetType() && delegateWrapper2.WrapArgs == wrapArgs) { num = i; delegateWrapper = delegateWrapper2; break; } } if (num >= 0) { Delegate @delegate = Delegate.Remove(delegateWrapper.Delegate, d); if ((object)@delegate != null) { delegateWrapper.Delegate = @delegate; } else { _delegateWrappers.RemoveAt(num); } } } } public object Invoke(object[] args) { object result = null; lock (_delegateWrappers) { foreach (DelegateWrapper delegateWrapper in _delegateWrappers) { result = delegateWrapper.Invoke(args); } return result; } } } [SupportedOSPlatform("windows")] internal sealed class ComEventsSink : IDispatch, ICustomQueryInterface { private Guid _iidSourceItf; private IConnectionPoint _connectionPoint; private int _cookie; private ComEventsMethod _methods; private ComEventsSink _next; public ComEventsSink(object rcw, Guid iid) { _iidSourceItf = iid; Advise(rcw); } public static ComEventsSink Find(ComEventsSink sinks, ref Guid iid) { ComEventsSink comEventsSink = sinks; while (comEventsSink != null && comEventsSink._iidSourceItf != iid) { comEventsSink = comEventsSink._next; } return comEventsSink; } public static ComEventsSink Add(ComEventsSink sinks, ComEventsSink sink) { sink._next = sinks; return sink; } public static ComEventsSink RemoveAll(ComEventsSink sinks) { while (sinks != null) { sinks.Unadvise(); sinks = sinks._next; } return null; } public static ComEventsSink Remove(ComEventsSink sinks, ComEventsSink sink) { ComEventsSink result = sinks; if (sink == sinks) { result = sinks._next; } else { ComEventsSink comEventsSink = sinks; while (comEventsSink != null && comEventsSink._next != sink) { comEventsSink = comEventsSink._next; } if (comEventsSink != null) { comEventsSink._next = sink._next; } } sink.Unadvise(); return result; } public ComEventsMethod RemoveMethod(ComEventsMethod method) { _methods = ComEventsMethod.Remove(_methods, method); return _methods; } public ComEventsMethod FindMethod(int dispid) { return ComEventsMethod.Find(_methods, dispid); } public ComEventsMethod AddMethod(int dispid) { ComEventsMethod comEventsMethod = new ComEventsMethod(dispid); _methods = ComEventsMethod.Add(_methods, comEventsMethod); return comEventsMethod; } int IDispatch.GetTypeInfoCount() { return 0; } ITypeInfo IDispatch.GetTypeInfo(int iTInfo, int lcid) { throw new NotImplementedException(); } void IDispatch.GetIDsOfNames(ref Guid iid, string[] names, int cNames, int lcid, int[] rgDispId) { throw new NotImplementedException(); } private unsafe static ref Variant GetVariant(ref Variant pSrc) { if (pSrc.VariantType == (VarEnum)16396) { Span span = new Span(pSrc.AsByRefVariant.ToPointer(), 1); if ((span[0].VariantType & (VarEnum)20479) == (VarEnum)16396) { return ref span[0]; } } return ref pSrc; } unsafe void IDispatch.Invoke(int dispid, ref Guid riid, int lcid, InvokeFlags wFlags, ref DISPPARAMS pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { ComEventsMethod comEventsMethod = FindMethod(dispid); if (comEventsMethod == null) { return; } object[] array = new object[pDispParams.cArgs]; int[] array2 = new int[pDispParams.cArgs]; bool[] array3 = new bool[pDispParams.cArgs]; int length = pDispParams.cNamedArgs + pDispParams.cArgs; Span span = new Span(pDispParams.rgvarg.ToPointer(), length); Span span2 = new Span(pDispParams.rgdispidNamedArgs.ToPointer(), length); int num; int i; for (i = 0; i < pDispParams.cNamedArgs; i++) { num = span2[i]; ref Variant variant = ref GetVariant(ref span[i]); array[num] = variant.ToObject(); array3[num] = true; int num2 = -1; if (variant.IsByRef) { num2 = i; } array2[num] = num2; } num = 0; for (; i < pDispParams.cArgs; i++) { for (; array3[num]; num++) { } ref Variant variant2 = ref GetVariant(ref span[pDispParams.cArgs - 1 - i]); array[num] = variant2.ToObject(); int num3 = -1; if (variant2.IsByRef) { num3 = pDispParams.cArgs - 1 - i; } array2[num] = num3; num++; } object obj = comEventsMethod.Invoke(array); if (pVarResult != IntPtr.Zero) { Marshal.GetNativeVariantForObject(obj, pVarResult); } for (i = 0; i < pDispParams.cArgs; i++) { int num4 = array2[i]; if (num4 != -1) { GetVariant(ref span[num4]).CopyFromIndirect(array[i]); } } } CustomQueryInterfaceResult ICustomQueryInterface.GetInterface(ref Guid iid, out IntPtr ppv) { ppv = IntPtr.Zero; if (iid == _iidSourceItf || iid == typeof(IDispatch).GUID) { ppv = Marshal.GetComInterfaceForObject(this, typeof(IDispatch), CustomQueryInterfaceMode.Ignore); return CustomQueryInterfaceResult.Handled; } return CustomQueryInterfaceResult.NotHandled; } private void Advise(object rcw) { IConnectionPointContainer connectionPointContainer = (IConnectionPointContainer)rcw; connectionPointContainer.FindConnectionPoint(ref _iidSourceItf, out IConnectionPoint ppCP); ppCP.Advise(this, out _cookie); _connectionPoint = ppCP; } private void Unadvise() { if (_connectionPoint == null) { return; } try { _connectionPoint.Unadvise(_cookie); Marshal.ReleaseComObject(_connectionPoint); } catch { } finally { _connectionPoint = null; } } } [StructLayout(LayoutKind.Explicit)] [SupportedOSPlatform("windows")] internal struct Variant { private struct TypeUnion { public ushort _vt; public ushort _wReserved1; public ushort _wReserved2; public ushort _wReserved3; public UnionTypes _unionTypes; } private struct Record { public IntPtr _record; public IntPtr _recordInfo; } [StructLayout(LayoutKind.Explicit)] private struct UnionTypes { [FieldOffset(0)] public sbyte _i1; [FieldOffset(0)] public short _i2; [FieldOffset(0)] public int _i4; [FieldOffset(0)] public long _i8; [FieldOffset(0)] public byte _ui1; [FieldOffset(0)] public ushort _ui2; [FieldOffset(0)] public uint _ui4; [FieldOffset(0)] public ulong _ui8; [FieldOffset(0)] public int _int; [FieldOffset(0)] public uint _uint; [FieldOffset(0)] public short _bool; [FieldOffset(0)] public int _error; [FieldOffset(0)] public float _r4; [FieldOffset(0)] public double _r8; [FieldOffset(0)] public long _cy; [FieldOffset(0)] public double _date; [FieldOffset(0)] public IntPtr _bstr; [FieldOffset(0)] public IntPtr _unknown; [FieldOffset(0)] public IntPtr _dispatch; [FieldOffset(0)] public IntPtr _pvarVal; [FieldOffset(0)] public IntPtr _byref; [FieldOffset(0)] public Record _record; } [FieldOffset(0)] private TypeUnion _typeUnion; [FieldOffset(0)] private decimal _decimal; public VarEnum VariantType { get { return (VarEnum)_typeUnion._vt; } set { _typeUnion._vt = (ushort)value; } } public bool IsEmpty => _typeUnion._vt == 0; public bool IsByRef => (_typeUnion._vt & 0x4000) != 0; public sbyte AsI1 => _typeUnion._unionTypes._i1; public short AsI2 => _typeUnion._unionTypes._i2; public int AsI4 => _typeUnion._unionTypes._i4; public long AsI8 => _typeUnion._unionTypes._i8; public byte AsUi1 => _typeUnion._unionTypes._ui1; public ushort AsUi2 => _typeUnion._unionTypes._ui2; public uint AsUi4 => _typeUnion._unionTypes._ui4; public ulong AsUi8 => _typeUnion._unionTypes._ui8; public int AsInt => _typeUnion._unionTypes._int; public uint AsUint => _typeUnion._unionTypes._uint; public bool AsBool => _typeUnion._unionTypes._bool != 0; public int AsError => _typeUnion._unionTypes._error; public float AsR4 => _typeUnion._unionTypes._r4; public double AsR8 => _typeUnion._unionTypes._r8; public decimal AsDecimal { get { Variant variant = this; variant._typeUnion._vt = 0; return variant._decimal; } } public decimal AsCy => decimal.FromOACurrency(_typeUnion._unionTypes._cy); public DateTime AsDate => DateTime.FromOADate(_typeUnion._unionTypes._date); public string AsBstr { get { if (_typeUnion._unionTypes._bstr == IntPtr.Zero) { return null; } return Marshal.PtrToStringBSTR(_typeUnion._unionTypes._bstr); } } public object AsUnknown { get { if (_typeUnion._unionTypes._unknown == IntPtr.Zero) { return null; } return Marshal.GetObjectForIUnknown(_typeUnion._unionTypes._unknown); } } public object AsDispatch { get { if (_typeUnion._unionTypes._dispatch == IntPtr.Zero) { return null; } return Marshal.GetObjectForIUnknown(_typeUnion._unionTypes._dispatch); } } public IntPtr AsByRefVariant => _typeUnion._unionTypes._pvarVal; public unsafe void CopyFromIndirect(object value) { VarEnum varEnum = VariantType & (VarEnum)(-16385); if (value == null) { if (varEnum == VarEnum.VT_DISPATCH || varEnum == VarEnum.VT_UNKNOWN || varEnum == VarEnum.VT_BSTR) { *(IntPtr*)(void*)_typeUnion._unionTypes._byref = IntPtr.Zero; } return; } if ((varEnum & VarEnum.VT_ARRAY) != 0) { System.Runtime.CompilerServices.Unsafe.SkipInit(out Variant variant); Marshal.GetNativeVariantForObject(value, (IntPtr)(&variant)); *(IntPtr*)(void*)_typeUnion._unionTypes._byref = variant._typeUnion._unionTypes._byref; return; } switch (varEnum) { case VarEnum.VT_I1: *(sbyte*)(void*)_typeUnion._unionTypes._byref = (sbyte)value; break; case VarEnum.VT_UI1: *(byte*)(void*)_typeUnion._unionTypes._byref = (byte)value; break; case VarEnum.VT_I2: *(short*)(void*)_typeUnion._unionTypes._byref = (short)value; break; case VarEnum.VT_UI2: *(ushort*)(void*)_typeUnion._unionTypes._byref = (ushort)value; break; case VarEnum.VT_BOOL: *(short*)(void*)_typeUnion._unionTypes._byref = (short)(((bool)value) ? (-1) : 0); break; case VarEnum.VT_I4: case VarEnum.VT_INT: *(int*)(void*)_typeUnion._unionTypes._byref = (int)value; break; case VarEnum.VT_UI4: case VarEnum.VT_UINT: *(uint*)(void*)_typeUnion._unionTypes._byref = (uint)value; break; case VarEnum.VT_ERROR: *(int*)(void*)_typeUnion._unionTypes._byref = ((ErrorWrapper)value).ErrorCode; break; case VarEnum.VT_I8: *(long*)(void*)_typeUnion._unionTypes._byref = (long)value; break; case VarEnum.VT_UI8: *(ulong*)(void*)_typeUnion._unionTypes._byref = (ulong)value; break; case VarEnum.VT_R4: *(float*)(void*)_typeUnion._unionTypes._byref = (float)value; break; case VarEnum.VT_R8: *(double*)(void*)_typeUnion._unionTypes._byref = (double)value; break; case VarEnum.VT_DATE: *(double*)(void*)_typeUnion._unionTypes._byref = ((DateTime)value).ToOADate(); break; case VarEnum.VT_UNKNOWN: *(IntPtr*)(void*)_typeUnion._unionTypes._byref = Marshal.GetIUnknownForObject(value); break; case VarEnum.VT_DISPATCH: *(IntPtr*)(void*)_typeUnion._unionTypes._byref = Marshal.GetIDispatchForObject(value); break; case VarEnum.VT_BSTR: *(IntPtr*)(void*)_typeUnion._unionTypes._byref = Marshal.StringToBSTR((string)value); break; case VarEnum.VT_CY: *(long*)(void*)_typeUnion._unionTypes._byref = decimal.ToOACurrency((decimal)value); break; case VarEnum.VT_DECIMAL: *(decimal*)(void*)_typeUnion._unionTypes._byref = (decimal)value; break; case VarEnum.VT_VARIANT: Marshal.GetNativeVariantForObject(value, _typeUnion._unionTypes._byref); break; default: throw new ArgumentException(); } } public unsafe object ToObject() { if (IsEmpty) { return null; } switch (VariantType) { case VarEnum.VT_NULL: return DBNull.Value; case VarEnum.VT_I1: return AsI1; case VarEnum.VT_I2: return AsI2; case VarEnum.VT_I4: return AsI4; case VarEnum.VT_I8: return AsI8; case VarEnum.VT_UI1: return AsUi1; case VarEnum.VT_UI2: return AsUi2; case VarEnum.VT_UI4: return AsUi4; case VarEnum.VT_UI8: return AsUi8; case VarEnum.VT_INT: return AsInt; case VarEnum.VT_UINT: return AsUint; case VarEnum.VT_BOOL: return AsBool; case VarEnum.VT_ERROR: return AsError; case VarEnum.VT_R4: return AsR4; case VarEnum.VT_R8: return AsR8; case VarEnum.VT_DECIMAL: return AsDecimal; case VarEnum.VT_CY: return AsCy; case VarEnum.VT_DATE: return AsDate; case VarEnum.VT_BSTR: return AsBstr; case VarEnum.VT_UNKNOWN: return AsUnknown; case VarEnum.VT_DISPATCH: return AsDispatch; default: fixed (Variant* ptr = &this) { void* ptr2 = ptr; return Marshal.GetObjectForNativeVariant((IntPtr)ptr2); } } } public unsafe void Clear() { VarEnum variantType = VariantType; if ((variantType & VarEnum.VT_BYREF) != 0) { VariantType = VarEnum.VT_EMPTY; } else if ((variantType & VarEnum.VT_ARRAY) != 0 || variantType == VarEnum.VT_BSTR || variantType == VarEnum.VT_UNKNOWN || variantType == VarEnum.VT_DISPATCH || variantType == VarEnum.VT_VARIANT || variantType == VarEnum.VT_RECORD) { fixed (Variant* ptr = &this) { void* ptr2 = ptr; Interop.OleAut32.VariantClear((IntPtr)ptr2); } } else { VariantType = VarEnum.VT_EMPTY; } } } [SupportedOSPlatform("windows")] public static class ComEventsHelper { public static void Combine(object rcw, Guid iid, int dispid, Delegate d) { lock (rcw) { ComEventsInfo comEventsInfo = ComEventsInfo.FromObject(rcw); ComEventsSink comEventsSink = comEventsInfo.FindSink(ref iid) ?? comEventsInfo.AddSink(ref iid); ComEventsMethod comEventsMethod = comEventsSink.FindMethod(dispid) ?? comEventsSink.AddMethod(dispid); comEventsMethod.AddDelegate(d); } } public static Delegate? Remove(object rcw, Guid iid, int dispid, Delegate d) { lock (rcw) { ComEventsInfo comEventsInfo = ComEventsInfo.Find(rcw); if (comEventsInfo == null) { return null; } ComEventsSink comEventsSink = comEventsInfo.FindSink(ref iid); if (comEventsSink == null) { return null; } ComEventsMethod comEventsMethod = comEventsSink.FindMethod(dispid); if (comEventsMethod == null) { return null; } comEventsMethod.RemoveDelegate(d); if (comEventsMethod.Empty) { comEventsMethod = comEventsSink.RemoveMethod(comEventsMethod); } if (comEventsMethod == null) { comEventsSink = comEventsInfo.RemoveSink(comEventsSink); } if (comEventsSink == null) { Marshal.SetComObjectData(rcw, typeof(ComEventsInfo), null); GC.SuppressFinalize(comEventsInfo); } return d; } } } [SupportedOSPlatform("windows")] internal sealed class ComEventsInfo { private ComEventsSink _sinks; private readonly object _rcw; private ComEventsInfo(object rcw) { _rcw = rcw; } ~ComEventsInfo() { _sinks = ComEventsSink.RemoveAll(_sinks); } public static ComEventsInfo Find(object rcw) { return (ComEventsInfo)Marshal.GetComObjectData(rcw, typeof(ComEventsInfo)); } public static ComEventsInfo FromObject(object rcw) { ComEventsInfo comEventsInfo = Find(rcw); if (comEventsInfo == null) { comEventsInfo = new ComEventsInfo(rcw); Marshal.SetComObjectData(rcw, typeof(ComEventsInfo), comEventsInfo); } return comEventsInfo; } public ComEventsSink FindSink(ref Guid iid) { return ComEventsSink.Find(_sinks, ref iid); } public ComEventsSink AddSink(ref Guid iid) { ComEventsSink sink = new ComEventsSink(_rcw, iid); _sinks = ComEventsSink.Add(_sinks, sink); return _sinks; } internal ComEventsSink RemoveSink(ComEventsSink sink) { _sinks = ComEventsSink.Remove(_sinks, sink); return _sinks; } } [Obsolete("Code Access Security is not supported or honored by the runtime.", DiagnosticId = "SYSLIB0003", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class AllowReversePInvokeCallsAttribute : Attribute { } public readonly struct ArrayWithOffset { private readonly object m_array; private readonly int m_offset; private readonly int m_count; public ArrayWithOffset(object? array, int offset) { int num = 0; if (array != null) { if (!(array is Array array2) || array2.Rank != 1 || !Marshal.IsPinnable(array2)) { throw new ArgumentException(SR.ArgumentException_NotIsomorphic); } nuint num2 = array2.NativeLength * array2.GetElementSize(); if (num2 > 2147483632) { throw new ArgumentException(SR.Argument_StructArrayTooLarge); } num = (int)num2; } if ((uint)offset > (uint)num) { throw new IndexOutOfRangeException(SR.IndexOutOfRange_ArrayWithOffset); } m_array = array; m_offset = offset; m_count = num - offset; } public object? GetArray() { return m_array; } public int GetOffset() { return m_offset; } public override int GetHashCode() { return m_count + m_offset; } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is ArrayWithOffset) { return Equals((ArrayWithOffset)obj); } return false; } public bool Equals(ArrayWithOffset obj) { if (obj.m_array == m_array && obj.m_offset == m_offset) { return obj.m_count == m_count; } return false; } public static bool operator ==(ArrayWithOffset a, ArrayWithOffset b) { return a.Equals(b); } public static bool operator !=(ArrayWithOffset a, ArrayWithOffset b) { return !(a == b); } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] public sealed class BestFitMappingAttribute : Attribute { public bool ThrowOnUnmappableChar; public bool BestFitMapping { get; } public BestFitMappingAttribute(bool BestFitMapping) { this.BestFitMapping = BestFitMapping; } } public sealed class BStrWrapper { public string? WrappedObject { get; } public BStrWrapper(string? value) { WrappedObject = value; } public BStrWrapper(object? value) { WrappedObject = (string)value; } } public enum CallingConvention { Winapi = 1, Cdecl, StdCall, ThisCall, FastCall } public enum CharSet { None = 1, Ansi, Unicode, Auto } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, Inherited = false)] public sealed class ClassInterfaceAttribute : Attribute { public ClassInterfaceType Value { get; } public ClassInterfaceAttribute(ClassInterfaceType classInterfaceType) { Value = classInterfaceType; } public ClassInterfaceAttribute(short classInterfaceType) { Value = (ClassInterfaceType)classInterfaceType; } } public enum ClassInterfaceType { None, AutoDispatch, AutoDual } [CLSCompliant(false)] [Intrinsic] public readonly struct CLong : IEquatable { private readonly int _value; public nint Value => _value; public CLong(int value) { _value = value; } public CLong(nint value) { _value = checked((int)value); } public override bool Equals([NotNullWhen(true)] object? o) { if (o is CLong other) { return Equals(other); } return false; } public bool Equals(CLong other) { return _value == other._value; } public override int GetHashCode() { return _value.GetHashCode(); } public override string ToString() { return _value.ToString(); } } [AttributeUsage(AttributeTargets.Interface, Inherited = false)] public sealed class CoClassAttribute : Attribute { public Type CoClass { get; } public CoClassAttribute(Type coClass) { CoClass = coClass; } } public static class CollectionsMarshal { public static Span AsSpan(List? list) { if (list != null) { return new Span(list._items, 0, list._size); } return default(Span); } public static ref TValue GetValueRefOrNullRef(Dictionary dictionary, TKey key) where TKey : notnull { return ref dictionary.FindValue(key); } public static ref TValue? GetValueRefOrAddDefault(Dictionary dictionary, TKey key, out bool exists) where TKey : notnull { return ref Dictionary.CollectionsMarshalHelper.GetValueRefOrAddDefault(dictionary, key, out exists); } } [AttributeUsage(AttributeTargets.Class, Inherited = false)] public sealed class ComDefaultInterfaceAttribute : Attribute { public Type Value { get; } public ComDefaultInterfaceAttribute(Type defaultInterface) { Value = defaultInterface; } } [AttributeUsage(AttributeTargets.Interface, Inherited = false)] public sealed class ComEventInterfaceAttribute : Attribute { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] public Type SourceInterface { get; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicEvents)] public Type EventProvider { get; } public ComEventInterfaceAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type SourceInterface, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicEvents)] Type EventProvider) { this.SourceInterface = SourceInterface; this.EventProvider = EventProvider; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class COMException : ExternalException { public COMException() : base(SR.Arg_COMException) { base.HResult = -2147467259; } public COMException(string? message) : base(message) { base.HResult = -2147467259; } public COMException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2147467259; } public COMException(string? message, int errorCode) : base(message) { base.HResult = errorCode; } protected COMException(SerializationInfo info, StreamingContext context) : base(info, context) { } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder2 = stringBuilder; StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(5, 2, stringBuilder2); handler.AppendFormatted(GetType()); handler.AppendLiteral(" (0x"); handler.AppendFormatted(base.HResult, "X8"); handler.AppendLiteral(")"); stringBuilder2.Append(ref handler); string message = Message; if (!string.IsNullOrEmpty(message)) { stringBuilder.Append(": ").Append(message); } Exception innerException = base.InnerException; if (innerException != null) { stringBuilder.Append("\r\n ---> ").Append(innerException.ToString()); } string stackTrace = StackTrace; if (stackTrace != null) { stringBuilder.AppendLine().Append(stackTrace); } return stringBuilder.ToString(); } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false)] public sealed class ComImportAttribute : Attribute { } public enum ComInterfaceType { InterfaceIsDual, InterfaceIsIUnknown, InterfaceIsIDispatch, InterfaceIsIInspectable } public enum ComMemberType { Method, PropGet, PropSet } [AttributeUsage(AttributeTargets.Class, Inherited = true)] public sealed class ComSourceInterfacesAttribute : Attribute { public string Value { get; } public ComSourceInterfacesAttribute(string sourceInterfaces) { Value = sourceInterfaces; } public ComSourceInterfacesAttribute(Type sourceInterface) { Value = sourceInterface.FullName; } public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2) { Value = sourceInterface1.FullName + "\0" + sourceInterface2.FullName; } public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2, Type sourceInterface3) { Value = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName; } public ComSourceInterfacesAttribute(Type sourceInterface1, Type sourceInterface2, Type sourceInterface3, Type sourceInterface4) { Value = sourceInterface1.FullName + "\0" + sourceInterface2.FullName + "\0" + sourceInterface3.FullName + "\0" + sourceInterface4.FullName; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] public sealed class ComVisibleAttribute : Attribute { public bool Value { get; } public ComVisibleAttribute(bool visibility) { Value = visibility; } } [Flags] public enum CreateComInterfaceFlags { None = 0, CallerDefinedIUnknown = 1, TrackerSupport = 2 } [Flags] public enum CreateObjectFlags { None = 0, TrackerObject = 1, UniqueInstance = 2, Aggregation = 4, Unwrap = 8 } public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable { protected IntPtr handle; private bool _isClosed; public bool IsClosed => _isClosed; public abstract bool IsInvalid { get; } protected CriticalHandle(IntPtr invalidHandleValue) { handle = invalidHandleValue; } ~CriticalHandle() { Dispose(disposing: false); } private void Cleanup() { if (!IsClosed) { _isClosed = true; if (!IsInvalid) { int lastPInvokeError = Marshal.GetLastPInvokeError(); ReleaseHandle(); Marshal.SetLastPInvokeError(lastPInvokeError); GC.SuppressFinalize(this); } } } protected void SetHandle(IntPtr handle) { this.handle = handle; } public void Close() { Dispose(disposing: true); } public void Dispose() { Dispose(disposing: true); } protected virtual void Dispose(bool disposing) { Cleanup(); } public void SetHandleAsInvalid() { _isClosed = true; GC.SuppressFinalize(this); } protected abstract bool ReleaseHandle(); } [CLSCompliant(false)] [Intrinsic] public readonly struct CULong : IEquatable { private readonly uint _value; public nuint Value => _value; public CULong(uint value) { _value = value; } public CULong(nuint value) { _value = checked((uint)value); } public override bool Equals([NotNullWhen(true)] object? o) { if (o is CULong other) { return Equals(other); } return false; } public bool Equals(CULong other) { return _value == other._value; } public override int GetHashCode() { return _value.GetHashCode(); } public override string ToString() { return _value.ToString(); } } public sealed class CurrencyWrapper { public decimal WrappedObject { get; } public CurrencyWrapper(decimal obj) { WrappedObject = obj; } public CurrencyWrapper(object obj) { if (!(obj is decimal)) { throw new ArgumentException(SR.Arg_MustBeDecimal, "obj"); } WrappedObject = (decimal)obj; } } public enum CustomQueryInterfaceMode { Ignore, Allow } public enum CustomQueryInterfaceResult { Handled, NotHandled, Failed } [AttributeUsage(AttributeTargets.Module, Inherited = false)] public sealed class DefaultCharSetAttribute : Attribute { public CharSet CharSet { get; } public DefaultCharSetAttribute(CharSet charSet) { CharSet = charSet; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Method, AllowMultiple = false)] public sealed class DefaultDllImportSearchPathsAttribute : Attribute { public DllImportSearchPath Paths { get; } public DefaultDllImportSearchPathsAttribute(DllImportSearchPath paths) { Paths = paths; } } [AttributeUsage(AttributeTargets.Parameter)] public sealed class DefaultParameterValueAttribute : Attribute { public object? Value { get; } public DefaultParameterValueAttribute(object? value) { Value = value; } } [SupportedOSPlatform("windows")] public sealed class DispatchWrapper { public object? WrappedObject { get; } public DispatchWrapper(object? obj) { if (obj != null) { IntPtr iDispatchForObject = Marshal.GetIDispatchForObject(obj); Marshal.Release(iDispatchForObject); WrappedObject = obj; } } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event, Inherited = false)] public sealed class DispIdAttribute : Attribute { public int Value { get; } public DispIdAttribute(int dispId) { Value = dispId; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class DllImportAttribute : Attribute { public string? EntryPoint; public CharSet CharSet; public bool SetLastError; public bool ExactSpelling; public CallingConvention CallingConvention; public bool BestFitMapping; public bool PreserveSig; public bool ThrowOnUnmappableChar; public string Value { get; } public DllImportAttribute(string dllName) { Value = dllName; } } [Flags] public enum DllImportSearchPath { UseDllDirectoryForDependencies = 0x100, ApplicationDirectory = 0x200, UserDirectories = 0x400, System32 = 0x800, SafeDirectories = 0x1000, AssemblyDirectory = 2, LegacyBehavior = 0 } public sealed class ErrorWrapper { public int ErrorCode { get; } public ErrorWrapper(int errorCode) { ErrorCode = errorCode; } public ErrorWrapper(object errorCode) { if (!(errorCode is int)) { throw new ArgumentException(SR.Arg_MustBeInt32, "errorCode"); } ErrorCode = (int)errorCode; } public ErrorWrapper(Exception e) { ErrorCode = Marshal.GetHRForException(e); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class ExternalException : SystemException { public virtual int ErrorCode => base.HResult; public ExternalException() : base(SR.Arg_ExternalException) { base.HResult = -2147467259; } public ExternalException(string? message) : base(message) { base.HResult = -2147467259; } public ExternalException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2147467259; } public ExternalException(string? message, int errorCode) : base(message) { base.HResult = errorCode; } protected ExternalException(SerializationInfo info, StreamingContext context) : base(info, context) { } public override string ToString() { string message = Message; string text = $"{GetType()} (0x{base.HResult:X8})"; if (!string.IsNullOrEmpty(message)) { text = text + ": " + message; } Exception innerException = base.InnerException; if (innerException != null) { text = text + "\r\n ---> " + innerException.ToString(); } if (StackTrace != null) { text = text + "\r\n" + StackTrace; } return text; } } [AttributeUsage(AttributeTargets.Field, Inherited = false)] public sealed class FieldOffsetAttribute : Attribute { public int Value { get; } public FieldOffsetAttribute(int offset) { Value = offset; } } public enum GCHandleType { Weak, WeakTrackResurrection, Normal, Pinned } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)] public sealed class GuidAttribute : Attribute { public string Value { get; } public GuidAttribute(string guid) { Value = guid; } } public readonly struct HandleRef { private readonly object _wrapper; private readonly IntPtr _handle; public object? Wrapper => _wrapper; public IntPtr Handle => _handle; public HandleRef(object? wrapper, IntPtr handle) { _wrapper = wrapper; _handle = handle; } public static explicit operator IntPtr(HandleRef value) { return value._handle; } public static IntPtr ToIntPtr(HandleRef value) { return value._handle; } } public interface ICustomAdapter { [return: MarshalAs(UnmanagedType.IUnknown)] object GetUnderlyingObject(); } public interface ICustomFactory { MarshalByRefObject CreateInstance(Type serverType); } public interface ICustomMarshaler { object MarshalNativeToManaged(IntPtr pNativeData); IntPtr MarshalManagedToNative(object ManagedObj); void CleanUpNativeData(IntPtr pNativeData); void CleanUpManagedData(object ManagedObj); int GetNativeDataSize(); } public interface ICustomQueryInterface { CustomQueryInterfaceResult GetInterface([In] ref Guid iid, out IntPtr ppv); } public interface IDynamicInterfaceCastable { bool IsInterfaceImplemented(RuntimeTypeHandle interfaceType, bool throwIfNotImplemented); RuntimeTypeHandle GetInterfaceImplementation(RuntimeTypeHandle interfaceType); } [AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = false)] public sealed class DynamicInterfaceCastableImplementationAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] public sealed class InAttribute : Attribute { } [AttributeUsage(AttributeTargets.Interface, Inherited = false)] public sealed class InterfaceTypeAttribute : Attribute { public ComInterfaceType Value { get; } public InterfaceTypeAttribute(ComInterfaceType interfaceType) { Value = interfaceType; } public InterfaceTypeAttribute(short interfaceType) { Value = (ComInterfaceType)interfaceType; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class InvalidComObjectException : SystemException { public InvalidComObjectException() : base(SR.Arg_InvalidComObjectException) { base.HResult = -2146233049; } public InvalidComObjectException(string? message) : base(message) { base.HResult = -2146233049; } public InvalidComObjectException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233049; } protected InvalidComObjectException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class InvalidOleVariantTypeException : SystemException { public InvalidOleVariantTypeException() : base(SR.Arg_InvalidOleVariantTypeException) { base.HResult = -2146233039; } public InvalidOleVariantTypeException(string? message) : base(message) { base.HResult = -2146233039; } public InvalidOleVariantTypeException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233039; } protected InvalidOleVariantTypeException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public enum LayoutKind { Sequential = 0, Explicit = 2, Auto = 3 } [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class LCIDConversionAttribute : Attribute { public int Value { get; } public LCIDConversionAttribute(int lcid) { Value = lcid; } } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] public sealed class MarshalAsAttribute : Attribute { public VarEnum SafeArraySubType; public Type? SafeArrayUserDefinedSubType; public int IidParameterIndex; public UnmanagedType ArraySubType; public short SizeParamIndex; public int SizeConst; public string? MarshalType; public Type? MarshalTypeRef; public string? MarshalCookie; public UnmanagedType Value { get; } public MarshalAsAttribute(UnmanagedType unmanagedType) { Value = unmanagedType; } public MarshalAsAttribute(short unmanagedType) { Value = (UnmanagedType)unmanagedType; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class MarshalDirectiveException : SystemException { public MarshalDirectiveException() : base(SR.Arg_MarshalDirectiveException) { base.HResult = -2146233035; } public MarshalDirectiveException(string? message) : base(message) { base.HResult = -2146233035; } public MarshalDirectiveException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233035; } protected MarshalDirectiveException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public static class NativeMemory { [CLSCompliant(false)] public unsafe static void* Alloc(nuint elementCount, nuint elementSize) { nuint byteCount = GetByteCount(elementCount, elementSize); return Alloc(byteCount); } [CLSCompliant(false)] public unsafe static void* AllocZeroed(nuint byteCount) { return AllocZeroed(byteCount, 1u); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe static nuint GetByteCount(nuint elementCount, nuint elementSize) { nuint num = (nuint)((nint)1 << 4 * sizeof(UIntPtr)); if ((elementSize < num && elementCount < num) || elementSize == 0 || (nuint)UIntPtr.MaxValue / elementSize >= elementCount) { return elementCount * elementSize; } return UIntPtr.MaxValue; } [CLSCompliant(false)] public unsafe static void* AlignedAlloc(nuint byteCount, nuint alignment) { if (!BitOperations.IsPow2(alignment)) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AlignmentMustBePow2); } void* ptr = Interop.Ucrtbase._aligned_malloc((byteCount != 0) ? byteCount : 1, alignment); if (ptr == null) { ThrowHelper.ThrowOutOfMemoryException(); } return ptr; } [CLSCompliant(false)] public unsafe static void AlignedFree(void* ptr) { if (ptr != null) { Interop.Ucrtbase._aligned_free(ptr); } } [CLSCompliant(false)] public unsafe static void* AlignedRealloc(void* ptr, nuint byteCount, nuint alignment) { if (!BitOperations.IsPow2(alignment)) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AlignmentMustBePow2); } void* ptr2 = Interop.Ucrtbase._aligned_realloc(ptr, (byteCount != 0) ? byteCount : 1, alignment); if (ptr2 == null) { ThrowHelper.ThrowOutOfMemoryException(); } return ptr2; } [CLSCompliant(false)] public unsafe static void* Alloc(nuint byteCount) { void* ptr = Interop.Ucrtbase.malloc(byteCount); if (ptr == null) { ThrowHelper.ThrowOutOfMemoryException(); } return ptr; } [CLSCompliant(false)] public unsafe static void* AllocZeroed(nuint elementCount, nuint elementSize) { void* ptr = Interop.Ucrtbase.calloc(elementCount, elementSize); if (ptr == null) { ThrowHelper.ThrowOutOfMemoryException(); } return ptr; } [CLSCompliant(false)] public unsafe static void Free(void* ptr) { if (ptr != null) { Interop.Ucrtbase.free(ptr); } } [CLSCompliant(false)] public unsafe static void* Realloc(void* ptr, nuint byteCount) { void* ptr2 = Interop.Ucrtbase.realloc(ptr, (byteCount != 0) ? byteCount : 1); if (ptr2 == null) { ThrowHelper.ThrowOutOfMemoryException(); } return ptr2; } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class UnmanagedCallConvAttribute : Attribute { public Type[]? CallConvs; } [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class UnmanagedCallersOnlyAttribute : Attribute { public Type[]? CallConvs; public string? EntryPoint; } public delegate IntPtr DllImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath); [Intrinsic] public readonly struct NFloat : IComparable, IComparable, IEquatable, ISpanFormattable, IFormattable { private readonly float _value; public static NFloat Epsilon { [NonVersionable] get { return new NFloat(float.Epsilon); } } public static NFloat MaxValue { [NonVersionable] get { return new NFloat(float.MaxValue); } } public static NFloat MinValue { [NonVersionable] get { return new NFloat(float.MinValue); } } public static NFloat NaN { [NonVersionable] get { return new NFloat(float.NaN); } } public static NFloat NegativeInfinity { [NonVersionable] get { return new NFloat(float.NegativeInfinity); } } public static NFloat PositiveInfinity { [NonVersionable] get { return new NFloat(float.PositiveInfinity); } } public static int Size { [NonVersionable] get { return 4; } } public double Value { [NonVersionable] get { return _value; } } [NonVersionable] public NFloat(float value) { _value = value; } [NonVersionable] public NFloat(double value) { _value = (float)value; } [NonVersionable] public static NFloat operator +(NFloat value) { return value; } [NonVersionable] public static NFloat operator -(NFloat value) { return new NFloat(0f - value._value); } [NonVersionable] public static NFloat operator ++(NFloat value) { return new NFloat(value._value + 1f); } [NonVersionable] public static NFloat operator --(NFloat value) { return new NFloat(value._value - 1f); } [NonVersionable] public static NFloat operator +(NFloat left, NFloat right) { return new NFloat(left._value + right._value); } [NonVersionable] public static NFloat operator -(NFloat left, NFloat right) { return new NFloat(left._value - right._value); } [NonVersionable] public static NFloat operator *(NFloat left, NFloat right) { return new NFloat(left._value * right._value); } [NonVersionable] public static NFloat operator /(NFloat left, NFloat right) { return new NFloat(left._value / right._value); } [NonVersionable] public static NFloat operator %(NFloat left, NFloat right) { return new NFloat(left._value % right._value); } [NonVersionable] public static bool operator ==(NFloat left, NFloat right) { return left._value == right._value; } [NonVersionable] public static bool operator !=(NFloat left, NFloat right) { return left._value != right._value; } [NonVersionable] public static bool operator <(NFloat left, NFloat right) { return left._value < right._value; } [NonVersionable] public static bool operator <=(NFloat left, NFloat right) { return left._value <= right._value; } [NonVersionable] public static bool operator >(NFloat left, NFloat right) { return left._value > right._value; } [NonVersionable] public static bool operator >=(NFloat left, NFloat right) { return left._value >= right._value; } [NonVersionable] public static explicit operator NFloat(decimal value) { return new NFloat((float)value); } [NonVersionable] public static explicit operator NFloat(double value) { return new NFloat((float)value); } [NonVersionable] public static explicit operator byte(NFloat value) { return (byte)value._value; } [NonVersionable] public static explicit operator char(NFloat value) { return (char)value._value; } [NonVersionable] public static explicit operator decimal(NFloat value) { return (decimal)value._value; } [NonVersionable] public static explicit operator short(NFloat value) { return (short)value._value; } [NonVersionable] public static explicit operator int(NFloat value) { return (int)value._value; } [NonVersionable] public static explicit operator long(NFloat value) { return (long)value._value; } [NonVersionable] public static explicit operator nint(NFloat value) { return (nint)value._value; } [NonVersionable] [CLSCompliant(false)] public static explicit operator sbyte(NFloat value) { return (sbyte)value._value; } [NonVersionable] public static explicit operator float(NFloat value) { return value._value; } [NonVersionable] [CLSCompliant(false)] public static explicit operator ushort(NFloat value) { return (ushort)value._value; } [NonVersionable] [CLSCompliant(false)] public static explicit operator uint(NFloat value) { return (uint)value._value; } [NonVersionable] [CLSCompliant(false)] public static explicit operator ulong(NFloat value) { return (ulong)value._value; } [NonVersionable] [CLSCompliant(false)] public static explicit operator nuint(NFloat value) { return (nuint)value._value; } [NonVersionable] public static implicit operator NFloat(byte value) { return new NFloat((int)value); } [NonVersionable] public static implicit operator NFloat(char value) { return new NFloat((int)value); } [NonVersionable] public static implicit operator NFloat(short value) { return new NFloat(value); } [NonVersionable] public static implicit operator NFloat(int value) { return new NFloat(value); } [NonVersionable] public static implicit operator NFloat(long value) { return new NFloat(value); } [NonVersionable] public static implicit operator NFloat(nint value) { return new NFloat(value); } [NonVersionable] [CLSCompliant(false)] public static implicit operator NFloat(sbyte value) { return new NFloat(value); } [NonVersionable] public static implicit operator NFloat(float value) { return new NFloat(value); } [NonVersionable] [CLSCompliant(false)] public static implicit operator NFloat(ushort value) { return new NFloat((int)value); } [NonVersionable] [CLSCompliant(false)] public static implicit operator NFloat(uint value) { return new NFloat(value); } [NonVersionable] [CLSCompliant(false)] public static implicit operator NFloat(ulong value) { return new NFloat(value); } [NonVersionable] [CLSCompliant(false)] public static implicit operator NFloat(nuint value) { return new NFloat((nint)value); } public static implicit operator double(NFloat value) { return value._value; } [NonVersionable] public static bool IsFinite(NFloat value) { return float.IsFinite(value._value); } [NonVersionable] public static bool IsInfinity(NFloat value) { return float.IsInfinity(value._value); } [NonVersionable] public static bool IsNaN(NFloat value) { return float.IsNaN(value._value); } [NonVersionable] public static bool IsNegative(NFloat value) { return float.IsNegative(value._value); } [NonVersionable] public static bool IsNegativeInfinity(NFloat value) { return float.IsNegativeInfinity(value._value); } [NonVersionable] public static bool IsNormal(NFloat value) { return float.IsNormal(value._value); } [NonVersionable] public static bool IsPositiveInfinity(NFloat value) { return float.IsPositiveInfinity(value._value); } [NonVersionable] public static bool IsSubnormal(NFloat value) { return float.IsSubnormal(value._value); } public static NFloat Parse(string s) { float value = float.Parse(s); return new NFloat(value); } public static NFloat Parse(string s, NumberStyles style) { float value = float.Parse(s, style); return new NFloat(value); } public static NFloat Parse(string s, IFormatProvider? provider) { float value = float.Parse(s, provider); return new NFloat(value); } public static NFloat Parse(string s, NumberStyles style, IFormatProvider? provider) { float value = float.Parse(s, style, provider); return new NFloat(value); } public static NFloat Parse(ReadOnlySpan s, NumberStyles style = NumberStyles.Float | NumberStyles.AllowThousands, IFormatProvider? provider = null) { float value = float.Parse(s, style, provider); return new NFloat(value); } public static bool TryParse([NotNullWhen(true)] string? s, out NFloat result) { Unsafe.SkipInit(out result); return float.TryParse(s, out Unsafe.As(ref result)); } public static bool TryParse(ReadOnlySpan s, out NFloat result) { Unsafe.SkipInit(out result); return float.TryParse(s, out Unsafe.As(ref result)); } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out NFloat result) { Unsafe.SkipInit(out result); return float.TryParse(s, style, provider, out Unsafe.As(ref result)); } public static bool TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, out NFloat result) { Unsafe.SkipInit(out result); return float.TryParse(s, style, provider, out Unsafe.As(ref result)); } public int CompareTo(object? obj) { if (obj is NFloat nFloat) { if (_value < nFloat._value) { return -1; } if (_value > nFloat._value) { return 1; } if (_value == nFloat._value) { return 0; } if (float.IsNaN(_value)) { if (!float.IsNaN(nFloat._value)) { return -1; } return 0; } return 1; } if (obj == null) { return 1; } throw new ArgumentException(SR.Arg_MustBeNFloat); } public int CompareTo(NFloat other) { return _value.CompareTo(other._value); } public override bool Equals([NotNullWhen(true)] object? obj) { if (obj is NFloat other) { return Equals(other); } return false; } public bool Equals(NFloat other) { return _value.Equals(other._value); } public override int GetHashCode() { return _value.GetHashCode(); } public override string ToString() { return _value.ToString(); } public string ToString(string? format) { return _value.ToString(format); } public string ToString(IFormatProvider? provider) { return _value.ToString(provider); } public string ToString(string? format, IFormatProvider? provider) { return _value.ToString(format, provider); } public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format = default(ReadOnlySpan), IFormatProvider? provider = null) { return _value.TryFormat(destination, out charsWritten, format, provider); } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] public sealed class OptionalAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] public sealed class OutAttribute : Attribute { } public enum PosixSignal { SIGHUP = -1, SIGINT = -2, SIGQUIT = -3, SIGTERM = -4, [UnsupportedOSPlatform("windows")] SIGCHLD = -5, [UnsupportedOSPlatform("windows")] SIGCONT = -6, [UnsupportedOSPlatform("windows")] SIGWINCH = -7, [UnsupportedOSPlatform("windows")] SIGTTIN = -8, [UnsupportedOSPlatform("windows")] SIGTTOU = -9, [UnsupportedOSPlatform("windows")] SIGTSTP = -10 } public sealed class PosixSignalContext { public PosixSignal Signal { get; internal set; } public bool Cancel { get; set; } public PosixSignalContext(PosixSignal signal) { Signal = signal; } } public sealed class PosixSignalRegistration : IDisposable { private sealed class Token { public PosixSignal Signal { get; } public Action Handler { get; } public Token(PosixSignal signal, Action handler) { Signal = signal; Handler = handler; } } private Token _token; private static readonly HashSet s_registrations = new HashSet(); [UnsupportedOSPlatform("android")] [UnsupportedOSPlatform("browser")] [UnsupportedOSPlatform("ios")] [UnsupportedOSPlatform("tvos")] public static PosixSignalRegistration Create(PosixSignal signal, Action handler) { if (handler == null) { throw new ArgumentNullException("handler"); } return Register(signal, handler); } private PosixSignalRegistration(Token token) { _token = token; } public void Dispose() { Unregister(); GC.SuppressFinalize(this); } ~PosixSignalRegistration() { Unregister(); } private unsafe static PosixSignalRegistration Register(PosixSignal signal, Action handler) { if ((uint)(signal - -4) > 3u) { throw new PlatformNotSupportedException(); } Token token = new Token(signal, handler); PosixSignalRegistration result = new PosixSignalRegistration(token); lock (s_registrations) { if (s_registrations.Count == 0 && !Interop.Kernel32.SetConsoleCtrlHandler((delegate* unmanaged)(delegate*)(&HandlerRoutine), Add: true)) { throw Win32Marshal.GetExceptionForLastWin32Error(); } s_registrations.Add(token); return result; } } private unsafe void Unregister() { lock (s_registrations) { Token token = _token; if (token != null) { _token = null; s_registrations.Remove(token); if (s_registrations.Count == 0 && !Interop.Kernel32.SetConsoleCtrlHandler((delegate* unmanaged)(delegate*)(&HandlerRoutine), Add: false)) { throw Win32Marshal.GetExceptionForLastWin32Error(); } } } } [UnmanagedCallersOnly] private static Interop.BOOL HandlerRoutine(int dwCtrlType) { PosixSignal posixSignal; switch (dwCtrlType) { case 0: posixSignal = PosixSignal.SIGINT; break; case 1: posixSignal = PosixSignal.SIGQUIT; break; case 6: posixSignal = PosixSignal.SIGTERM; break; case 2: posixSignal = PosixSignal.SIGHUP; break; default: return Interop.BOOL.FALSE; } List list = null; lock (s_registrations) { foreach (Token s_registration in s_registrations) { if (s_registration.Signal == posixSignal) { (list ?? (list = new List())).Add(s_registration); } } } if (list == null) { return Interop.BOOL.FALSE; } PosixSignalContext posixSignalContext = new PosixSignalContext(posixSignal); foreach (Token item in list) { item.Handler(posixSignalContext); } if (!posixSignalContext.Cancel) { return Interop.BOOL.FALSE; } return Interop.BOOL.TRUE; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class PreserveSigAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, Inherited = false)] public sealed class ProgIdAttribute : Attribute { public string Value { get; } public ProgIdAttribute(string progId) { Value = progId; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SafeArrayRankMismatchException : SystemException { public SafeArrayRankMismatchException() : base(SR.Arg_SafeArrayRankMismatchException) { base.HResult = -2146233032; } public SafeArrayRankMismatchException(string? message) : base(message) { base.HResult = -2146233032; } public SafeArrayRankMismatchException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233032; } protected SafeArrayRankMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SafeArrayTypeMismatchException : SystemException { public SafeArrayTypeMismatchException() : base(SR.Arg_SafeArrayTypeMismatchException) { base.HResult = -2146233037; } public SafeArrayTypeMismatchException(string? message) : base(message) { base.HResult = -2146233037; } public SafeArrayTypeMismatchException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233037; } protected SafeArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public abstract class SafeBuffer : SafeHandleZeroOrMinusOneIsInvalid { private nuint _numBytes; private static nuint Uninitialized => UIntPtr.MaxValue; [CLSCompliant(false)] public ulong ByteLength { get { if (_numBytes == Uninitialized) { throw NotInitialized(); } return _numBytes; } } protected SafeBuffer(bool ownsHandle) : base(ownsHandle) { _numBytes = Uninitialized; } [CLSCompliant(false)] public void Initialize(ulong numBytes) { _ = IntPtr.Size; if (numBytes > uint.MaxValue) { throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_AddressSpace); } if (numBytes >= Uninitialized) { throw new ArgumentOutOfRangeException("numBytes", SR.ArgumentOutOfRange_UIntPtrMax); } _numBytes = (nuint)numBytes; } [CLSCompliant(false)] public void Initialize(uint numElements, uint sizeOfEachElement) { Initialize((ulong)numElements * (ulong)sizeOfEachElement); } [CLSCompliant(false)] public void Initialize(uint numElements) where T : struct { Initialize(numElements, AlignedSizeOf()); } [CLSCompliant(false)] public unsafe void AcquirePointer(ref byte* pointer) { if (_numBytes == Uninitialized) { throw NotInitialized(); } pointer = null; bool success = false; DangerousAddRef(ref success); pointer = (byte*)(void*)handle; } public void ReleasePointer() { if (_numBytes == Uninitialized) { throw NotInitialized(); } DangerousRelease(); } [CLSCompliant(false)] public unsafe T Read(ulong byteOffset) where T : struct { if (_numBytes == Uninitialized) { throw NotInitialized(); } uint num = SizeOf(); byte* ptr = (byte*)(void*)handle + byteOffset; SpaceCheck(ptr, num); T source = default(T); bool success = false; try { DangerousAddRef(ref success); Buffer.Memmove(ref Unsafe.As(ref source), ref *ptr, num); return source; } finally { if (success) { DangerousRelease(); } } } [CLSCompliant(false)] public void ReadArray(ulong byteOffset, T[] array, int index, int count) where T : struct { if (array == null) { throw new ArgumentNullException("array", SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } ReadSpan(byteOffset, new Span(array, index, count)); } [CLSCompliant(false)] public unsafe void ReadSpan(ulong byteOffset, Span buffer) where T : struct { if (_numBytes == Uninitialized) { throw NotInitialized(); } uint num = AlignedSizeOf(); byte* ptr = (byte*)(void*)handle + byteOffset; SpaceCheck(ptr, checked((nuint)(num * buffer.Length))); bool success = false; try { DangerousAddRef(ref success); ref T reference = ref MemoryMarshal.GetReference(buffer); for (int i = 0; i < buffer.Length; i++) { Buffer.Memmove(ref Unsafe.Add(ref reference, i), ref Unsafe.AsRef(ptr + num * i), 1u); } } finally { if (success) { DangerousRelease(); } } } [CLSCompliant(false)] public unsafe void Write(ulong byteOffset, T value) where T : struct { if (_numBytes == Uninitialized) { throw NotInitialized(); } uint num = SizeOf(); byte* ptr = (byte*)(void*)handle + byteOffset; SpaceCheck(ptr, num); bool success = false; try { DangerousAddRef(ref success); Buffer.Memmove(ref *ptr, ref Unsafe.As(ref value), num); } finally { if (success) { DangerousRelease(); } } } [CLSCompliant(false)] public void WriteArray(ulong byteOffset, T[] array, int index, int count) where T : struct { if (array == null) { throw new ArgumentNullException("array", SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } WriteSpan(byteOffset, new ReadOnlySpan(array, index, count)); } [CLSCompliant(false)] public unsafe void WriteSpan(ulong byteOffset, ReadOnlySpan data) where T : struct { if (_numBytes == Uninitialized) { throw NotInitialized(); } uint num = AlignedSizeOf(); byte* ptr = (byte*)(void*)handle + byteOffset; SpaceCheck(ptr, checked((nuint)(num * data.Length))); bool success = false; try { DangerousAddRef(ref success); ref T reference = ref MemoryMarshal.GetReference(data); for (int i = 0; i < data.Length; i++) { Buffer.Memmove(ref Unsafe.AsRef(ptr + num * i), ref Unsafe.Add(ref reference, i), 1u); } } finally { if (success) { DangerousRelease(); } } } private unsafe void SpaceCheck(byte* ptr, nuint sizeInBytes) { if (_numBytes < sizeInBytes) { NotEnoughRoom(); } if ((ulong)(ptr - (byte*)(void*)handle) > (ulong)(_numBytes - sizeInBytes)) { NotEnoughRoom(); } } private static void NotEnoughRoom() { throw new ArgumentException(SR.Arg_BufferTooSmall); } private static InvalidOperationException NotInitialized() { return new InvalidOperationException(SR.InvalidOperation_MustCallInitialize); } internal static uint AlignedSizeOf() where T : struct { uint num = SizeOf(); if (num == 1 || num == 2) { return num; } return (uint)((num + 3) & -4); } internal static uint SizeOf() where T : struct { if (RuntimeHelpers.IsReferenceOrContainsReferences()) { throw new ArgumentException(SR.Argument_NeedStructWithNoRefs); } return (uint)Unsafe.SizeOf(); } } public abstract class SafeHandle : CriticalFinalizerObject, IDisposable { protected IntPtr handle; private volatile int _state; private readonly bool _ownsHandle; private volatile bool _fullyInitialized; internal bool OwnsHandle => _ownsHandle; public bool IsClosed => (_state & 1) == 1; public abstract bool IsInvalid { get; } protected SafeHandle(IntPtr invalidHandleValue, bool ownsHandle) { handle = invalidHandleValue; _state = 4; _ownsHandle = ownsHandle; if (!ownsHandle) { GC.SuppressFinalize(this); } _fullyInitialized = true; } ~SafeHandle() { if (_fullyInitialized) { Dispose(disposing: false); } } protected internal void SetHandle(IntPtr handle) { this.handle = handle; } public IntPtr DangerousGetHandle() { return handle; } public void Close() { Dispose(); } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { InternalRelease(disposeOrFinalizeOperation: true); } public void SetHandleAsInvalid() { Interlocked.Or(ref _state, 1); GC.SuppressFinalize(this); } protected abstract bool ReleaseHandle(); public void DangerousAddRef(ref bool success) { int state; int value; do { state = _state; if (((uint)state & (true ? 1u : 0u)) != 0) { throw new ObjectDisposedException("SafeHandle", SR.ObjectDisposed_SafeHandleClosed); } value = state + 4; } while (Interlocked.CompareExchange(ref _state, value, state) != state); success = true; } public void DangerousRelease() { InternalRelease(disposeOrFinalizeOperation: false); } private void InternalRelease(bool disposeOrFinalizeOperation) { bool flag = false; int state; int num; do { state = _state; if (disposeOrFinalizeOperation && ((uint)state & 2u) != 0) { return; } if ((state & -4) == 0) { throw new ObjectDisposedException("SafeHandle", SR.ObjectDisposed_SafeHandleClosed); } flag = (state & -3) == 4 && _ownsHandle && !IsInvalid; num = state - 4; if ((state & -4) == 4) { num |= 1; } if (disposeOrFinalizeOperation) { num |= 2; } } while (Interlocked.CompareExchange(ref _state, num, state) != state); if (flag) { int lastPInvokeError = Marshal.GetLastPInvokeError(); ReleaseHandle(); Marshal.SetLastPInvokeError(lastPInvokeError); } } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SEHException : ExternalException { public SEHException() { base.HResult = -2147467259; } public SEHException(string? message) : base(message) { base.HResult = -2147467259; } public SEHException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2147467259; } protected SEHException(SerializationInfo info, StreamingContext context) : base(info, context) { } public virtual bool CanResume() { return false; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)] public sealed class StructLayoutAttribute : Attribute { public int Pack; public int Size; public CharSet CharSet; public LayoutKind Value { get; } public StructLayoutAttribute(LayoutKind layoutKind) { Value = layoutKind; } public StructLayoutAttribute(short layoutKind) { Value = (LayoutKind)layoutKind; } } [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class SuppressGCTransitionAttribute : Attribute { } [AttributeUsage(AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class TypeIdentifierAttribute : Attribute { public string? Scope { get; } public string? Identifier { get; } public TypeIdentifierAttribute() { } public TypeIdentifierAttribute(string? scope, string? identifier) { Scope = scope; Identifier = identifier; } } public sealed class UnknownWrapper { public object? WrappedObject { get; } public UnknownWrapper(object? obj) { WrappedObject = obj; } } [AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class UnmanagedFunctionPointerAttribute : Attribute { public bool BestFitMapping; public bool SetLastError; public bool ThrowOnUnmappableChar; public CharSet CharSet; public CallingConvention CallingConvention { get; } public UnmanagedFunctionPointerAttribute() { CallingConvention = CallingConvention.Winapi; } public UnmanagedFunctionPointerAttribute(CallingConvention callingConvention) { CallingConvention = callingConvention; } } public enum UnmanagedType { Bool = 2, I1 = 3, U1 = 4, I2 = 5, U2 = 6, I4 = 7, U4 = 8, I8 = 9, U8 = 10, R4 = 11, R8 = 12, Currency = 15, BStr = 19, LPStr = 20, LPWStr = 21, LPTStr = 22, ByValTStr = 23, IUnknown = 25, IDispatch = 26, Struct = 27, Interface = 28, SafeArray = 29, ByValArray = 30, SysInt = 31, SysUInt = 32, VBByRefStr = 34, AnsiBStr = 35, TBStr = 36, VariantBool = 37, FunctionPtr = 38, AsAny = 40, LPArray = 42, LPStruct = 43, CustomMarshaler = 44, Error = 45, IInspectable = 46, HString = 47, LPUTF8Str = 48 } public enum VarEnum { VT_EMPTY = 0, VT_NULL = 1, VT_I2 = 2, VT_I4 = 3, VT_R4 = 4, VT_R8 = 5, VT_CY = 6, VT_DATE = 7, VT_BSTR = 8, VT_DISPATCH = 9, VT_ERROR = 10, VT_BOOL = 11, VT_VARIANT = 12, VT_UNKNOWN = 13, VT_DECIMAL = 14, VT_I1 = 16, VT_UI1 = 17, VT_UI2 = 18, VT_UI4 = 19, VT_I8 = 20, VT_UI8 = 21, VT_INT = 22, VT_UINT = 23, VT_VOID = 24, VT_HRESULT = 25, VT_PTR = 26, VT_SAFEARRAY = 27, VT_CARRAY = 28, VT_USERDEFINED = 29, VT_LPSTR = 30, VT_LPWSTR = 31, VT_RECORD = 36, VT_FILETIME = 64, VT_BLOB = 65, VT_STREAM = 66, VT_STORAGE = 67, VT_STREAMED_OBJECT = 68, VT_STORED_OBJECT = 69, VT_BLOB_OBJECT = 70, VT_CF = 71, VT_CLSID = 72, VT_VECTOR = 4096, VT_ARRAY = 8192, VT_BYREF = 16384 } public sealed class VariantWrapper { public object? WrappedObject { get; } public VariantWrapper(object? obj) { WrappedObject = obj; } } public class StandardOleMarshalObject : MarshalByRefObject, IMarshal { [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetMarshalSizeMaxDelegate(IntPtr _this, ref Guid riid, IntPtr pv, int dwDestContext, IntPtr pvDestContext, int mshlflags, out int pSize); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int MarshalInterfaceDelegate(IntPtr _this, IntPtr pStm, ref Guid riid, IntPtr pv, int dwDestContext, IntPtr pvDestContext, int mshlflags); private static readonly Guid CLSID_StdMarshal = new Guid("00000017-0000-0000-c000-000000000046"); protected StandardOleMarshalObject() { } private IntPtr GetStdMarshaler(ref Guid riid, int dwDestContext, int mshlflags) { IntPtr iUnknownForObject = Marshal.GetIUnknownForObject(this); if (iUnknownForObject != IntPtr.Zero) { try { IntPtr ppMarshal = IntPtr.Zero; if (Interop.Ole32.CoGetStandardMarshal(ref riid, iUnknownForObject, dwDestContext, IntPtr.Zero, mshlflags, out ppMarshal) == 0) { return ppMarshal; } } finally { Marshal.Release(iUnknownForObject); } } throw new InvalidOperationException(SR.Format(SR.StandardOleMarshalObjectGetMarshalerFailed, riid)); } int IMarshal.GetUnmarshalClass(ref Guid riid, IntPtr pv, int dwDestContext, IntPtr pvDestContext, int mshlflags, out Guid pCid) { pCid = CLSID_StdMarshal; return 0; } unsafe int IMarshal.GetMarshalSizeMax(ref Guid riid, IntPtr pv, int dwDestContext, IntPtr pvDestContext, int mshlflags, out int pSize) { IntPtr stdMarshaler = GetStdMarshaler(ref riid, dwDestContext, mshlflags); try { IntPtr intPtr = *(IntPtr*)stdMarshaler.ToPointer(); IntPtr ptr = *(IntPtr*)((byte*)intPtr.ToPointer() + (nint)4 * (nint)sizeof(IntPtr)); GetMarshalSizeMaxDelegate getMarshalSizeMaxDelegate = (GetMarshalSizeMaxDelegate)Marshal.GetDelegateForFunctionPointer(ptr, typeof(GetMarshalSizeMaxDelegate)); return getMarshalSizeMaxDelegate(stdMarshaler, ref riid, pv, dwDestContext, pvDestContext, mshlflags, out pSize); } finally { Marshal.Release(stdMarshaler); } } unsafe int IMarshal.MarshalInterface(IntPtr pStm, ref Guid riid, IntPtr pv, int dwDestContext, IntPtr pvDestContext, int mshlflags) { IntPtr stdMarshaler = GetStdMarshaler(ref riid, dwDestContext, mshlflags); try { IntPtr intPtr = *(IntPtr*)stdMarshaler.ToPointer(); IntPtr ptr = *(IntPtr*)((byte*)intPtr.ToPointer() + (nint)5 * (nint)sizeof(IntPtr)); MarshalInterfaceDelegate marshalInterfaceDelegate = (MarshalInterfaceDelegate)Marshal.GetDelegateForFunctionPointer(ptr, typeof(MarshalInterfaceDelegate)); return marshalInterfaceDelegate(stdMarshaler, pStm, ref riid, pv, dwDestContext, pvDestContext, mshlflags); } finally { Marshal.Release(stdMarshaler); } } int IMarshal.UnmarshalInterface(IntPtr pStm, ref Guid riid, out IntPtr ppv) { ppv = IntPtr.Zero; return -2147467263; } int IMarshal.ReleaseMarshalData(IntPtr pStm) { return -2147467263; } int IMarshal.DisconnectObject(int dwReserved) { return -2147467263; } } [ComImport] [Guid("00000003-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IMarshal { [PreserveSig] int GetUnmarshalClass(ref Guid riid, IntPtr pv, int dwDestContext, IntPtr pvDestContext, int mshlflags, out Guid pCid); [PreserveSig] int GetMarshalSizeMax(ref Guid riid, IntPtr pv, int dwDestContext, IntPtr pvDestContext, int mshlflags, out int pSize); [PreserveSig] int MarshalInterface(IntPtr pStm, ref Guid riid, IntPtr pv, int dwDestContext, IntPtr pvDestContext, int mshlflags); [PreserveSig] int UnmarshalInterface(IntPtr pStm, ref Guid riid, out IntPtr ppv); [PreserveSig] int ReleaseMarshalData(IntPtr pStm); [PreserveSig] int DisconnectObject(int dwReserved); } } namespace System.Runtime.InteropServices.ObjectiveC { [SupportedOSPlatform("macos")] [CLSCompliant(false)] public static class ObjectiveCMarshal { public unsafe delegate delegate* unmanaged UnhandledExceptionPropagationHandler(Exception exception, RuntimeMethodHandle lastMethod, out IntPtr context); public enum MessageSendFunction { MsgSend, MsgSendFpret, MsgSendStret, MsgSendSuper, MsgSendSuperStret } public unsafe static void Initialize(delegate* unmanaged beginEndCallback, delegate* unmanaged isReferencedCallback, delegate* unmanaged trackedObjectEnteredFinalization, UnhandledExceptionPropagationHandler unhandledExceptionPropagationHandler) { throw new PlatformNotSupportedException(); } public static GCHandle CreateReferenceTrackingHandle(object obj, out Span taggedMemory) { throw new PlatformNotSupportedException(); } public static void SetMessageSendCallback(MessageSendFunction msgSendFunction, IntPtr func) { throw new PlatformNotSupportedException(); } public static void SetMessageSendPendingException(Exception? exception) { throw new PlatformNotSupportedException(); } } [SupportedOSPlatform("macos")] [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public sealed class ObjectiveCTrackedTypeAttribute : Attribute { } } namespace System.Runtime.InteropServices.CustomMarshalers { internal static class ComDataHelpers { [SupportedOSPlatform("windows")] public static TView GetOrCreateManagedViewFromComData(object comObject, Func createCallback) { object typeFromHandle = typeof(TView); object comObjectData = Marshal.GetComObjectData(comObject, typeFromHandle); if (comObjectData is TView) { return (TView)comObjectData; } TView val = createCallback((T)comObject); if (!Marshal.SetComObjectData(comObject, typeFromHandle, val)) { val = (TView)Marshal.GetComObjectData(comObject, typeFromHandle); } return val; } } internal sealed class EnumVariantViewOfEnumerator : IEnumVARIANT, ICustomAdapter { public System.Collections.IEnumerator Enumerator { get; } public EnumVariantViewOfEnumerator(System.Collections.IEnumerator enumerator) { if (enumerator == null) { throw new ArgumentNullException("enumerator"); } Enumerator = enumerator; } public IEnumVARIANT Clone() { if (Enumerator is ICloneable cloneable) { return new EnumVariantViewOfEnumerator((System.Collections.IEnumerator)cloneable.Clone()); } throw new COMException(SR.Arg_EnumNotCloneable, -2147467259); } public int Next(int celt, object[] rgVar, IntPtr pceltFetched) { int num = 0; try { if (celt > 0 && rgVar == null) { return -2147024809; } while (num < celt && Enumerator.MoveNext()) { rgVar[num++] = Enumerator.Current; } if (pceltFetched != IntPtr.Zero) { Marshal.WriteInt32(pceltFetched, num); } } catch (Exception ex) { return ex.HResult; } if (num != celt) { return 1; } return 0; } public int Reset() { try { Enumerator.Reset(); } catch (Exception ex) { return ex.HResult; } return 0; } public int Skip(int celt) { try { while (celt > 0 && Enumerator.MoveNext()) { celt--; } } catch (Exception ex) { return ex.HResult; } if (celt != 0) { return 1; } return 0; } public object GetUnderlyingObject() { return Enumerator; } } [SupportedOSPlatform("windows")] internal sealed class EnumerableToDispatchMarshaler : ICustomMarshaler { private static readonly EnumerableToDispatchMarshaler s_enumerableToDispatchMarshaler = new EnumerableToDispatchMarshaler(); public static ICustomMarshaler GetInstance(string cookie) { return s_enumerableToDispatchMarshaler; } private EnumerableToDispatchMarshaler() { } public void CleanUpManagedData(object ManagedObj) { } public void CleanUpNativeData(IntPtr pNativeData) { Marshal.Release(pNativeData); } public int GetNativeDataSize() { return -1; } public IntPtr MarshalManagedToNative(object ManagedObj) { if (ManagedObj == null) { throw new ArgumentNullException("ManagedObj"); } return Marshal.GetComInterfaceForObject(ManagedObj); } public object MarshalNativeToManaged(IntPtr pNativeData) { if (pNativeData == IntPtr.Zero) { throw new ArgumentNullException("pNativeData"); } object objectForIUnknown = Marshal.GetObjectForIUnknown(pNativeData); return ComDataHelpers.GetOrCreateManagedViewFromComData(objectForIUnknown, (object obj) => new EnumerableViewOfDispatch(obj)); } } internal sealed class EnumerableViewOfDispatch : ICustomAdapter, System.Collections.IEnumerable { private const int DISPID_NEWENUM = -4; private const int LCID_DEFAULT = 1; private readonly object _dispatch; private IDispatch Dispatch => (IDispatch)_dispatch; public EnumerableViewOfDispatch(object dispatch) { _dispatch = dispatch; } public unsafe System.Collections.IEnumerator GetEnumerator() { System.Runtime.CompilerServices.Unsafe.SkipInit(out Variant variant); void* value = &variant; DISPPARAMS pDispParams = default(DISPPARAMS); Guid riid = Guid.Empty; Dispatch.Invoke(-4, ref riid, 1, InvokeFlags.DISPATCH_METHOD | InvokeFlags.DISPATCH_PROPERTYGET, ref pDispParams, new IntPtr(value), IntPtr.Zero, IntPtr.Zero); IntPtr intPtr = IntPtr.Zero; try { object obj = variant.ToObject(); if (!(obj is IEnumVARIANT o)) { throw new InvalidOperationException(SR.InvalidOp_InvalidNewEnumVariant); } intPtr = Marshal.GetIUnknownForObject(o); return (System.Collections.IEnumerator)EnumeratorToEnumVariantMarshaler.GetInstance(null).MarshalNativeToManaged(intPtr); } finally { variant.Clear(); if (intPtr != IntPtr.Zero) { Marshal.Release(intPtr); } } } public object GetUnderlyingObject() { return _dispatch; } } [SupportedOSPlatform("windows")] internal sealed class EnumeratorToEnumVariantMarshaler : ICustomMarshaler { private static readonly EnumeratorToEnumVariantMarshaler s_enumeratorToEnumVariantMarshaler = new EnumeratorToEnumVariantMarshaler(); public static ICustomMarshaler GetInstance(string cookie) { return s_enumeratorToEnumVariantMarshaler; } private EnumeratorToEnumVariantMarshaler() { } public void CleanUpManagedData(object ManagedObj) { } public void CleanUpNativeData(IntPtr pNativeData) { Marshal.Release(pNativeData); } public int GetNativeDataSize() { return -1; } public IntPtr MarshalManagedToNative(object ManagedObj) { if (ManagedObj == null) { throw new ArgumentNullException("ManagedObj"); } if (ManagedObj is EnumeratorViewOfEnumVariant enumeratorViewOfEnumVariant) { return Marshal.GetComInterfaceForObject(enumeratorViewOfEnumVariant.GetUnderlyingObject()); } EnumVariantViewOfEnumerator o = new EnumVariantViewOfEnumerator((System.Collections.IEnumerator)ManagedObj); return Marshal.GetComInterfaceForObject(o); } public object MarshalNativeToManaged(IntPtr pNativeData) { if (pNativeData == IntPtr.Zero) { throw new ArgumentNullException("pNativeData"); } object objectForIUnknown = Marshal.GetObjectForIUnknown(pNativeData); if (!objectForIUnknown.GetType().IsCOMObject) { if (objectForIUnknown is EnumVariantViewOfEnumerator enumVariantViewOfEnumerator) { return enumVariantViewOfEnumerator.Enumerator; } return objectForIUnknown as System.Collections.IEnumerator; } return ComDataHelpers.GetOrCreateManagedViewFromComData(objectForIUnknown, (IEnumVARIANT var) => new EnumeratorViewOfEnumVariant(var)); } } internal sealed class EnumeratorViewOfEnumVariant : ICustomAdapter, System.Collections.IEnumerator { private readonly IEnumVARIANT _enumVariantObject; private bool _fetchedLastObject; private readonly object[] _nextArray = new object[1]; private object _current; public object Current => _current; public EnumeratorViewOfEnumVariant(IEnumVARIANT enumVariantObject) { _enumVariantObject = enumVariantObject; _fetchedLastObject = false; _current = null; } public unsafe bool MoveNext() { if (_fetchedLastObject) { _current = null; return false; } int num = 0; if (_enumVariantObject.Next(1, _nextArray, (IntPtr)(&num)) == 1) { _fetchedLastObject = true; if (num == 0) { _current = null; return false; } } _current = _nextArray[0]; return true; } public void Reset() { int num = _enumVariantObject.Reset(); if (num < 0) { Marshal.ThrowExceptionForHR(num); } _fetchedLastObject = false; _current = null; } public object GetUnderlyingObject() { return _enumVariantObject; } } internal sealed class ExpandoToDispatchExMarshaler : ICustomMarshaler { private static readonly ExpandoToDispatchExMarshaler s_ExpandoToDispatchExMarshaler = new ExpandoToDispatchExMarshaler(); public static ICustomMarshaler GetInstance(string cookie) { return s_ExpandoToDispatchExMarshaler; } private ExpandoToDispatchExMarshaler() { } public void CleanUpManagedData(object ManagedObj) { } public void CleanUpNativeData(IntPtr pNativeData) { } public int GetNativeDataSize() { return -1; } public IntPtr MarshalManagedToNative(object ManagedObj) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_IExpando); } public object MarshalNativeToManaged(IntPtr pNativeData) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_IExpando); } } internal sealed class TypeToTypeInfoMarshaler : ICustomMarshaler { private static readonly TypeToTypeInfoMarshaler s_typeToTypeInfoMarshaler = new TypeToTypeInfoMarshaler(); public static ICustomMarshaler GetInstance(string cookie) { return s_typeToTypeInfoMarshaler; } private TypeToTypeInfoMarshaler() { } public void CleanUpManagedData(object ManagedObj) { } public void CleanUpNativeData(IntPtr pNativeData) { } public int GetNativeDataSize() { return -1; } public IntPtr MarshalManagedToNative(object ManagedObj) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ITypeInfo); } public object MarshalNativeToManaged(IntPtr pNativeData) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ITypeInfo); } } } namespace System.Runtime.InteropServices.ComTypes { [Guid("496B0ABE-CDEE-11d3-88E8-00902754C43A")] internal interface IEnumerable { [DispId(-4)] System.Collections.IEnumerator GetEnumerator(); } [Guid("496B0ABF-CDEE-11d3-88E8-00902754C43A")] internal interface IEnumerator { object Current { get; } bool MoveNext(); void Reset(); } public struct BIND_OPTS { public int cbStruct; public int grfFlags; public int grfMode; public int dwTickCountDeadline; } [ComImport] [Guid("0000000e-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IBindCtx { void RegisterObjectBound([MarshalAs(UnmanagedType.Interface)] object punk); void RevokeObjectBound([MarshalAs(UnmanagedType.Interface)] object punk); void ReleaseBoundObjects(); void SetBindOptions([In] ref BIND_OPTS pbindopts); void GetBindOptions(ref BIND_OPTS pbindopts); void GetRunningObjectTable(out IRunningObjectTable? pprot); void RegisterObjectParam([MarshalAs(UnmanagedType.LPWStr)] string pszKey, [MarshalAs(UnmanagedType.Interface)] object punk); void GetObjectParam([MarshalAs(UnmanagedType.LPWStr)] string pszKey, [MarshalAs(UnmanagedType.Interface)] out object? ppunk); void EnumObjectParam(out IEnumString? ppenum); [PreserveSig] int RevokeObjectParam([MarshalAs(UnmanagedType.LPWStr)] string pszKey); } [ComImport] [Guid("B196B286-BAB4-101A-B69C-00AA00341D07")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IConnectionPoint { void GetConnectionInterface(out Guid pIID); void GetConnectionPointContainer(out IConnectionPointContainer ppCPC); void Advise([MarshalAs(UnmanagedType.Interface)] object pUnkSink, out int pdwCookie); void Unadvise(int dwCookie); void EnumConnections(out IEnumConnections ppEnum); } [ComImport] [Guid("B196B284-BAB4-101A-B69C-00AA00341D07")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IConnectionPointContainer { void EnumConnectionPoints(out IEnumConnectionPoints ppEnum); void FindConnectionPoint([In] ref Guid riid, out IConnectionPoint? ppCP); } [ComImport] [Guid("B196B285-BAB4-101A-B69C-00AA00341D07")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IEnumConnectionPoints { [PreserveSig] int Next(int celt, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] IConnectionPoint[] rgelt, IntPtr pceltFetched); [PreserveSig] int Skip(int celt); void Reset(); void Clone(out IEnumConnectionPoints ppenum); } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct CONNECTDATA { [MarshalAs(UnmanagedType.Interface)] public object pUnk; public int dwCookie; } [ComImport] [Guid("B196B287-BAB4-101A-B69C-00AA00341D07")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IEnumConnections { [PreserveSig] int Next(int celt, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] CONNECTDATA[] rgelt, IntPtr pceltFetched); [PreserveSig] int Skip(int celt); void Reset(); void Clone(out IEnumConnections ppenum); } [ComImport] [Guid("00000102-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IEnumMoniker { [PreserveSig] int Next(int celt, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] IMoniker[] rgelt, IntPtr pceltFetched); [PreserveSig] int Skip(int celt); void Reset(); void Clone(out IEnumMoniker ppenum); } [ComImport] [Guid("00000101-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IEnumString { [PreserveSig] int Next(int celt, [Out][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 0)] string[] rgelt, IntPtr pceltFetched); [PreserveSig] int Skip(int celt); void Reset(); void Clone(out IEnumString ppenum); } [ComImport] [Guid("00020404-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IEnumVARIANT { [PreserveSig] int Next(int celt, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] object?[] rgVar, IntPtr pceltFetched); [PreserveSig] int Skip(int celt); [PreserveSig] int Reset(); IEnumVARIANT Clone(); } public struct FILETIME { public int dwLowDateTime; public int dwHighDateTime; } [ComImport] [Guid("0000000f-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IMoniker { void GetClassID(out Guid pClassID); [PreserveSig] int IsDirty(); void Load(IStream pStm); void Save(IStream pStm, [MarshalAs(UnmanagedType.Bool)] bool fClearDirty); void GetSizeMax(out long pcbSize); void BindToObject(IBindCtx pbc, IMoniker? pmkToLeft, [In] ref Guid riidResult, [MarshalAs(UnmanagedType.Interface)] out object ppvResult); void BindToStorage(IBindCtx pbc, IMoniker? pmkToLeft, [In] ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObj); void Reduce(IBindCtx pbc, int dwReduceHowFar, ref IMoniker? ppmkToLeft, out IMoniker? ppmkReduced); void ComposeWith(IMoniker pmkRight, [MarshalAs(UnmanagedType.Bool)] bool fOnlyIfNotGeneric, out IMoniker? ppmkComposite); void Enum([MarshalAs(UnmanagedType.Bool)] bool fForward, out IEnumMoniker? ppenumMoniker); [PreserveSig] int IsEqual(IMoniker pmkOtherMoniker); void Hash(out int pdwHash); [PreserveSig] int IsRunning(IBindCtx pbc, IMoniker? pmkToLeft, IMoniker? pmkNewlyRunning); void GetTimeOfLastChange(IBindCtx pbc, IMoniker? pmkToLeft, out FILETIME pFileTime); void Inverse(out IMoniker ppmk); void CommonPrefixWith(IMoniker pmkOther, out IMoniker? ppmkPrefix); void RelativePathTo(IMoniker pmkOther, out IMoniker? ppmkRelPath); void GetDisplayName(IBindCtx pbc, IMoniker? pmkToLeft, [MarshalAs(UnmanagedType.LPWStr)] out string ppszDisplayName); void ParseDisplayName(IBindCtx pbc, IMoniker pmkToLeft, [MarshalAs(UnmanagedType.LPWStr)] string pszDisplayName, out int pchEaten, out IMoniker ppmkOut); [PreserveSig] int IsSystemMoniker(out int pdwMksys); } [ComImport] [Guid("0000010b-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IPersistFile { void GetClassID(out Guid pClassID); [PreserveSig] int IsDirty(); void Load([MarshalAs(UnmanagedType.LPWStr)] string pszFileName, int dwMode); void Save([MarshalAs(UnmanagedType.LPWStr)] string? pszFileName, [MarshalAs(UnmanagedType.Bool)] bool fRemember); void SaveCompleted([MarshalAs(UnmanagedType.LPWStr)] string pszFileName); void GetCurFile([MarshalAs(UnmanagedType.LPWStr)] out string ppszFileName); } [ComImport] [Guid("00000010-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IRunningObjectTable { int Register(int grfFlags, [MarshalAs(UnmanagedType.Interface)] object punkObject, IMoniker pmkObjectName); void Revoke(int dwRegister); [PreserveSig] int IsRunning(IMoniker pmkObjectName); [PreserveSig] int GetObject(IMoniker pmkObjectName, [MarshalAs(UnmanagedType.Interface)] out object ppunkObject); void NoteChangeTime(int dwRegister, ref FILETIME pfiletime); [PreserveSig] int GetTimeOfLastChange(IMoniker pmkObjectName, out FILETIME pfiletime); void EnumRunning(out IEnumMoniker ppenumMoniker); } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct STATSTG { public string pwcsName; public int type; public long cbSize; public FILETIME mtime; public FILETIME ctime; public FILETIME atime; public int grfMode; public int grfLocksSupported; public Guid clsid; public int grfStateBits; public int reserved; } [ComImport] [Guid("0000000c-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IStream { void Read([Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] pv, int cb, IntPtr pcbRead); void Write([MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] pv, int cb, IntPtr pcbWritten); void Seek(long dlibMove, int dwOrigin, IntPtr plibNewPosition); void SetSize(long libNewSize); void CopyTo(IStream pstm, long cb, IntPtr pcbRead, IntPtr pcbWritten); void Commit(int grfCommitFlags); void Revert(); void LockRegion(long libOffset, long cb, int dwLockType); void UnlockRegion(long libOffset, long cb, int dwLockType); void Stat(out STATSTG pstatstg, int grfStatFlag); void Clone(out IStream ppstm); } public enum DESCKIND { DESCKIND_NONE, DESCKIND_FUNCDESC, DESCKIND_VARDESC, DESCKIND_TYPECOMP, DESCKIND_IMPLICITAPPOBJ, DESCKIND_MAX } [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] public struct BINDPTR { [FieldOffset(0)] public IntPtr lpfuncdesc; [FieldOffset(0)] public IntPtr lpvardesc; [FieldOffset(0)] public IntPtr lptcomp; } [ComImport] [Guid("00020403-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface ITypeComp { void Bind([MarshalAs(UnmanagedType.LPWStr)] string szName, int lHashVal, short wFlags, out ITypeInfo ppTInfo, out DESCKIND pDescKind, out BINDPTR pBindPtr); void BindType([MarshalAs(UnmanagedType.LPWStr)] string szName, int lHashVal, out ITypeInfo ppTInfo, out ITypeComp ppTComp); } public enum TYPEKIND { TKIND_ENUM, TKIND_RECORD, TKIND_MODULE, TKIND_INTERFACE, TKIND_DISPATCH, TKIND_COCLASS, TKIND_ALIAS, TKIND_UNION, TKIND_MAX } [Flags] public enum TYPEFLAGS : short { TYPEFLAG_FAPPOBJECT = 1, TYPEFLAG_FCANCREATE = 2, TYPEFLAG_FLICENSED = 4, TYPEFLAG_FPREDECLID = 8, TYPEFLAG_FHIDDEN = 0x10, TYPEFLAG_FCONTROL = 0x20, TYPEFLAG_FDUAL = 0x40, TYPEFLAG_FNONEXTENSIBLE = 0x80, TYPEFLAG_FOLEAUTOMATION = 0x100, TYPEFLAG_FRESTRICTED = 0x200, TYPEFLAG_FAGGREGATABLE = 0x400, TYPEFLAG_FREPLACEABLE = 0x800, TYPEFLAG_FDISPATCHABLE = 0x1000, TYPEFLAG_FREVERSEBIND = 0x2000, TYPEFLAG_FPROXY = 0x4000 } [Flags] public enum IMPLTYPEFLAGS { IMPLTYPEFLAG_FDEFAULT = 1, IMPLTYPEFLAG_FSOURCE = 2, IMPLTYPEFLAG_FRESTRICTED = 4, IMPLTYPEFLAG_FDEFAULTVTABLE = 8 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TYPEATTR { public const int MEMBER_ID_NIL = -1; public Guid guid; public int lcid; public int dwReserved; public int memidConstructor; public int memidDestructor; public IntPtr lpstrSchema; public int cbSizeInstance; public TYPEKIND typekind; public short cFuncs; public short cVars; public short cImplTypes; public short cbSizeVft; public short cbAlignment; public TYPEFLAGS wTypeFlags; public short wMajorVerNum; public short wMinorVerNum; public TYPEDESC tdescAlias; public IDLDESC idldescType; } public struct FUNCDESC { public int memid; public IntPtr lprgscode; public IntPtr lprgelemdescParam; public FUNCKIND funckind; public INVOKEKIND invkind; public CALLCONV callconv; public short cParams; public short cParamsOpt; public short oVft; public short cScodes; public ELEMDESC elemdescFunc; public short wFuncFlags; } [Flags] public enum IDLFLAG : short { IDLFLAG_NONE = 0, IDLFLAG_FIN = 1, IDLFLAG_FOUT = 2, IDLFLAG_FLCID = 4, IDLFLAG_FRETVAL = 8 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct IDLDESC { public IntPtr dwReserved; public IDLFLAG wIDLFlags; } [Flags] public enum PARAMFLAG : short { PARAMFLAG_NONE = 0, PARAMFLAG_FIN = 1, PARAMFLAG_FOUT = 2, PARAMFLAG_FLCID = 4, PARAMFLAG_FRETVAL = 8, PARAMFLAG_FOPT = 0x10, PARAMFLAG_FHASDEFAULT = 0x20, PARAMFLAG_FHASCUSTDATA = 0x40 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct PARAMDESC { public IntPtr lpVarValue; public PARAMFLAG wParamFlags; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TYPEDESC { public IntPtr lpValue; public short vt; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct ELEMDESC { [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] public struct DESCUNION { [FieldOffset(0)] public IDLDESC idldesc; [FieldOffset(0)] public PARAMDESC paramdesc; } public TYPEDESC tdesc; public DESCUNION desc; } public enum VARKIND { VAR_PERINSTANCE, VAR_STATIC, VAR_CONST, VAR_DISPATCH } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct VARDESC { [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] public struct DESCUNION { [FieldOffset(0)] public int oInst; [FieldOffset(0)] public IntPtr lpvarValue; } public int memid; public string lpstrSchema; public DESCUNION desc; public ELEMDESC elemdescVar; public short wVarFlags; public VARKIND varkind; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct DISPPARAMS { public IntPtr rgvarg; public IntPtr rgdispidNamedArgs; public int cArgs; public int cNamedArgs; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct EXCEPINFO { public short wCode; public short wReserved; [MarshalAs(UnmanagedType.BStr)] public string bstrSource; [MarshalAs(UnmanagedType.BStr)] public string bstrDescription; [MarshalAs(UnmanagedType.BStr)] public string bstrHelpFile; public int dwHelpContext; public IntPtr pvReserved; public IntPtr pfnDeferredFillIn; public int scode; } public enum FUNCKIND { FUNC_VIRTUAL, FUNC_PUREVIRTUAL, FUNC_NONVIRTUAL, FUNC_STATIC, FUNC_DISPATCH } [Flags] public enum INVOKEKIND { INVOKE_FUNC = 1, INVOKE_PROPERTYGET = 2, INVOKE_PROPERTYPUT = 4, INVOKE_PROPERTYPUTREF = 8 } public enum CALLCONV { CC_CDECL = 1, CC_MSCPASCAL = 2, CC_PASCAL = 2, CC_MACPASCAL = 3, CC_STDCALL = 4, CC_RESERVED = 5, CC_SYSCALL = 6, CC_MPWCDECL = 7, CC_MPWPASCAL = 8, CC_MAX = 9 } [Flags] public enum FUNCFLAGS : short { FUNCFLAG_FRESTRICTED = 1, FUNCFLAG_FSOURCE = 2, FUNCFLAG_FBINDABLE = 4, FUNCFLAG_FREQUESTEDIT = 8, FUNCFLAG_FDISPLAYBIND = 0x10, FUNCFLAG_FDEFAULTBIND = 0x20, FUNCFLAG_FHIDDEN = 0x40, FUNCFLAG_FUSESGETLASTERROR = 0x80, FUNCFLAG_FDEFAULTCOLLELEM = 0x100, FUNCFLAG_FUIDEFAULT = 0x200, FUNCFLAG_FNONBROWSABLE = 0x400, FUNCFLAG_FREPLACEABLE = 0x800, FUNCFLAG_FIMMEDIATEBIND = 0x1000 } [Flags] public enum VARFLAGS : short { VARFLAG_FREADONLY = 1, VARFLAG_FSOURCE = 2, VARFLAG_FBINDABLE = 4, VARFLAG_FREQUESTEDIT = 8, VARFLAG_FDISPLAYBIND = 0x10, VARFLAG_FDEFAULTBIND = 0x20, VARFLAG_FHIDDEN = 0x40, VARFLAG_FRESTRICTED = 0x80, VARFLAG_FDEFAULTCOLLELEM = 0x100, VARFLAG_FUIDEFAULT = 0x200, VARFLAG_FNONBROWSABLE = 0x400, VARFLAG_FREPLACEABLE = 0x800, VARFLAG_FIMMEDIATEBIND = 0x1000 } [ComImport] [Guid("00020401-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface ITypeInfo { void GetTypeAttr(out IntPtr ppTypeAttr); void GetTypeComp(out ITypeComp ppTComp); void GetFuncDesc(int index, out IntPtr ppFuncDesc); void GetVarDesc(int index, out IntPtr ppVarDesc); void GetNames(int memid, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] string[] rgBstrNames, int cMaxNames, out int pcNames); void GetRefTypeOfImplType(int index, out int href); void GetImplTypeFlags(int index, out IMPLTYPEFLAGS pImplTypeFlags); void GetIDsOfNames([In][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] string[] rgszNames, int cNames, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] pMemId); void Invoke([MarshalAs(UnmanagedType.IUnknown)] object pvInstance, int memid, short wFlags, ref DISPPARAMS pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, out int puArgErr); void GetDocumentation(int index, out string strName, out string strDocString, out int dwHelpContext, out string strHelpFile); void GetDllEntry(int memid, INVOKEKIND invKind, IntPtr pBstrDllName, IntPtr pBstrName, IntPtr pwOrdinal); void GetRefTypeInfo(int hRef, out ITypeInfo ppTI); void AddressOfMember(int memid, INVOKEKIND invKind, out IntPtr ppv); void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] object? pUnkOuter, [In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppvObj); void GetMops(int memid, out string? pBstrMops); void GetContainingTypeLib(out ITypeLib ppTLB, out int pIndex); [PreserveSig] void ReleaseTypeAttr(IntPtr pTypeAttr); [PreserveSig] void ReleaseFuncDesc(IntPtr pFuncDesc); [PreserveSig] void ReleaseVarDesc(IntPtr pVarDesc); } [ComImport] [Guid("00020412-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface ITypeInfo2 : ITypeInfo { new void GetTypeAttr(out IntPtr ppTypeAttr); new void GetTypeComp(out ITypeComp ppTComp); new void GetFuncDesc(int index, out IntPtr ppFuncDesc); new void GetVarDesc(int index, out IntPtr ppVarDesc); new void GetNames(int memid, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] string[] rgBstrNames, int cMaxNames, out int pcNames); new void GetRefTypeOfImplType(int index, out int href); new void GetImplTypeFlags(int index, out IMPLTYPEFLAGS pImplTypeFlags); new void GetIDsOfNames([In][MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr, SizeParamIndex = 1)] string[] rgszNames, int cNames, [Out][MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] int[] pMemId); new void Invoke([MarshalAs(UnmanagedType.IUnknown)] object pvInstance, int memid, short wFlags, ref DISPPARAMS pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, out int puArgErr); new void GetDocumentation(int index, out string strName, out string strDocString, out int dwHelpContext, out string strHelpFile); new void GetDllEntry(int memid, INVOKEKIND invKind, IntPtr pBstrDllName, IntPtr pBstrName, IntPtr pwOrdinal); new void GetRefTypeInfo(int hRef, out ITypeInfo ppTI); new void AddressOfMember(int memid, INVOKEKIND invKind, out IntPtr ppv); new void CreateInstance([MarshalAs(UnmanagedType.IUnknown)] object? pUnkOuter, [In] ref Guid riid, [MarshalAs(UnmanagedType.IUnknown)] out object ppvObj); new void GetMops(int memid, out string? pBstrMops); new void GetContainingTypeLib(out ITypeLib ppTLB, out int pIndex); [PreserveSig] new void ReleaseTypeAttr(IntPtr pTypeAttr); [PreserveSig] new void ReleaseFuncDesc(IntPtr pFuncDesc); [PreserveSig] new void ReleaseVarDesc(IntPtr pVarDesc); void GetTypeKind(out TYPEKIND pTypeKind); void GetTypeFlags(out int pTypeFlags); void GetFuncIndexOfMemId(int memid, INVOKEKIND invKind, out int pFuncIndex); void GetVarIndexOfMemId(int memid, out int pVarIndex); void GetCustData(ref Guid guid, out object pVarVal); void GetFuncCustData(int index, ref Guid guid, out object pVarVal); void GetParamCustData(int indexFunc, int indexParam, ref Guid guid, out object pVarVal); void GetVarCustData(int index, ref Guid guid, out object pVarVal); void GetImplTypeCustData(int index, ref Guid guid, out object pVarVal); [LCIDConversion(1)] void GetDocumentation2(int memid, out string pbstrHelpString, out int pdwHelpStringContext, out string pbstrHelpStringDll); void GetAllCustData(IntPtr pCustData); void GetAllFuncCustData(int index, IntPtr pCustData); void GetAllParamCustData(int indexFunc, int indexParam, IntPtr pCustData); void GetAllVarCustData(int index, IntPtr pCustData); void GetAllImplTypeCustData(int index, IntPtr pCustData); } public enum SYSKIND { SYS_WIN16, SYS_WIN32, SYS_MAC, SYS_WIN64 } [Flags] public enum LIBFLAGS : short { LIBFLAG_FRESTRICTED = 1, LIBFLAG_FCONTROL = 2, LIBFLAG_FHIDDEN = 4, LIBFLAG_FHASDISKIMAGE = 8 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct TYPELIBATTR { public Guid guid; public int lcid; public SYSKIND syskind; public short wMajorVerNum; public short wMinorVerNum; public LIBFLAGS wLibFlags; } [ComImport] [Guid("00020402-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface ITypeLib { [PreserveSig] int GetTypeInfoCount(); void GetTypeInfo(int index, out ITypeInfo ppTI); void GetTypeInfoType(int index, out TYPEKIND pTKind); void GetTypeInfoOfGuid(ref Guid guid, out ITypeInfo ppTInfo); void GetLibAttr(out IntPtr ppTLibAttr); void GetTypeComp(out ITypeComp ppTComp); void GetDocumentation(int index, out string strName, out string strDocString, out int dwHelpContext, out string strHelpFile); [return: MarshalAs(UnmanagedType.Bool)] bool IsName([MarshalAs(UnmanagedType.LPWStr)] string szNameBuf, int lHashVal); void FindName([MarshalAs(UnmanagedType.LPWStr)] string szNameBuf, int lHashVal, [Out][MarshalAs(UnmanagedType.LPArray)] ITypeInfo[] ppTInfo, [Out][MarshalAs(UnmanagedType.LPArray)] int[] rgMemId, ref short pcFound); [PreserveSig] void ReleaseTLibAttr(IntPtr pTLibAttr); } [ComImport] [Guid("00020411-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface ITypeLib2 : ITypeLib { [PreserveSig] new int GetTypeInfoCount(); new void GetTypeInfo(int index, out ITypeInfo ppTI); new void GetTypeInfoType(int index, out TYPEKIND pTKind); new void GetTypeInfoOfGuid(ref Guid guid, out ITypeInfo ppTInfo); new void GetLibAttr(out IntPtr ppTLibAttr); new void GetTypeComp(out ITypeComp ppTComp); new void GetDocumentation(int index, out string strName, out string strDocString, out int dwHelpContext, out string strHelpFile); [return: MarshalAs(UnmanagedType.Bool)] new bool IsName([MarshalAs(UnmanagedType.LPWStr)] string szNameBuf, int lHashVal); new void FindName([MarshalAs(UnmanagedType.LPWStr)] string szNameBuf, int lHashVal, [Out][MarshalAs(UnmanagedType.LPArray)] ITypeInfo[] ppTInfo, [Out][MarshalAs(UnmanagedType.LPArray)] int[] rgMemId, ref short pcFound); [PreserveSig] new void ReleaseTLibAttr(IntPtr pTLibAttr); void GetCustData(ref Guid guid, out object pVarVal); [LCIDConversion(1)] void GetDocumentation2(int index, out string pbstrHelpString, out int pdwHelpStringContext, out string pbstrHelpStringDll); void GetLibStatistics(IntPtr pcUniqueNames, out int pcchUniqueNames); void GetAllCustData(IntPtr pCustData); } } namespace System.Runtime.CompilerServices { [StructLayout(LayoutKind.Sequential)] internal sealed class LAHashDependentHashTracker { private GCHandle _dependentHandle; private IntPtr _loaderAllocator; ~LAHashDependentHashTracker() { if (_dependentHandle.IsAllocated) { _dependentHandle.Free(); } } } [StructLayout(LayoutKind.Sequential)] internal sealed class LAHashKeyToTrackers { private object _trackerOrTrackerSet; private object _laLocalKeyValueStore; } [StructLayout(LayoutKind.Sequential)] internal sealed class GCHeapHash { private Array _data; private int _count; private int _deletedCount; } internal static class CastHelpers { [DebuggerDisplay("Source = {_source}; Target = {_targetAndResult & ~1}; Result = {_targetAndResult & 1}; VersionNum = {_version & ((1 << 29) - 1)}; Distance = {_version >> 29};")] private struct CastCacheEntry { internal int _version; internal nuint _source; internal nuint _targetAndResult; } private enum CastResult { CannotCast, CanCast, MaybeCast } internal struct ArrayElement { public object Value; } private static int[] s_table; [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int KeyToBucket(ref int tableData, nuint source, nuint target) { int num = HashShift(ref tableData); uint num2 = BitOperations.RotateLeft((uint)source, 16) ^ (uint)(int)target; return (int)num2 * -1640531527 >>> num; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ref int TableData(int[] table) { return ref MemoryMarshal.GetArrayDataReference(table); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static ref CastCacheEntry Element(ref int tableData, int index) { return ref Unsafe.Add(ref Unsafe.As(ref tableData), index + 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int HashShift(ref int tableData) { return tableData; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static int TableMask(ref int tableData) { return Unsafe.Add(ref tableData, 1); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static CastResult TryGet(nuint source, nuint target) { ref int tableData = ref TableData(s_table); int num = KeyToBucket(ref tableData, source, target); int num2 = 0; while (num2 < 8) { ref CastCacheEntry reference = ref Element(ref tableData, num); int num3 = Volatile.Read(ref reference._version); nuint source2 = reference._source; num3 &= -2; if (source2 == source) { nuint targetAndResult = reference._targetAndResult; targetAndResult ^= target; if (targetAndResult <= 1) { Interlocked.ReadMemoryBarrier(); if (num3 != reference._version) { break; } return (CastResult)targetAndResult; } } if (num3 == 0) { break; } num2++; num = (num + num2) & TableMask(ref tableData); } return CastResult.MaybeCast; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern object IsInstanceOfAny_NoCacheLookup(void* toTypeHnd, object obj); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern object ChkCastAny_NoCacheLookup(void* toTypeHnd, object obj); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern ref byte Unbox_Helper(void* toTypeHnd, object obj); [MethodImpl(MethodImplOptions.InternalCall)] private static extern void WriteBarrier(ref object dst, object obj); [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private unsafe static object IsInstanceOfAny(void* toTypeHnd, object obj) { if (obj != null) { void* methodTable = RuntimeHelpers.GetMethodTable(obj); if (methodTable != toTypeHnd) { CastResult castResult = TryGet((nuint)methodTable, (nuint)toTypeHnd); if (castResult != CastResult.CanCast) { if (castResult != 0) { return IsInstanceOfAny_NoCacheLookup(toTypeHnd, obj); } obj = null; } } } return obj; } [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private unsafe static object IsInstanceOfInterface(void* toTypeHnd, object obj) { MethodTable* methodTable; nint num; MethodTable** ptr; if (obj != null) { methodTable = RuntimeHelpers.GetMethodTable(obj); num = methodTable->InterfaceCount; if (num == 0) { goto IL_0083; } ptr = methodTable->InterfaceMap; if (num < 4) { goto IL_006c; } while (*ptr != toTypeHnd && ptr[1] != toTypeHnd && ptr[2] != toTypeHnd && ptr[3] != toTypeHnd) { ptr += 4; num -= 4; if (num >= 4) { continue; } goto IL_0069; } } goto IL_008e; IL_0069: if (num != 0) { goto IL_006c; } goto IL_0083; IL_0083: if (!methodTable->NonTrivialInterfaceCast) { obj = null; goto IL_008e; } return IsInstance_Helper(toTypeHnd, obj); IL_008e: return obj; IL_006c: while (*ptr != toTypeHnd) { ptr++; num--; if (num > 0) { continue; } goto IL_0083; } goto IL_008e; } [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private unsafe static object IsInstanceOfClass(void* toTypeHnd, object obj) { if (obj == null || RuntimeHelpers.GetMethodTable(obj) == toTypeHnd) { return obj; } MethodTable* parentMethodTable = RuntimeHelpers.GetMethodTable(obj)->ParentMethodTable; while (parentMethodTable != toTypeHnd) { if (parentMethodTable != null) { parentMethodTable = parentMethodTable->ParentMethodTable; if (parentMethodTable == toTypeHnd) { break; } if (parentMethodTable != null) { parentMethodTable = parentMethodTable->ParentMethodTable; if (parentMethodTable == toTypeHnd) { break; } if (parentMethodTable != null) { parentMethodTable = parentMethodTable->ParentMethodTable; if (parentMethodTable == toTypeHnd) { break; } if (parentMethodTable != null) { parentMethodTable = parentMethodTable->ParentMethodTable; continue; } } } } obj = null; break; } return obj; } [MethodImpl(MethodImplOptions.NoInlining)] [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private unsafe static object IsInstance_Helper(void* toTypeHnd, object obj) { return TryGet((nuint)RuntimeHelpers.GetMethodTable(obj), (nuint)toTypeHnd) switch { CastResult.CanCast => obj, CastResult.CannotCast => null, _ => IsInstanceOfAny_NoCacheLookup(toTypeHnd, obj), }; } [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private unsafe static object ChkCastAny(void* toTypeHnd, object obj) { if (obj != null) { void* methodTable = RuntimeHelpers.GetMethodTable(obj); if (methodTable != toTypeHnd) { CastResult castResult = TryGet((nuint)methodTable, (nuint)toTypeHnd); if (castResult != CastResult.CanCast) { return ChkCastAny_NoCacheLookup(toTypeHnd, obj); } } } return obj; } [MethodImpl(MethodImplOptions.NoInlining)] [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private unsafe static object ChkCast_Helper(void* toTypeHnd, object obj) { CastResult castResult = TryGet((nuint)RuntimeHelpers.GetMethodTable(obj), (nuint)toTypeHnd); if (castResult == CastResult.CanCast) { return obj; } return ChkCastAny_NoCacheLookup(toTypeHnd, obj); } [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private unsafe static object ChkCastInterface(void* toTypeHnd, object obj) { nint num; MethodTable** ptr; if (obj != null) { MethodTable* methodTable = RuntimeHelpers.GetMethodTable(obj); num = methodTable->InterfaceCount; if (num == 0) { goto IL_0084; } ptr = methodTable->InterfaceMap; if (num < 4) { goto IL_0069; } while (*ptr != toTypeHnd && ptr[1] != toTypeHnd && ptr[2] != toTypeHnd && ptr[3] != toTypeHnd) { ptr += 4; num -= 4; if (num >= 4) { continue; } goto IL_0066; } } goto IL_0082; IL_0082: return obj; IL_0069: while (*ptr != toTypeHnd) { ptr++; num--; if (num > 0) { continue; } goto IL_0084; } goto IL_0082; IL_0066: if (num != 0) { goto IL_0069; } goto IL_0084; IL_0084: return ChkCast_Helper(toTypeHnd, obj); } [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private unsafe static object ChkCastClass(void* toTypeHnd, object obj) { if (obj == null || RuntimeHelpers.GetMethodTable(obj) == toTypeHnd) { return obj; } return ChkCastClassSpecial(toTypeHnd, obj); } [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private unsafe static object ChkCastClassSpecial(void* toTypeHnd, object obj) { MethodTable* ptr = RuntimeHelpers.GetMethodTable(obj); while (true) { ptr = ptr->ParentMethodTable; if (ptr != toTypeHnd) { if (ptr == null) { break; } ptr = ptr->ParentMethodTable; if (ptr != toTypeHnd) { if (ptr == null) { break; } ptr = ptr->ParentMethodTable; if (ptr != toTypeHnd) { if (ptr == null) { break; } ptr = ptr->ParentMethodTable; if (ptr != toTypeHnd) { if (ptr == null) { break; } continue; } } } } return obj; } return ChkCast_Helper(toTypeHnd, obj); } [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private unsafe static ref byte Unbox(void* toTypeHnd, object obj) { if (RuntimeHelpers.GetMethodTable(obj) == toTypeHnd) { return ref obj.GetRawData(); } return ref Unbox_Helper(toTypeHnd, obj); } [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private static ref object ThrowArrayMismatchException() { throw new ArrayTypeMismatchException(); } [MethodImpl(MethodImplOptions.AggressiveOptimization)] [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private unsafe static ref object LdelemaRef(Array array, int index, void* type) { ref object value = ref Unsafe.As(array)[index].Value; void* elementType = RuntimeHelpers.GetMethodTable(array)->ElementType; if (elementType == type) { return ref value; } return ref ThrowArrayMismatchException(); } [MethodImpl(MethodImplOptions.AggressiveOptimization)] [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private unsafe static void StelemRef(Array array, int index, object obj) { ref object value = ref Unsafe.As(array)[index].Value; void* elementType = RuntimeHelpers.GetMethodTable(array)->ElementType; if (obj != null) { if (elementType == RuntimeHelpers.GetMethodTable(obj) || array.GetType() == typeof(object[])) { WriteBarrier(ref value, obj); } else { StelemRef_Helper(ref value, elementType, obj); } } else { value = null; } } [MethodImpl(MethodImplOptions.NoInlining)] [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private unsafe static void StelemRef_Helper(ref object element, void* elementType, object obj) { CastResult castResult = TryGet((nuint)RuntimeHelpers.GetMethodTable(obj), (nuint)elementType); if (castResult == CastResult.CanCast) { WriteBarrier(ref element, obj); } else { StelemRef_Helper_NoCacheLookup(ref element, elementType, obj); } } [DebuggerHidden] [StackTraceHidden] [DebuggerStepThrough] private unsafe static void StelemRef_Helper_NoCacheLookup(ref object element, void* elementType, object obj) { obj = IsInstanceOfAny_NoCacheLookup(elementType, obj); if (obj != null) { WriteBarrier(ref element, obj); return; } throw new ArrayTypeMismatchException(); } } internal static class ICastableHelpers { internal static bool IsInstanceOfInterface(ICastable castable, RuntimeType type, [NotNullWhen(true)] out Exception castError) { return castable.IsInstanceOfInterface(new RuntimeTypeHandle(type), out castError); } internal static RuntimeType GetImplType(ICastable castable, RuntimeType interfaceType) { return castable.GetImplType(new RuntimeTypeHandle(interfaceType)).GetRuntimeType(); } } public static class RuntimeFeature { public const string PortablePdb = "PortablePdb"; public const string DefaultImplementationsOfInterfaces = "DefaultImplementationsOfInterfaces"; public const string UnmanagedSignatureCallingConvention = "UnmanagedSignatureCallingConvention"; public const string CovariantReturnsOfClasses = "CovariantReturnsOfClasses"; [RequiresPreviewFeatures("Generic Math is in preview.", Url = "https://aka.ms/dotnet-warnings/generic-math-preview")] public const string VirtualStaticsInInterfaces = "VirtualStaticsInInterfaces"; public static bool IsDynamicCodeSupported => true; public static bool IsDynamicCodeCompiled => true; public static bool IsSupported(string feature) { switch (feature) { case "PortablePdb": case "CovariantReturnsOfClasses": case "UnmanagedSignatureCallingConvention": case "DefaultImplementationsOfInterfaces": case "VirtualStaticsInInterfaces": return true; case "IsDynamicCodeSupported": return IsDynamicCodeSupported; case "IsDynamicCodeCompiled": return IsDynamicCodeCompiled; default: return false; } } } public static class RuntimeHelpers { public delegate void TryCode(object? userData); public delegate void CleanupCode(object? userData, bool exceptionThrown); public static int OffsetToStringData { [NonVersionable] get { return 8; } } [MethodImpl(MethodImplOptions.InternalCall)] [Intrinsic] public static extern void InitializeArray(Array array, RuntimeFieldHandle fldHandle); [MethodImpl(MethodImplOptions.InternalCall)] [return: NotNullIfNotNull("obj")] public static extern object? GetObjectValue(object? obj); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void RunClassConstructor(QCallTypeHandle type); [RequiresUnreferencedCode("Trimmer can't guarantee existence of class constructor")] public static void RunClassConstructor(RuntimeTypeHandle type) { RuntimeType type2 = type.GetRuntimeType(); if ((object)type2 == null) { throw new ArgumentException(SR.InvalidOperation_HandleIsNotInitialized, "type"); } RunClassConstructor(new QCallTypeHandle(ref type2)); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void RunModuleConstructor(QCallModule module); public static void RunModuleConstructor(ModuleHandle module) { RuntimeModule module2 = module.GetRuntimeModule(); if ((object)module2 == null) { throw new ArgumentException(SR.InvalidOperation_HandleIsNotInitialized, "module"); } RunModuleConstructor(new QCallModule(ref module2)); } [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern void CompileMethod(RuntimeMethodHandleInternal method); [DllImport("QCall", CharSet = CharSet.Unicode)] private unsafe static extern void PrepareMethod(RuntimeMethodHandleInternal method, IntPtr* pInstantiation, int cInstantiation); public static void PrepareMethod(RuntimeMethodHandle method) { PrepareMethod(method, null); } public unsafe static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[]? instantiation) { IRuntimeMethodInfo methodInfo = method.GetMethodInfo(); if (methodInfo == null) { throw new ArgumentException(SR.InvalidOperation_HandleIsNotInitialized, "method"); } instantiation = (RuntimeTypeHandle[])instantiation?.Clone(); int length; fixed (IntPtr* pInstantiation = RuntimeTypeHandle.CopyRuntimeTypeHandles(instantiation, out length)) { PrepareMethod(methodInfo.Value, pInstantiation, length); GC.KeepAlive(instantiation); GC.KeepAlive(methodInfo); } } [MethodImpl(MethodImplOptions.InternalCall)] public static extern void PrepareDelegate(Delegate d); [MethodImpl(MethodImplOptions.InternalCall)] public static extern int GetHashCode(object? o); [MethodImpl(MethodImplOptions.InternalCall)] public new static extern bool Equals(object? o1, object? o2); [MethodImpl(MethodImplOptions.InternalCall)] public static extern void EnsureSufficientExecutionStack(); [MethodImpl(MethodImplOptions.InternalCall)] public static extern bool TryEnsureSufficientExecutionStack(); public static object GetUninitializedObject([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type type) { RuntimeType type2 = type as RuntimeType; if ((object)type2 == null) { if ((object)type == null) { throw new ArgumentNullException("type", SR.ArgumentNull_Type); } throw new SerializationException(SR.Format(SR.Serialization_InvalidType, type)); } object o = null; GetUninitializedObject(new QCallTypeHandle(ref type2), ObjectHandleOnStack.Create(ref o)); return o; } [DllImport("QCall")] private static extern void GetUninitializedObject(QCallTypeHandle type, ObjectHandleOnStack retObject); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern object AllocateUninitializedClone(object obj); [Intrinsic] public static bool IsReferenceOrContainsReferences() { throw new InvalidOperationException(); } [Intrinsic] internal static bool IsBitwiseEquatable() { throw new InvalidOperationException(); } [Intrinsic] internal static bool EnumEquals(T x, T y) where T : struct, Enum { return x.Equals(y); } [Intrinsic] internal static int EnumCompareTo(T x, T y) where T : struct, Enum { return x.CompareTo(y); } internal static ref byte GetRawData(this object obj) { return ref Unsafe.As(obj).Data; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe static nuint GetRawObjectDataSize(object obj) { MethodTable* methodTable = GetMethodTable(obj); nuint num = (nuint)methodTable->BaseSize - (nuint)(2 * sizeof(IntPtr)); if (methodTable->HasComponentSize) { num += (nuint)((nint)Unsafe.As(obj).Length * (nint)methodTable->ComponentSize); } GC.KeepAlive(obj); return num; } internal unsafe static ushort GetElementSize(this Array array) { return GetMethodTable(array)->ComponentSize; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static ref int GetMultiDimensionalArrayBounds(Array array) { return ref Unsafe.As(ref Unsafe.As(array).Data); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe static int GetMultiDimensionalArrayRank(Array array) { int multiDimensionalArrayRank = GetMethodTable(array)->MultiDimensionalArrayRank; GC.KeepAlive(array); return multiDimensionalArrayRank; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal unsafe static bool ObjectHasComponentSize(object obj) { return GetMethodTable(obj)->HasComponentSize; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [Intrinsic] internal unsafe static MethodTable* GetMethodTable(object obj) { return (MethodTable*)(void*)Unsafe.Add(ref Unsafe.As(ref obj.GetRawData()), -1); } public static IntPtr AllocateTypeAssociatedMemory(Type type, int size) { RuntimeType type2 = type as RuntimeType; if (type2 == null) { throw new ArgumentException(SR.Arg_MustBeType, "type"); } if (size < 0) { throw new ArgumentOutOfRangeException("size"); } return AllocateTypeAssociatedMemory(new QCallTypeHandle(ref type2), (uint)size); } [DllImport("QCall")] private static extern IntPtr AllocateTypeAssociatedMemory(QCallTypeHandle type, uint size); [MethodImpl(MethodImplOptions.InternalCall)] private static extern IntPtr AllocTailCallArgBuffer(int size, IntPtr gcDesc); [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern TailCallTls* GetTailCallInfo(IntPtr retAddrSlot, IntPtr* retAddr); [StackTraceHidden] private unsafe static void DispatchTailCalls(IntPtr callersRetAddrSlot, delegate* callTarget, IntPtr retVal) { System.Runtime.CompilerServices.Unsafe.SkipInit(out IntPtr intPtr); TailCallTls* tailCallInfo = GetTailCallInfo(callersRetAddrSlot, &intPtr); PortableTailCallFrame* frame = tailCallInfo->Frame; if (intPtr == frame->TailCallAwareReturnAddress) { frame->NextCall = callTarget; return; } System.Runtime.CompilerServices.Unsafe.SkipInit(out PortableTailCallFrame portableTailCallFrame); portableTailCallFrame.NextCall = null; try { tailCallInfo->Frame = &portableTailCallFrame; do { callTarget(tailCallInfo->ArgBuffer, retVal, &portableTailCallFrame); callTarget = portableTailCallFrame.NextCall; } while (callTarget != (delegate*)null); } finally { tailCallInfo->Frame = frame; if (tailCallInfo->ArgBuffer != IntPtr.Zero && *(int*)(void*)tailCallInfo->ArgBuffer == 1) { *(int*)(void*)tailCallInfo->ArgBuffer = 2; } } } public static T[] GetSubArray(T[] array, Range range) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } var (elementOffset, num) = range.GetOffsetAndLength(array.Length); T[] array2; if (typeof(T).IsValueType || typeof(T[]) == array.GetType()) { if (num == 0) { return Array.Empty(); } array2 = new T[num]; } else { array2 = Unsafe.As(Array.CreateInstance(array.GetType().GetElementType(), num)); } Buffer.Memmove(ref MemoryMarshal.GetArrayDataReference(array2), ref Unsafe.Add(ref MemoryMarshal.GetArrayDataReference(array), elementOffset), (uint)num); return array2; } [Obsolete("The Constrained Execution Region (CER) feature is not supported.", DiagnosticId = "SYSLIB0004", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public static void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, object? userData) { if (code == null) { throw new ArgumentNullException("code"); } if (backoutCode == null) { throw new ArgumentNullException("backoutCode"); } bool exceptionThrown = true; try { code(userData); exceptionThrown = false; } finally { backoutCode(userData, exceptionThrown); } } [Obsolete("The Constrained Execution Region (CER) feature is not supported.", DiagnosticId = "SYSLIB0004", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public static void PrepareContractedDelegate(Delegate d) { } [Obsolete("The Constrained Execution Region (CER) feature is not supported.", DiagnosticId = "SYSLIB0004", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public static void ProbeForSufficientStack() { } [Obsolete("The Constrained Execution Region (CER) feature is not supported.", DiagnosticId = "SYSLIB0004", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public static void PrepareConstrainedRegions() { } [Obsolete("The Constrained Execution Region (CER) feature is not supported.", DiagnosticId = "SYSLIB0004", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public static void PrepareConstrainedRegionsNoOP() { } internal static bool IsPrimitiveType(this CorElementType et) { return ((1 << (int)et) & 0x3003FFC) != 0; } } internal sealed class RawData { public byte Data; } internal sealed class RawArrayData { public uint Length; public byte Data; } [StructLayout(LayoutKind.Explicit)] internal struct MethodTable { [FieldOffset(0)] public ushort ComponentSize; [FieldOffset(0)] private uint Flags; [FieldOffset(4)] public uint BaseSize; [FieldOffset(14)] public ushort InterfaceCount; [FieldOffset(16)] public unsafe MethodTable* ParentMethodTable; [FieldOffset(32)] public unsafe void* ElementType; [FieldOffset(36)] public unsafe MethodTable** InterfaceMap; public bool HasComponentSize => (Flags & 0x80000000u) != 0; public bool ContainsGCPointers => (Flags & 0x1000000) != 0; public bool NonTrivialInterfaceCast => (Flags & 0x406C0000) != 0; public unsafe bool IsMultiDimensionalArray { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return BaseSize > (uint)(3 * sizeof(IntPtr)); } } public unsafe int MultiDimensionalArrayRank { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return (int)((uint)((int)BaseSize - 3 * sizeof(IntPtr)) / 8u); } } } internal struct PortableTailCallFrame { public IntPtr TailCallAwareReturnAddress; public unsafe delegate* NextCall; } internal struct TailCallTls { public unsafe PortableTailCallFrame* Frame; public IntPtr ArgBuffer; } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] internal sealed class TypeDependencyAttribute : Attribute { private readonly string typeName; public TypeDependencyAttribute(string typeName) { if (typeName == null) { throw new ArgumentNullException("typeName"); } this.typeName = typeName; } } [AttributeUsage(AttributeTargets.Field)] public sealed class AccessedThroughPropertyAttribute : Attribute { public string PropertyName { get; } public AccessedThroughPropertyAttribute(string propertyName) { PropertyName = propertyName; } } [StructLayout(LayoutKind.Auto)] public struct AsyncIteratorMethodBuilder { private Task m_task; internal object ObjectIdForDebugger => m_task ?? (m_task = AsyncTaskMethodBuilder.CreateWeaklyTypedStateMachineBox()); public static AsyncIteratorMethodBuilder Create() { return default(AsyncIteratorMethodBuilder); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void MoveNext(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { AsyncMethodBuilderCore.Start(ref stateMachine); } public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { AsyncTaskMethodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine, ref m_task); } public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine, ref m_task); } public void Complete() { if (m_task == null) { m_task = Task.s_cachedCompleted; return; } AsyncTaskMethodBuilder.SetExistingTaskResult(m_task, default(VoidTaskResult)); if (m_task is IAsyncStateMachineBox asyncStateMachineBox) { asyncStateMachineBox.ClearStateUponCompletion(); } } } [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] public sealed class AsyncIteratorStateMachineAttribute : StateMachineAttribute { public AsyncIteratorStateMachineAttribute(Type stateMachineType) : base(stateMachineType) { } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)] public sealed class AsyncMethodBuilderAttribute : Attribute { public Type BuilderType { get; } public AsyncMethodBuilderAttribute(Type builderType) { BuilderType = builderType; } } internal static class AsyncMethodBuilderCore { private sealed class ContinuationWrapper { private readonly Action _invokeAction; internal readonly Action _continuation; internal readonly Task _innerTask; internal ContinuationWrapper(Action continuation, Action invokeAction, Task innerTask) { _invokeAction = invokeAction; _continuation = continuation; _innerTask = innerTask; } internal void Invoke() { _invokeAction(_continuation, _innerTask); } } internal static bool TrackAsyncMethodCompletion { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return TplEventSource.Log.IsEnabled(EventLevel.Warning, (EventKeywords)256L); } } [DebuggerStepThrough] public static void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { if (stateMachine == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stateMachine); } Thread currentThread = Thread.CurrentThread; ExecutionContext executionContext = currentThread._executionContext; SynchronizationContext synchronizationContext = currentThread._synchronizationContext; try { stateMachine.MoveNext(); } finally { if (synchronizationContext != currentThread._synchronizationContext) { currentThread._synchronizationContext = synchronizationContext; } ExecutionContext executionContext2 = currentThread._executionContext; if (executionContext != executionContext2) { ExecutionContext.RestoreChangedContextToThread(currentThread, executionContext, executionContext2); } } } public static void SetStateMachine(IAsyncStateMachine stateMachine, Task task) { if (stateMachine == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.stateMachine); } if (task != null) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.AsyncMethodBuilder_InstanceNotInitialized); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", Justification = "It's okay if unused fields disappear from debug views")] internal static string GetAsyncStateMachineDescription(IAsyncStateMachine stateMachine) { Type type = stateMachine.GetType(); FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(type.FullName); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { stringBuilder.Append(" ").Append(fieldInfo.Name).Append(": ") .Append(fieldInfo.GetValue(stateMachine)) .AppendLine(); } return stringBuilder.ToString(); } internal static Action CreateContinuationWrapper(Action continuation, Action invokeAction, Task innerTask) { return new ContinuationWrapper(continuation, invokeAction, innerTask).Invoke; } internal static Action TryGetStateMachineForDebugger(Action action) { object target = action.Target; if (!(target is IAsyncStateMachineBox asyncStateMachineBox)) { if (!(target is ContinuationWrapper continuationWrapper)) { return action; } return TryGetStateMachineForDebugger(continuationWrapper._continuation); } return asyncStateMachineBox.GetStateMachineObject().MoveNext; } internal static Task TryGetContinuationTask(Action continuation) { if (!(continuation.Target is ContinuationWrapper continuationWrapper)) { return continuation.Target as Task; } return continuationWrapper._innerTask; } } [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] public sealed class AsyncStateMachineAttribute : StateMachineAttribute { public AsyncStateMachineAttribute(Type stateMachineType) : base(stateMachineType) { } } public struct AsyncTaskMethodBuilder { private Task m_task; public Task Task { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_task ?? InitializeTaskAsPromise(); } } internal object ObjectIdForDebugger => m_task ?? (m_task = AsyncTaskMethodBuilder.CreateWeaklyTypedStateMachineBox()); public static AsyncTaskMethodBuilder Create() { return default(AsyncTaskMethodBuilder); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [DebuggerStepThrough] public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { AsyncMethodBuilderCore.Start(ref stateMachine); } public void SetStateMachine(IAsyncStateMachine stateMachine) { AsyncMethodBuilderCore.SetStateMachine(stateMachine, null); } public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { AsyncTaskMethodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine, ref m_task); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine, ref m_task); } [MethodImpl(MethodImplOptions.NoInlining)] private Task InitializeTaskAsPromise() { return m_task = new Task(); } public void SetResult() { if (m_task == null) { m_task = System.Threading.Tasks.Task.s_cachedCompleted; } else { AsyncTaskMethodBuilder.SetExistingTaskResult(m_task, default(VoidTaskResult)); } } public void SetException(Exception exception) { AsyncTaskMethodBuilder.SetException(exception, ref m_task); } internal void SetNotificationForWaitCompletion(bool enabled) { AsyncTaskMethodBuilder.SetNotificationForWaitCompletion(enabled, ref m_task); } } public struct AsyncTaskMethodBuilder { private sealed class DebugFinalizableAsyncStateMachineBox : AsyncStateMachineBox where TStateMachine : IAsyncStateMachine { ~DebugFinalizableAsyncStateMachineBox() { if (!base.IsCompleted) { TplEventSource.Log.IncompleteAsyncMethod(this); } } } private class AsyncStateMachineBox : Task, IAsyncStateMachineBox where TStateMachine : IAsyncStateMachine { private static readonly ContextCallback s_callback = ExecutionContextCallback; private Action _moveNextAction; public TStateMachine StateMachine; public ExecutionContext Context; public Action MoveNextAction => _moveNextAction ?? (_moveNextAction = MoveNext); private static void ExecutionContextCallback(object s) { Unsafe.As>(s).StateMachine.MoveNext(); } internal sealed override void ExecuteFromThreadPool(Thread threadPoolThread) { MoveNext(threadPoolThread); } public void MoveNext() { MoveNext(null); } private void MoveNext(Thread threadPoolThread) { bool flag = TplEventSource.Log.IsEnabled(); if (flag) { TplEventSource.Log.TraceSynchronousWorkBegin(base.Id, CausalitySynchronousWork.Execution); } ExecutionContext context = Context; if (context == null) { StateMachine.MoveNext(); } else if (threadPoolThread == null) { ExecutionContext.RunInternal(context, s_callback, this); } else { ExecutionContext.RunFromThreadPoolDispatchLoop(threadPoolThread, context, s_callback, this); } if (base.IsCompleted) { ClearStateUponCompletion(); } if (flag) { TplEventSource.Log.TraceSynchronousWorkEnd(CausalitySynchronousWork.Execution); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ClearStateUponCompletion() { if (System.Threading.Tasks.Task.s_asyncDebuggingEnabled) { System.Threading.Tasks.Task.RemoveFromActiveTasks(this); } StateMachine = default(TStateMachine); Context = null; if (AsyncMethodBuilderCore.TrackAsyncMethodCompletion) { GC.SuppressFinalize(this); } } IAsyncStateMachine IAsyncStateMachineBox.GetStateMachineObject() { return StateMachine; } } private Task m_task; public Task Task { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_task ?? InitializeTaskAsPromise(); } } internal object ObjectIdForDebugger => m_task ?? (m_task = CreateWeaklyTypedStateMachineBox()); public static AsyncTaskMethodBuilder Create() { return default(AsyncTaskMethodBuilder); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [DebuggerStepThrough] public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { AsyncMethodBuilderCore.Start(ref stateMachine); } public void SetStateMachine(IAsyncStateMachine stateMachine) { AsyncMethodBuilderCore.SetStateMachine(stateMachine, m_task); } public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { AwaitOnCompleted(ref awaiter, ref stateMachine, ref m_task); } internal static void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine, ref Task taskField) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { try { awaiter.OnCompleted(GetStateMachineBox(ref stateMachine, ref taskField).MoveNextAction); } catch (Exception exception) { System.Threading.Tasks.Task.ThrowAsync(exception, null); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine, ref m_task); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine, [NotNull] ref Task taskField) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { IAsyncStateMachineBox stateMachineBox = GetStateMachineBox(ref stateMachine, ref taskField); AwaitUnsafeOnCompleted(ref awaiter, stateMachineBox); } [MethodImpl(MethodImplOptions.AggressiveOptimization)] internal static void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, IAsyncStateMachineBox box) where TAwaiter : ICriticalNotifyCompletion { if (default(TAwaiter) != null && awaiter is ITaskAwaiter) { TaskAwaiter.UnsafeOnCompletedInternal(Unsafe.As(ref awaiter).m_task, box, continueOnCapturedContext: true); return; } if (default(TAwaiter) != null && awaiter is IConfiguredTaskAwaiter) { ref ConfiguredTaskAwaitable.ConfiguredTaskAwaiter reference = ref Unsafe.As(ref awaiter); TaskAwaiter.UnsafeOnCompletedInternal(reference.m_task, box, reference.m_continueOnCapturedContext); return; } if (default(TAwaiter) != null && awaiter is IStateMachineBoxAwareAwaiter) { try { ((IStateMachineBoxAwareAwaiter)(object)awaiter).AwaitUnsafeOnCompleted(box); return; } catch (Exception exception) { System.Threading.Tasks.Task.ThrowAsync(exception, null); return; } } try { awaiter.UnsafeOnCompleted(box.MoveNextAction); } catch (Exception exception2) { System.Threading.Tasks.Task.ThrowAsync(exception2, null); } } private static IAsyncStateMachineBox GetStateMachineBox(ref TStateMachine stateMachine, [NotNull] ref Task taskField) where TStateMachine : IAsyncStateMachine { ExecutionContext executionContext = ExecutionContext.Capture(); if (taskField is AsyncStateMachineBox asyncStateMachineBox) { if (asyncStateMachineBox.Context != executionContext) { asyncStateMachineBox.Context = executionContext; } return asyncStateMachineBox; } if (taskField is AsyncStateMachineBox asyncStateMachineBox2) { if (asyncStateMachineBox2.StateMachine == null) { Debugger.NotifyOfCrossThreadDependency(); asyncStateMachineBox2.StateMachine = stateMachine; } asyncStateMachineBox2.Context = executionContext; return asyncStateMachineBox2; } Debugger.NotifyOfCrossThreadDependency(); AsyncStateMachineBox asyncStateMachineBox3 = (AsyncStateMachineBox)(taskField = (AsyncMethodBuilderCore.TrackAsyncMethodCompletion ? CreateDebugFinalizableAsyncStateMachineBox() : new AsyncStateMachineBox())); asyncStateMachineBox3.StateMachine = stateMachine; asyncStateMachineBox3.Context = executionContext; if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationBegin(asyncStateMachineBox3.Id, "Async: " + stateMachine.GetType().Name, 0L); } if (System.Threading.Tasks.Task.s_asyncDebuggingEnabled) { System.Threading.Tasks.Task.AddToActiveTasks(asyncStateMachineBox3); } return asyncStateMachineBox3; } [MethodImpl(MethodImplOptions.NoInlining)] private static AsyncStateMachineBox CreateDebugFinalizableAsyncStateMachineBox() where TStateMachine : IAsyncStateMachine { return new DebugFinalizableAsyncStateMachineBox(); } [MethodImpl(MethodImplOptions.NoInlining)] private Task InitializeTaskAsPromise() { return m_task = new Task(); } internal static Task CreateWeaklyTypedStateMachineBox() { if (!AsyncMethodBuilderCore.TrackAsyncMethodCompletion) { return new AsyncStateMachineBox(); } return CreateDebugFinalizableAsyncStateMachineBox(); } public void SetResult(TResult result) { if (m_task == null) { m_task = System.Threading.Tasks.Task.FromResult(result); } else { SetExistingTaskResult(m_task, result); } } internal static void SetExistingTaskResult(Task task, TResult result) { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(task.Id, AsyncCausalityStatus.Completed); } if (!task.TrySetResult(result)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } public void SetException(Exception exception) { SetException(exception, ref m_task); } internal static void SetException(Exception exception, ref Task taskField) { if (exception == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); } Task task = taskField ?? (taskField = new Task()); if (!((exception is OperationCanceledException ex) ? task.TrySetCanceled(ex.CancellationToken, ex) : task.TrySetException(exception))) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.TaskT_TransitionToFinal_AlreadyCompleted); } } internal void SetNotificationForWaitCompletion(bool enabled) { SetNotificationForWaitCompletion(enabled, ref m_task); } internal static void SetNotificationForWaitCompletion(bool enabled, [NotNull] ref Task taskField) { (taskField ?? (taskField = CreateWeaklyTypedStateMachineBox())).SetNotificationForWaitCompletion(enabled); } } [StructLayout(LayoutKind.Auto)] public struct AsyncValueTaskMethodBuilder { private static readonly Task s_syncSuccessSentinel = AsyncValueTaskMethodBuilder.s_syncSuccessSentinel; private Task m_task; public ValueTask Task { get { if (m_task == s_syncSuccessSentinel) { return default(ValueTask); } Task task = m_task ?? (m_task = new Task()); return new ValueTask(task); } } internal object ObjectIdForDebugger => m_task ?? (m_task = AsyncTaskMethodBuilder.CreateWeaklyTypedStateMachineBox()); public static AsyncValueTaskMethodBuilder Create() { return default(AsyncValueTaskMethodBuilder); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { AsyncMethodBuilderCore.Start(ref stateMachine); } public void SetStateMachine(IAsyncStateMachine stateMachine) { AsyncMethodBuilderCore.SetStateMachine(stateMachine, null); } public void SetResult() { if (m_task == null) { m_task = s_syncSuccessSentinel; } else { AsyncTaskMethodBuilder.SetExistingTaskResult(m_task, default(VoidTaskResult)); } } public void SetException(Exception exception) { AsyncTaskMethodBuilder.SetException(exception, ref m_task); } public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { AsyncTaskMethodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine, ref m_task); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine, ref m_task); } } [StructLayout(LayoutKind.Auto)] public struct AsyncValueTaskMethodBuilder { internal static readonly Task s_syncSuccessSentinel = new Task(default(TResult)); private Task m_task; private TResult _result; public ValueTask Task { get { if (m_task == s_syncSuccessSentinel) { return new ValueTask(_result); } Task task = m_task ?? (m_task = new Task()); return new ValueTask(task); } } internal object ObjectIdForDebugger => m_task ?? (m_task = AsyncTaskMethodBuilder.CreateWeaklyTypedStateMachineBox()); public static AsyncValueTaskMethodBuilder Create() { return default(AsyncValueTaskMethodBuilder); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { AsyncMethodBuilderCore.Start(ref stateMachine); } public void SetStateMachine(IAsyncStateMachine stateMachine) { AsyncMethodBuilderCore.SetStateMachine(stateMachine, null); } public void SetResult(TResult result) { if (m_task == null) { _result = result; m_task = s_syncSuccessSentinel; } else { AsyncTaskMethodBuilder.SetExistingTaskResult(m_task, result); } } public void SetException(Exception exception) { AsyncTaskMethodBuilder.SetException(exception, ref m_task); } public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { AsyncTaskMethodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine, ref m_task); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine, ref m_task); } } public struct AsyncVoidMethodBuilder { private SynchronizationContext _synchronizationContext; private AsyncTaskMethodBuilder _builder; private Task Task => _builder.Task; internal object ObjectIdForDebugger => _builder.ObjectIdForDebugger; public static AsyncVoidMethodBuilder Create() { SynchronizationContext current = SynchronizationContext.Current; current?.OperationStarted(); AsyncVoidMethodBuilder result = default(AsyncVoidMethodBuilder); result._synchronizationContext = current; return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] [DebuggerStepThrough] public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { AsyncMethodBuilderCore.Start(ref stateMachine); } public void SetStateMachine(IAsyncStateMachine stateMachine) { _builder.SetStateMachine(stateMachine); } public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { _builder.AwaitOnCompleted(ref awaiter, ref stateMachine); } public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { _builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine); } public void SetResult() { if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(Task.Id, AsyncCausalityStatus.Completed); } _builder.SetResult(); if (_synchronizationContext != null) { NotifySynchronizationContextOfCompletion(); } } public void SetException(Exception exception) { if (exception == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); } if (TplEventSource.Log.IsEnabled()) { TplEventSource.Log.TraceOperationEnd(Task.Id, AsyncCausalityStatus.Error); } if (_synchronizationContext != null) { try { System.Threading.Tasks.Task.ThrowAsync(exception, _synchronizationContext); } finally { NotifySynchronizationContextOfCompletion(); } } else { System.Threading.Tasks.Task.ThrowAsync(exception, null); } _builder.SetResult(); } private void NotifySynchronizationContextOfCompletion() { try { _synchronizationContext.OperationCompleted(); } catch (Exception exception) { System.Threading.Tasks.Task.ThrowAsync(exception, null); } } } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] public sealed class CallerArgumentExpressionAttribute : Attribute { public string ParameterName { get; } public CallerArgumentExpressionAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] public sealed class CallerFilePathAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] public sealed class CallerLineNumberAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] public sealed class CallerMemberNameAttribute : Attribute { } public class CallConvCdecl { } public class CallConvFastcall { } public class CallConvStdcall { } public class CallConvSuppressGCTransition { } public class CallConvThiscall { } public class CallConvMemberFunction { } [Flags] public enum CompilationRelaxations { NoStringInterning = 8 } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Method)] public class CompilationRelaxationsAttribute : Attribute { public int CompilationRelaxations { get; } public CompilationRelaxationsAttribute(int relaxations) { CompilationRelaxations = relaxations; } public CompilationRelaxationsAttribute(CompilationRelaxations relaxations) { CompilationRelaxations = (int)relaxations; } } [AttributeUsage(AttributeTargets.All, Inherited = true)] public sealed class CompilerGeneratedAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class)] public class CompilerGlobalScopeAttribute : Attribute { } public sealed class ConditionalWeakTable : IEnumerable>, System.Collections.IEnumerable where TKey : class where TValue : class? { public delegate TValue CreateValueCallback(TKey key); private sealed class Enumerator : IEnumerator>, IDisposable, System.Collections.IEnumerator { private ConditionalWeakTable _table; private readonly int _maxIndexInclusive; private int _currentIndex; private KeyValuePair _current; public KeyValuePair Current { get { if (_currentIndex < 0) { ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen(); } return _current; } } object System.Collections.IEnumerator.Current => Current; public Enumerator(ConditionalWeakTable table) { _table = table; table._activeEnumeratorRefCount++; _maxIndexInclusive = table._container.FirstFreeEntry - 1; _currentIndex = -1; } ~Enumerator() { Dispose(); } public void Dispose() { ConditionalWeakTable conditionalWeakTable = Interlocked.Exchange(ref _table, null); if (conditionalWeakTable != null) { _current = default(KeyValuePair); lock (conditionalWeakTable._lock) { conditionalWeakTable._activeEnumeratorRefCount--; } GC.SuppressFinalize(this); } } public bool MoveNext() { ConditionalWeakTable table = _table; if (table != null) { lock (table._lock) { Container container = table._container; if (container != null) { while (_currentIndex < _maxIndexInclusive) { _currentIndex++; if (container.TryGetEntry(_currentIndex, out var key, out var value)) { _current = new KeyValuePair(key, value); return true; } } } } } return false; } public void Reset() { } } private struct Entry { public DependentHandle depHnd; public int HashCode; public int Next; } private sealed class Container { private readonly ConditionalWeakTable _parent; private int[] _buckets; private Entry[] _entries; private int _firstFreeEntry; private bool _invalid; private bool _finalized; private volatile object _oldKeepAlive; internal bool HasCapacity => _firstFreeEntry < _entries.Length; internal int FirstFreeEntry => _firstFreeEntry; internal Container(ConditionalWeakTable parent) { _buckets = new int[8]; for (int i = 0; i < _buckets.Length; i++) { _buckets[i] = -1; } _entries = new Entry[8]; _parent = parent; } private Container(ConditionalWeakTable parent, int[] buckets, Entry[] entries, int firstFreeEntry) { _parent = parent; _buckets = buckets; _entries = entries; _firstFreeEntry = firstFreeEntry; } internal void CreateEntryNoResize(TKey key, TValue value) { VerifyIntegrity(); _invalid = true; int num = RuntimeHelpers.GetHashCode(key) & 0x7FFFFFFF; int num2 = _firstFreeEntry++; _entries[num2].HashCode = num; _entries[num2].depHnd = new DependentHandle(key, value); int num3 = num & (_buckets.Length - 1); _entries[num2].Next = _buckets[num3]; Volatile.Write(ref _buckets[num3], num2); _invalid = false; } internal bool TryGetValueWorker(TKey key, [MaybeNullWhen(false)] out TValue value) { object value2; int num = FindEntry(key, out value2); value = Unsafe.As(value2); return num != -1; } internal int FindEntry(TKey key, out object value) { int num = RuntimeHelpers.GetHashCode(key) & 0x7FFFFFFF; int num2 = num & (_buckets.Length - 1); for (int num3 = Volatile.Read(ref _buckets[num2]); num3 != -1; num3 = _entries[num3].Next) { if (_entries[num3].HashCode == num && _entries[num3].depHnd.UnsafeGetTargetAndDependent(out value) == key) { GC.KeepAlive(this); return num3; } } GC.KeepAlive(this); value = null; return -1; } internal bool TryGetEntry(int index, [NotNullWhen(true)] out TKey key, [MaybeNullWhen(false)] out TValue value) { if (index < _entries.Length) { object dependent; object obj = _entries[index].depHnd.UnsafeGetTargetAndDependent(out dependent); GC.KeepAlive(this); if (obj != null) { key = Unsafe.As(obj); value = Unsafe.As(dependent); return true; } } key = null; value = null; return false; } internal void RemoveAllKeys() { for (int i = 0; i < _firstFreeEntry; i++) { RemoveIndex(i); } } internal bool Remove(TKey key) { VerifyIntegrity(); object value; int num = FindEntry(key, out value); if (num != -1) { RemoveIndex(num); return true; } return false; } private void RemoveIndex(int entryIndex) { ref Entry reference = ref _entries[entryIndex]; Volatile.Write(ref reference.HashCode, -1); reference.depHnd.UnsafeSetTargetToNull(); } internal void UpdateValue(int entryIndex, TValue newValue) { VerifyIntegrity(); _invalid = true; _entries[entryIndex].depHnd.UnsafeSetDependent(newValue); _invalid = false; } internal Container Resize() { bool flag = false; int newSize = _buckets.Length; if (_parent == null || _parent._activeEnumeratorRefCount == 0) { for (int i = 0; i < _entries.Length; i++) { ref Entry reference = ref _entries[i]; if (reference.HashCode == -1) { flag = true; break; } if (reference.depHnd.IsAllocated && reference.depHnd.UnsafeGetTarget() == null) { flag = true; break; } } } if (!flag) { newSize = _buckets.Length * 2; } return Resize(newSize); } internal Container Resize(int newSize) { int[] array = new int[newSize]; for (int i = 0; i < array.Length; i++) { array[i] = -1; } Entry[] array2 = new Entry[newSize]; int j = 0; bool flag = _parent != null && _parent._activeEnumeratorRefCount > 0; if (flag) { for (; j < _entries.Length; j++) { ref Entry reference = ref _entries[j]; ref Entry reference2 = ref array2[j]; int num = (reference2.HashCode = reference.HashCode); reference2.depHnd = reference.depHnd; int num2 = num & (array.Length - 1); reference2.Next = array[num2]; array[num2] = j; } } else { for (int k = 0; k < _entries.Length; k++) { ref Entry reference3 = ref _entries[k]; int hashCode = reference3.HashCode; DependentHandle depHnd = reference3.depHnd; if (hashCode != -1 && depHnd.IsAllocated) { if (depHnd.UnsafeGetTarget() != null) { ref Entry reference4 = ref array2[j]; reference4.HashCode = hashCode; reference4.depHnd = depHnd; int num3 = hashCode & (array.Length - 1); reference4.Next = array[num3]; array[num3] = j; j++; } else { Volatile.Write(ref reference3.HashCode, -1); } } } } Container container = new Container(_parent, array, array2, j); if (flag) { GC.SuppressFinalize(this); } _oldKeepAlive = container; GC.KeepAlive(this); return container; } private void VerifyIntegrity() { if (_invalid) { throw new InvalidOperationException(SR.InvalidOperation_CollectionCorrupted); } } ~Container() { if (_invalid || _parent == null) { return; } if (!_finalized) { _finalized = true; lock (_parent._lock) { if (_parent._container == this) { _parent._container = null; } } GC.ReRegisterForFinalize(this); return; } Entry[] entries = _entries; _invalid = true; _entries = null; _buckets = null; if (entries == null) { return; } int i = 0; for (; i < entries.Length; i++) { if (_oldKeepAlive == null || entries[i].HashCode == -1) { entries[i].depHnd.Dispose(); } } } } private readonly object _lock; private volatile Container _container; private int _activeEnumeratorRefCount; public ConditionalWeakTable() { _lock = new object(); _container = new Container(this); } public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } return _container.TryGetValueWorker(key, out value); } public void Add(TKey key, TValue value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } lock (_lock) { object value2; int num = _container.FindEntry(key, out value2); if (num != -1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); } CreateEntry(key, value); } } public void AddOrUpdate(TKey key, TValue value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } lock (_lock) { object value2; int num = _container.FindEntry(key, out value2); if (num != -1) { _container.UpdateValue(num, value); } else { CreateEntry(key, value); } } } public bool Remove(TKey key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } lock (_lock) { return _container.Remove(key); } } public void Clear() { lock (_lock) { if (_activeEnumeratorRefCount > 0) { _container.RemoveAllKeys(); } else { _container = new Container(this); } } } public TValue GetValue(TKey key, CreateValueCallback createValueCallback) { if (createValueCallback == null) { throw new ArgumentNullException("createValueCallback"); } if (!TryGetValue(key, out var value)) { return GetValueLocked(key, createValueCallback); } return value; } private TValue GetValueLocked(TKey key, CreateValueCallback createValueCallback) { TValue val = createValueCallback(key); lock (_lock) { if (_container.TryGetValueWorker(key, out var value)) { return value; } CreateEntry(key, val); return val; } } public TValue GetOrCreateValue(TKey key) { return GetValue(key, (TKey _) => Activator.CreateInstance()); } IEnumerator> IEnumerable>.GetEnumerator() { lock (_lock) { Container container = _container; IEnumerator> result; if (container != null && container.FirstFreeEntry != 0) { IEnumerator> enumerator = new Enumerator(this); result = enumerator; } else { result = ((IEnumerable>)Array.Empty>()).GetEnumerator(); } return result; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable>)this).GetEnumerator(); } private void CreateEntry(TKey key, TValue value) { Container container = _container; if (!container.HasCapacity) { container = (_container = container.Resize()); } container.CreateEntryNoResize(key, value); } } [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 { [StructLayout(LayoutKind.Auto)] public readonly struct Enumerator { private readonly IAsyncEnumerator _enumerator; private readonly bool _continueOnCapturedContext; public T Current => _enumerator.Current; internal Enumerator(IAsyncEnumerator enumerator, bool continueOnCapturedContext) { _enumerator = enumerator; _continueOnCapturedContext = continueOnCapturedContext; } public ConfiguredValueTaskAwaitable MoveNextAsync() { return _enumerator.MoveNextAsync().ConfigureAwait(_continueOnCapturedContext); } public ConfiguredValueTaskAwaitable DisposeAsync() { return _enumerator.DisposeAsync().ConfigureAwait(_continueOnCapturedContext); } } private readonly IAsyncEnumerable _enumerable; private readonly CancellationToken _cancellationToken; private readonly bool _continueOnCapturedContext; internal ConfiguredCancelableAsyncEnumerable(IAsyncEnumerable enumerable, bool continueOnCapturedContext, CancellationToken cancellationToken) { _enumerable = enumerable; _continueOnCapturedContext = continueOnCapturedContext; _cancellationToken = cancellationToken; } public ConfiguredCancelableAsyncEnumerable ConfigureAwait(bool continueOnCapturedContext) { return new ConfiguredCancelableAsyncEnumerable(_enumerable, continueOnCapturedContext, _cancellationToken); } public ConfiguredCancelableAsyncEnumerable WithCancellation(CancellationToken cancellationToken) { return new ConfiguredCancelableAsyncEnumerable(_enumerable, _continueOnCapturedContext, cancellationToken); } public Enumerator GetAsyncEnumerator() { return new Enumerator(_enumerable.GetAsyncEnumerator(_cancellationToken), _continueOnCapturedContext); } } [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaitable { [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion, IStateMachineBoxAwareAwaiter { private readonly ValueTask _value; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _value.IsCompleted; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaiter(in ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void GetResult() { _value.ThrowIfCompletedUnsuccessfully(); } public void OnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None)); } else { Task.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } } public void UnsafeOnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { Task.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } } void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { object obj = _value._obj; if (obj is Task task) { TaskAwaiter.UnsafeOnCompletedInternal(task, box, _value._continueOnCapturedContext); } else if (obj != null) { Unsafe.As(obj).OnCompleted(ThreadPool.s_invokeAsyncStateMachineBox, box, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, _value._continueOnCapturedContext); } } } private readonly ValueTask _value; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaitable(in ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaiter GetAwaiter() { return new ConfiguredValueTaskAwaiter(in _value); } } [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaitable { [StructLayout(LayoutKind.Auto)] public readonly struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion, IStateMachineBoxAwareAwaiter { private readonly ValueTask _value; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _value.IsCompleted; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaiter(in ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public TResult GetResult() { return _value.Result; } public void OnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.FlowExecutionContext | (_value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None)); } else { Task.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().OnCompleted(continuation); } } public void UnsafeOnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { Task.CompletedTask.ConfigureAwait(_value._continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation); } } void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { object obj = _value._obj; if (obj is Task task) { TaskAwaiter.UnsafeOnCompletedInternal(task, box, _value._continueOnCapturedContext); } else if (obj != null) { Unsafe.As>(obj).OnCompleted(ThreadPool.s_invokeAsyncStateMachineBox, box, _value._token, _value._continueOnCapturedContext ? ValueTaskSourceOnCompletedFlags.UseSchedulingContext : ValueTaskSourceOnCompletedFlags.None); } else { TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, _value._continueOnCapturedContext); } } } private readonly ValueTask _value; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ConfiguredValueTaskAwaitable(in ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public ConfiguredValueTaskAwaiter GetAwaiter() { return new ConfiguredValueTaskAwaiter(in _value); } } public static class ContractHelper { internal static event EventHandler? InternalContractFailed; [DebuggerNonUserCode] public static string? RaiseContractFailedEvent(ContractFailureKind failureKind, string? userMessage, string? conditionText, Exception? innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), "failureKind"); } string text = "contract failed."; ContractFailedEventArgs contractFailedEventArgs = null; string result; try { text = GetDisplayMessage(failureKind, userMessage, conditionText); EventHandler internalContractFailed = ContractHelper.InternalContractFailed; if (internalContractFailed != null) { contractFailedEventArgs = new ContractFailedEventArgs(failureKind, text, conditionText, innerException); Delegate[] invocationList = internalContractFailed.GetInvocationList(); for (int i = 0; i < invocationList.Length; i++) { EventHandler eventHandler = (EventHandler)invocationList[i]; try { eventHandler(null, contractFailedEventArgs); } catch (Exception thrownDuringHandler) { contractFailedEventArgs.thrownDuringHandler = thrownDuringHandler; contractFailedEventArgs.SetUnwind(); } } if (contractFailedEventArgs.Unwind) { if (innerException == null) { innerException = contractFailedEventArgs.thrownDuringHandler; } throw new ContractException(failureKind, text, userMessage, conditionText, innerException); } } } finally { result = ((contractFailedEventArgs == null || !contractFailedEventArgs.Handled) ? text : null); } return result; } [DebuggerNonUserCode] public static void TriggerFailure(ContractFailureKind kind, string? displayMessage, string? userMessage, string? conditionText, Exception? innerException) { if (string.IsNullOrEmpty(displayMessage)) { displayMessage = GetDisplayMessage(kind, userMessage, conditionText); } Debug.ContractFailure(displayMessage, string.Empty, GetFailureMessage(kind, null)); } private static string GetFailureMessage(ContractFailureKind failureKind, string conditionText) { bool flag = !string.IsNullOrEmpty(conditionText); switch (failureKind) { case ContractFailureKind.Assert: if (!flag) { return SR.AssertionFailed; } return SR.Format(SR.AssertionFailed_Cnd, conditionText); case ContractFailureKind.Assume: if (!flag) { return SR.AssumptionFailed; } return SR.Format(SR.AssumptionFailed_Cnd, conditionText); case ContractFailureKind.Precondition: if (!flag) { return SR.PreconditionFailed; } return SR.Format(SR.PreconditionFailed_Cnd, conditionText); case ContractFailureKind.Postcondition: if (!flag) { return SR.PostconditionFailed; } return SR.Format(SR.PostconditionFailed_Cnd, conditionText); case ContractFailureKind.Invariant: if (!flag) { return SR.InvariantFailed; } return SR.Format(SR.InvariantFailed_Cnd, conditionText); case ContractFailureKind.PostconditionOnException: if (!flag) { return SR.PostconditionOnExceptionFailed; } return SR.Format(SR.PostconditionOnExceptionFailed_Cnd, conditionText); default: Contract.Assume(condition: false, "Unreachable code"); return SR.AssumptionFailed; } } private static string GetDisplayMessage(ContractFailureKind failureKind, string userMessage, string conditionText) { string text = (string.IsNullOrEmpty(conditionText) ? "" : GetFailureMessage(failureKind, conditionText)); if (!string.IsNullOrEmpty(userMessage)) { return text + " " + userMessage; } return text; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false)] public sealed class CreateNewOnMetadataUpdateAttribute : Attribute { } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public abstract class CustomConstantAttribute : Attribute { public abstract object? Value { get; } } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public sealed class DateTimeConstantAttribute : CustomConstantAttribute { private readonly DateTime _date; public override object Value => _date; public DateTimeConstantAttribute(long ticks) { _date = new DateTime(ticks); } } [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] public sealed class DecimalConstantAttribute : Attribute { private readonly decimal _dec; public decimal Value => _dec; [CLSCompliant(false)] public DecimalConstantAttribute(byte scale, byte sign, uint hi, uint mid, uint low) { _dec = new decimal((int)low, (int)mid, (int)hi, sign != 0, scale); } public DecimalConstantAttribute(byte scale, byte sign, int hi, int mid, int low) { _dec = new decimal(low, mid, hi, sign != 0, scale); } } [AttributeUsage(AttributeTargets.Assembly)] public sealed class DefaultDependencyAttribute : Attribute { public LoadHint LoadHint { get; } public DefaultDependencyAttribute(LoadHint loadHintArgument) { LoadHint = loadHintArgument; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class DependencyAttribute : Attribute { public string DependentAssembly { get; } public LoadHint LoadHint { get; } public DependencyAttribute(string dependentAssemblyArgument, LoadHint loadHintArgument) { DependentAssembly = dependentAssemblyArgument; LoadHint = loadHintArgument; } } [Obsolete("DisablePrivateReflectionAttribute has no effect in .NET 6.0+.", DiagnosticId = "SYSLIB0015", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] public sealed class DisablePrivateReflectionAttribute : Attribute { } [AttributeUsage(AttributeTargets.All)] public class DiscardableAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] public sealed class EnumeratorCancellationAttribute : Attribute { } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)] public sealed class ExtensionAttribute : Attribute { } [AttributeUsage(AttributeTargets.Field)] public sealed class FixedAddressValueTypeAttribute : Attribute { } [AttributeUsage(AttributeTargets.Field, Inherited = false)] public sealed class FixedBufferAttribute : Attribute { public Type ElementType { get; } public int Length { get; } public FixedBufferAttribute(Type elementType, int length) { ElementType = elementType; Length = length; } } public static class FormattableStringFactory { private sealed class ConcreteFormattableString : FormattableString { private readonly string _format; private readonly object[] _arguments; public override string Format => _format; public override int ArgumentCount => _arguments.Length; internal ConcreteFormattableString(string format, object[] arguments) { _format = format; _arguments = arguments; } public override object[] GetArguments() { return _arguments; } public override object GetArgument(int index) { return _arguments[index]; } public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, _format, _arguments); } } public static FormattableString Create(string format, params object?[] arguments) { if (format == null) { throw new ArgumentNullException("format"); } if (arguments == null) { throw new ArgumentNullException("arguments"); } return new ConcreteFormattableString(format, arguments); } } public interface IAsyncStateMachine { void MoveNext(); void SetStateMachine(IAsyncStateMachine stateMachine); } internal interface IAsyncStateMachineBox { Action MoveNextAction { get; } void MoveNext(); IAsyncStateMachine GetStateMachineObject(); void ClearStateUponCompletion(); } public interface ICastable { bool IsInstanceOfInterface(RuntimeTypeHandle interfaceType, [NotNullWhen(true)] out Exception? castError); RuntimeTypeHandle GetImplType(RuntimeTypeHandle interfaceType); } [AttributeUsage(AttributeTargets.Property, Inherited = true)] public sealed class IndexerNameAttribute : Attribute { public IndexerNameAttribute(string indexerName) { } } public interface INotifyCompletion { void OnCompleted(Action continuation); } public interface ICriticalNotifyCompletion : INotifyCompletion { void UnsafeOnCompleted(Action continuation); } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] public sealed class InternalsVisibleToAttribute : Attribute { public string AssemblyName { get; } public bool AllInternalsVisible { get; set; } = true; public InternalsVisibleToAttribute(string assemblyName) { AssemblyName = assemblyName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, Inherited = false)] internal sealed class IntrinsicAttribute : Attribute { } [EditorBrowsable(EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.Struct)] public sealed class IsByRefLikeAttribute : Attribute { } public static class IsConst { } [EditorBrowsable(EditorBrowsableState.Never)] [AttributeUsage(AttributeTargets.All, Inherited = false)] public sealed class IsReadOnlyAttribute : Attribute { } public static class IsVolatile { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] public sealed class InterpolatedStringHandlerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] public sealed class InterpolatedStringHandlerArgumentAttribute : Attribute { public string[] Arguments { get; } public InterpolatedStringHandlerArgumentAttribute(string argument) { Arguments = new string[1] { argument }; } public InterpolatedStringHandlerArgumentAttribute(params string[] arguments) { Arguments = arguments; } } [InterpolatedStringHandler] public ref struct DefaultInterpolatedStringHandler { private readonly IFormatProvider _provider; private char[] _arrayToReturnToPool; private Span _chars; private int _pos; private readonly bool _hasCustomFormatter; internal ReadOnlySpan Text => _chars.Slice(0, _pos); public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _provider = null; _chars = (_arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount))); _pos = 0; _hasCustomFormatter = false; } public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider) { _provider = provider; _chars = (_arrayToReturnToPool = ArrayPool.Shared.Rent(GetDefaultLength(literalLength, formattedCount))); _pos = 0; _hasCustomFormatter = provider != null && HasCustomFormatter(provider); } public DefaultInterpolatedStringHandler(int literalLength, int formattedCount, IFormatProvider? provider, Span initialBuffer) { _provider = provider; _chars = initialBuffer; _arrayToReturnToPool = null; _pos = 0; _hasCustomFormatter = provider != null && HasCustomFormatter(provider); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static int GetDefaultLength(int literalLength, int formattedCount) { return Math.Max(256, literalLength + formattedCount * 11); } public override string ToString() { return new string(Text); } public string ToStringAndClear() { string result = new string(Text); Clear(); return result; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void Clear() { char[] arrayToReturnToPool = _arrayToReturnToPool; this = default(DefaultInterpolatedStringHandler); if (arrayToReturnToPool != null) { ArrayPool.Shared.Return(arrayToReturnToPool); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AppendLiteral(string value) { if (value.Length == 1) { Span chars = _chars; int pos = _pos; if ((uint)pos < (uint)chars.Length) { chars[pos] = value[0]; _pos = pos + 1; } else { GrowThenCopyString(value); } } else if (value.Length == 2) { Span chars2 = _chars; int pos2 = _pos; if ((uint)pos2 < chars2.Length - 1) { Unsafe.WriteUnaligned(ref Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetReference(chars2), pos2)), Unsafe.ReadUnaligned(ref Unsafe.As(ref value.GetRawStringData()))); _pos = pos2 + 2; } else { GrowThenCopyString(value); } } else { AppendStringDirect(value); } } private void AppendStringDirect(string value) { if (value.TryCopyTo(_chars.Slice(_pos))) { _pos += value.Length; } else { GrowThenCopyString(value); } } public void AppendFormatted(T value) { if (_hasCustomFormatter) { AppendCustomFormatter(value, null); return; } string text; if (value is IFormattable) { if (value is ISpanFormattable) { int charsWritten; while (!((ISpanFormattable)(object)value).TryFormat(_chars.Slice(_pos), out charsWritten, default(ReadOnlySpan), _provider)) { Grow(); } _pos += charsWritten; return; } text = ((IFormattable)(object)value).ToString(null, _provider); } else { text = value?.ToString(); } if (text != null) { AppendStringDirect(text); } } public void AppendFormatted(T value, string? format) { if (_hasCustomFormatter) { AppendCustomFormatter(value, format); return; } string text; if (value is IFormattable) { if (value is ISpanFormattable) { int charsWritten; while (!((ISpanFormattable)(object)value).TryFormat(_chars.Slice(_pos), out charsWritten, format, _provider)) { Grow(); } _pos += charsWritten; return; } text = ((IFormattable)(object)value).ToString(format, _provider); } else { text = value?.ToString(); } if (text != null) { AppendStringDirect(text); } } public void AppendFormatted(T value, int alignment) { int pos = _pos; AppendFormatted(value); if (alignment != 0) { AppendOrInsertAlignmentIfNeeded(pos, alignment); } } public void AppendFormatted(T value, int alignment, string? format) { int pos = _pos; AppendFormatted(value, format); if (alignment != 0) { AppendOrInsertAlignmentIfNeeded(pos, alignment); } } public void AppendFormatted(ReadOnlySpan value) { if (value.TryCopyTo(_chars.Slice(_pos))) { _pos += value.Length; } else { GrowThenCopySpan(value); } } public void AppendFormatted(ReadOnlySpan value, int alignment = 0, string? format = null) { bool flag = false; if (alignment < 0) { flag = true; alignment = -alignment; } int num = alignment - value.Length; if (num <= 0) { AppendFormatted(value); return; } EnsureCapacityForAdditionalChars(value.Length + num); if (flag) { value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; _chars.Slice(_pos, num).Fill(' '); _pos += num; } else { _chars.Slice(_pos, num).Fill(' '); _pos += num; value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } } public void AppendFormatted(string? value) { if (!_hasCustomFormatter && value != null && value.TryCopyTo(_chars.Slice(_pos))) { _pos += value.Length; } else { AppendFormattedSlow(value); } } [MethodImpl(MethodImplOptions.NoInlining)] private void AppendFormattedSlow(string value) { if (_hasCustomFormatter) { AppendCustomFormatter(value, null); } else if (value != null) { EnsureCapacityForAdditionalChars(value.Length); value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } } public void AppendFormatted(string? value, int alignment = 0, string? format = null) { this.AppendFormatted(value, alignment, format); } public void AppendFormatted(object? value, int alignment = 0, string? format = null) { this.AppendFormatted(value, alignment, format); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool HasCustomFormatter(IFormatProvider provider) { if (provider.GetType() != typeof(CultureInfo)) { return provider.GetFormat(typeof(ICustomFormatter)) != null; } return false; } [MethodImpl(MethodImplOptions.NoInlining)] private void AppendCustomFormatter(T value, string format) { ICustomFormatter customFormatter = (ICustomFormatter)_provider.GetFormat(typeof(ICustomFormatter)); if (customFormatter != null) { string text = customFormatter.Format(format, value, _provider); if (text != null) { AppendStringDirect(text); } } } private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment) { int num = _pos - startingPos; bool flag = false; if (alignment < 0) { flag = true; alignment = -alignment; } int num2 = alignment - num; if (num2 > 0) { EnsureCapacityForAdditionalChars(num2); if (flag) { _chars.Slice(_pos, num2).Fill(' '); } else { _chars.Slice(startingPos, num).CopyTo(_chars.Slice(startingPos + num2)); _chars.Slice(startingPos, num2).Fill(' '); } _pos += num2; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void EnsureCapacityForAdditionalChars(int additionalChars) { if (_chars.Length - _pos < additionalChars) { Grow(additionalChars); } } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowThenCopyString(string value) { Grow(value.Length); value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(MethodImplOptions.NoInlining)] private void GrowThenCopySpan(ReadOnlySpan value) { Grow(value.Length); value.CopyTo(_chars.Slice(_pos)); _pos += value.Length; } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow(int additionalChars) { GrowCore((uint)(_pos + additionalChars)); } [MethodImpl(MethodImplOptions.NoInlining)] private void Grow() { GrowCore((uint)(_chars.Length + 1)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void GrowCore(uint requiredMinCapacity) { uint value = Math.Max(requiredMinCapacity, Math.Min((uint)(_chars.Length * 2), 1073741791u)); int minimumLength = (int)Math.Clamp(value, 256u, 2147483647u); char[] array = ArrayPool.Shared.Rent(minimumLength); _chars.Slice(0, _pos).CopyTo(array); char[] arrayToReturnToPool = _arrayToReturnToPool; _chars = (_arrayToReturnToPool = array); if (arrayToReturnToPool != null) { ArrayPool.Shared.Return(arrayToReturnToPool); } } } [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] public sealed class IteratorStateMachineAttribute : StateMachineAttribute { public IteratorStateMachineAttribute(Type stateMachineType) : base(stateMachineType) { } } public interface ITuple { int Length { get; } object? this[int index] { get; } } public enum LoadHint { Default, Always, Sometimes } public enum MethodCodeType { IL, Native, OPTIL, Runtime } [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)] public sealed class MethodImplAttribute : Attribute { public MethodCodeType MethodCodeType; public MethodImplOptions Value { get; } public MethodImplAttribute(MethodImplOptions methodImplOptions) { Value = methodImplOptions; } public MethodImplAttribute(short value) { Value = (MethodImplOptions)value; } public MethodImplAttribute() { } } [Flags] public enum MethodImplOptions { Unmanaged = 4, NoInlining = 8, ForwardRef = 0x10, Synchronized = 0x20, NoOptimization = 0x40, PreserveSig = 0x80, AggressiveInlining = 0x100, AggressiveOptimization = 0x200, InternalCall = 0x1000 } [AttributeUsage(AttributeTargets.Method, Inherited = false)] public sealed class ModuleInitializerAttribute : Attribute { } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public sealed class ReferenceAssemblyAttribute : Attribute { public string? Description { get; } public ReferenceAssemblyAttribute() { } public ReferenceAssemblyAttribute(string? description) { Description = description; } } [StructLayout(LayoutKind.Auto)] public struct PoolingAsyncValueTaskMethodBuilder { private static readonly PoolingAsyncValueTaskMethodBuilder.StateMachineBox s_syncSuccessSentinel = PoolingAsyncValueTaskMethodBuilder.s_syncSuccessSentinel; private PoolingAsyncValueTaskMethodBuilder.StateMachineBox m_task; public ValueTask Task { get { if (m_task == s_syncSuccessSentinel) { return default(ValueTask); } PoolingAsyncValueTaskMethodBuilder.StateMachineBox stateMachineBox = m_task ?? (m_task = PoolingAsyncValueTaskMethodBuilder.CreateWeaklyTypedStateMachineBox()); return new ValueTask(stateMachineBox, stateMachineBox.Version); } } public static PoolingAsyncValueTaskMethodBuilder Create() { return default(PoolingAsyncValueTaskMethodBuilder); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { AsyncMethodBuilderCore.Start(ref stateMachine); } public void SetStateMachine(IAsyncStateMachine stateMachine) { AsyncMethodBuilderCore.SetStateMachine(stateMachine, null); } public void SetResult() { if (m_task == null) { m_task = s_syncSuccessSentinel; } else { m_task.SetResult(default(VoidTaskResult)); } } public void SetException(Exception exception) { PoolingAsyncValueTaskMethodBuilder.SetException(exception, ref m_task); } public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { PoolingAsyncValueTaskMethodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine, ref m_task); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { PoolingAsyncValueTaskMethodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine, ref m_task); } } [StructLayout(LayoutKind.Auto)] public struct PoolingAsyncValueTaskMethodBuilder { internal abstract class StateMachineBox : IValueTaskSource, IValueTaskSource { protected Action _moveNextAction; public ExecutionContext Context; protected ManualResetValueTaskSourceCore _valueTaskSource; public short Version => _valueTaskSource.Version; public void SetResult(TResult result) { _valueTaskSource.SetResult(result); } public void SetException(Exception error) { _valueTaskSource.SetException(error); } public ValueTaskSourceStatus GetStatus(short token) { return _valueTaskSource.GetStatus(token); } public void OnCompleted(Action continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags) { _valueTaskSource.OnCompleted(continuation, state, token, flags); } TResult IValueTaskSource.GetResult(short token) { throw NotImplemented.ByDesign; } void IValueTaskSource.GetResult(short token) { throw NotImplemented.ByDesign; } } private sealed class SyncSuccessSentinelStateMachineBox : StateMachineBox { public SyncSuccessSentinelStateMachineBox() { SetResult(default(TResult)); } } private sealed class StateMachineBox : StateMachineBox, IValueTaskSource, IValueTaskSource, IAsyncStateMachineBox, IThreadPoolWorkItem where TStateMachine : IAsyncStateMachine { private static readonly ContextCallback s_callback = ExecutionContextCallback; private static readonly PaddedReference[] s_perCoreCache = new PaddedReference[Environment.ProcessorCount]; [ThreadStatic] private static StateMachineBox t_tlsCache; public TStateMachine StateMachine; private static ref StateMachineBox PerCoreCacheSlot { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { int num = (int)((uint)Thread.GetCurrentProcessorId() % (uint)Environment.ProcessorCount); return ref Unsafe.As>(ref s_perCoreCache[num].Object); } } public Action MoveNextAction => _moveNextAction ?? (_moveNextAction = MoveNext); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static StateMachineBox RentFromCache() { StateMachineBox stateMachineBox = t_tlsCache; if (stateMachineBox != null) { t_tlsCache = null; } else { ref StateMachineBox perCoreCacheSlot = ref PerCoreCacheSlot; if (perCoreCacheSlot == null || (stateMachineBox = Interlocked.Exchange(ref perCoreCacheSlot, null)) == null) { stateMachineBox = new StateMachineBox(); } } return stateMachineBox; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void ReturnToCache() { ClearStateUponCompletion(); _valueTaskSource.Reset(); if (t_tlsCache == null) { t_tlsCache = this; return; } ref StateMachineBox perCoreCacheSlot = ref PerCoreCacheSlot; if (perCoreCacheSlot == null) { Volatile.Write(ref perCoreCacheSlot, this); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void ClearStateUponCompletion() { StateMachine = default(TStateMachine); Context = null; } private static void ExecutionContextCallback(object s) { Unsafe.As>(s).StateMachine.MoveNext(); } void IThreadPoolWorkItem.Execute() { MoveNext(); } public void MoveNext() { ExecutionContext context = Context; if (context == null) { StateMachine.MoveNext(); } else { ExecutionContext.RunInternal(context, s_callback, this); } } TResult IValueTaskSource.GetResult(short token) { try { return _valueTaskSource.GetResult(token); } finally { ReturnToCache(); } } void IValueTaskSource.GetResult(short token) { try { _valueTaskSource.GetResult(token); } finally { ReturnToCache(); } } IAsyncStateMachine IAsyncStateMachineBox.GetStateMachineObject() { return StateMachine; } } internal static readonly StateMachineBox s_syncSuccessSentinel = new SyncSuccessSentinelStateMachineBox(); private StateMachineBox m_task; private TResult _result; public ValueTask Task { get { if (m_task == s_syncSuccessSentinel) { return new ValueTask(_result); } StateMachineBox stateMachineBox = m_task ?? (m_task = CreateWeaklyTypedStateMachineBox()); return new ValueTask(stateMachineBox, stateMachineBox.Version); } } public static PoolingAsyncValueTaskMethodBuilder Create() { return default(PoolingAsyncValueTaskMethodBuilder); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Start(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { AsyncMethodBuilderCore.Start(ref stateMachine); } public void SetStateMachine(IAsyncStateMachine stateMachine) { AsyncMethodBuilderCore.SetStateMachine(stateMachine, null); } public void SetResult(TResult result) { if (m_task == null) { _result = result; m_task = s_syncSuccessSentinel; } else { m_task.SetResult(result); } } public void SetException(Exception exception) { SetException(exception, ref m_task); } internal static void SetException(Exception exception, [NotNull] ref StateMachineBox boxFieldRef) { if (exception == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.exception); } (boxFieldRef ?? (boxFieldRef = CreateWeaklyTypedStateMachineBox())).SetException(exception); } public void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { AwaitOnCompleted(ref awaiter, ref stateMachine, ref m_task); } internal static void AwaitOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine, ref StateMachineBox box) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { try { awaiter.OnCompleted(GetStateMachineBox(ref stateMachine, ref box).MoveNextAction); } catch (Exception exception) { System.Threading.Tasks.Task.ThrowAsync(exception, null); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine, ref m_task); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void AwaitUnsafeOnCompleted(ref TAwaiter awaiter, ref TStateMachine stateMachine, [NotNull] ref StateMachineBox boxRef) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { IAsyncStateMachineBox stateMachineBox = GetStateMachineBox(ref stateMachine, ref boxRef); AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted(ref awaiter, stateMachineBox); } private static IAsyncStateMachineBox GetStateMachineBox(ref TStateMachine stateMachine, [NotNull] ref StateMachineBox boxFieldRef) where TStateMachine : IAsyncStateMachine { ExecutionContext executionContext = ExecutionContext.Capture(); if (boxFieldRef is StateMachineBox stateMachineBox) { if (stateMachineBox.Context != executionContext) { stateMachineBox.Context = executionContext; } return stateMachineBox; } if (boxFieldRef is StateMachineBox stateMachineBox2) { if (stateMachineBox2.StateMachine == null) { Debugger.NotifyOfCrossThreadDependency(); stateMachineBox2.StateMachine = stateMachine; } stateMachineBox2.Context = executionContext; return stateMachineBox2; } Debugger.NotifyOfCrossThreadDependency(); StateMachineBox stateMachineBox3 = (StateMachineBox)(boxFieldRef = StateMachineBox.RentFromCache()); stateMachineBox3.StateMachine = stateMachine; stateMachineBox3.Context = executionContext; return stateMachineBox3; } internal static StateMachineBox CreateWeaklyTypedStateMachineBox() { return new StateMachineBox(); } } [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class PreserveBaseOverridesAttribute : Attribute { } [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] public sealed class RuntimeCompatibilityAttribute : Attribute { public bool WrapNonExceptionThrows { get; set; } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class RuntimeWrappedException : Exception { private object _wrappedException; public object WrappedException => _wrappedException; public RuntimeWrappedException(object thrownObject) : base(SR.RuntimeWrappedException) { base.HResult = -2146233026; _wrappedException = thrownObject; } private RuntimeWrappedException(SerializationInfo info, StreamingContext context) : base(info, context) { _wrappedException = info.GetValue("WrappedException", typeof(object)); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("WrappedException", _wrappedException, typeof(object)); } } [AttributeUsage(AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Interface, Inherited = false)] public sealed class SkipLocalsInitAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event)] public sealed class SpecialNameAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = false)] public class StateMachineAttribute : Attribute { public Type StateMachineType { get; } public StateMachineAttribute(Type stateMachineType) { StateMachineType = stateMachineType; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class StringFreezingAttribute : Attribute { } public class StrongBox : IStrongBox { [MaybeNull] public T Value; object? IStrongBox.Value { get { return Value; } set { Value = (T)value; } } public StrongBox() { } public StrongBox(T value) { Value = value; } } public interface IStrongBox { object? Value { get; set; } } [Obsolete("SuppressIldasmAttribute has no effect in .NET 6.0+.", DiagnosticId = "SYSLIB0025", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module)] public sealed class SuppressIldasmAttribute : Attribute { } [Serializable] [TypeForwardedFrom("System.Runtime.Extensions, Version=4.2.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] public sealed class SwitchExpressionException : InvalidOperationException { public object? UnmatchedValue { get; } public override string Message { get { if (UnmatchedValue == null) { return base.Message; } string text = SR.Format(SR.SwitchExpressionException_UnmatchedValue, UnmatchedValue); return base.Message + Environment.NewLine + text; } } public SwitchExpressionException() : base(SR.Arg_SwitchExpressionException) { } public SwitchExpressionException(Exception? innerException) : base(SR.Arg_SwitchExpressionException, innerException) { } public SwitchExpressionException(object? unmatchedValue) : this() { UnmatchedValue = unmatchedValue; } private SwitchExpressionException(SerializationInfo info, StreamingContext context) : base(info, context) { UnmatchedValue = info.GetValue("UnmatchedValue", typeof(object)); } public SwitchExpressionException(string? message) : base(message) { } public SwitchExpressionException(string? message, Exception? innerException) : base(message, innerException) { } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("UnmatchedValue", UnmatchedValue, typeof(object)); } } public readonly struct TaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion, ITaskAwaiter { internal readonly Task m_task; public bool IsCompleted => m_task.IsCompleted; internal TaskAwaiter(Task task) { m_task = task; } public void OnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } public void UnsafeOnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } [StackTraceHidden] public void GetResult() { ValidateEnd(m_task); } [StackTraceHidden] internal static void ValidateEnd(Task task) { if (task.IsWaitNotificationEnabledOrNotRanToCompletion) { HandleNonSuccessAndDebuggerNotification(task); } } [StackTraceHidden] private static void HandleNonSuccessAndDebuggerNotification(Task task) { if (!task.IsCompleted) { bool flag = task.InternalWait(-1, default(CancellationToken)); } task.NotifyDebuggerOfWaitCompletionIfNecessary(); if (!task.IsCompletedSuccessfully) { ThrowForNonSuccess(task); } } [StackTraceHidden] private static void ThrowForNonSuccess(Task task) { switch (task.Status) { case TaskStatus.Canceled: task.GetCancellationExceptionDispatchInfo()?.Throw(); throw new TaskCanceledException(task); case TaskStatus.Faulted: { List exceptionDispatchInfos = task.GetExceptionDispatchInfos(); if (exceptionDispatchInfos.Count > 0) { exceptionDispatchInfos[0].Throw(); break; } throw task.Exception; } } } internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext) { if (continuation == null) { throw new ArgumentNullException("continuation"); } if (TplEventSource.Log.IsEnabled() || Task.s_asyncDebuggingEnabled) { continuation = OutputWaitEtwEvents(task, continuation); } task.SetContinuationForAwait(continuation, continueOnCapturedContext, flowExecutionContext); } internal static void UnsafeOnCompletedInternal(Task task, IAsyncStateMachineBox stateMachineBox, bool continueOnCapturedContext) { if (TplEventSource.Log.IsEnabled() || Task.s_asyncDebuggingEnabled) { task.SetContinuationForAwait(OutputWaitEtwEvents(task, stateMachineBox.MoveNextAction), continueOnCapturedContext, flowExecutionContext: false); } else { task.UnsafeSetContinuationForAwait(stateMachineBox, continueOnCapturedContext); } } private static Action OutputWaitEtwEvents(Task task, Action continuation) { if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(task); } TplEventSource log = TplEventSource.Log; if (log.IsEnabled()) { Task internalCurrent = Task.InternalCurrent; Task task2 = AsyncMethodBuilderCore.TryGetContinuationTask(continuation); log.TaskWaitBegin(internalCurrent?.m_taskScheduler.Id ?? TaskScheduler.Default.Id, internalCurrent?.Id ?? 0, task.Id, TplEventSource.TaskWaitBehavior.Asynchronous, task2?.Id ?? 0); } return AsyncMethodBuilderCore.CreateContinuationWrapper(continuation, delegate(Action innerContinuation, Task innerTask) { if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(innerTask); } TplEventSource log2 = TplEventSource.Log; Guid oldActivityThatWillContinue = default(Guid); bool flag = log2.IsEnabled(); if (flag) { Task internalCurrent2 = Task.InternalCurrent; log2.TaskWaitEnd(internalCurrent2?.m_taskScheduler.Id ?? TaskScheduler.Default.Id, internalCurrent2?.Id ?? 0, innerTask.Id); if (log2.TasksSetActivityIds && (innerTask.Options & (TaskCreationOptions)1024) != 0) { EventSource.SetCurrentThreadActivityId(TplEventSource.CreateGuidForTaskID(innerTask.Id), out oldActivityThatWillContinue); } } innerContinuation(); if (flag) { log2.TaskWaitContinuationComplete(innerTask.Id); if (log2.TasksSetActivityIds && (innerTask.Options & (TaskCreationOptions)1024) != 0) { EventSource.SetCurrentThreadActivityId(oldActivityThatWillContinue); } } }, task); } } public readonly struct TaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion, ITaskAwaiter { private readonly Task m_task; public bool IsCompleted => m_task.IsCompleted; internal TaskAwaiter(Task task) { m_task = task; } public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: true); } public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext: true, flowExecutionContext: false); } [StackTraceHidden] public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.ResultOnSuccess; } } internal interface ITaskAwaiter { } internal interface IConfiguredTaskAwaiter { } public readonly struct ConfiguredTaskAwaitable { public readonly struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion, IConfiguredTaskAwaiter { internal readonly Task m_task; internal readonly bool m_continueOnCapturedContext; public bool IsCompleted => m_task.IsCompleted; internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext) { m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); } public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); } [StackTraceHidden] public void GetResult() { TaskAwaiter.ValidateEnd(m_task); } } private readonly ConfiguredTaskAwaiter m_configuredTaskAwaiter; internal ConfiguredTaskAwaitable(Task task, bool continueOnCapturedContext) { m_configuredTaskAwaiter = new ConfiguredTaskAwaiter(task, continueOnCapturedContext); } public ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } } public readonly struct ConfiguredTaskAwaitable { public readonly struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion, IConfiguredTaskAwaiter { private readonly Task m_task; private readonly bool m_continueOnCapturedContext; public bool IsCompleted => m_task.IsCompleted; internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext) { m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: true); } public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext: false); } [StackTraceHidden] public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.ResultOnSuccess; } } private readonly ConfiguredTaskAwaiter m_configuredTaskAwaiter; internal ConfiguredTaskAwaitable(Task task, bool continueOnCapturedContext) { m_configuredTaskAwaiter = new ConfiguredTaskAwaiter(task, continueOnCapturedContext); } public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } } [CLSCompliant(false)] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] public sealed class TupleElementNamesAttribute : Attribute { private readonly string[] _transformNames; public IList TransformNames => _transformNames; public TupleElementNamesAttribute(string?[] transformNames) { if (transformNames == null) { throw new ArgumentNullException("transformNames"); } _transformNames = transformNames; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false, AllowMultiple = false)] public sealed class TypeForwardedFromAttribute : Attribute { public string AssemblyFullName { get; } public TypeForwardedFromAttribute(string assemblyFullName) { if (string.IsNullOrEmpty(assemblyFullName)) { throw new ArgumentNullException("assemblyFullName"); } AssemblyFullName = assemblyFullName; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] public sealed class TypeForwardedToAttribute : Attribute { public Type Destination { get; } public TypeForwardedToAttribute(Type destination) { Destination = destination; } } [AttributeUsage(AttributeTargets.Struct)] public sealed class UnsafeValueTypeAttribute : Attribute { } public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion, IStateMachineBoxAwareAwaiter { internal static readonly Action s_invokeActionDelegate = delegate(object state) { if (!(state is Action action)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.state); } else { action(); } }; private readonly ValueTask _value; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _value.IsCompleted; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ValueTaskAwaiter(in ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public void GetResult() { _value.ThrowIfCompletedUnsuccessfully(); } public void OnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As(obj).OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext); } else { Task.CompletedTask.GetAwaiter().OnCompleted(continuation); } } public void UnsafeOnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As(obj).OnCompleted(s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); } else { Task.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation); } } void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { object obj = _value._obj; if (obj is Task task) { TaskAwaiter.UnsafeOnCompletedInternal(task, box, continueOnCapturedContext: true); } else if (obj != null) { Unsafe.As(obj).OnCompleted(ThreadPool.s_invokeAsyncStateMachineBox, box, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); } else { TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, continueOnCapturedContext: true); } } } public readonly struct ValueTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion, IStateMachineBoxAwareAwaiter { private readonly ValueTask _value; public bool IsCompleted { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return _value.IsCompleted; } } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal ValueTaskAwaiter(in ValueTask value) { _value = value; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public TResult GetResult() { return _value.Result; } public void OnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.GetAwaiter().OnCompleted(continuation); } else if (obj != null) { Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext | ValueTaskSourceOnCompletedFlags.FlowExecutionContext); } else { Task.CompletedTask.GetAwaiter().OnCompleted(continuation); } } public void UnsafeOnCompleted(Action continuation) { object obj = _value._obj; if (obj is Task task) { task.GetAwaiter().UnsafeOnCompleted(continuation); } else if (obj != null) { Unsafe.As>(obj).OnCompleted(ValueTaskAwaiter.s_invokeActionDelegate, continuation, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); } else { Task.CompletedTask.GetAwaiter().UnsafeOnCompleted(continuation); } } void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { object obj = _value._obj; if (obj is Task task) { TaskAwaiter.UnsafeOnCompletedInternal(task, box, continueOnCapturedContext: true); } else if (obj != null) { Unsafe.As>(obj).OnCompleted(ThreadPool.s_invokeAsyncStateMachineBox, box, _value._token, ValueTaskSourceOnCompletedFlags.UseSchedulingContext); } else { TaskAwaiter.UnsafeOnCompletedInternal(Task.CompletedTask, box, continueOnCapturedContext: true); } } } internal interface IStateMachineBoxAwareAwaiter { void AwaitUnsafeOnCompleted(IAsyncStateMachineBox box); } [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly struct YieldAwaitable { [StructLayout(LayoutKind.Sequential, Size = 1)] public readonly struct YieldAwaiter : ICriticalNotifyCompletion, INotifyCompletion, IStateMachineBoxAwareAwaiter { private static readonly WaitCallback s_waitCallbackRunAction = RunAction; private static readonly SendOrPostCallback s_sendOrPostCallbackRunAction = RunAction; public bool IsCompleted => false; public void OnCompleted(Action continuation) { QueueContinuation(continuation, flowContext: true); } public void UnsafeOnCompleted(Action continuation) { QueueContinuation(continuation, flowContext: false); } private static void QueueContinuation(Action continuation, bool flowContext) { if (continuation == null) { throw new ArgumentNullException("continuation"); } if (TplEventSource.Log.IsEnabled()) { continuation = OutputCorrelationEtwEvent(continuation); } SynchronizationContext current = SynchronizationContext.Current; if (current != null && current.GetType() != typeof(SynchronizationContext)) { current.Post(s_sendOrPostCallbackRunAction, continuation); return; } TaskScheduler current2 = TaskScheduler.Current; if (current2 == TaskScheduler.Default) { if (flowContext) { ThreadPool.QueueUserWorkItem(s_waitCallbackRunAction, continuation); } else { ThreadPool.UnsafeQueueUserWorkItem(s_waitCallbackRunAction, continuation); } } else { Task.Factory.StartNew(continuation, default(CancellationToken), TaskCreationOptions.PreferFairness, current2); } } void IStateMachineBoxAwareAwaiter.AwaitUnsafeOnCompleted(IAsyncStateMachineBox box) { if (TplEventSource.Log.IsEnabled()) { QueueContinuation(box.MoveNextAction, flowContext: false); return; } SynchronizationContext current = SynchronizationContext.Current; if (current != null && current.GetType() != typeof(SynchronizationContext)) { current.Post(delegate(object s) { ((IAsyncStateMachineBox)s).MoveNext(); }, box); return; } TaskScheduler current2 = TaskScheduler.Current; if (current2 == TaskScheduler.Default) { ThreadPool.UnsafeQueueUserWorkItemInternal(box, preferLocal: false); return; } Task.Factory.StartNew(delegate(object s) { ((IAsyncStateMachineBox)s).MoveNext(); }, box, default(CancellationToken), TaskCreationOptions.PreferFairness, current2); } private static Action OutputCorrelationEtwEvent(Action continuation) { int num = Task.NewId(); Task internalCurrent = Task.InternalCurrent; TplEventSource.Log.AwaitTaskContinuationScheduled(TaskScheduler.Current.Id, internalCurrent?.Id ?? 0, num); return AsyncMethodBuilderCore.CreateContinuationWrapper(continuation, delegate(Action innerContinuation, Task continuationIdTask) { TplEventSource log = TplEventSource.Log; log.TaskWaitContinuationStarted(((Task)continuationIdTask).Result); Guid oldActivityThatWillContinue = default(Guid); if (log.TasksSetActivityIds) { EventSource.SetCurrentThreadActivityId(TplEventSource.CreateGuidForTaskID(((Task)continuationIdTask).Result), out oldActivityThatWillContinue); } innerContinuation(); if (log.TasksSetActivityIds) { EventSource.SetCurrentThreadActivityId(oldActivityThatWillContinue); } log.TaskWaitContinuationComplete(((Task)continuationIdTask).Result); }, Task.FromResult(num)); } private static void RunAction(object state) { ((Action)state)(); } public void GetResult() { } } public YieldAwaiter GetAwaiter() { return default(YieldAwaiter); } } [EditorBrowsable(EditorBrowsableState.Never)] public static class IsExternalInit { } internal ref struct StringHandleOnStack { private unsafe void* _ptr; internal unsafe StringHandleOnStack(ref string s) { _ptr = Unsafe.AsPointer(ref s); } } internal ref struct ObjectHandleOnStack { private unsafe void* _ptr; private unsafe ObjectHandleOnStack(void* pObject) { _ptr = pObject; } internal unsafe static ObjectHandleOnStack Create(ref T o) where T : class { return new ObjectHandleOnStack(Unsafe.AsPointer(ref o)); } } internal ref struct StackCrawlMarkHandle { private unsafe void* _ptr; internal unsafe StackCrawlMarkHandle(ref StackCrawlMark stackMark) { _ptr = Unsafe.AsPointer(ref stackMark); } } internal ref struct QCallModule { private unsafe void* _ptr; private IntPtr _module; internal unsafe QCallModule(ref RuntimeModule module) { _ptr = Unsafe.AsPointer(ref module); _module = module.GetUnderlyingNativeHandle(); } internal unsafe QCallModule(ref ModuleBuilder module) { _ptr = Unsafe.AsPointer(ref module); _module = module.InternalModule.GetUnderlyingNativeHandle(); } } internal ref struct QCallAssembly { private unsafe void* _ptr; private IntPtr _assembly; internal unsafe QCallAssembly(ref RuntimeAssembly assembly) { _ptr = Unsafe.AsPointer(ref assembly); _assembly = assembly.GetUnderlyingNativeHandle(); } } internal ref struct QCallTypeHandle { private unsafe void* _ptr; private IntPtr _handle; internal unsafe QCallTypeHandle(ref RuntimeType type) { _ptr = Unsafe.AsPointer(ref type); if (type != null) { _handle = type.GetUnderlyingNativeHandle(); } else { _handle = IntPtr.Zero; } } internal unsafe QCallTypeHandle(ref RuntimeTypeHandle rth) { _ptr = Unsafe.AsPointer(ref rth); _handle = rth.Value; } } } namespace System.Resources { internal sealed class ManifestBasedResourceGroveler : IResourceGroveler { private readonly ResourceManager.ResourceManagerMediator _mediator; private static Assembly InternalGetSatelliteAssembly(Assembly mainAssembly, CultureInfo culture, Version version) { return ((RuntimeAssembly)mainAssembly).InternalGetSatelliteAssembly(culture, version, throwOnFileNotFound: false); } public ManifestBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator) { _mediator = mediator; } public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary localResourceSets, bool tryParents, bool createIfNotExists) { ResourceSet value = null; Stream stream = null; CultureInfo cultureInfo = UltimateFallbackFixup(culture); Assembly assembly; if (cultureInfo.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly) { assembly = _mediator.MainAssembly; } else { assembly = GetSatelliteAssembly(cultureInfo); if (assembly == null && culture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite) { HandleSatelliteMissing(); } } string resourceFileName = _mediator.GetResourceFileName(cultureInfo); if (assembly != null) { lock (localResourceSets) { localResourceSets.TryGetValue(culture.Name, out value); } stream = GetManifestResourceStream(assembly, resourceFileName); } if (createIfNotExists && stream != null && value == null) { value = CreateResourceSet(stream, assembly); } else if (stream == null && tryParents && culture.HasInvariantCultureName) { HandleResourceStreamMissing(resourceFileName); } return value; } private CultureInfo UltimateFallbackFixup(CultureInfo lookForCulture) { CultureInfo result = lookForCulture; if (lookForCulture.Name == _mediator.NeutralResourcesCulture.Name && _mediator.FallbackLoc == UltimateResourceFallbackLocation.MainAssembly) { result = CultureInfo.InvariantCulture; } else if (lookForCulture.HasInvariantCultureName && _mediator.FallbackLoc == UltimateResourceFallbackLocation.Satellite) { result = _mediator.NeutralResourcesCulture; } return result; } internal static CultureInfo GetNeutralResourcesLanguage(Assembly a, out UltimateResourceFallbackLocation fallbackLocation) { NeutralResourcesLanguageAttribute customAttribute = a.GetCustomAttribute(); if (customAttribute == null || (GlobalizationMode.Invariant && GlobalizationMode.PredefinedCulturesOnly)) { fallbackLocation = UltimateResourceFallbackLocation.MainAssembly; return CultureInfo.InvariantCulture; } fallbackLocation = customAttribute.Location; if (fallbackLocation < UltimateResourceFallbackLocation.MainAssembly || fallbackLocation > UltimateResourceFallbackLocation.Satellite) { throw new ArgumentException(SR.Format(SR.Arg_InvalidNeutralResourcesLanguage_FallbackLoc, fallbackLocation)); } try { return CultureInfo.GetCultureInfo(customAttribute.CultureName); } catch (ArgumentException innerException) { if (a == typeof(object).Assembly) { return CultureInfo.InvariantCulture; } throw new ArgumentException(SR.Format(SR.Arg_InvalidNeutralResourcesLanguage_Asm_Culture, a, customAttribute.CultureName), innerException); } } internal ResourceSet CreateResourceSet(Stream store, Assembly assembly) { if (store.CanSeek && store.Length > 4) { long position = store.Position; BinaryReader binaryReader = new BinaryReader(store); int num = binaryReader.ReadInt32(); if (num == ResourceManager.MagicNumber) { int num2 = binaryReader.ReadInt32(); string text = null; string text2 = null; if (num2 == ResourceManager.HeaderVersionNumber) { binaryReader.ReadInt32(); text = binaryReader.ReadString(); text2 = binaryReader.ReadString(); } else { if (num2 <= ResourceManager.HeaderVersionNumber) { throw new NotSupportedException(SR.Format(SR.NotSupported_ObsoleteResourcesFile, _mediator.MainAssembly.GetName().Name)); } int num3 = binaryReader.ReadInt32(); long offset = binaryReader.BaseStream.Position + num3; text = binaryReader.ReadString(); text2 = binaryReader.ReadString(); binaryReader.BaseStream.Seek(offset, SeekOrigin.Begin); } store.Position = position; if (CanUseDefaultResourceClasses(text, text2)) { return new RuntimeResourceSet(store, permitDeserialization: true); } if (ResourceReader.AllowCustomResourceTypes) { return InternalGetResourceSetFromSerializedData(store, text, text2, _mediator); } throw new NotSupportedException(SR.ResourceManager_ReflectionNotAllowed); } store.Position = position; } if (_mediator.UserResourceSet == null) { return new RuntimeResourceSet(store, permitDeserialization: true); } object[] args = new object[2] { store, assembly }; try { try { return (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); } catch (MissingMethodException) { } return (ResourceSet)Activator.CreateInstance(args: new object[1] { store }, type: _mediator.UserResourceSet); } catch (MissingMethodException innerException) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResMgrBadResSet_Type, _mediator.UserResourceSet.AssemblyQualifiedName), innerException); } } [RequiresUnreferencedCode("The CustomResourceTypesSupport feature switch has been enabled for this app which is being trimmed. Custom readers as well as custom objects on the resources file are not observable by the trimmer and so required assemblies, types and members may be removed.")] private static ResourceSet InternalGetResourceSetFromSerializedData(Stream store, string readerTypeName, string resSetTypeName, ResourceManager.ResourceManagerMediator mediator) { IResourceReader resourceReader; if (ResourceManager.IsDefaultType(readerTypeName, "System.Resources.ResourceReader")) { resourceReader = new ResourceReader(store, new Dictionary(FastResourceComparer.Default), permitDeserialization: true); } else { Type type = Type.GetType(readerTypeName, throwOnError: true); resourceReader = (IResourceReader)Activator.CreateInstance(type, store); } object[] args = new object[1] { resourceReader }; Type type2 = mediator.UserResourceSet; if (type2 == null) { type2 = Type.GetType(resSetTypeName, throwOnError: true, ignoreCase: false); } return (ResourceSet)Activator.CreateInstance(type2, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.CreateInstance, null, args, null, null); } private Stream GetManifestResourceStream(Assembly satellite, string fileName) { return satellite.GetManifestResourceStream(_mediator.LocationInfo, fileName) ?? CaseInsensitiveManifestResourceStreamLookup(satellite, fileName); } private Stream CaseInsensitiveManifestResourceStreamLookup(Assembly satellite, string name) { string text = _mediator.LocationInfo?.Namespace; char ptr = Type.Delimiter; string text2 = ((text != null && name != null) ? string.Concat(text, new ReadOnlySpan(ref ptr, 1), name) : (text + name)); string text3 = null; string[] manifestResourceNames = satellite.GetManifestResourceNames(); foreach (string text4 in manifestResourceNames) { if (string.Equals(text4, text2, StringComparison.InvariantCultureIgnoreCase)) { if (text3 != null) { throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_MultipleBlobs, text2, satellite.ToString())); } text3 = text4; } } if (text3 == null) { return null; } return satellite.GetManifestResourceStream(text3); } private Assembly GetSatelliteAssembly(CultureInfo lookForCulture) { if (!_mediator.LookedForSatelliteContractVersion) { _mediator.SatelliteContractVersion = ResourceManager.ResourceManagerMediator.ObtainSatelliteContractVersion(_mediator.MainAssembly); _mediator.LookedForSatelliteContractVersion = true; } Assembly result = null; try { result = InternalGetSatelliteAssembly(_mediator.MainAssembly, lookForCulture, _mediator.SatelliteContractVersion); } catch (FileLoadException) { } catch (BadImageFormatException) { } return result; } private bool CanUseDefaultResourceClasses(string readerTypeName, string resSetTypeName) { if (_mediator.UserResourceSet != null) { return false; } if (readerTypeName != null && !ResourceManager.IsDefaultType(readerTypeName, "System.Resources.ResourceReader")) { return false; } if (resSetTypeName != null && !ResourceManager.IsDefaultType(resSetTypeName, "System.Resources.RuntimeResourceSet")) { return false; } return true; } private void HandleSatelliteMissing() { AssemblyName name = _mediator.MainAssembly.GetName(); string p = AssemblyNameFormatter.ComputeDisplayName(name.Name + ".resources.dll", _mediator.SatelliteContractVersion, null, name.GetPublicKeyToken()); string text = _mediator.NeutralResourcesCulture.Name; if (text.Length == 0) { text = ""; } throw new MissingSatelliteAssemblyException(SR.Format(SR.MissingSatelliteAssembly_Culture_Name, _mediator.NeutralResourcesCulture, p), text); } private static string GetManifestResourceNamesList(Assembly assembly) { try { string[] manifestResourceNames = assembly.GetManifestResourceNames(); int num = manifestResourceNames.Length; string text = "\""; if (num > 10) { num = 10; text = "\", ..."; } return "\"" + string.Join("\", \"", manifestResourceNames, 0, num) + text; } catch { return "\"\""; } } private void HandleResourceStreamMissing(string fileName) { if (_mediator.MainAssembly == typeof(object).Assembly && _mediator.BaseName.Equals("System.Private.CoreLib")) { Environment.FailFast("System.Private.CoreLib.resources couldn't be found! Large parts of the BCL won't work!"); } string text = string.Empty; if (_mediator.LocationInfo != null && _mediator.LocationInfo.Namespace != null) { text = _mediator.LocationInfo.Namespace + Type.Delimiter; } text += fileName; throw new MissingManifestResourceException(SR.Format(SR.MissingManifestResource_NoNeutralAsm, text, _mediator.MainAssembly.GetName().Name, GetManifestResourceNamesList(_mediator.MainAssembly))); } } internal sealed class FastResourceComparer : IComparer, IEqualityComparer, IComparer, IEqualityComparer { internal static readonly FastResourceComparer Default = new FastResourceComparer(); public int GetHashCode(object key) { string key2 = (string)key; return HashFunction(key2); } public int GetHashCode([DisallowNull] string key) { return HashFunction(key); } internal static int HashFunction(string key) { uint num = 5381u; for (int i = 0; i < key.Length; i++) { num = ((num << 5) + num) ^ key[i]; } return (int)num; } public int Compare(object a, object b) { if (a == b) { return 0; } string strA = (string)a; string strB = (string)b; return string.CompareOrdinal(strA, strB); } public int Compare(string a, string b) { return string.CompareOrdinal(a, b); } public bool Equals(string a, string b) { return string.Equals(a, b); } public new bool Equals(object a, object b) { if (a == b) { return true; } string a2 = (string)a; string b2 = (string)b; return string.Equals(a2, b2); } public unsafe static int CompareOrdinal(string a, byte[] bytes, int bCharLength) { int num = 0; int num2 = 0; int num3 = a.Length; if (num3 > bCharLength) { num3 = bCharLength; } if (bCharLength == 0) { if (a.Length != 0) { return -1; } return 0; } fixed (byte* ptr = bytes) { byte* ptr2 = ptr; while (num < num3 && num2 == 0) { int num4 = *ptr2 | (ptr2[1] << 8); num2 = a[num++] - num4; ptr2 += 2; } } if (num2 != 0) { return num2; } return a.Length - bCharLength; } public static int CompareOrdinal(byte[] bytes, int aCharLength, string b) { return -CompareOrdinal(b, bytes, aCharLength); } internal unsafe static int CompareOrdinal(byte* a, int byteLen, string b) { int num = 0; int num2 = 0; int num3 = byteLen >> 1; if (num3 > b.Length) { num3 = b.Length; } while (num2 < num3 && num == 0) { char c = (char)(*(a++) | (*(a++) << 8)); num = c - b[num2++]; } if (num != 0) { return num; } return byteLen - b.Length * 2; } } internal sealed class FileBasedResourceGroveler : IResourceGroveler { private readonly ResourceManager.ResourceManagerMediator _mediator; public FileBasedResourceGroveler(ResourceManager.ResourceManagerMediator mediator) { _mediator = mediator; } public ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary localResourceSets, bool tryParents, bool createIfNotExists) { ResourceSet result = null; string resourceFileName = _mediator.GetResourceFileName(culture); string text = FindResourceFile(culture, resourceFileName); if (text == null) { if (tryParents && culture.HasInvariantCultureName) { string value = ((_mediator.LocationInfo == null) ? "" : _mediator.LocationInfo.FullName); throw new MissingManifestResourceException($"{SR.MissingManifestResource_NoNeutralDisk}{"\r\n"}baseName: {_mediator.BaseNameField} locationInfo: {value} fileName: {_mediator.GetResourceFileName(culture)}"); } } else { result = CreateResourceSet(text); } return result; } private string FindResourceFile(CultureInfo culture, string fileName) { if (_mediator.ModuleDir != null) { string text = Path.Combine(_mediator.ModuleDir, fileName); if (File.Exists(text)) { return text; } } if (File.Exists(fileName)) { return fileName; } return null; } private ResourceSet CreateResourceSet(string file) { if (_mediator.UserResourceSet == null) { return new RuntimeResourceSet(file); } object[] args = new object[1] { file }; try { return (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args); } catch (MissingMethodException innerException) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResMgrBadResSet_Type, _mediator.UserResourceSet.AssemblyQualifiedName), innerException); } } } internal interface IResourceGroveler { ResourceSet GrovelForResourceSet(CultureInfo culture, Dictionary localResourceSets, bool tryParents, bool createIfNotExists); } public interface IResourceReader : System.Collections.IEnumerable, IDisposable { void Close(); new IDictionaryEnumerator GetEnumerator(); } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class MissingManifestResourceException : SystemException { public MissingManifestResourceException() : base(SR.Arg_MissingManifestResourceException) { base.HResult = -2146233038; } public MissingManifestResourceException(string? message) : base(message) { base.HResult = -2146233038; } public MissingManifestResourceException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233038; } protected MissingManifestResourceException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class MissingSatelliteAssemblyException : SystemException { private readonly string _cultureName; public string? CultureName => _cultureName; public MissingSatelliteAssemblyException() : base(SR.MissingSatelliteAssembly_Default) { base.HResult = -2146233034; } public MissingSatelliteAssemblyException(string? message) : base(message) { base.HResult = -2146233034; } public MissingSatelliteAssemblyException(string? message, string? cultureName) : base(message) { base.HResult = -2146233034; _cultureName = cultureName; } public MissingSatelliteAssemblyException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146233034; } protected MissingSatelliteAssemblyException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public sealed class NeutralResourcesLanguageAttribute : Attribute { public string CultureName { get; } public UltimateResourceFallbackLocation Location { get; } public NeutralResourcesLanguageAttribute(string cultureName) { if (cultureName == null) { throw new ArgumentNullException("cultureName"); } CultureName = cultureName; Location = UltimateResourceFallbackLocation.MainAssembly; } public NeutralResourcesLanguageAttribute(string cultureName, UltimateResourceFallbackLocation location) { if (cultureName == null) { throw new ArgumentNullException("cultureName"); } if (!Enum.IsDefined(typeof(UltimateResourceFallbackLocation), location)) { throw new ArgumentException(SR.Format(SR.Arg_InvalidNeutralResourcesLanguage_FallbackLoc, location)); } CultureName = cultureName; Location = location; } } internal sealed class ResourceFallbackManager : IEnumerable, System.Collections.IEnumerable { private readonly CultureInfo m_startingCulture; private readonly CultureInfo m_neutralResourcesCulture; private readonly bool m_useParents; internal ResourceFallbackManager(CultureInfo startingCulture, CultureInfo neutralResourcesCulture, bool useParents) { if (startingCulture != null) { m_startingCulture = startingCulture; } else { m_startingCulture = CultureInfo.CurrentUICulture; } m_neutralResourcesCulture = neutralResourcesCulture; m_useParents = useParents; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator GetEnumerator() { bool reachedNeutralResourcesCulture = false; CultureInfo currentCulture = m_startingCulture; do { if (m_neutralResourcesCulture != null && currentCulture.Name == m_neutralResourcesCulture.Name) { yield return CultureInfo.InvariantCulture; reachedNeutralResourcesCulture = true; break; } yield return currentCulture; currentCulture = currentCulture.Parent; } while (m_useParents && !currentCulture.HasInvariantCultureName); if (m_useParents && !m_startingCulture.HasInvariantCultureName && !reachedNeutralResourcesCulture) { yield return CultureInfo.InvariantCulture; } } } public class ResourceManager { internal sealed class CultureNameResourceSetPair { public string lastCultureName; public ResourceSet lastResourceSet; } internal sealed class ResourceManagerMediator { private readonly ResourceManager _rm; internal string ModuleDir => _rm._moduleDir; internal Type LocationInfo => _rm._locationInfo; [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] internal Type UserResourceSet => _rm._userResourceSet; internal string BaseNameField => _rm.BaseNameField; internal CultureInfo NeutralResourcesCulture => _rm._neutralResourcesCulture; internal bool LookedForSatelliteContractVersion { get { return _rm._lookedForSatelliteContractVersion; } set { _rm._lookedForSatelliteContractVersion = value; } } internal Version SatelliteContractVersion { get { return _rm._satelliteContractVersion; } set { _rm._satelliteContractVersion = value; } } internal UltimateResourceFallbackLocation FallbackLoc => _rm.FallbackLocation; internal Assembly MainAssembly => _rm.MainAssembly; internal string BaseName => _rm.BaseName; internal ResourceManagerMediator(ResourceManager rm) { if (rm == null) { throw new ArgumentNullException("rm"); } _rm = rm; } internal string GetResourceFileName(CultureInfo culture) { return _rm.GetResourceFileName(culture); } internal static Version ObtainSatelliteContractVersion(Assembly a) { return GetSatelliteContractVersion(a); } } protected string BaseNameField; protected Assembly? MainAssembly; private Dictionary _resourceSets; private readonly string _moduleDir; private readonly Type _locationInfo; [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] private readonly Type _userResourceSet; private CultureInfo _neutralResourcesCulture; private CultureNameResourceSetPair _lastUsedResourceCache; private bool _ignoreCase; private bool _useManifest; private UltimateResourceFallbackLocation _fallbackLoc; private Version _satelliteContractVersion; private bool _lookedForSatelliteContractVersion; private IResourceGroveler _resourceGroveler; public static readonly int MagicNumber = -1091581234; public static readonly int HeaderVersionNumber = 1; private static readonly Type s_minResourceSet = typeof(ResourceSet); public virtual string BaseName => BaseNameField; public virtual bool IgnoreCase { get { return _ignoreCase; } set { _ignoreCase = value; } } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] public virtual Type ResourceSetType => _userResourceSet ?? typeof(RuntimeResourceSet); protected UltimateResourceFallbackLocation FallbackLocation { get { return _fallbackLoc; } set { _fallbackLoc = value; } } protected ResourceManager() { _lastUsedResourceCache = new CultureNameResourceSetPair(); ResourceManagerMediator mediator = new ResourceManagerMediator(this); _resourceGroveler = new ManifestBasedResourceGroveler(mediator); BaseNameField = string.Empty; } private ResourceManager(string baseName, string resourceDir, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type userResourceSet) { if (baseName == null) { throw new ArgumentNullException("baseName"); } if (resourceDir == null) { throw new ArgumentNullException("resourceDir"); } BaseNameField = baseName; _moduleDir = resourceDir; _userResourceSet = userResourceSet; _resourceSets = new Dictionary(); _lastUsedResourceCache = new CultureNameResourceSetPair(); ResourceManagerMediator mediator = new ResourceManagerMediator(this); _resourceGroveler = new FileBasedResourceGroveler(mediator); } public ResourceManager(string baseName, Assembly assembly) { if (baseName == null) { throw new ArgumentNullException("baseName"); } if (null == assembly) { throw new ArgumentNullException("assembly"); } if (!assembly.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); } MainAssembly = assembly; BaseNameField = baseName; CommonAssemblyInit(); } public ResourceManager(string baseName, Assembly assembly, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type? usingResourceSet) { if (baseName == null) { throw new ArgumentNullException("baseName"); } if (null == assembly) { throw new ArgumentNullException("assembly"); } if (!assembly.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); } MainAssembly = assembly; BaseNameField = baseName; if (usingResourceSet != null && usingResourceSet != s_minResourceSet && !usingResourceSet.IsSubclassOf(s_minResourceSet)) { throw new ArgumentException(SR.Arg_ResMgrNotResSet, "usingResourceSet"); } _userResourceSet = usingResourceSet; CommonAssemblyInit(); } public ResourceManager(Type resourceSource) { if (null == resourceSource) { throw new ArgumentNullException("resourceSource"); } if (!resourceSource.IsRuntimeImplemented()) { throw new ArgumentException(SR.Argument_MustBeRuntimeType); } _locationInfo = resourceSource; MainAssembly = _locationInfo.Assembly; BaseNameField = resourceSource.Name; CommonAssemblyInit(); } [MemberNotNull("_resourceGroveler")] private void CommonAssemblyInit() { _useManifest = true; _resourceSets = new Dictionary(); _lastUsedResourceCache = new CultureNameResourceSetPair(); ResourceManagerMediator mediator = new ResourceManagerMediator(this); _resourceGroveler = new ManifestBasedResourceGroveler(mediator); _neutralResourcesCulture = ManifestBasedResourceGroveler.GetNeutralResourcesLanguage(MainAssembly, out _fallbackLoc); } public virtual void ReleaseAllResources() { Dictionary resourceSets = _resourceSets; _resourceSets = new Dictionary(); _lastUsedResourceCache = new CultureNameResourceSetPair(); lock (resourceSets) { foreach (var (_, resourceSet2) in resourceSets) { resourceSet2.Close(); } } } public static ResourceManager CreateFileBasedResourceManager(string baseName, string resourceDir, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type? usingResourceSet) { return new ResourceManager(baseName, resourceDir, usingResourceSet); } protected virtual string GetResourceFileName(CultureInfo culture) { if (culture.HasInvariantCultureName) { return BaseNameField + ".resources"; } CultureInfo.VerifyCultureName(culture.Name, throwException: true); return BaseNameField + "." + culture.Name + ".resources"; } internal ResourceSet GetFirstResourceSet(CultureInfo culture) { if (_neutralResourcesCulture != null && culture.Name == _neutralResourcesCulture.Name) { culture = CultureInfo.InvariantCulture; } if (_lastUsedResourceCache != null) { lock (_lastUsedResourceCache) { if (culture.Name == _lastUsedResourceCache.lastCultureName) { return _lastUsedResourceCache.lastResourceSet; } } } Dictionary resourceSets = _resourceSets; ResourceSet value = null; if (resourceSets != null) { lock (resourceSets) { resourceSets.TryGetValue(culture.Name, out value); } } if (value != null) { if (_lastUsedResourceCache != null) { lock (_lastUsedResourceCache) { _lastUsedResourceCache.lastCultureName = culture.Name; _lastUsedResourceCache.lastResourceSet = value; } } return value; } return null; } public virtual ResourceSet? GetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) { if (culture == null) { throw new ArgumentNullException("culture"); } Dictionary resourceSets = _resourceSets; if (resourceSets != null) { lock (resourceSets) { if (resourceSets.TryGetValue(culture.Name, out var value)) { return value; } } } if (_useManifest && culture.HasInvariantCultureName) { string resourceFileName = GetResourceFileName(culture); Stream manifestResourceStream = MainAssembly.GetManifestResourceStream(_locationInfo, resourceFileName); if (createIfNotExists && manifestResourceStream != null) { ResourceSet value = ((ManifestBasedResourceGroveler)_resourceGroveler).CreateResourceSet(manifestResourceStream, MainAssembly); AddResourceSet(resourceSets, culture.Name, ref value); return value; } } return InternalGetResourceSet(culture, createIfNotExists, tryParents); } protected virtual ResourceSet? InternalGetResourceSet(CultureInfo culture, bool createIfNotExists, bool tryParents) { Dictionary resourceSets = _resourceSets; ResourceSet value = null; CultureInfo cultureInfo = null; lock (resourceSets) { if (resourceSets.TryGetValue(culture.Name, out value)) { return value; } } ResourceFallbackManager resourceFallbackManager = new ResourceFallbackManager(culture, _neutralResourcesCulture, tryParents); foreach (CultureInfo item in resourceFallbackManager) { lock (resourceSets) { if (resourceSets.TryGetValue(item.Name, out value)) { if (culture != item) { cultureInfo = item; } break; } } value = _resourceGroveler.GrovelForResourceSet(item, resourceSets, tryParents, createIfNotExists); if (value != null) { cultureInfo = item; break; } } if (value != null && cultureInfo != null) { foreach (CultureInfo item2 in resourceFallbackManager) { AddResourceSet(resourceSets, item2.Name, ref value); if (item2 == cultureInfo) { break; } } } return value; } private static void AddResourceSet(Dictionary localResourceSets, string cultureName, ref ResourceSet rs) { lock (localResourceSets) { if (localResourceSets.TryGetValue(cultureName, out var value)) { if (value != rs) { if (!localResourceSets.ContainsValue(rs)) { rs.Dispose(); } rs = value; } } else { localResourceSets.Add(cultureName, rs); } } } protected static Version? GetSatelliteContractVersion(Assembly a) { if (a == null) { throw new ArgumentNullException("a", SR.ArgumentNull_Assembly); } string text = a.GetCustomAttribute()?.Version; if (text == null) { return null; } if (!Version.TryParse(text, out Version result)) { throw new ArgumentException(SR.Format(SR.Arg_InvalidSatelliteContract_Asm_Ver, a, text)); } return result; } protected static CultureInfo GetNeutralResourcesLanguage(Assembly a) { UltimateResourceFallbackLocation fallbackLocation; return ManifestBasedResourceGroveler.GetNeutralResourcesLanguage(a, out fallbackLocation); } internal static bool IsDefaultType(string asmTypeName, string typeName) { int num = asmTypeName.IndexOf(','); if (((num == -1) ? asmTypeName.Length : num) != typeName.Length) { return false; } if (string.Compare(asmTypeName, 0, typeName, 0, typeName.Length, StringComparison.Ordinal) != 0) { return false; } if (num == -1) { return true; } while (char.IsWhiteSpace(asmTypeName[++num])) { } AssemblyName assemblyName = new AssemblyName(asmTypeName.Substring(num)); return string.Equals(assemblyName.Name, "mscorlib", StringComparison.OrdinalIgnoreCase); } public virtual string? GetString(string name) { return GetString(name, null); } public virtual string? GetString(string name, CultureInfo? culture) { if (name == null) { throw new ArgumentNullException("name"); } if (culture == null) { culture = CultureInfo.CurrentUICulture; } ResourceSet resourceSet = GetFirstResourceSet(culture); if (resourceSet != null) { string @string = resourceSet.GetString(name, _ignoreCase); if (@string != null) { return @string; } } ResourceFallbackManager resourceFallbackManager = new ResourceFallbackManager(culture, _neutralResourcesCulture, useParents: true); foreach (CultureInfo item in resourceFallbackManager) { ResourceSet resourceSet2 = InternalGetResourceSet(item, createIfNotExists: true, tryParents: true); if (resourceSet2 == null) { break; } if (resourceSet2 == resourceSet) { continue; } string string2 = resourceSet2.GetString(name, _ignoreCase); if (string2 != null) { if (_lastUsedResourceCache != null) { lock (_lastUsedResourceCache) { _lastUsedResourceCache.lastCultureName = item.Name; _lastUsedResourceCache.lastResourceSet = resourceSet2; } } return string2; } resourceSet = resourceSet2; } return null; } public virtual object? GetObject(string name) { return GetObject(name, null, wrapUnmanagedMemStream: true); } public virtual object? GetObject(string name, CultureInfo? culture) { return GetObject(name, culture, wrapUnmanagedMemStream: true); } private object GetObject(string name, CultureInfo culture, bool wrapUnmanagedMemStream) { if (name == null) { throw new ArgumentNullException("name"); } if (culture == null) { culture = CultureInfo.CurrentUICulture; } ResourceSet resourceSet = GetFirstResourceSet(culture); if (resourceSet != null) { object @object = resourceSet.GetObject(name, _ignoreCase); if (@object != null) { UnmanagedMemoryStream unmanagedMemoryStream = @object as UnmanagedMemoryStream; if (unmanagedMemoryStream != null && wrapUnmanagedMemStream) { return new UnmanagedMemoryStreamWrapper(unmanagedMemoryStream); } return @object; } } ResourceFallbackManager resourceFallbackManager = new ResourceFallbackManager(culture, _neutralResourcesCulture, useParents: true); foreach (CultureInfo item in resourceFallbackManager) { ResourceSet resourceSet2 = InternalGetResourceSet(item, createIfNotExists: true, tryParents: true); if (resourceSet2 == null) { break; } if (resourceSet2 == resourceSet) { continue; } object object2 = resourceSet2.GetObject(name, _ignoreCase); if (object2 != null) { if (_lastUsedResourceCache != null) { lock (_lastUsedResourceCache) { _lastUsedResourceCache.lastCultureName = item.Name; _lastUsedResourceCache.lastResourceSet = resourceSet2; } } UnmanagedMemoryStream unmanagedMemoryStream2 = object2 as UnmanagedMemoryStream; if (unmanagedMemoryStream2 != null && wrapUnmanagedMemStream) { return new UnmanagedMemoryStreamWrapper(unmanagedMemoryStream2); } return object2; } resourceSet = resourceSet2; } return null; } public UnmanagedMemoryStream? GetStream(string name) { return GetStream(name, null); } public UnmanagedMemoryStream? GetStream(string name, CultureInfo? culture) { object @object = GetObject(name, culture, wrapUnmanagedMemStream: false); UnmanagedMemoryStream unmanagedMemoryStream = @object as UnmanagedMemoryStream; if (unmanagedMemoryStream == null && @object != null) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotStream_Name, name)); } return unmanagedMemoryStream; } } public sealed class ResourceReader : IResourceReader, System.Collections.IEnumerable, IDisposable { internal sealed class ResourceEnumerator : IDictionaryEnumerator, System.Collections.IEnumerator { private readonly ResourceReader _reader; private bool _currentIsValid; private int _currentName; private int _dataPosition; public object Key { get { if (_currentName == int.MinValue) { throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } if (!_currentIsValid) { throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); } if (_reader._resCache == null) { throw new InvalidOperationException(SR.ResourceReaderIsClosed); } return _reader.AllocateStringForNameIndex(_currentName, out _dataPosition); } } public object Current => Entry; internal int DataPosition => _dataPosition; public DictionaryEntry Entry { get { if (_currentName == int.MinValue) { throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } if (!_currentIsValid) { throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); } if (_reader._resCache == null) { throw new InvalidOperationException(SR.ResourceReaderIsClosed); } object obj = null; string key; lock (_reader) { lock (_reader._resCache) { key = _reader.AllocateStringForNameIndex(_currentName, out _dataPosition); if (_reader._resCache.TryGetValue(key, out var value)) { obj = value.Value; } if (obj == null) { obj = ((_dataPosition != -1) ? _reader.LoadObject(_dataPosition) : _reader.GetValueForNameIndex(_currentName)); } } } return new DictionaryEntry(key, obj); } } public object Value { get { if (_currentName == int.MinValue) { throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } if (!_currentIsValid) { throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); } if (_reader._resCache == null) { throw new InvalidOperationException(SR.ResourceReaderIsClosed); } return _reader.GetValueForNameIndex(_currentName); } } internal ResourceEnumerator(ResourceReader reader) { _currentName = -1; _reader = reader; _dataPosition = -2; } public bool MoveNext() { if (_currentName == _reader._numResources - 1 || _currentName == int.MinValue) { _currentIsValid = false; _currentName = int.MinValue; return false; } _currentIsValid = true; _currentName++; return true; } public void Reset() { if (_reader._resCache == null) { throw new InvalidOperationException(SR.ResourceReaderIsClosed); } _currentIsValid = false; _currentName = -1; } } private readonly bool _permitDeserialization; private object _binaryFormatter; [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] private static Type s_binaryFormatterType; private static Func s_deserializeMethod; private BinaryReader _store; internal Dictionary _resCache; private long _nameSectionOffset; private long _dataSectionOffset; private int[] _nameHashes; private unsafe int* _nameHashesPtr; private int[] _namePositions; private unsafe int* _namePositionsPtr; private Type[] _typeTable; private int[] _typeNamePositions; private int _numResources; private UnmanagedMemoryStream _ums; private int _version; internal static bool AllowCustomResourceTypes { get; } = !AppContext.TryGetSwitch("System.Resources.ResourceManager.AllowCustomResourceTypes", out var isEnabled) || isEnabled; internal ResourceReader(Stream stream, Dictionary resCache, bool permitDeserialization) { _resCache = resCache; _store = new BinaryReader(stream, Encoding.UTF8); _ums = stream as UnmanagedMemoryStream; _permitDeserialization = permitDeserialization; ReadResources(); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "InitializeBinaryFormatter will get trimmed out when AllowCustomResourceTypes is set to false. When set to true, we will already throw a warning for this feature switch, so we suppress this one in order forthe user to only get one error.")] private object DeserializeObject(int typeIndex) { if (!AllowCustomResourceTypes) { throw new NotSupportedException(SR.ResourceManager_ReflectionNotAllowed); } if (!_permitDeserialization) { throw new NotSupportedException(SR.NotSupported_ResourceObjectSerialization); } if (Volatile.Read(ref _binaryFormatter) == null && !InitializeBinaryFormatter()) { throw new NotSupportedException(SR.BinaryFormatter_SerializationDisallowed); } Type type = FindType(typeIndex); object obj = s_deserializeMethod(_binaryFormatter, _store.BaseStream); if (obj.GetType() != type) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResType_SerBlobMismatch, type.FullName, obj.GetType().FullName)); } return obj; } [RequiresUnreferencedCode("The CustomResourceTypesSupport feature switch has been enabled for this app which is being trimmed. Custom readers as well as custom objects on the resources file are not observable by the trimmer and so required assemblies, types and members may be removed.")] private bool InitializeBinaryFormatter() { if ((object)Volatile.Read(ref s_binaryFormatterType) == null || Volatile.Read(ref s_deserializeMethod) == null) { Type type = Type.GetType("System.Runtime.Serialization.Formatters.Binary.BinaryFormatter, System.Runtime.Serialization.Formatters", throwOnError: true); MethodInfo method = type.GetMethod("Deserialize", new Type[1] { typeof(Stream) }); MethodInfo? method2 = typeof(ResourceReader).GetMethod("CreateUntypedDelegate", BindingFlags.Static | BindingFlags.NonPublic); object obj; if ((object)method2 == null) { obj = null; } else { MethodInfo methodInfo = method2.MakeGenericMethod(type); object[] parameters = new MethodInfo[1] { method }; obj = methodInfo.Invoke(null, parameters); } Func value = (Func)obj; Interlocked.CompareExchange(ref s_binaryFormatterType, type, null); Interlocked.CompareExchange(ref s_deserializeMethod, value, null); } Volatile.Write(ref _binaryFormatter, Activator.CreateInstance(s_binaryFormatterType)); return s_deserializeMethod != null; } private static Func CreateUntypedDelegate(MethodInfo method) { Func typedDelegate = (Func)Delegate.CreateDelegate(typeof(Func), null, method); return (object obj, Stream stream) => typedDelegate((TInstance)obj, stream); } private static bool ValidateReaderType(string readerType) { return ResourceManager.IsDefaultType(readerType, "System.Resources.ResourceReader"); } public void GetResourceData(string resourceName, out string resourceType, out byte[] resourceData) { if (resourceName == null) { throw new ArgumentNullException("resourceName"); } if (_resCache == null) { throw new InvalidOperationException(SR.ResourceReaderIsClosed); } int[] array = new int[_numResources]; int num = FindPosForResource(resourceName); if (num == -1) { throw new ArgumentException(SR.Format(SR.Arg_ResourceNameNotExist, resourceName)); } lock (this) { for (int i = 0; i < _numResources; i++) { _store.BaseStream.Position = _nameSectionOffset + GetNamePosition(i); int num2 = _store.Read7BitEncodedInt(); if (num2 < 0) { throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesNameInvalidOffset, num2)); } _store.BaseStream.Position += num2; int num3 = _store.ReadInt32(); if (num3 < 0 || num3 >= _store.BaseStream.Length - _dataSectionOffset) { throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, num3)); } array[i] = num3; } Array.Sort(array); int num4 = Array.BinarySearch(array, num); long num5 = ((num4 < _numResources - 1) ? (array[num4 + 1] + _dataSectionOffset) : _store.BaseStream.Length); int num6 = (int)(num5 - (num + _dataSectionOffset)); _store.BaseStream.Position = _dataSectionOffset + num; ResourceTypeCode resourceTypeCode = (ResourceTypeCode)_store.Read7BitEncodedInt(); if (resourceTypeCode < ResourceTypeCode.Null || (int)resourceTypeCode >= 64 + _typeTable.Length) { throw new BadImageFormatException(SR.BadImageFormat_InvalidType); } resourceType = TypeNameFromTypeCode(resourceTypeCode); num6 -= (int)(_store.BaseStream.Position - (_dataSectionOffset + num)); byte[] array2 = _store.ReadBytes(num6); if (array2.Length != num6) { throw new FormatException(SR.BadImageFormat_ResourceNameCorrupted); } resourceData = array2; } } public ResourceReader(string fileName) { _resCache = new Dictionary(FastResourceComparer.Default); _store = new BinaryReader(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.RandomAccess), Encoding.UTF8); try { ReadResources(); } catch { _store.Close(); throw; } } public ResourceReader(Stream stream) { if (stream == null) { throw new ArgumentNullException("stream"); } if (!stream.CanRead) { throw new ArgumentException(SR.Argument_StreamNotReadable); } _resCache = new Dictionary(FastResourceComparer.Default); _store = new BinaryReader(stream, Encoding.UTF8); _ums = stream as UnmanagedMemoryStream; ReadResources(); } public void Close() { Dispose(disposing: true); } public void Dispose() { Close(); } private unsafe void Dispose(bool disposing) { if (_store != null) { _resCache = null; if (disposing) { BinaryReader store = _store; _store = null; store?.Close(); } _store = null; _namePositions = null; _nameHashes = null; _ums = null; _namePositionsPtr = null; _nameHashesPtr = null; } } internal unsafe static int ReadUnalignedI4(int* p) { return BinaryPrimitives.ReadInt32LittleEndian(new ReadOnlySpan(p, 4)); } private void SkipString() { int num = _store.Read7BitEncodedInt(); if (num < 0) { throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength); } _store.BaseStream.Seek(num, SeekOrigin.Current); } private unsafe int GetNameHash(int index) { if (_ums == null) { return _nameHashes[index]; } return ReadUnalignedI4(_nameHashesPtr + index); } private unsafe int GetNamePosition(int index) { int num = ((_ums != null) ? ReadUnalignedI4(_namePositionsPtr + index) : _namePositions[index]); if (num < 0 || num > _dataSectionOffset - _nameSectionOffset) { throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesNameInvalidOffset, num)); } return num; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public IDictionaryEnumerator GetEnumerator() { if (_resCache == null) { throw new InvalidOperationException(SR.ResourceReaderIsClosed); } return new ResourceEnumerator(this); } internal ResourceEnumerator GetEnumeratorInternal() { return new ResourceEnumerator(this); } internal int FindPosForResource(string name) { int num = FastResourceComparer.HashFunction(name); int num2 = 0; int i = _numResources - 1; int num3 = -1; bool flag = false; while (num2 <= i) { num3 = num2 + i >> 1; int nameHash = GetNameHash(num3); int num4 = ((nameHash != num) ? ((nameHash >= num) ? 1 : (-1)) : 0); if (num4 == 0) { flag = true; break; } if (num4 < 0) { num2 = num3 + 1; } else { i = num3 - 1; } } if (!flag) { return -1; } if (num2 != num3) { num2 = num3; while (num2 > 0 && GetNameHash(num2 - 1) == num) { num2--; } } if (i != num3) { for (i = num3; i < _numResources - 1 && GetNameHash(i + 1) == num; i++) { } } lock (this) { for (int j = num2; j <= i; j++) { _store.BaseStream.Seek(_nameSectionOffset + GetNamePosition(j), SeekOrigin.Begin); if (CompareStringEqualsName(name)) { int num5 = _store.ReadInt32(); if (num5 < 0 || num5 >= _store.BaseStream.Length - _dataSectionOffset) { throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, num5)); } return num5; } } } return -1; } private unsafe bool CompareStringEqualsName(string name) { int num = _store.Read7BitEncodedInt(); if (num < 0) { throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength); } if (_ums != null) { byte* positionPointer = _ums.PositionPointer; _ums.Seek(num, SeekOrigin.Current); if (_ums.Position > _ums.Length) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesNameTooLong); } return FastResourceComparer.CompareOrdinal(positionPointer, num, name) == 0; } byte[] array = new byte[num]; int num2 = num; while (num2 > 0) { int num3 = _store.Read(array, num - num2, num2); if (num3 == 0) { throw new BadImageFormatException(SR.BadImageFormat_ResourceNameCorrupted); } num2 -= num3; } return FastResourceComparer.CompareOrdinal(array, num / 2, name) == 0; } private unsafe string AllocateStringForNameIndex(int index, out int dataOffset) { long num = GetNamePosition(index); int num2; byte[] array; lock (this) { _store.BaseStream.Seek(num + _nameSectionOffset, SeekOrigin.Begin); num2 = _store.Read7BitEncodedInt(); if (num2 < 0) { throw new BadImageFormatException(SR.BadImageFormat_NegativeStringLength); } if (_ums != null) { if (_ums.Position > _ums.Length - num2) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourcesIndexTooLong, index)); } string text = null; char* positionPointer = (char*)_ums.PositionPointer; _ = BitConverter.IsLittleEndian; text = new string(positionPointer, 0, num2 / 2); _ums.Position += num2; dataOffset = _store.ReadInt32(); if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset) { throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, dataOffset)); } return text; } array = new byte[num2]; int num3 = num2; while (num3 > 0) { int num4 = _store.Read(array, num2 - num3, num3); if (num4 == 0) { throw new EndOfStreamException(SR.Format(SR.BadImageFormat_ResourceNameCorrupted_NameIndex, index)); } num3 -= num4; } dataOffset = _store.ReadInt32(); if (dataOffset < 0 || dataOffset >= _store.BaseStream.Length - _dataSectionOffset) { throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, dataOffset)); } } return Encoding.Unicode.GetString(array, 0, num2); } private object GetValueForNameIndex(int index) { long num = GetNamePosition(index); lock (this) { _store.BaseStream.Seek(num + _nameSectionOffset, SeekOrigin.Begin); SkipString(); int num2 = _store.ReadInt32(); if (num2 < 0 || num2 >= _store.BaseStream.Length - _dataSectionOffset) { throw new FormatException(SR.Format(SR.BadImageFormat_ResourcesDataInvalidOffset, num2)); } if (_version == 1) { return LoadObjectV1(num2); } ResourceTypeCode typeCode; return LoadObjectV2(num2, out typeCode); } } internal string LoadString(int pos) { _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); string result = null; int num = _store.Read7BitEncodedInt(); if (_version == 1) { if (num == -1) { return null; } if (FindType(num) != typeof(string)) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Type, FindType(num).FullName)); } result = _store.ReadString(); } else { ResourceTypeCode resourceTypeCode = (ResourceTypeCode)num; if (resourceTypeCode != ResourceTypeCode.String && resourceTypeCode != 0) { throw new InvalidOperationException(SR.Format(p1: (resourceTypeCode >= ResourceTypeCode.StartOfUserTypes) ? FindType((int)(resourceTypeCode - 64)).FullName : resourceTypeCode.ToString(), resourceFormat: SR.InvalidOperation_ResourceNotString_Type)); } if (resourceTypeCode == ResourceTypeCode.String) { result = _store.ReadString(); } } return result; } internal object LoadObject(int pos) { if (_version == 1) { return LoadObjectV1(pos); } ResourceTypeCode typeCode; return LoadObjectV2(pos, out typeCode); } internal object LoadObject(int pos, out ResourceTypeCode typeCode) { if (_version == 1) { object obj = LoadObjectV1(pos); typeCode = ((obj is string) ? ResourceTypeCode.String : ResourceTypeCode.StartOfUserTypes); return obj; } return LoadObjectV2(pos, out typeCode); } internal object LoadObjectV1(int pos) { try { return _LoadObjectV1(pos); } catch (EndOfStreamException inner) { throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, inner); } catch (ArgumentOutOfRangeException inner2) { throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, inner2); } } private object _LoadObjectV1(int pos) { _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); int num = _store.Read7BitEncodedInt(); if (num == -1) { return null; } Type type = FindType(num); if (type == typeof(string)) { return _store.ReadString(); } if (type == typeof(int)) { return _store.ReadInt32(); } if (type == typeof(byte)) { return _store.ReadByte(); } if (type == typeof(sbyte)) { return _store.ReadSByte(); } if (type == typeof(short)) { return _store.ReadInt16(); } if (type == typeof(long)) { return _store.ReadInt64(); } if (type == typeof(ushort)) { return _store.ReadUInt16(); } if (type == typeof(uint)) { return _store.ReadUInt32(); } if (type == typeof(ulong)) { return _store.ReadUInt64(); } if (type == typeof(float)) { return _store.ReadSingle(); } if (type == typeof(double)) { return _store.ReadDouble(); } if (type == typeof(DateTime)) { return new DateTime(_store.ReadInt64()); } if (type == typeof(TimeSpan)) { return new TimeSpan(_store.ReadInt64()); } if (type == typeof(decimal)) { int[] array = new int[4]; for (int i = 0; i < array.Length; i++) { array[i] = _store.ReadInt32(); } return new decimal(array); } return DeserializeObject(num); } internal object LoadObjectV2(int pos, out ResourceTypeCode typeCode) { try { return _LoadObjectV2(pos, out typeCode); } catch (EndOfStreamException inner) { throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, inner); } catch (ArgumentOutOfRangeException inner2) { throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch, inner2); } } private unsafe object _LoadObjectV2(int pos, out ResourceTypeCode typeCode) { _store.BaseStream.Seek(_dataSectionOffset + pos, SeekOrigin.Begin); typeCode = (ResourceTypeCode)_store.Read7BitEncodedInt(); switch (typeCode) { case ResourceTypeCode.Null: return null; case ResourceTypeCode.String: return _store.ReadString(); case ResourceTypeCode.Boolean: return _store.ReadBoolean(); case ResourceTypeCode.Char: return (char)_store.ReadUInt16(); case ResourceTypeCode.Byte: return _store.ReadByte(); case ResourceTypeCode.SByte: return _store.ReadSByte(); case ResourceTypeCode.Int16: return _store.ReadInt16(); case ResourceTypeCode.UInt16: return _store.ReadUInt16(); case ResourceTypeCode.Int32: return _store.ReadInt32(); case ResourceTypeCode.UInt32: return _store.ReadUInt32(); case ResourceTypeCode.Int64: return _store.ReadInt64(); case ResourceTypeCode.UInt64: return _store.ReadUInt64(); case ResourceTypeCode.Single: return _store.ReadSingle(); case ResourceTypeCode.Double: return _store.ReadDouble(); case ResourceTypeCode.Decimal: return _store.ReadDecimal(); case ResourceTypeCode.DateTime: { long dateData = _store.ReadInt64(); return DateTime.FromBinary(dateData); } case ResourceTypeCode.TimeSpan: { long ticks = _store.ReadInt64(); return new TimeSpan(ticks); } case ResourceTypeCode.ByteArray: { int num2 = _store.ReadInt32(); if (num2 < 0) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, num2)); } if (_ums == null) { if (num2 > _store.BaseStream.Length) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, num2)); } return _store.ReadBytes(num2); } if (num2 > _ums.Length - _ums.Position) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, num2)); } byte[] array2 = new byte[num2]; int num3 = _ums.Read(array2, 0, num2); return array2; } case ResourceTypeCode.Stream: { int num = _store.ReadInt32(); if (num < 0) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, num)); } if (_ums == null) { byte[] array = _store.ReadBytes(num); return new PinnedBufferMemoryStream(array); } if (num > _ums.Length - _ums.Position) { throw new BadImageFormatException(SR.Format(SR.BadImageFormat_ResourceDataLengthInvalid, num)); } return new UnmanagedMemoryStream(_ums.PositionPointer, num, num, FileAccess.Read); } default: { if (typeCode < ResourceTypeCode.StartOfUserTypes) { throw new BadImageFormatException(SR.BadImageFormat_TypeMismatch); } int typeIndex = (int)(typeCode - 64); return DeserializeObject(typeIndex); } } } [MemberNotNull("_typeTable")] [MemberNotNull("_typeNamePositions")] private void ReadResources() { try { _ReadResources(); } catch (EndOfStreamException inner) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, inner); } catch (IndexOutOfRangeException inner2) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted, inner2); } } [MemberNotNull("_typeTable")] [MemberNotNull("_typeNamePositions")] private unsafe void _ReadResources() { int num = _store.ReadInt32(); if (num != ResourceManager.MagicNumber) { throw new ArgumentException(SR.Resources_StreamNotValid); } int num2 = _store.ReadInt32(); int num3 = _store.ReadInt32(); if (num3 < 0 || num2 < 0) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted); } if (num2 > 1) { _store.BaseStream.Seek(num3, SeekOrigin.Current); } else { string text = _store.ReadString(); if (!ValidateReaderType(text)) { throw new NotSupportedException(SR.Format(SR.NotSupported_WrongResourceReader_Type, text)); } SkipString(); } int num4 = _store.ReadInt32(); if (num4 != 2 && num4 != 1) { throw new ArgumentException(SR.Format(SR.Arg_ResourceFileUnsupportedVersion, 2, num4)); } _version = num4; _numResources = _store.ReadInt32(); if (_numResources < 0) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted); } int num5 = _store.ReadInt32(); if (num5 < 0) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted); } _typeTable = new Type[num5]; _typeNamePositions = new int[num5]; for (int i = 0; i < num5; i++) { _typeNamePositions[i] = (int)_store.BaseStream.Position; SkipString(); } long position = _store.BaseStream.Position; int num6 = (int)position & 7; if (num6 != 0) { for (int j = 0; j < 8 - num6; j++) { _store.ReadByte(); } } if (_ums == null) { _nameHashes = new int[_numResources]; for (int k = 0; k < _numResources; k++) { _nameHashes[k] = _store.ReadInt32(); } } else { int num7 = 4 * _numResources; if (num7 < 0) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted); } _nameHashesPtr = (int*)_ums.PositionPointer; _ums.Seek(num7, SeekOrigin.Current); _ = _ums.PositionPointer; } if (_ums == null) { _namePositions = new int[_numResources]; for (int l = 0; l < _numResources; l++) { int num8 = _store.ReadInt32(); if (num8 < 0) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted); } _namePositions[l] = num8; } } else { int num9 = 4 * _numResources; if (num9 < 0) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted); } _namePositionsPtr = (int*)_ums.PositionPointer; _ums.Seek(num9, SeekOrigin.Current); _ = _ums.PositionPointer; } _dataSectionOffset = _store.ReadInt32(); if (_dataSectionOffset < 0) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted); } _nameSectionOffset = _store.BaseStream.Position; if (_dataSectionOffset < _nameSectionOffset) { throw new BadImageFormatException(SR.BadImageFormat_ResourcesHeaderCorrupted); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "UseReflectionToGetType will get trimmed out when AllowCustomResourceTypes is set to false. When set to true, we will already throw a warning for this feature switch, so we suppress this one in order forthe user to only get one error.")] private Type FindType(int typeIndex) { if (!AllowCustomResourceTypes) { throw new NotSupportedException(SR.ResourceManager_ReflectionNotAllowed); } if (typeIndex < 0 || typeIndex >= _typeTable.Length) { throw new BadImageFormatException(SR.BadImageFormat_InvalidType); } return _typeTable[typeIndex] ?? UseReflectionToGetType(typeIndex); } [RequiresUnreferencedCode("The CustomResourceTypesSupport feature switch has been enabled for this app which is being trimmed. Custom readers as well as custom objects on the resources file are not observable by the trimmer and so required assemblies, types and members may be removed.")] private Type UseReflectionToGetType(int typeIndex) { long position = _store.BaseStream.Position; try { _store.BaseStream.Position = _typeNamePositions[typeIndex]; string typeName = _store.ReadString(); _typeTable[typeIndex] = Type.GetType(typeName, throwOnError: true); return _typeTable[typeIndex]; } catch (FileNotFoundException) { throw new NotSupportedException(SR.NotSupported_ResourceObjectSerialization); } finally { _store.BaseStream.Position = position; } } private string TypeNameFromTypeCode(ResourceTypeCode typeCode) { if (typeCode < ResourceTypeCode.StartOfUserTypes) { return "ResourceTypeCode." + typeCode; } int num = (int)(typeCode - 64); long position = _store.BaseStream.Position; try { _store.BaseStream.Position = _typeNamePositions[num]; return _store.ReadString(); } finally { _store.BaseStream.Position = position; } } } internal readonly struct ResourceLocator { internal int DataPosition { get; } internal object Value { get; } internal ResourceLocator(int dataPos, object value) { DataPosition = dataPos; Value = value; } internal static bool CanCache(ResourceTypeCode value) { return value <= ResourceTypeCode.TimeSpan; } } public class ResourceSet : IDisposable, System.Collections.IEnumerable { protected IResourceReader Reader; private Dictionary _table; private Dictionary _caseInsensitiveTable; protected ResourceSet() { _table = new Dictionary(); } internal ResourceSet(bool junk) { } public ResourceSet(string fileName) : this() { Reader = new ResourceReader(fileName); ReadResources(); } public ResourceSet(Stream stream) : this() { Reader = new ResourceReader(stream); ReadResources(); } public ResourceSet(IResourceReader reader) : this() { Reader = reader ?? throw new ArgumentNullException("reader"); ReadResources(); } public virtual void Close() { Dispose(disposing: true); } protected virtual void Dispose(bool disposing) { if (disposing) { IResourceReader reader = Reader; Reader = null; reader?.Close(); } Reader = null; _caseInsensitiveTable = null; _table = null; } public void Dispose() { Dispose(disposing: true); } public virtual Type GetDefaultReader() { return typeof(ResourceReader); } public virtual Type GetDefaultWriter() { return Type.GetType("System.Resources.ResourceWriter, System.Resources.Writer", throwOnError: true); } public virtual IDictionaryEnumerator GetEnumerator() { return GetEnumeratorHelper(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumeratorHelper(); } private IDictionaryEnumerator GetEnumeratorHelper() { IDictionary table = _table; if (table == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); } return table.GetEnumerator(); } public virtual string? GetString(string name) { object objectInternal = GetObjectInternal(name); if (objectInternal is string result) { return result; } if (objectInternal == null) { return null; } throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name)); } public virtual string? GetString(string name, bool ignoreCase) { object objectInternal = GetObjectInternal(name); if (objectInternal is string result) { return result; } if (objectInternal != null) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name)); } if (!ignoreCase) { return null; } objectInternal = GetCaseInsensitiveObjectInternal(name); if (objectInternal is string result2) { return result2; } if (objectInternal == null) { return null; } throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name)); } public virtual object? GetObject(string name) { return GetObjectInternal(name); } public virtual object? GetObject(string name, bool ignoreCase) { object objectInternal = GetObjectInternal(name); if (objectInternal != null || !ignoreCase) { return objectInternal; } return GetCaseInsensitiveObjectInternal(name); } protected virtual void ReadResources() { IDictionaryEnumerator enumerator = Reader.GetEnumerator(); while (enumerator.MoveNext()) { _table.Add(enumerator.Key, enumerator.Value); } } private object GetObjectInternal(string name) { if (name == null) { throw new ArgumentNullException("name"); } Dictionary table = _table; if (table == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); } table.TryGetValue(name, out var value); return value; } private object GetCaseInsensitiveObjectInternal(string name) { Dictionary table = _table; if (table == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); } Dictionary dictionary = _caseInsensitiveTable; if (dictionary == null) { dictionary = new Dictionary(table.Count, StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair item in table) { if (item.Key is string key) { dictionary.Add(key, item.Value); } } _caseInsensitiveTable = dictionary; } dictionary.TryGetValue(name, out var value); return value; } } internal enum ResourceTypeCode { Null = 0, String = 1, Boolean = 2, Char = 3, Byte = 4, SByte = 5, Int16 = 6, UInt16 = 7, Int32 = 8, UInt32 = 9, Int64 = 10, UInt64 = 11, Single = 12, Double = 13, Decimal = 14, DateTime = 15, TimeSpan = 16, LastPrimitive = 16, ByteArray = 32, Stream = 33, StartOfUserTypes = 64 } internal sealed class RuntimeResourceSet : ResourceSet, System.Collections.IEnumerable { private Dictionary _resCache; private ResourceReader _defaultReader; private Dictionary _caseInsensitiveTable; internal RuntimeResourceSet(string fileName) : this(new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { } internal RuntimeResourceSet(Stream stream, bool permitDeserialization = false) : base(junk: false) { _resCache = new Dictionary(FastResourceComparer.Default); _defaultReader = new ResourceReader(stream, _resCache, permitDeserialization); } protected override void Dispose(bool disposing) { if (_defaultReader != null) { if (disposing) { _defaultReader?.Close(); } _defaultReader = null; _resCache = null; _caseInsensitiveTable = null; base.Dispose(disposing); } } public override IDictionaryEnumerator GetEnumerator() { return GetEnumeratorHelper(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumeratorHelper(); } private IDictionaryEnumerator GetEnumeratorHelper() { ResourceReader defaultReader = _defaultReader; if (defaultReader == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); } return defaultReader.GetEnumerator(); } public override string GetString(string key) { object @object = GetObject(key, ignoreCase: false, isString: true); return (string)@object; } public override string GetString(string key, bool ignoreCase) { object @object = GetObject(key, ignoreCase, isString: true); return (string)@object; } public override object GetObject(string key) { return GetObject(key, ignoreCase: false, isString: false); } public override object GetObject(string key, bool ignoreCase) { return GetObject(key, ignoreCase, isString: false); } private object GetObject(string key, bool ignoreCase, bool isString) { if (key == null) { throw new ArgumentNullException("key"); } ResourceReader defaultReader = _defaultReader; Dictionary resCache = _resCache; if (defaultReader == null || resCache == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); } ResourceLocator value; object obj; lock (resCache) { int dataPosition; if (resCache.TryGetValue(key, out value)) { obj = value.Value; if (obj != null) { return obj; } dataPosition = value.DataPosition; ResourceTypeCode typeCode; return isString ? defaultReader.LoadString(dataPosition) : defaultReader.LoadObject(dataPosition, out typeCode); } dataPosition = defaultReader.FindPosForResource(key); if (dataPosition >= 0) { obj = ReadValue(defaultReader, dataPosition, isString, out value); resCache[key] = value; return obj; } } if (!ignoreCase) { return null; } bool flag = false; Dictionary dictionary = _caseInsensitiveTable; if (dictionary == null) { dictionary = new Dictionary(StringComparer.OrdinalIgnoreCase); flag = true; } lock (dictionary) { if (flag) { ResourceReader.ResourceEnumerator enumeratorInternal = defaultReader.GetEnumeratorInternal(); while (enumeratorInternal.MoveNext()) { string key2 = (string)enumeratorInternal.Key; ResourceLocator value2 = new ResourceLocator(enumeratorInternal.DataPosition, null); dictionary.Add(key2, value2); } _caseInsensitiveTable = dictionary; } if (!dictionary.TryGetValue(key, out value)) { return null; } if (value.Value != null) { return value.Value; } obj = ReadValue(defaultReader, value.DataPosition, isString, out value); if (value.Value != null) { dictionary[key] = value; } } return obj; } private static object ReadValue(ResourceReader reader, int dataPos, bool isString, out ResourceLocator locator) { object obj; ResourceTypeCode typeCode; if (isString) { obj = reader.LoadString(dataPos); typeCode = ResourceTypeCode.String; } else { obj = reader.LoadObject(dataPos, out typeCode); } locator = new ResourceLocator(dataPos, ResourceLocator.CanCache(typeCode) ? obj : null); return obj; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public sealed class SatelliteContractVersionAttribute : Attribute { public string Version { get; } public SatelliteContractVersionAttribute(string version) { if (version == null) { throw new ArgumentNullException("version"); } Version = version; } } public enum UltimateResourceFallbackLocation { MainAssembly, Satellite } } namespace System.Reflection { public abstract class Assembly : ICustomAttributeProvider, ISerializable { private static readonly Dictionary s_loadfile = new Dictionary(); private static readonly List s_loadFromAssemblyList = new List(); private static bool s_loadFromHandlerSet; private static int s_cachedSerializationSwitch; private static bool s_forceNullEntryPoint; public virtual IEnumerable DefinedTypes { [RequiresUnreferencedCode("Types might be removed")] get { Type[] types = GetTypes(); TypeInfo[] array = new TypeInfo[types.Length]; for (int i = 0; i < types.Length; i++) { TypeInfo typeInfo = types[i].GetTypeInfo(); if (typeInfo == null) { throw new NotSupportedException(SR.Format(SR.NotSupported_NoTypeInfo, types[i].FullName)); } array[i] = typeInfo; } return array; } } public virtual IEnumerable ExportedTypes { [RequiresUnreferencedCode("Types might be removed")] get { return GetExportedTypes(); } } [RequiresAssemblyFiles("This member throws an exception for assemblies embedded in a single-file app")] public virtual string? CodeBase { get { throw NotImplemented.ByDesign; } } public virtual MethodInfo? EntryPoint { get { throw NotImplemented.ByDesign; } } public virtual string? FullName { get { throw NotImplemented.ByDesign; } } public virtual string ImageRuntimeVersion { get { throw NotImplemented.ByDesign; } } public virtual bool IsDynamic => false; public virtual string Location { get { throw NotImplemented.ByDesign; } } public virtual bool ReflectionOnly { get { throw NotImplemented.ByDesign; } } public virtual bool IsCollectible => true; public bool IsFullyTrusted => true; public virtual IEnumerable CustomAttributes => GetCustomAttributesData(); [RequiresAssemblyFiles("This member throws an exception for assemblies embedded in a single-file app")] public virtual string EscapedCodeBase => AssemblyName.EscapeCodeBase(CodeBase); public virtual Module ManifestModule { get { throw NotImplemented.ByDesign; } } public virtual IEnumerable Modules => GetLoadedModules(getResourceModules: true); [Obsolete("The Global Assembly Cache is not supported.", DiagnosticId = "SYSLIB0005", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public virtual bool GlobalAssemblyCache { get { throw NotImplemented.ByDesign; } } public virtual long HostContext { get { throw NotImplemented.ByDesign; } } public virtual SecurityRuleSet SecurityRuleSet => SecurityRuleSet.None; public virtual event ModuleResolveEventHandler? ModuleResolve { add { throw NotImplemented.ByDesign; } remove { throw NotImplemented.ByDesign; } } public static Assembly Load(string assemblyString) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeAssembly.InternalLoad(assemblyString, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext); } [Obsolete("Assembly.LoadWithPartialName has been deprecated. Use Assembly.Load() instead.")] public static Assembly? LoadWithPartialName(string partialName) { if (partialName == null) { throw new ArgumentNullException("partialName"); } if (partialName.Length == 0 || partialName[0] == '\0') { throw new ArgumentException(SR.Format_StringZeroLength, "partialName"); } try { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeAssembly.InternalLoad(partialName, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext); } catch (FileNotFoundException) { return null; } } public static Assembly Load(AssemblyName assemblyRef) { if (assemblyRef == null) { throw new ArgumentNullException("assemblyRef"); } StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeAssembly.InternalLoad(assemblyRef, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetExecutingAssemblyNative(StackCrawlMarkHandle stackMark, ObjectHandleOnStack retAssembly); internal static RuntimeAssembly GetExecutingAssembly(ref StackCrawlMark stackMark) { RuntimeAssembly o = null; GetExecutingAssemblyNative(new StackCrawlMarkHandle(ref stackMark), ObjectHandleOnStack.Create(ref o)); return o; } public static Assembly GetExecutingAssembly() { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return GetExecutingAssembly(ref stackMark); } public static Assembly GetCallingAssembly() { StackCrawlMark stackMark = StackCrawlMark.LookForMyCallersCaller; return GetExecutingAssembly(ref stackMark); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetEntryAssemblyNative(ObjectHandleOnStack retAssembly); private static Assembly GetEntryAssemblyInternal() { RuntimeAssembly o = null; GetEntryAssemblyNative(ObjectHandleOnStack.Create(ref o)); return o; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal bool IsRuntimeImplemented() { return this is RuntimeAssembly; } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern uint GetAssemblyCount(); [RequiresUnreferencedCode("Types might be removed")] public virtual Type[] GetTypes() { Module[] modules = GetModules(getResourceModules: false); if (modules.Length == 1) { return modules[0].GetTypes(); } int num = 0; Type[][] array = new Type[modules.Length][]; for (int i = 0; i < array.Length; i++) { array[i] = modules[i].GetTypes(); num += array[i].Length; } int num2 = 0; Type[] array2 = new Type[num]; for (int j = 0; j < array.Length; j++) { int num3 = array[j].Length; Array.Copy(array[j], 0, array2, num2, num3); num2 += num3; } return array2; } [RequiresUnreferencedCode("Types might be removed")] public virtual Type[] GetExportedTypes() { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Types might be removed")] public virtual Type[] GetForwardedTypes() { throw NotImplemented.ByDesign; } public virtual ManifestResourceInfo? GetManifestResourceInfo(string resourceName) { throw NotImplemented.ByDesign; } public virtual string[] GetManifestResourceNames() { throw NotImplemented.ByDesign; } public virtual Stream? GetManifestResourceStream(string name) { throw NotImplemented.ByDesign; } public virtual Stream? GetManifestResourceStream(Type type, string name) { throw NotImplemented.ByDesign; } public virtual AssemblyName GetName() { return GetName(copiedName: false); } public virtual AssemblyName GetName(bool copiedName) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Types might be removed")] public virtual Type? GetType(string name) { return GetType(name, throwOnError: false, ignoreCase: false); } [RequiresUnreferencedCode("Types might be removed")] public virtual Type? GetType(string name, bool throwOnError) { return GetType(name, throwOnError, ignoreCase: false); } [RequiresUnreferencedCode("Types might be removed")] public virtual Type? GetType(string name, bool throwOnError, bool ignoreCase) { throw NotImplemented.ByDesign; } public virtual bool IsDefined(Type attributeType, bool inherit) { throw NotImplemented.ByDesign; } public virtual IList GetCustomAttributesData() { throw NotImplemented.ByDesign; } public virtual object[] GetCustomAttributes(bool inherit) { throw NotImplemented.ByDesign; } public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Assembly.CreateInstance is not supported with trimming. Use Type.GetType instead.")] public object? CreateInstance(string typeName) { return CreateInstance(typeName, ignoreCase: false, BindingFlags.Instance | BindingFlags.Public, null, null, null, null); } [RequiresUnreferencedCode("Assembly.CreateInstance is not supported with trimming. Use Type.GetType instead.")] public object? CreateInstance(string typeName, bool ignoreCase) { return CreateInstance(typeName, ignoreCase, BindingFlags.Instance | BindingFlags.Public, null, null, null, null); } [RequiresUnreferencedCode("Assembly.CreateInstance is not supported with trimming. Use Type.GetType instead.")] public virtual object? CreateInstance(string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder? binder, object[]? args, CultureInfo? culture, object[]? activationAttributes) { Type type = GetType(typeName, throwOnError: false, ignoreCase); if (type == null) { return null; } return Activator.CreateInstance(type, bindingAttr, binder, args, culture, activationAttributes); } public virtual Module? GetModule(string name) { throw NotImplemented.ByDesign; } public Module[] GetModules() { return GetModules(getResourceModules: false); } public virtual Module[] GetModules(bool getResourceModules) { throw NotImplemented.ByDesign; } public Module[] GetLoadedModules() { return GetLoadedModules(getResourceModules: false); } public virtual Module[] GetLoadedModules(bool getResourceModules) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Assembly references might be removed")] public virtual AssemblyName[] GetReferencedAssemblies() { throw NotImplemented.ByDesign; } public virtual Assembly GetSatelliteAssembly(CultureInfo culture) { throw NotImplemented.ByDesign; } public virtual Assembly GetSatelliteAssembly(CultureInfo culture, Version? version) { throw NotImplemented.ByDesign; } [RequiresAssemblyFiles("This member throws an exception for assemblies embedded in a single-file app")] public virtual FileStream? GetFile(string name) { throw NotImplemented.ByDesign; } [RequiresAssemblyFiles("This member throws an exception for assemblies embedded in a single-file app")] public virtual FileStream[] GetFiles() { return GetFiles(getResourceModules: false); } [RequiresAssemblyFiles("This member throws an exception for assemblies embedded in a single-file app")] public virtual FileStream[] GetFiles(bool getResourceModules) { throw NotImplemented.ByDesign; } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw NotImplemented.ByDesign; } public override string ToString() { return FullName ?? base.ToString(); } public override bool Equals(object? o) { return base.Equals(o); } public override int GetHashCode() { return base.GetHashCode(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Assembly? left, Assembly? right) { if ((object)right == null) { if ((object)left != null) { return false; } return true; } if ((object)left == right) { return true; } return left?.Equals(right) ?? false; } public static bool operator !=(Assembly? left, Assembly? right) { return !(left == right); } public static string CreateQualifiedName(string? assemblyName, string? typeName) { return typeName + ", " + assemblyName; } public static Assembly? GetAssembly(Type type) { if (type == null) { throw new ArgumentNullException("type"); } Module module = type.Module; if (module == null) { return null; } return module.Assembly; } public static Assembly? GetEntryAssembly() { if (s_forceNullEntryPoint) { return null; } return GetEntryAssemblyInternal(); } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public static Assembly Load(byte[] rawAssembly) { return Load(rawAssembly, null); } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public static Assembly Load(byte[] rawAssembly, byte[]? rawSymbolStore) { if (rawAssembly == null) { throw new ArgumentNullException("rawAssembly"); } if (rawAssembly.Length == 0) { throw new BadImageFormatException(SR.BadImageFormat_BadILFormat); } SerializationInfo.ThrowIfDeserializationInProgress("AllowAssembliesFromByteArrays", ref s_cachedSerializationSwitch); AssemblyLoadContext assemblyLoadContext = new IndividualAssemblyLoadContext("Assembly.Load(byte[], ...)"); return assemblyLoadContext.InternalLoad(rawAssembly, rawSymbolStore); } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public static Assembly LoadFile(string path) { if (path == null) { throw new ArgumentNullException("path"); } if (PathInternal.IsPartiallyQualified(path)) { throw new ArgumentException(SR.Format(SR.Argument_AbsolutePathRequired, path), "path"); } string fullPath = Path.GetFullPath(path); lock (s_loadfile) { if (s_loadfile.TryGetValue(fullPath, out var value)) { return value; } AssemblyLoadContext assemblyLoadContext = new IndividualAssemblyLoadContext("Assembly.LoadFile(" + fullPath + ")"); value = assemblyLoadContext.LoadFromAssemblyPath(fullPath); s_loadfile.Add(fullPath, value); return value; } } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] [UnconditionalSuppressMessage("SingleFile", "IL3000:Avoid accessing Assembly file path when publishing as a single file", Justification = "The assembly is loaded by specifying a path outside of the single-file bundle, the location of the path will not be empty if the path exist, otherwise it will be handled as null")] private static Assembly LoadFromResolveHandler(object sender, ResolveEventArgs args) { Assembly requestingAssembly = args.RequestingAssembly; if (requestingAssembly == null) { return null; } if (AssemblyLoadContext.Default != AssemblyLoadContext.GetLoadContext(requestingAssembly)) { return null; } string location = requestingAssembly.Location; if (string.IsNullOrEmpty(location)) { return null; } location = Path.GetFullPath(location); lock (s_loadFromAssemblyList) { if (!s_loadFromAssemblyList.Contains(location)) { if (AssemblyLoadContext.IsTracingEnabled()) { AssemblyLoadContext.TraceAssemblyLoadFromResolveHandlerInvoked(args.Name, isTrackedAssembly: false, location, null); } return null; } } AssemblyName assemblyName = new AssemblyName(args.Name); string text = Path.Combine(Path.GetDirectoryName(location), assemblyName.Name + ".dll"); if (AssemblyLoadContext.IsTracingEnabled()) { AssemblyLoadContext.TraceAssemblyLoadFromResolveHandlerInvoked(args.Name, isTrackedAssembly: true, location, text); } try { return LoadFrom(text); } catch (FileNotFoundException) { return null; } } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public static Assembly LoadFrom(string assemblyFile) { if (assemblyFile == null) { throw new ArgumentNullException("assemblyFile"); } string fullPath = Path.GetFullPath(assemblyFile); if (!s_loadFromHandlerSet) { lock (s_loadFromAssemblyList) { if (!s_loadFromHandlerSet) { AssemblyLoadContext.AssemblyResolve += LoadFromResolveHandler; s_loadFromHandlerSet = true; } } } lock (s_loadFromAssemblyList) { if (!s_loadFromAssemblyList.Contains(fullPath)) { s_loadFromAssemblyList.Add(fullPath); } } return AssemblyLoadContext.Default.LoadFromAssemblyPath(fullPath); } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public static Assembly LoadFrom(string assemblyFile, byte[]? hashValue, AssemblyHashAlgorithm hashAlgorithm) { throw new NotSupportedException(SR.NotSupported_AssemblyLoadFromHash); } [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public static Assembly UnsafeLoadFrom(string assemblyFile) { return LoadFrom(assemblyFile); } [RequiresUnreferencedCode("Types and members the loaded module depends on might be removed")] public Module LoadModule(string moduleName, byte[]? rawModule) { return LoadModule(moduleName, rawModule, null); } [RequiresUnreferencedCode("Types and members the loaded module depends on might be removed")] public virtual Module LoadModule(string moduleName, byte[]? rawModule, byte[]? rawSymbolStore) { throw NotImplemented.ByDesign; } [Obsolete("ReflectionOnly loading is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0018", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public static Assembly ReflectionOnlyLoad(byte[] rawAssembly) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } [Obsolete("ReflectionOnly loading is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0018", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public static Assembly ReflectionOnlyLoad(string assemblyString) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } [Obsolete("ReflectionOnly loading is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0018", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] [RequiresUnreferencedCode("Types and members the loaded assembly depends on might be removed")] public static Assembly ReflectionOnlyLoadFrom(string assemblyFile) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_ReflectionOnly); } } public sealed class AssemblyName : ICloneable, IDeserializationCallback, ISerializable { private string _name; private byte[] _publicKey; private byte[] _publicKeyToken; private CultureInfo _cultureInfo; private string _codeBase; private Version _version; private AssemblyHashAlgorithm _hashAlgorithm; private AssemblyVersionCompatibility _versionCompatibility; private AssemblyNameFlags _flags; internal const char c_DummyChar = '\uffff'; private const short c_MaxAsciiCharsReallocate = 40; private const short c_MaxUnicodeCharsReallocate = 40; private const short c_MaxUTF_8BytesPerUnicodeChar = 4; private const short c_EncodedCharsPerByte = 3; private const string RFC3986ReservedMarks = ":/?#[]@!$&'()*+,;="; private const string RFC3986UnreservedMarks = "-._~"; public string? Name { get { return _name; } set { _name = value; } } public Version? Version { get { return _version; } set { _version = value; } } public CultureInfo? CultureInfo { get { return _cultureInfo; } set { _cultureInfo = value; } } public string? CultureName { get { return _cultureInfo?.Name; } set { _cultureInfo = ((value == null) ? null : new CultureInfo(value)); } } public string? CodeBase { [RequiresAssemblyFiles("The code will return an empty string for assemblies embedded in a single-file app")] get { return _codeBase; } set { _codeBase = value; } } [RequiresAssemblyFiles("The code will return an empty string for assemblies embedded in a single-file app")] public string? EscapedCodeBase { get { if (_codeBase == null) { return null; } return EscapeCodeBase(_codeBase); } } public ProcessorArchitecture ProcessorArchitecture { get { int num = (int)(_flags & (AssemblyNameFlags)112) >> 4; if (num > 5) { num = 0; } return (ProcessorArchitecture)num; } set { int num = (int)(value & (ProcessorArchitecture)7); if (num <= 5) { _flags = (AssemblyNameFlags)((long)_flags & 0xFFFFFF0FL); _flags |= (AssemblyNameFlags)(num << 4); } } } public AssemblyContentType ContentType { get { int num = (int)(_flags & (AssemblyNameFlags)3584) >> 9; if (num > 1) { num = 0; } return (AssemblyContentType)num; } set { int num = (int)(value & (AssemblyContentType)7); if (num <= 1) { _flags = (AssemblyNameFlags)((long)_flags & 0xFFFFF1FFL); _flags |= (AssemblyNameFlags)(num << 9); } } } public AssemblyNameFlags Flags { get { return _flags & (AssemblyNameFlags)(-3825); } set { _flags &= (AssemblyNameFlags)3824; _flags |= value & (AssemblyNameFlags)(-3825); } } public AssemblyHashAlgorithm HashAlgorithm { get { return _hashAlgorithm; } set { _hashAlgorithm = value; } } public AssemblyVersionCompatibility VersionCompatibility { get { return _versionCompatibility; } set { _versionCompatibility = value; } } [Obsolete("Strong name signing is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0017", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public StrongNameKeyPair? KeyPair { get { throw new PlatformNotSupportedException(SR.PlatformNotSupported_StrongNameSigning); } set { throw new PlatformNotSupportedException(SR.PlatformNotSupported_StrongNameSigning); } } public string FullName { get { if (string.IsNullOrEmpty(Name)) { return string.Empty; } byte[] pkt = _publicKeyToken ?? ComputePublicKeyToken(); return AssemblyNameFormatter.ComputeDisplayName(Name, Version, CultureName, pkt, Flags, ContentType); } } public AssemblyName(string assemblyName) { if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } if (assemblyName.Length == 0 || assemblyName[0] == '\0') { throw new ArgumentException(SR.Format_StringZeroLength); } _name = assemblyName; nInit(); } internal AssemblyName(string name, byte[] publicKey, byte[] publicKeyToken, Version version, CultureInfo cultureInfo, AssemblyHashAlgorithm hashAlgorithm, AssemblyVersionCompatibility versionCompatibility, string codeBase, AssemblyNameFlags flags) { _name = name; _publicKey = publicKey; _publicKeyToken = publicKeyToken; _version = version; _cultureInfo = cultureInfo; _hashAlgorithm = hashAlgorithm; _versionCompatibility = versionCompatibility; _codeBase = codeBase; _flags = flags; } [MethodImpl(MethodImplOptions.InternalCall)] internal extern void nInit(); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern AssemblyName nGetFileInformation(string s); internal static AssemblyName GetFileInformationCore(string assemblyFile) { string fullPath = Path.GetFullPath(assemblyFile); return nGetFileInformation(fullPath); } [MethodImpl(MethodImplOptions.InternalCall)] private extern byte[] ComputePublicKeyToken(); internal void SetProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm) { ProcessorArchitecture = CalculateProcArchIndex(pek, ifm, _flags); } internal static ProcessorArchitecture CalculateProcArchIndex(PortableExecutableKinds pek, ImageFileMachine ifm, AssemblyNameFlags flags) { if ((flags & (AssemblyNameFlags)240) == (AssemblyNameFlags)112) { return ProcessorArchitecture.None; } if ((pek & PortableExecutableKinds.PE32Plus) == PortableExecutableKinds.PE32Plus) { switch (ifm) { case ImageFileMachine.IA64: return ProcessorArchitecture.IA64; case ImageFileMachine.AMD64: return ProcessorArchitecture.Amd64; case ImageFileMachine.I386: if ((pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly) { return ProcessorArchitecture.MSIL; } break; } } else { switch (ifm) { case ImageFileMachine.I386: if ((pek & PortableExecutableKinds.Required32Bit) == PortableExecutableKinds.Required32Bit) { return ProcessorArchitecture.X86; } if ((pek & PortableExecutableKinds.ILOnly) == PortableExecutableKinds.ILOnly) { return ProcessorArchitecture.MSIL; } return ProcessorArchitecture.X86; case ImageFileMachine.ARM: return ProcessorArchitecture.Arm; } } return ProcessorArchitecture.None; } public AssemblyName() { _versionCompatibility = AssemblyVersionCompatibility.SameMachine; } public object Clone() { return new AssemblyName { _name = _name, _publicKey = (byte[])_publicKey?.Clone(), _publicKeyToken = (byte[])_publicKeyToken?.Clone(), _cultureInfo = _cultureInfo, _version = _version, _flags = _flags, _codeBase = _codeBase, _hashAlgorithm = _hashAlgorithm, _versionCompatibility = _versionCompatibility }; } public static AssemblyName GetAssemblyName(string assemblyFile) { if (assemblyFile == null) { throw new ArgumentNullException("assemblyFile"); } return GetFileInformationCore(assemblyFile); } public byte[]? GetPublicKey() { return _publicKey; } public void SetPublicKey(byte[]? publicKey) { _publicKey = publicKey; if (publicKey == null) { _flags &= ~AssemblyNameFlags.PublicKey; } else { _flags |= AssemblyNameFlags.PublicKey; } } public byte[]? GetPublicKeyToken() { return _publicKeyToken ?? (_publicKeyToken = ComputePublicKeyToken()); } public void SetPublicKeyToken(byte[]? publicKeyToken) { _publicKeyToken = publicKeyToken; } public override string ToString() { string fullName = FullName; if (fullName == null) { return base.ToString(); } return fullName; } public void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public void OnDeserialization(object? sender) { throw new PlatformNotSupportedException(); } public static bool ReferenceMatchesDefinition(AssemblyName? reference, AssemblyName? definition) { if (reference == definition) { return true; } if (reference == null) { throw new ArgumentNullException("reference"); } if (definition == null) { throw new ArgumentNullException("definition"); } string text = reference.Name ?? string.Empty; string value = definition.Name ?? string.Empty; return text.Equals(value, StringComparison.OrdinalIgnoreCase); } [RequiresAssemblyFiles("The code will return an empty string for assemblies embedded in a single-file app")] internal static string EscapeCodeBase(string codebase) { if (codebase == null) { return string.Empty; } int destPos = 0; char[] array = EscapeString(codebase, 0, codebase.Length, null, ref destPos, isUriString: true, '\uffff', '\uffff', '\uffff'); if (array == null) { return codebase; } return new string(array, 0, destPos); } internal unsafe static char[] EscapeString(string input, int start, int end, char[] dest, ref int destPos, bool isUriString, char force1, char force2, char rsvd) { int i = start; int num = start; byte* ptr = stackalloc byte[160]; fixed (char* ptr2 = input) { for (; i < end; i++) { char c = ptr2[i]; if (c > '\u007f') { short num2 = (short)Math.Min(end - i, 39); short num3 = 1; while (num3 < num2 && ptr2[i + num3] > '\u007f') { num3++; } if (ptr2[i + num3 - 1] >= '\ud800' && ptr2[i + num3 - 1] <= '\udbff') { if (num3 == 1 || num3 == end - i) { throw new FormatException(SR.Arg_FormatException); } num3++; } dest = EnsureDestinationSize(ptr2, dest, i, (short)(num3 * 4 * 3), 480, ref destPos, num); short num4 = (short)Encoding.UTF8.GetBytes(ptr2 + i, num3, ptr, 160); if (num4 == 0) { throw new FormatException(SR.Arg_FormatException); } i += num3 - 1; for (num3 = 0; num3 < num4; num3++) { EscapeAsciiChar((char)ptr[num3], dest, ref destPos); } num = i + 1; } else if (c == '%' && rsvd == '%') { dest = EnsureDestinationSize(ptr2, dest, i, 3, 120, ref destPos, num); if (i + 2 < end && HexConverter.IsHexChar(ptr2[i + 1]) && HexConverter.IsHexChar(ptr2[i + 2])) { dest[destPos++] = '%'; dest[destPos++] = ptr2[i + 1]; dest[destPos++] = ptr2[i + 2]; i += 2; } else { EscapeAsciiChar('%', dest, ref destPos); } num = i + 1; } else if (c == force1 || c == force2 || (c != rsvd && (isUriString ? (!IsReservedUnreservedOrHash(c)) : (!IsUnreserved(c))))) { dest = EnsureDestinationSize(ptr2, dest, i, 3, 120, ref destPos, num); EscapeAsciiChar(c, dest, ref destPos); num = i + 1; } } if (num != i && (num != start || dest != null)) { dest = EnsureDestinationSize(ptr2, dest, i, 0, 0, ref destPos, num); } } return dest; } private unsafe static char[] EnsureDestinationSize(char* pStr, char[] dest, int currentInputPos, short charsToAdd, short minReallocateChars, ref int destPos, int prevInputPos) { if (dest == null || dest.Length < destPos + (currentInputPos - prevInputPos) + charsToAdd) { char[] array = new char[destPos + (currentInputPos - prevInputPos) + minReallocateChars]; if (dest != null && destPos != 0) { Buffer.BlockCopy(dest, 0, array, 0, destPos << 1); } dest = array; } while (prevInputPos != currentInputPos) { dest[destPos++] = pStr[prevInputPos++]; } return dest; } internal static void EscapeAsciiChar(char ch, char[] to, ref int pos) { to[pos++] = '%'; to[pos++] = HexConverter.ToCharUpper((int)ch >> 4); to[pos++] = HexConverter.ToCharUpper(ch); } private static bool IsReservedUnreservedOrHash(char c) { if (IsUnreserved(c)) { return true; } return ":/?#[]@!$&'()*+,;=".Contains(c); } internal static bool IsUnreserved(char c) { if (IsAsciiLetterOrDigit(c)) { return true; } return "-._~".Contains(c); } internal static bool IsAsciiLetter(char character) { if (character < 'a' || character > 'z') { if (character >= 'A') { return character <= 'Z'; } return false; } return true; } internal static bool IsAsciiLetterOrDigit(char character) { if (!IsAsciiLetter(character)) { if (character >= '0') { return character <= '9'; } return false; } return true; } } internal static class Associates { [Flags] internal enum Attributes { ComposedOfAllVirtualMethods = 1, ComposedOfAllPrivateMethods = 2, ComposedOfNoPublicMembers = 4, ComposedOfNoStaticMembers = 8 } internal static bool IncludeAccessor(MethodInfo associate, bool nonPublic) { if ((object)associate == null) { return false; } if (nonPublic) { return true; } if (associate.IsPublic) { return true; } return false; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Module.ResolveMethod is marked as RequiresUnreferencedCode because it relies on tokenswhich are not guaranteed to be stable across trimming. So if somebody hardcodes a token it could break.The usage here is not like that as all these tokens come from existing metadata loaded from some ILand so trimming has no effect (the tokens are read AFTER trimming occured).")] private static RuntimeMethodInfo AssignAssociates(int tkMethod, RuntimeType declaredType, RuntimeType reflectedType) { if (MetadataToken.IsNullToken(tkMethod)) { return null; } bool flag = declaredType != reflectedType; IntPtr[] array = null; int typeInstCount = 0; RuntimeType[] instantiationInternal = declaredType.GetTypeHandleInternal().GetInstantiationInternal(); if (instantiationInternal != null) { typeInstCount = instantiationInternal.Length; array = new IntPtr[instantiationInternal.Length]; for (int i = 0; i < instantiationInternal.Length; i++) { array[i] = instantiationInternal[i].GetTypeHandleInternal().Value; } } RuntimeMethodHandleInternal runtimeMethodHandleInternal = ModuleHandle.ResolveMethodHandleInternal(RuntimeTypeHandle.GetModule(declaredType), tkMethod, array, typeInstCount, null, 0); if (flag) { MethodAttributes attributes = RuntimeMethodHandle.GetAttributes(runtimeMethodHandleInternal); if ((attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) { return null; } if ((attributes & MethodAttributes.Virtual) != 0 && (RuntimeTypeHandle.GetAttributes(declaredType) & TypeAttributes.ClassSemanticsMask) == 0) { int slot = RuntimeMethodHandle.GetSlot(runtimeMethodHandleInternal); runtimeMethodHandleInternal = RuntimeTypeHandle.GetMethodAt(reflectedType, slot); } } RuntimeMethodInfo runtimeMethodInfo = RuntimeType.GetMethodBase(reflectedType, runtimeMethodHandleInternal) as RuntimeMethodInfo; return runtimeMethodInfo ?? (reflectedType.Module.ResolveMethod(tkMethod, null, null) as RuntimeMethodInfo); } internal static void AssignAssociates(MetadataImport scope, int mdPropEvent, RuntimeType declaringType, RuntimeType reflectedType, out RuntimeMethodInfo addOn, out RuntimeMethodInfo removeOn, out RuntimeMethodInfo fireOn, out RuntimeMethodInfo getter, out RuntimeMethodInfo setter, out MethodInfo[] other, out bool composedOfAllPrivateMethods, out BindingFlags bindingFlags) { addOn = (removeOn = (fireOn = (getter = (setter = null)))); Attributes attributes = Attributes.ComposedOfAllVirtualMethods | Attributes.ComposedOfAllPrivateMethods | Attributes.ComposedOfNoPublicMembers | Attributes.ComposedOfNoStaticMembers; while (RuntimeTypeHandle.IsGenericVariable(reflectedType)) { reflectedType = (RuntimeType)reflectedType.BaseType; } bool isInherited = declaringType != reflectedType; List list = null; scope.Enum(MetadataTokenType.MethodDef, mdPropEvent, out var result); int num = result.Length / 2; for (int i = 0; i < num; i++) { int tkMethod = result[i * 2]; MethodSemanticsAttributes methodSemanticsAttributes = (MethodSemanticsAttributes)result[i * 2 + 1]; RuntimeMethodInfo runtimeMethodInfo = AssignAssociates(tkMethod, declaringType, reflectedType); if (runtimeMethodInfo == null) { continue; } MethodAttributes attributes2 = runtimeMethodInfo.Attributes; bool flag = (attributes2 & MethodAttributes.MemberAccessMask) == MethodAttributes.Private; bool flag2 = (attributes2 & MethodAttributes.Virtual) != 0; MethodAttributes methodAttributes = attributes2 & MethodAttributes.MemberAccessMask; bool flag3 = methodAttributes == MethodAttributes.Public; bool flag4 = (attributes2 & MethodAttributes.Static) != 0; if (flag3) { attributes &= ~Attributes.ComposedOfNoPublicMembers; attributes &= ~Attributes.ComposedOfAllPrivateMethods; } else if (!flag) { attributes &= ~Attributes.ComposedOfAllPrivateMethods; } if (flag4) { attributes &= ~Attributes.ComposedOfNoStaticMembers; } if (!flag2) { attributes &= ~Attributes.ComposedOfAllVirtualMethods; } switch (methodSemanticsAttributes) { case MethodSemanticsAttributes.Setter: setter = runtimeMethodInfo; continue; case MethodSemanticsAttributes.Getter: getter = runtimeMethodInfo; continue; case MethodSemanticsAttributes.Fire: fireOn = runtimeMethodInfo; continue; case MethodSemanticsAttributes.AddOn: addOn = runtimeMethodInfo; continue; case MethodSemanticsAttributes.RemoveOn: removeOn = runtimeMethodInfo; continue; } if (list == null) { list = new List(num); } list.Add(runtimeMethodInfo); } bool isPublic = (attributes & Attributes.ComposedOfNoPublicMembers) == 0; bool isStatic = (attributes & Attributes.ComposedOfNoStaticMembers) == 0; bindingFlags = RuntimeType.FilterPreCalculate(isPublic, isInherited, isStatic); composedOfAllPrivateMethods = (attributes & Attributes.ComposedOfAllPrivateMethods) != 0; other = list?.ToArray(); } } public abstract class ConstructorInfo : MethodBase { public static readonly string ConstructorName = ".ctor"; public static readonly string TypeConstructorName = ".cctor"; public override MemberTypes MemberType => MemberTypes.Constructor; internal virtual Type GetReturnType() { throw new NotImplementedException(); } [DebuggerHidden] [DebuggerStepThrough] public object Invoke(object?[]? parameters) { return Invoke(BindingFlags.Default, null, parameters, null); } public abstract object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture); public override bool Equals(object? obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(ConstructorInfo? left, ConstructorInfo? right) { if ((object)right == null) { if ((object)left != null) { return false; } return true; } if ((object)left == right) { return true; } return left?.Equals(right) ?? false; } public static bool operator !=(ConstructorInfo? left, ConstructorInfo? right) { return !(left == right); } } public abstract class FieldInfo : MemberInfo { public override MemberTypes MemberType => MemberTypes.Field; public abstract FieldAttributes Attributes { get; } public abstract Type FieldType { get; } public bool IsInitOnly => (Attributes & FieldAttributes.InitOnly) != 0; public bool IsLiteral => (Attributes & FieldAttributes.Literal) != 0; public bool IsNotSerialized => (Attributes & FieldAttributes.NotSerialized) != 0; public bool IsPinvokeImpl => (Attributes & FieldAttributes.PinvokeImpl) != 0; public bool IsSpecialName => (Attributes & FieldAttributes.SpecialName) != 0; public bool IsStatic => (Attributes & FieldAttributes.Static) != 0; public bool IsAssembly => (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; public bool IsFamily => (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; public bool IsFamilyAndAssembly => (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; public bool IsFamilyOrAssembly => (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; public bool IsPrivate => (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; public bool IsPublic => (Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; public virtual bool IsSecurityCritical => true; public virtual bool IsSecuritySafeCritical => false; public virtual bool IsSecurityTransparent => false; public abstract RuntimeFieldHandle FieldHandle { get; } public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle) { if (handle.IsNullHandle()) { throw new ArgumentException(SR.Argument_InvalidHandle, "handle"); } FieldInfo fieldInfo = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo()); Type declaringType = fieldInfo.DeclaringType; if (declaringType != null && declaringType.IsGenericType) { throw new ArgumentException(SR.Format(SR.Argument_FieldDeclaringTypeGeneric, fieldInfo.Name, declaringType.GetGenericTypeDefinition())); } return fieldInfo; } public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle, RuntimeTypeHandle declaringType) { if (handle.IsNullHandle()) { throw new ArgumentException(SR.Argument_InvalidHandle); } return RuntimeType.GetFieldInfo(declaringType.GetRuntimeType(), handle.GetRuntimeFieldInfo()); } public override bool Equals(object? obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(FieldInfo? left, FieldInfo? right) { if ((object)right == null) { if ((object)left != null) { return false; } return true; } if ((object)left == right) { return true; } return left?.Equals(right) ?? false; } public static bool operator !=(FieldInfo? left, FieldInfo? right) { return !(left == right); } public abstract object? GetValue(object? obj); [DebuggerHidden] [DebuggerStepThrough] public void SetValue(object? obj, object? value) { SetValue(obj, value, BindingFlags.Default, Type.DefaultBinder, null); } public abstract void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture); [CLSCompliant(false)] public virtual void SetValueDirect(TypedReference obj, object value) { throw new NotSupportedException(SR.NotSupported_AbstractNonCLS); } [CLSCompliant(false)] public virtual object? GetValueDirect(TypedReference obj) { throw new NotSupportedException(SR.NotSupported_AbstractNonCLS); } public virtual object? GetRawConstantValue() { throw new NotSupportedException(SR.NotSupported_AbstractNonCLS); } public virtual Type[] GetOptionalCustomModifiers() { throw NotImplemented.ByDesign; } public virtual Type[] GetRequiredCustomModifiers() { throw NotImplemented.ByDesign; } } [Flags] internal enum INVOCATION_FLAGS : uint { INVOCATION_FLAGS_UNKNOWN = 0u, INVOCATION_FLAGS_INITIALIZED = 1u, INVOCATION_FLAGS_NO_INVOKE = 2u, INVOCATION_FLAGS_RUN_CLASS_CONSTRUCTOR = 4u, INVOCATION_FLAGS_NO_CTOR_INVOKE = 8u, INVOCATION_FLAGS_IS_CTOR = 0x10u, INVOCATION_FLAGS_IS_DELEGATE_CTOR = 0x80u, INVOCATION_FLAGS_CONTAINS_STACK_POINTERS = 0x100u, INVOCATION_FLAGS_SPECIAL_FIELD = 0x10u, INVOCATION_FLAGS_FIELD_SPECIAL_CAST = 0x20u, INVOCATION_FLAGS_CONSTRUCTOR_INVOKE = 0x10000000u } internal sealed class LoaderAllocatorScout { internal IntPtr m_nativeLoaderAllocator; [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern bool Destroy(IntPtr nativeLoaderAllocator); ~LoaderAllocatorScout() { if (!(m_nativeLoaderAllocator == IntPtr.Zero) && !Destroy(m_nativeLoaderAllocator)) { GC.ReRegisterForFinalize(this); } } } internal sealed class LoaderAllocator { private LoaderAllocatorScout m_scout; private object[] m_slots; internal CerHashtable m_methodInstantiations; private int m_slotsUsed; private LoaderAllocator() { m_slots = new object[5]; m_scout = new LoaderAllocatorScout(); } } internal static class MdConstant { public unsafe static object GetValue(MetadataImport scope, int token, RuntimeTypeHandle fieldTypeHandle, bool raw) { long value; int length; CorElementType corElementType; string defaultValue = scope.GetDefaultValue(token, out value, out length, out corElementType); RuntimeType runtimeType = fieldTypeHandle.GetRuntimeType(); if (runtimeType.IsEnum && !raw) { long num = 0L; switch (corElementType) { case CorElementType.ELEMENT_TYPE_VOID: return DBNull.Value; case CorElementType.ELEMENT_TYPE_CHAR: num = *(ushort*)(&value); break; case CorElementType.ELEMENT_TYPE_I1: num = *(sbyte*)(&value); break; case CorElementType.ELEMENT_TYPE_U1: num = *(byte*)(&value); break; case CorElementType.ELEMENT_TYPE_I2: num = *(short*)(&value); break; case CorElementType.ELEMENT_TYPE_U2: num = *(ushort*)(&value); break; case CorElementType.ELEMENT_TYPE_I4: num = *(int*)(&value); break; case CorElementType.ELEMENT_TYPE_U4: num = (uint)(*(int*)(&value)); break; case CorElementType.ELEMENT_TYPE_I8: num = value; break; case CorElementType.ELEMENT_TYPE_U8: num = value; break; case CorElementType.ELEMENT_TYPE_CLASS: return null; default: throw new FormatException(SR.Arg_BadLiteralFormat); } return RuntimeType.CreateEnum(runtimeType, num); } if (runtimeType == typeof(DateTime)) { long num2 = 0L; switch (corElementType) { case CorElementType.ELEMENT_TYPE_VOID: return DBNull.Value; case CorElementType.ELEMENT_TYPE_I8: num2 = value; break; case CorElementType.ELEMENT_TYPE_U8: num2 = value; break; case CorElementType.ELEMENT_TYPE_CLASS: return null; default: throw new FormatException(SR.Arg_BadLiteralFormat); } return new DateTime(num2); } return corElementType switch { CorElementType.ELEMENT_TYPE_VOID => DBNull.Value, CorElementType.ELEMENT_TYPE_CHAR => *(char*)(&value), CorElementType.ELEMENT_TYPE_I1 => *(sbyte*)(&value), CorElementType.ELEMENT_TYPE_U1 => *(byte*)(&value), CorElementType.ELEMENT_TYPE_I2 => *(short*)(&value), CorElementType.ELEMENT_TYPE_U2 => *(ushort*)(&value), CorElementType.ELEMENT_TYPE_I4 => *(int*)(&value), CorElementType.ELEMENT_TYPE_U4 => *(uint*)(&value), CorElementType.ELEMENT_TYPE_I8 => value, CorElementType.ELEMENT_TYPE_U8 => (ulong)value, CorElementType.ELEMENT_TYPE_BOOLEAN => *(int*)(&value) != 0, CorElementType.ELEMENT_TYPE_R4 => *(float*)(&value), CorElementType.ELEMENT_TYPE_R8 => *(double*)(&value), CorElementType.ELEMENT_TYPE_STRING => defaultValue ?? string.Empty, CorElementType.ELEMENT_TYPE_CLASS => null, _ => throw new FormatException(SR.Arg_BadLiteralFormat), }; } } internal sealed class MdFieldInfo : RuntimeFieldInfo { private int m_tkField; private string m_name; private RuntimeType m_fieldType; private FieldAttributes m_fieldAttributes; public override string Name => m_name ?? (m_name = GetRuntimeModule().MetadataImport.GetName(m_tkField).ToString()); public override int MetadataToken => m_tkField; public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(); } } public override FieldAttributes Attributes => m_fieldAttributes; public override bool IsSecurityCritical => DeclaringType.IsSecurityCritical; public override bool IsSecuritySafeCritical => DeclaringType.IsSecuritySafeCritical; public override bool IsSecurityTransparent => DeclaringType.IsSecurityTransparent; public unsafe override Type FieldType { get { if (m_fieldType == null) { ConstArray sigOfFieldDef = GetRuntimeModule().MetadataImport.GetSigOfFieldDef(m_tkField); m_fieldType = new Signature(sigOfFieldDef.Signature.ToPointer(), sigOfFieldDef.Length, m_declaringType).FieldType; } return m_fieldType; } } internal MdFieldInfo(int tkField, FieldAttributes fieldAttributes, RuntimeTypeHandle declaringTypeHandle, RuntimeType.RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags) : base(reflectedTypeCache, declaringTypeHandle.GetRuntimeType(), bindingFlags) { m_tkField = tkField; m_name = null; m_fieldAttributes = fieldAttributes; } internal override bool CacheEquals(object o) { if (o is MdFieldInfo mdFieldInfo && mdFieldInfo.m_tkField == m_tkField) { return m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals(mdFieldInfo.m_declaringType.GetTypeHandleInternal().GetModuleHandle()); } return false; } internal override RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } [DebuggerStepThrough] [DebuggerHidden] public override object GetValueDirect(TypedReference obj) { return GetValue(null); } [DebuggerStepThrough] [DebuggerHidden] public override void SetValueDirect(TypedReference obj, object value) { throw new FieldAccessException(SR.Acc_ReadOnly); } [DebuggerStepThrough] [DebuggerHidden] public override object GetValue(object obj) { return GetValue(raw: false); } public override object GetRawConstantValue() { return GetValue(raw: true); } private object GetValue(bool raw) { object value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw); if (value == DBNull.Value) { throw new NotSupportedException(SR.Arg_EnumLitValueNotFound); } return value; } [DebuggerStepThrough] [DebuggerHidden] public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { throw new FieldAccessException(SR.Acc_ReadOnly); } public override Type[] GetRequiredCustomModifiers() { return Type.EmptyTypes; } public override Type[] GetOptionalCustomModifiers() { return Type.EmptyTypes; } } [Flags] internal enum MdSigCallingConvention : byte { CallConvMask = 0xF, Default = 0, C = 1, StdCall = 2, ThisCall = 3, FastCall = 4, Vararg = 5, Field = 6, LocalSig = 7, Property = 8, Unmanaged = 9, GenericInst = 0xA, Generic = 0x10, HasThis = 0x20, ExplicitThis = 0x40 } [Flags] internal enum PInvokeAttributes { NoMangle = 1, CharSetMask = 6, CharSetNotSpec = 0, CharSetAnsi = 2, CharSetUnicode = 4, CharSetAuto = 6, BestFitUseAssem = 0, BestFitEnabled = 0x10, BestFitDisabled = 0x20, BestFitMask = 0x30, ThrowOnUnmappableCharUseAssem = 0, ThrowOnUnmappableCharEnabled = 0x1000, ThrowOnUnmappableCharDisabled = 0x2000, ThrowOnUnmappableCharMask = 0x3000, SupportsLastError = 0x40, CallConvMask = 0x700, CallConvWinapi = 0x100, CallConvCdecl = 0x200, CallConvStdcall = 0x300, CallConvThiscall = 0x400, CallConvFastcall = 0x500, MaxValue = 0xFFFF } [Flags] internal enum MethodSemanticsAttributes { Setter = 1, Getter = 2, Other = 4, AddOn = 8, RemoveOn = 0x10, Fire = 0x20 } internal enum MetadataTokenType { Module = 0, TypeRef = 16777216, TypeDef = 33554432, FieldDef = 67108864, MethodDef = 100663296, ParamDef = 134217728, InterfaceImpl = 150994944, MemberRef = 167772160, CustomAttribute = 201326592, Permission = 234881024, Signature = 285212672, Event = 335544320, Property = 385875968, ModuleRef = 436207616, TypeSpec = 452984832, Assembly = 536870912, AssemblyRef = 587202560, File = 637534208, ExportedType = 654311424, ManifestResource = 671088640, GenericPar = 704643072, MethodSpec = 721420288, String = 1879048192, Name = 1895825408, BaseType = 1912602624, Invalid = int.MaxValue } internal readonly struct ConstArray { internal readonly int m_length; internal readonly IntPtr m_constArray; public IntPtr Signature => m_constArray; public int Length => m_length; public unsafe byte this[int index] { get { if (index < 0 || index >= m_length) { throw new IndexOutOfRangeException(); } return ((byte*)m_constArray.ToPointer())[index]; } } } internal struct MetadataToken { public int Value; public bool IsGlobalTypeDefToken => Value == 33554433; public MetadataTokenType TokenType => (MetadataTokenType)(Value & 0xFF000000u); public bool IsTypeRef => TokenType == MetadataTokenType.TypeRef; public bool IsTypeDef => TokenType == MetadataTokenType.TypeDef; public bool IsFieldDef => TokenType == MetadataTokenType.FieldDef; public bool IsMethodDef => TokenType == MetadataTokenType.MethodDef; public bool IsMemberRef => TokenType == MetadataTokenType.MemberRef; public bool IsEvent => TokenType == MetadataTokenType.Event; public bool IsProperty => TokenType == MetadataTokenType.Property; public bool IsParamDef => TokenType == MetadataTokenType.ParamDef; public bool IsTypeSpec => TokenType == MetadataTokenType.TypeSpec; public bool IsMethodSpec => TokenType == MetadataTokenType.MethodSpec; public bool IsString => TokenType == MetadataTokenType.String; public bool IsSignature => TokenType == MetadataTokenType.Signature; public bool IsGenericPar => TokenType == MetadataTokenType.GenericPar; public static implicit operator int(MetadataToken token) { return token.Value; } public static implicit operator MetadataToken(int token) { return new MetadataToken(token); } public static bool IsNullToken(int token) { return (token & 0xFFFFFF) == 0; } public MetadataToken(int token) { Value = token; } public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "0x{0:x8}", Value); } } internal struct MetadataEnumResult { private int[] largeResult; private int length; private unsafe fixed int smallResult[16]; public int Length => length; public unsafe int this[int index] { get { if (largeResult != null) { return largeResult[index]; } fixed (int* ptr = smallResult) { return ptr[index]; } } } } internal readonly struct MetadataImport { private readonly IntPtr m_metadataImport2; private readonly object m_keepalive; internal static readonly MetadataImport EmptyImport = new MetadataImport((IntPtr)0, null); public override int GetHashCode() { return ValueType.GetHashCodeOfPtr(m_metadataImport2); } public override bool Equals(object obj) { if (!(obj is MetadataImport)) { return false; } return Equals((MetadataImport)obj); } private bool Equals(MetadataImport import) { return import.m_metadataImport2 == m_metadataImport2; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _GetMarshalAs(IntPtr pNativeType, int cNativeType, out int unmanagedType, out int safeArraySubType, out string safeArrayUserDefinedSubType, out int arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie, out int iidParamIndex); internal static void GetMarshalAs(ConstArray nativeType, out UnmanagedType unmanagedType, out VarEnum safeArraySubType, out string safeArrayUserDefinedSubType, out UnmanagedType arraySubType, out int sizeParamIndex, out int sizeConst, out string marshalType, out string marshalCookie, out int iidParamIndex) { _GetMarshalAs(nativeType.Signature, nativeType.Length, out var unmanagedType2, out var safeArraySubType2, out safeArrayUserDefinedSubType, out var arraySubType2, out sizeParamIndex, out sizeConst, out marshalType, out marshalCookie, out iidParamIndex); unmanagedType = (UnmanagedType)unmanagedType2; safeArraySubType = (VarEnum)safeArraySubType2; arraySubType = (UnmanagedType)arraySubType2; } internal static void ThrowError(int hResult) { throw new MetadataException(hResult); } internal MetadataImport(IntPtr metadataImport2, object keepalive) { m_metadataImport2 = metadataImport2; m_keepalive = keepalive; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _Enum(IntPtr scope, int type, int parent, out MetadataEnumResult result); public void Enum(MetadataTokenType type, int parent, out MetadataEnumResult result) { _Enum(m_metadataImport2, (int)type, parent, out result); } public void EnumNestedTypes(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.TypeDef, mdTypeDef, out result); } public void EnumCustomAttributes(int mdToken, out MetadataEnumResult result) { Enum(MetadataTokenType.CustomAttribute, mdToken, out result); } public void EnumParams(int mdMethodDef, out MetadataEnumResult result) { Enum(MetadataTokenType.ParamDef, mdMethodDef, out result); } public void EnumFields(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.FieldDef, mdTypeDef, out result); } public void EnumProperties(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.Property, mdTypeDef, out result); } public void EnumEvents(int mdTypeDef, out MetadataEnumResult result) { Enum(MetadataTokenType.Event, mdTypeDef, out result); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern string _GetDefaultValue(IntPtr scope, int mdToken, out long value, out int length, out int corElementType); public string GetDefaultValue(int mdToken, out long value, out int length, out CorElementType corElementType) { int corElementType2; string result = _GetDefaultValue(m_metadataImport2, mdToken, out value, out length, out corElementType2); corElementType = (CorElementType)corElementType2; return result; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void _GetUserString(IntPtr scope, int mdToken, void** name, out int length); public unsafe string GetUserString(int mdToken) { System.Runtime.CompilerServices.Unsafe.SkipInit(out void* ptr); _GetUserString(m_metadataImport2, mdToken, &ptr, out var length); if (ptr == null) { return null; } return new string((char*)ptr, 0, length); } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void _GetName(IntPtr scope, int mdToken, void** name); public unsafe MdUtf8String GetName(int mdToken) { System.Runtime.CompilerServices.Unsafe.SkipInit(out void* pStringHeap); _GetName(m_metadataImport2, mdToken, &pStringHeap); return new MdUtf8String(pStringHeap); } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void _GetNamespace(IntPtr scope, int mdToken, void** namesp); public unsafe MdUtf8String GetNamespace(int mdToken) { System.Runtime.CompilerServices.Unsafe.SkipInit(out void* pStringHeap); _GetNamespace(m_metadataImport2, mdToken, &pStringHeap); return new MdUtf8String(pStringHeap); } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void _GetEventProps(IntPtr scope, int mdToken, void** name, out int eventAttributes); public unsafe void GetEventProps(int mdToken, out void* name, out EventAttributes eventAttributes) { System.Runtime.CompilerServices.Unsafe.SkipInit(out void* ptr); _GetEventProps(m_metadataImport2, mdToken, &ptr, out var eventAttributes2); name = ptr; eventAttributes = (EventAttributes)eventAttributes2; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _GetFieldDefProps(IntPtr scope, int mdToken, out int fieldAttributes); public void GetFieldDefProps(int mdToken, out FieldAttributes fieldAttributes) { _GetFieldDefProps(m_metadataImport2, mdToken, out var fieldAttributes2); fieldAttributes = (FieldAttributes)fieldAttributes2; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void _GetPropertyProps(IntPtr scope, int mdToken, void** name, out int propertyAttributes, out ConstArray signature); public unsafe void GetPropertyProps(int mdToken, out void* name, out PropertyAttributes propertyAttributes, out ConstArray signature) { System.Runtime.CompilerServices.Unsafe.SkipInit(out void* ptr); _GetPropertyProps(m_metadataImport2, mdToken, &ptr, out var propertyAttributes2, out signature); name = ptr; propertyAttributes = (PropertyAttributes)propertyAttributes2; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _GetParentToken(IntPtr scope, int mdToken, out int tkParent); public int GetParentToken(int tkToken) { _GetParentToken(m_metadataImport2, tkToken, out var tkParent); return tkParent; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _GetParamDefProps(IntPtr scope, int parameterToken, out int sequence, out int attributes); public void GetParamDefProps(int parameterToken, out int sequence, out ParameterAttributes attributes) { _GetParamDefProps(m_metadataImport2, parameterToken, out sequence, out var attributes2); attributes = (ParameterAttributes)attributes2; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _GetGenericParamProps(IntPtr scope, int genericParameter, out int flags); public void GetGenericParamProps(int genericParameter, out GenericParameterAttributes attributes) { _GetGenericParamProps(m_metadataImport2, genericParameter, out var flags); attributes = (GenericParameterAttributes)flags; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _GetScopeProps(IntPtr scope, out Guid mvid); public void GetScopeProps(out Guid mvid) { _GetScopeProps(m_metadataImport2, out mvid); } public ConstArray GetMethodSignature(MetadataToken token) { if (token.IsMemberRef) { return GetMemberRefProps(token); } return GetSigOfMethodDef(token); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _GetSigOfMethodDef(IntPtr scope, int methodToken, ref ConstArray signature); public ConstArray GetSigOfMethodDef(int methodToken) { ConstArray signature = default(ConstArray); _GetSigOfMethodDef(m_metadataImport2, methodToken, ref signature); return signature; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _GetSignatureFromToken(IntPtr scope, int methodToken, ref ConstArray signature); public ConstArray GetSignatureFromToken(int token) { ConstArray signature = default(ConstArray); _GetSignatureFromToken(m_metadataImport2, token, ref signature); return signature; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _GetMemberRefProps(IntPtr scope, int memberTokenRef, out ConstArray signature); public ConstArray GetMemberRefProps(int memberTokenRef) { _GetMemberRefProps(m_metadataImport2, memberTokenRef, out var signature); return signature; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _GetCustomAttributeProps(IntPtr scope, int customAttributeToken, out int constructorToken, out ConstArray signature); public void GetCustomAttributeProps(int customAttributeToken, out int constructorToken, out ConstArray signature) { _GetCustomAttributeProps(m_metadataImport2, customAttributeToken, out constructorToken, out signature); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _GetClassLayout(IntPtr scope, int typeTokenDef, out int packSize, out int classSize); public void GetClassLayout(int typeTokenDef, out int packSize, out int classSize) { _GetClassLayout(m_metadataImport2, typeTokenDef, out packSize, out classSize); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool _GetFieldOffset(IntPtr scope, int typeTokenDef, int fieldTokenDef, out int offset); public bool GetFieldOffset(int typeTokenDef, int fieldTokenDef, out int offset) { return _GetFieldOffset(m_metadataImport2, typeTokenDef, fieldTokenDef, out offset); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _GetSigOfFieldDef(IntPtr scope, int fieldToken, ref ConstArray fieldMarshal); public ConstArray GetSigOfFieldDef(int fieldToken) { ConstArray fieldMarshal = default(ConstArray); _GetSigOfFieldDef(m_metadataImport2, fieldToken, ref fieldMarshal); return fieldMarshal; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _GetFieldMarshal(IntPtr scope, int fieldToken, ref ConstArray fieldMarshal); public ConstArray GetFieldMarshal(int fieldToken) { ConstArray fieldMarshal = default(ConstArray); _GetFieldMarshal(m_metadataImport2, fieldToken, ref fieldMarshal); return fieldMarshal; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void _GetPInvokeMap(IntPtr scope, int token, out int attributes, void** importName, void** importDll); public unsafe void GetPInvokeMap(int token, out PInvokeAttributes attributes, out string importName, out string importDll) { System.Runtime.CompilerServices.Unsafe.SkipInit(out void* pStringHeap); System.Runtime.CompilerServices.Unsafe.SkipInit(out void* pStringHeap2); _GetPInvokeMap(m_metadataImport2, token, out var attributes2, &pStringHeap, &pStringHeap2); importName = new MdUtf8String(pStringHeap).ToString(); importDll = new MdUtf8String(pStringHeap2).ToString(); attributes = (PInvokeAttributes)attributes2; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool _IsValidToken(IntPtr scope, int token); public bool IsValidToken(int token) { return _IsValidToken(m_metadataImport2, token); } } internal sealed class MetadataException : Exception { private int m_hr; internal MetadataException(int hr) { m_hr = hr; } public override string ToString() { return $"MetadataException HResult = {m_hr:x}."; } } public abstract class MemberInfo : ICustomAttributeProvider { public abstract MemberTypes MemberType { get; } public abstract string Name { get; } public abstract Type? DeclaringType { get; } public abstract Type? ReflectedType { get; } public virtual Module Module { get { if (this is Type type) { return type.Module; } throw NotImplemented.ByDesign; } } public virtual IEnumerable CustomAttributes => GetCustomAttributesData(); public virtual bool IsCollectible => true; public virtual int MetadataToken { get { throw new InvalidOperationException(); } } internal virtual bool CacheEquals(object o) { throw new NotImplementedException(); } internal bool HasSameMetadataDefinitionAsCore(MemberInfo other) where TOther : MemberInfo { if ((object)other == null) { throw new ArgumentNullException("other"); } if (!(other is TOther)) { return false; } if (MetadataToken != other.MetadataToken) { return false; } if (!Module.Equals(other.Module)) { return false; } return true; } public virtual bool HasSameMetadataDefinitionAs(MemberInfo other) { throw NotImplemented.ByDesign; } public abstract bool IsDefined(Type attributeType, bool inherit); public abstract object[] GetCustomAttributes(bool inherit); public abstract object[] GetCustomAttributes(Type attributeType, bool inherit); public virtual IList GetCustomAttributesData() { throw NotImplemented.ByDesign; } public override bool Equals(object? obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(MemberInfo? left, MemberInfo? right) { if ((object)right == null) { if ((object)left != null) { return false; } return true; } if ((object)left == right) { return true; } return left?.Equals(right) ?? false; } public static bool operator !=(MemberInfo? left, MemberInfo? right) { return !(left == right); } } public abstract class MethodBase : MemberInfo { private protected struct StackAllocedArguments { internal object _arg0; private object _arg1; private object _arg2; private object _arg3; } public abstract MethodAttributes Attributes { get; } public virtual MethodImplAttributes MethodImplementationFlags => GetMethodImplementationFlags(); public virtual CallingConventions CallingConvention => CallingConventions.Standard; public bool IsAbstract => (Attributes & MethodAttributes.Abstract) != 0; public bool IsConstructor { get { if (this is ConstructorInfo && !IsStatic) { return (Attributes & MethodAttributes.RTSpecialName) == MethodAttributes.RTSpecialName; } return false; } } public bool IsFinal => (Attributes & MethodAttributes.Final) != 0; public bool IsHideBySig => (Attributes & MethodAttributes.HideBySig) != 0; public bool IsSpecialName => (Attributes & MethodAttributes.SpecialName) != 0; public bool IsStatic => (Attributes & MethodAttributes.Static) != 0; public bool IsVirtual => (Attributes & MethodAttributes.Virtual) != 0; public bool IsAssembly => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Assembly; public bool IsFamily => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Family; public bool IsFamilyAndAssembly => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamANDAssem; public bool IsFamilyOrAssembly => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamORAssem; public bool IsPrivate => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private; public bool IsPublic => (Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; public virtual bool IsConstructedGenericMethod { get { if (IsGenericMethod) { return !IsGenericMethodDefinition; } return false; } } public virtual bool IsGenericMethod => false; public virtual bool IsGenericMethodDefinition => false; public virtual bool ContainsGenericParameters => false; public abstract RuntimeMethodHandle MethodHandle { get; } public virtual bool IsSecurityCritical { get { throw NotImplemented.ByDesign; } } public virtual bool IsSecuritySafeCritical { get { throw NotImplemented.ByDesign; } } public virtual bool IsSecurityTransparent { get { throw NotImplemented.ByDesign; } } public static MethodBase? GetMethodFromHandle(RuntimeMethodHandle handle) { if (handle.IsNullHandle()) { throw new ArgumentException(SR.Argument_InvalidHandle); } MethodBase methodBase = RuntimeType.GetMethodBase(handle.GetMethodInfo()); Type type = methodBase?.DeclaringType; if (type != null && type.IsGenericType) { throw new ArgumentException(SR.Format(SR.Argument_MethodDeclaringTypeGeneric, methodBase, type.GetGenericTypeDefinition())); } return methodBase; } public static MethodBase? GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType) { if (handle.IsNullHandle()) { throw new ArgumentException(SR.Argument_InvalidHandle); } return RuntimeType.GetMethodBase(declaringType.GetRuntimeType(), handle.GetMethodInfo()); } public static MethodBase? GetCurrentMethod() { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeMethodInfo.InternalGetCurrentMethod(ref stackMark); } private IntPtr GetMethodDesc() { return MethodHandle.Value; } internal virtual ParameterInfo[] GetParametersNoCopy() { return GetParameters(); } internal virtual Type[] GetParameterTypes() { ParameterInfo[] parametersNoCopy = GetParametersNoCopy(); Type[] array = new Type[parametersNoCopy.Length]; for (int i = 0; i < parametersNoCopy.Length; i++) { array[i] = parametersNoCopy[i].ParameterType; } return array; } private protected Span CheckArguments(ref StackAllocedArguments stackArgs, ReadOnlySpan parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig) { Span result = ((parameters.Length <= 4) ? MemoryMarshal.CreateSpan(ref stackArgs._arg0, parameters.Length) : new Span(new object[parameters.Length])); ParameterInfo[] array = null; for (int i = 0; i < parameters.Length; i++) { object obj = parameters[i]; RuntimeType runtimeType = sig.Arguments[i]; if (obj == Type.Missing) { if (array == null) { array = GetParametersNoCopy(); } if (array[i].DefaultValue == DBNull.Value) { throw new ArgumentException(SR.Arg_VarMissNull, "parameters"); } obj = array[i].DefaultValue; } result[i] = runtimeType.CheckValue(obj, binder, culture, invokeAttr); } return result; } public abstract ParameterInfo[] GetParameters(); public abstract MethodImplAttributes GetMethodImplementationFlags(); [RequiresUnreferencedCode("Trimming may change method bodies. For example it can change some instructions, remove branches or local variables.")] public virtual MethodBody? GetMethodBody() { throw new InvalidOperationException(); } public virtual Type[] GetGenericArguments() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } [DebuggerHidden] [DebuggerStepThrough] public object? Invoke(object? obj, object?[]? parameters) { return Invoke(obj, BindingFlags.Default, null, parameters, null); } public abstract object? Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture); public override bool Equals(object? obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(MethodBase? left, MethodBase? right) { if ((object)right == null) { if ((object)left != null) { return false; } return true; } if ((object)left == right) { return true; } return left?.Equals(right) ?? false; } public static bool operator !=(MethodBase? left, MethodBase? right) { return !(left == right); } internal static void AppendParameters(ref ValueStringBuilder sbParamList, Type[] parameterTypes, CallingConventions callingConvention) { string s = ""; foreach (Type type in parameterTypes) { sbParamList.Append(s); string text = type.FormatTypeName(); if (type.IsByRef) { sbParamList.Append(text.AsSpan().TrimEnd('&')); sbParamList.Append(" ByRef"); } else { sbParamList.Append(text); } s = ", "; } if ((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { sbParamList.Append(s); sbParamList.Append("..."); } } } internal sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo { private IntPtr m_fieldHandle; private FieldAttributes m_fieldAttributes; private string m_name; private RuntimeType m_fieldType; private INVOCATION_FLAGS m_invocationFlags; internal INVOCATION_FLAGS InvocationFlags { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) { return InitializeInvocationFlags(); } return m_invocationFlags; } } RuntimeFieldHandleInternal IRuntimeFieldInfo.Value => new RuntimeFieldHandleInternal(m_fieldHandle); public override string Name => m_name ?? (m_name = RuntimeFieldHandle.GetName(this)); public override int MetadataToken => RuntimeFieldHandle.GetToken(this); public override RuntimeFieldHandle FieldHandle => new RuntimeFieldHandle(this); public override FieldAttributes Attributes => m_fieldAttributes; public override Type FieldType { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_fieldType ?? InitializeFieldType(); } } [MethodImpl(MethodImplOptions.NoInlining)] private INVOCATION_FLAGS InitializeInvocationFlags() { Type declaringType = DeclaringType; INVOCATION_FLAGS iNVOCATION_FLAGS = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN; if (declaringType != null && declaringType.ContainsGenericParameters) { iNVOCATION_FLAGS |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; } if (iNVOCATION_FLAGS == INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN) { if ((m_fieldAttributes & FieldAttributes.InitOnly) != 0) { iNVOCATION_FLAGS |= INVOCATION_FLAGS.INVOCATION_FLAGS_IS_CTOR; } if ((m_fieldAttributes & FieldAttributes.HasFieldRVA) != 0) { iNVOCATION_FLAGS |= INVOCATION_FLAGS.INVOCATION_FLAGS_IS_CTOR; } Type fieldType = FieldType; if (fieldType.IsPointer || fieldType.IsEnum || fieldType.IsPrimitive) { iNVOCATION_FLAGS |= INVOCATION_FLAGS.INVOCATION_FLAGS_FIELD_SPECIAL_CAST; } } return m_invocationFlags = iNVOCATION_FLAGS | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; } internal RtFieldInfo(RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeType.RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags) : base(reflectedTypeCache, declaringType, bindingFlags) { m_fieldHandle = handle.Value; m_fieldAttributes = RuntimeFieldHandle.GetAttributes(handle); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void CheckConsistency(object target) { if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static && !m_declaringType.IsInstanceOfType(target)) { if (target == null) { throw new TargetException(SR.RFLCT_Targ_StatFldReqTarg); } throw new ArgumentException(SR.Format(SR.Arg_FieldDeclTarget, Name, m_declaringType, target.GetType())); } } internal override bool CacheEquals(object o) { if (o is RtFieldInfo rtFieldInfo) { return rtFieldInfo.m_fieldHandle == m_fieldHandle; } return false; } internal override RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this)); } [DebuggerStepThrough] [DebuggerHidden] public override object GetValue(object obj) { INVOCATION_FLAGS invocationFlags = InvocationFlags; RuntimeType runtimeType = DeclaringType as RuntimeType; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) { if (runtimeType != null && DeclaringType.ContainsGenericParameters) { throw new InvalidOperationException(SR.Arg_UnboundGenField); } throw new FieldAccessException(); } CheckConsistency(obj); RuntimeType fieldType = (RuntimeType)FieldType; bool domainInitialized = false; if (runtimeType == null) { return RuntimeFieldHandle.GetValue(this, obj, fieldType, null, ref domainInitialized); } domainInitialized = runtimeType.DomainInitialized; object value = RuntimeFieldHandle.GetValue(this, obj, fieldType, runtimeType, ref domainInitialized); runtimeType.DomainInitialized = domainInitialized; return value; } public override object GetRawConstantValue() { throw new InvalidOperationException(); } [DebuggerStepThrough] [DebuggerHidden] public unsafe override object GetValueDirect(TypedReference obj) { if (obj.IsNull) { throw new ArgumentException(SR.Arg_TypedReference_Null); } return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType); } [DebuggerStepThrough] [DebuggerHidden] public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { INVOCATION_FLAGS invocationFlags = InvocationFlags; RuntimeType runtimeType = DeclaringType as RuntimeType; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) { if (runtimeType != null && runtimeType.ContainsGenericParameters) { throw new InvalidOperationException(SR.Arg_UnboundGenField); } throw new FieldAccessException(); } CheckConsistency(obj); RuntimeType runtimeType2 = (RuntimeType)FieldType; value = runtimeType2.CheckValue(value, binder, culture, invokeAttr); bool domainInitialized = false; if (runtimeType == null) { RuntimeFieldHandle.SetValue(this, obj, value, runtimeType2, m_fieldAttributes, null, ref domainInitialized); return; } domainInitialized = runtimeType.DomainInitialized; RuntimeFieldHandle.SetValue(this, obj, value, runtimeType2, m_fieldAttributes, runtimeType, ref domainInitialized); runtimeType.DomainInitialized = domainInitialized; } [DebuggerStepThrough] [DebuggerHidden] public unsafe override void SetValueDirect(TypedReference obj, object value) { if (obj.IsNull) { throw new ArgumentException(SR.Arg_TypedReference_Null); } RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType); } internal IntPtr GetFieldHandle() { return m_fieldHandle; } [MethodImpl(MethodImplOptions.NoInlining)] private RuntimeType InitializeFieldType() { return m_fieldType = new Signature(this, m_declaringType).FieldType; } public override Type[] GetRequiredCustomModifiers() { return new Signature(this, m_declaringType).GetCustomModifiers(1, required: true); } public override Type[] GetOptionalCustomModifiers() { return new Signature(this, m_declaringType).GetCustomModifiers(1, required: false); } } internal class RuntimeAssembly : Assembly { private sealed class ManifestResourceStream : UnmanagedMemoryStream { private RuntimeAssembly _manifestAssembly; internal unsafe ManifestResourceStream(RuntimeAssembly manifestAssembly, byte* pointer, long length, long capacity, FileAccess access) : base(pointer, length, capacity, access) { _manifestAssembly = manifestAssembly; } } private string m_fullname; private object m_syncRoot; private IntPtr m_assembly; internal object SyncRoot { get { if (m_syncRoot == null) { Interlocked.CompareExchange(ref m_syncRoot, new object(), (object)null); } return m_syncRoot; } } [RequiresAssemblyFiles("This member throws an exception for assemblies embedded in a single-file app")] public override string CodeBase { get { string codeBase = GetCodeBase(); if (codeBase == null) { throw new NotSupportedException(SR.NotSupported_CodeBase); } return codeBase; } } public override string FullName { get { if (m_fullname == null) { string s = null; RuntimeAssembly assembly = this; GetFullName(new QCallAssembly(ref assembly), new StringHandleOnStack(ref s)); Interlocked.CompareExchange(ref m_fullname, s, null); } return m_fullname; } } public override MethodInfo EntryPoint { get { IRuntimeMethodInfo o = null; RuntimeAssembly assembly = this; GetEntryPoint(new QCallAssembly(ref assembly), ObjectHandleOnStack.Create(ref o)); if (o == null) { return null; } return (MethodInfo)RuntimeType.GetMethodBase(o); } } public override IEnumerable DefinedTypes { [RequiresUnreferencedCode("Types might be removed")] get { RuntimeModule[] modulesInternal = GetModulesInternal(loadIfNotFound: true, getResourceModules: false); if (modulesInternal.Length == 1) { return modulesInternal[0].GetDefinedTypes(); } List list = new List(); for (int i = 0; i < modulesInternal.Length; i++) { list.AddRange(modulesInternal[i].GetDefinedTypes()); } return list.ToArray(); } } public override bool IsCollectible { get { RuntimeAssembly assembly = this; return GetIsCollectible(new QCallAssembly(ref assembly)) != Interop.BOOL.FALSE; } } public override Module ManifestModule => GetManifestModule(GetNativeHandle()); public override bool ReflectionOnly => false; public override string Location { get { string s = null; RuntimeAssembly assembly = this; GetLocation(new QCallAssembly(ref assembly), new StringHandleOnStack(ref s)); return s; } } public override string ImageRuntimeVersion { get { string s = null; RuntimeAssembly assembly = this; GetImageRuntimeVersion(new QCallAssembly(ref assembly), new StringHandleOnStack(ref s)); return s; } } [Obsolete("The Global Assembly Cache is not supported.", DiagnosticId = "SYSLIB0005", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public override bool GlobalAssemblyCache => false; public override long HostContext => 0L; public override bool IsDynamic => FCallIsDynamic(GetNativeHandle()); private event ModuleResolveEventHandler _ModuleResolve; public override event ModuleResolveEventHandler ModuleResolve { add { _ModuleResolve += value; } remove { _ModuleResolve -= value; } } internal RuntimeAssembly() { throw new NotSupportedException(); } internal IntPtr GetUnderlyingNativeHandle() { return m_assembly; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern bool GetCodeBase(QCallAssembly assembly, StringHandleOnStack retString); internal string GetCodeBase() { string s = null; RuntimeAssembly assembly = this; if (GetCodeBase(new QCallAssembly(ref assembly), new StringHandleOnStack(ref s))) { return s; } return null; } internal RuntimeAssembly GetNativeHandle() { return this; } public override AssemblyName GetName(bool copiedName) { string codeBase = GetCodeBase(); AssemblyName assemblyName = new AssemblyName(GetSimpleName(), GetPublicKey(), null, GetVersion(), GetLocale(), GetHashAlgorithm(), AssemblyVersionCompatibility.SameMachine, codeBase, GetFlags() | AssemblyNameFlags.PublicKey); Module manifestModule = ManifestModule; if (manifestModule.MDStreamVersion > 65536) { manifestModule.GetPEKind(out var peKind, out var machine); assemblyName.SetProcArchIndex(peKind, machine); } return assemblyName; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetFullName(QCallAssembly assembly, StringHandleOnStack retString); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetEntryPoint(QCallAssembly assembly, ObjectHandleOnStack retMethod); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetType(QCallAssembly assembly, string name, bool throwOnError, bool ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive, ObjectHandleOnStack assemblyLoadContext); [RequiresUnreferencedCode("Types might be removed")] public override Type GetType(string name, bool throwOnError, bool ignoreCase) { if (name == null) { throw new ArgumentNullException("name"); } RuntimeType o = null; object o2 = null; AssemblyLoadContext o3 = AssemblyLoadContext.CurrentContextualReflectionContext; RuntimeAssembly assembly = this; GetType(new QCallAssembly(ref assembly), name, throwOnError, ignoreCase, ObjectHandleOnStack.Create(ref o), ObjectHandleOnStack.Create(ref o2), ObjectHandleOnStack.Create(ref o3)); GC.KeepAlive(o2); return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetExportedTypes(QCallAssembly assembly, ObjectHandleOnStack retTypes); [RequiresUnreferencedCode("Types might be removed")] public override Type[] GetExportedTypes() { Type[] o = null; RuntimeAssembly assembly = this; GetExportedTypes(new QCallAssembly(ref assembly), ObjectHandleOnStack.Create(ref o)); return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern Interop.BOOL GetIsCollectible(QCallAssembly assembly); [DllImport("QCall", CharSet = CharSet.Unicode)] private unsafe static extern byte* GetResource(QCallAssembly assembly, string resourceName, out uint length); public override Stream GetManifestResourceStream(Type type, string name) { if (type == null && name == null) { throw new ArgumentNullException("type"); } string text = type?.Namespace; char ptr = Type.Delimiter; string name2 = ((text != null && name != null) ? string.Concat(text, new ReadOnlySpan(ref ptr, 1), name) : (text + name)); return GetManifestResourceStream(name2); } public unsafe override Stream GetManifestResourceStream(string name) { RuntimeAssembly assembly = this; uint length; byte* resource = GetResource(new QCallAssembly(ref assembly), name, out length); if (resource != null) { return new ManifestResourceStream(this, resource, length, length, FileAccess.Read); } return null; } public override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public override object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.GetCustomAttributes(this, runtimeType); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.IsDefined(this, runtimeType); } public override IList GetCustomAttributesData() { return RuntimeCustomAttributeData.GetCustomAttributesInternal(this); } internal static RuntimeAssembly InternalLoad(string assemblyName, ref StackCrawlMark stackMark, AssemblyLoadContext assemblyLoadContext = null) { return InternalLoad(new AssemblyName(assemblyName), ref stackMark, assemblyLoadContext); } internal static RuntimeAssembly InternalLoad(AssemblyName assemblyName, ref StackCrawlMark stackMark, AssemblyLoadContext assemblyLoadContext = null) { return InternalLoad(assemblyName, null, ref stackMark, throwOnFileNotFound: true, assemblyLoadContext); } internal static RuntimeAssembly InternalLoad(AssemblyName assemblyName, RuntimeAssembly requestingAssembly, ref StackCrawlMark stackMark, bool throwOnFileNotFound, AssemblyLoadContext assemblyLoadContext = null) { RuntimeAssembly o = null; InternalLoad(ObjectHandleOnStack.Create(ref assemblyName), ObjectHandleOnStack.Create(ref requestingAssembly), new StackCrawlMarkHandle(ref stackMark), throwOnFileNotFound, ObjectHandleOnStack.Create(ref assemblyLoadContext), ObjectHandleOnStack.Create(ref o)); return o; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void InternalLoad(ObjectHandleOnStack assemblyName, ObjectHandleOnStack requestingAssembly, StackCrawlMarkHandle stackMark, bool throwOnFileNotFound, ObjectHandleOnStack assemblyLoadContext, ObjectHandleOnStack retAssembly); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetModule(QCallAssembly assembly, string name, ObjectHandleOnStack retModule); public override Module GetModule(string name) { Module o = null; RuntimeAssembly assembly = this; GetModule(new QCallAssembly(ref assembly), name, ObjectHandleOnStack.Create(ref o)); return o; } [RequiresAssemblyFiles("This member throws an exception for assemblies embedded in a single-file app")] public override FileStream GetFile(string name) { if (Location.Length == 0) { throw new FileNotFoundException(SR.IO_NoFileTableInInMemoryAssemblies); } RuntimeModule runtimeModule = (RuntimeModule)GetModule(name); if (runtimeModule == null) { return null; } return new FileStream(runtimeModule.GetFullyQualifiedName(), FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: false); } [RequiresAssemblyFiles("This member throws an exception for assemblies embedded in a single-file app")] public override FileStream[] GetFiles(bool getResourceModules) { if (Location.Length == 0) { throw new FileNotFoundException(SR.IO_NoFileTableInInMemoryAssemblies); } Module[] modules = GetModules(getResourceModules); FileStream[] array = new FileStream[modules.Length]; for (int i = 0; i < array.Length; i++) { array[i] = new FileStream(((RuntimeModule)modules[i]).GetFullyQualifiedName(), FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: false); } return array; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern string[] GetManifestResourceNames(RuntimeAssembly assembly); public override string[] GetManifestResourceNames() { return GetManifestResourceNames(GetNativeHandle()); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern AssemblyName[] GetReferencedAssemblies(RuntimeAssembly assembly); [RequiresUnreferencedCode("Assembly references might be removed")] public override AssemblyName[] GetReferencedAssemblies() { return GetReferencedAssemblies(GetNativeHandle()); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern int GetManifestResourceInfo(QCallAssembly assembly, string resourceName, ObjectHandleOnStack assemblyRef, StringHandleOnStack retFileName); public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) { RuntimeAssembly o = null; string s = null; RuntimeAssembly assembly = this; int manifestResourceInfo = GetManifestResourceInfo(new QCallAssembly(ref assembly), resourceName, ObjectHandleOnStack.Create(ref o), new StringHandleOnStack(ref s)); if (manifestResourceInfo == -1) { return null; } return new ManifestResourceInfo(o, s, (ResourceLocation)manifestResourceInfo); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetLocation(QCallAssembly assembly, StringHandleOnStack retString); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetImageRuntimeVersion(QCallAssembly assembly, StringHandleOnStack retString); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetVersion(QCallAssembly assembly, out int majVer, out int minVer, out int buildNum, out int revNum); internal Version GetVersion() { RuntimeAssembly assembly = this; GetVersion(new QCallAssembly(ref assembly), out var majVer, out var minVer, out var buildNum, out var revNum); return new Version(majVer, minVer, buildNum, revNum); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetLocale(QCallAssembly assembly, StringHandleOnStack retString); internal CultureInfo GetLocale() { string s = null; RuntimeAssembly assembly = this; GetLocale(new QCallAssembly(ref assembly), new StringHandleOnStack(ref s)); if (s == null) { return CultureInfo.InvariantCulture; } return CultureInfo.GetCultureInfo(s); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool FCallIsDynamic(RuntimeAssembly assembly); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetSimpleName(QCallAssembly assembly, StringHandleOnStack retSimpleName); internal string GetSimpleName() { RuntimeAssembly assembly = this; string s = null; GetSimpleName(new QCallAssembly(ref assembly), new StringHandleOnStack(ref s)); return s; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern AssemblyHashAlgorithm GetHashAlgorithm(QCallAssembly assembly); private AssemblyHashAlgorithm GetHashAlgorithm() { RuntimeAssembly assembly = this; return GetHashAlgorithm(new QCallAssembly(ref assembly)); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern AssemblyNameFlags GetFlags(QCallAssembly assembly); private AssemblyNameFlags GetFlags() { RuntimeAssembly assembly = this; return GetFlags(new QCallAssembly(ref assembly)); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetPublicKey(QCallAssembly assembly, ObjectHandleOnStack retPublicKey); internal byte[] GetPublicKey() { byte[] o = null; RuntimeAssembly assembly = this; GetPublicKey(new QCallAssembly(ref assembly), ObjectHandleOnStack.Create(ref o)); return o; } public override Assembly GetSatelliteAssembly(CultureInfo culture) { return GetSatelliteAssembly(culture, null); } public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version) { if (culture == null) { throw new ArgumentNullException("culture"); } return InternalGetSatelliteAssembly(culture, version, throwOnFileNotFound: true); } internal Assembly InternalGetSatelliteAssembly(CultureInfo culture, Version version, bool throwOnFileNotFound) { AssemblyName assemblyName = new AssemblyName(); assemblyName.SetPublicKey(GetPublicKey()); assemblyName.Flags = GetFlags() | AssemblyNameFlags.PublicKey; assemblyName.Version = version ?? GetVersion(); assemblyName.CultureInfo = culture; assemblyName.Name = GetSimpleName() + ".resources"; StackCrawlMark stackMark = StackCrawlMark.LookForMe; RuntimeAssembly runtimeAssembly = InternalLoad(assemblyName, this, ref stackMark, throwOnFileNotFound); if (runtimeAssembly == this) { runtimeAssembly = null; } if (runtimeAssembly == null && throwOnFileNotFound) { throw new FileNotFoundException(SR.Format(culture, SR.IO_FileNotFound_FileName, assemblyName.Name)); } return runtimeAssembly; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetModules(QCallAssembly assembly, bool loadIfNotFound, bool getResourceModules, ObjectHandleOnStack retModuleHandles); private RuntimeModule[] GetModulesInternal(bool loadIfNotFound, bool getResourceModules) { RuntimeModule[] o = null; RuntimeAssembly assembly = this; GetModules(new QCallAssembly(ref assembly), loadIfNotFound, getResourceModules, ObjectHandleOnStack.Create(ref o)); return o; } public override Module[] GetModules(bool getResourceModules) { return GetModulesInternal(loadIfNotFound: true, getResourceModules); } public override Module[] GetLoadedModules(bool getResourceModules) { return GetModulesInternal(loadIfNotFound: false, getResourceModules); } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern RuntimeModule GetManifestModule(RuntimeAssembly assembly); [MethodImpl(MethodImplOptions.InternalCall)] internal static extern int GetToken(RuntimeAssembly assembly); [RequiresUnreferencedCode("Types might be removed")] public sealed override Type[] GetForwardedTypes() { List list = new List(); List list2 = new List(); GetManifestModule(GetNativeHandle()).MetadataImport.Enum(MetadataTokenType.ExportedType, 0, out var result); RuntimeAssembly assembly = this; QCallAssembly assembly2 = new QCallAssembly(ref assembly); for (int i = 0; i < result.Length; i++) { MetadataToken mdtExternalType = result[i]; Type o = null; Exception item = null; ObjectHandleOnStack type = ObjectHandleOnStack.Create(ref o); try { GetForwardedType(assembly2, mdtExternalType, type); if (o == null) { continue; } } catch (Exception ex) { o = null; item = ex; } if (o != null) { list.Add(o); AddPublicNestedTypes(o, list, list2); } else { list2.Add(item); } } if (list2.Count != 0) { int count = list.Count; int count2 = list2.Count; list.AddRange(new Type[count2]); list2.InsertRange(0, new Exception[count]); throw new ReflectionTypeLoadException(list.ToArray(), list2.ToArray()); } return list.ToArray(); } [RequiresUnreferencedCode("Types might be removed because recursive nested types can't currently be annotated for dynamic access.")] private static void AddPublicNestedTypes(Type type, List types, List exceptions) { Type[] nestedTypes; try { nestedTypes = type.GetNestedTypes(BindingFlags.Public); } catch (Exception item) { exceptions.Add(item); return; } Type[] array = nestedTypes; foreach (Type type2 in array) { types.Add(type2); AddPublicNestedTypes(type2, types, exceptions); } } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetForwardedType(QCallAssembly assembly, MetadataToken mdtExternalType, ObjectHandleOnStack type); } internal sealed class RuntimeConstructorInfo : ConstructorInfo, IRuntimeMethodInfo { private volatile RuntimeType m_declaringType; private RuntimeType.RuntimeTypeCache m_reflectedTypeCache; private string m_toString; private ParameterInfo[] m_parameters; private object _empty1; private object _empty2; private object _empty3; private IntPtr m_handle; private MethodAttributes m_methodAttributes; private BindingFlags m_bindingFlags; private Signature m_signature; private INVOCATION_FLAGS m_invocationFlags; internal INVOCATION_FLAGS InvocationFlags { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { INVOCATION_FLAGS iNVOCATION_FLAGS = m_invocationFlags; if ((iNVOCATION_FLAGS & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) { iNVOCATION_FLAGS = LazyCreateInvocationFlags(); } return iNVOCATION_FLAGS; [MethodImpl(MethodImplOptions.NoInlining)] INVOCATION_FLAGS LazyCreateInvocationFlags() { INVOCATION_FLAGS iNVOCATION_FLAGS2 = INVOCATION_FLAGS.INVOCATION_FLAGS_IS_CTOR; Type declaringType = DeclaringType; if (declaringType == typeof(void) || (declaringType != null && declaringType.ContainsGenericParameters) || (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { iNVOCATION_FLAGS2 |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; } else if (base.IsStatic) { iNVOCATION_FLAGS2 |= INVOCATION_FLAGS.INVOCATION_FLAGS_RUN_CLASS_CONSTRUCTOR | INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE; } else if (declaringType != null && declaringType.IsAbstract) { iNVOCATION_FLAGS2 |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE; } else { if (declaringType != null && declaringType.IsByRefLike) { iNVOCATION_FLAGS2 |= INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS; } if (typeof(Delegate).IsAssignableFrom(DeclaringType)) { iNVOCATION_FLAGS2 |= INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR; } } return m_invocationFlags = iNVOCATION_FLAGS2 | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; } } } RuntimeMethodHandleInternal IRuntimeMethodInfo.Value => new RuntimeMethodHandleInternal(m_handle); private Signature Signature { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_signature ?? LazyCreateSignature(); [MethodImpl(MethodImplOptions.NoInlining)] Signature LazyCreateSignature() { Signature signature = new Signature(this, m_declaringType); Volatile.Write(ref m_signature, signature); return signature; } } } private RuntimeType ReflectedTypeInternal => m_reflectedTypeCache.GetRuntimeType(); internal BindingFlags BindingFlags => m_bindingFlags; public override string Name => RuntimeMethodHandle.GetName(this); public override MemberTypes MemberType => MemberTypes.Constructor; public override Type DeclaringType { get { if (!m_reflectedTypeCache.IsGlobal) { return m_declaringType; } return null; } } public override Type ReflectedType { get { if (!m_reflectedTypeCache.IsGlobal) { return ReflectedTypeInternal; } return null; } } public override int MetadataToken => RuntimeMethodHandle.GetMethodDef(this); public override Module Module => GetRuntimeModule(); public override RuntimeMethodHandle MethodHandle => new RuntimeMethodHandle(this); public override MethodAttributes Attributes => m_methodAttributes; public override CallingConventions CallingConvention => Signature.CallingConvention; public override bool IsSecurityCritical => true; public override bool IsSecuritySafeCritical => false; public override bool IsSecurityTransparent => false; public override bool ContainsGenericParameters { get { if (DeclaringType != null) { return DeclaringType.ContainsGenericParameters; } return false; } } internal RuntimeConstructorInfo(RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeType.RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags) { m_bindingFlags = bindingFlags; m_reflectedTypeCache = reflectedTypeCache; m_declaringType = declaringType; m_handle = handle.Value; m_methodAttributes = methodAttributes; } internal override bool CacheEquals(object o) { if (o is RuntimeConstructorInfo runtimeConstructorInfo) { return runtimeConstructorInfo.m_handle == m_handle; } return false; } private void CheckConsistency(object target) { if ((target != null || !base.IsStatic) && !m_declaringType.IsInstanceOfType(target)) { if (target == null) { throw new TargetException(SR.RFLCT_Targ_StatMethReqTarg); } throw new TargetException(SR.RFLCT_Targ_ITargMismatch); } } public override string ToString() { if (m_toString == null) { ValueStringBuilder sbParamList = new ValueStringBuilder(100); sbParamList.Append("Void "); sbParamList.Append(Name); sbParamList.Append('('); MethodBase.AppendParameters(ref sbParamList, GetParameterTypes(), CallingConvention); sbParamList.Append(')'); m_toString = sbParamList.ToString(); } return m_toString; } public override object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.GetCustomAttributes(this, runtimeType); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.IsDefined(this, runtimeType); } public override IList GetCustomAttributesData() { return RuntimeCustomAttributeData.GetCustomAttributesInternal(this); } public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) { return HasSameMetadataDefinitionAsCore(other); } internal RuntimeType GetRuntimeType() { return m_declaringType; } internal RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(m_declaringType); } internal override Type GetReturnType() { return Signature.ReturnType; } internal override ParameterInfo[] GetParametersNoCopy() { return m_parameters ?? (m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature)); } public override ParameterInfo[] GetParameters() { ParameterInfo[] parametersNoCopy = GetParametersNoCopy(); if (parametersNoCopy.Length == 0) { return parametersNoCopy; } ParameterInfo[] array = new ParameterInfo[parametersNoCopy.Length]; Array.Copy(parametersNoCopy, array, parametersNoCopy.Length); return array; } public override MethodImplAttributes GetMethodImplementationFlags() { return RuntimeMethodHandle.GetImplAttributes(this); } internal static void CheckCanCreateInstance(Type declaringType, bool isVarArg) { if (declaringType == null) { throw new ArgumentNullException("declaringType"); } if (declaringType.IsInterface) { throw new MemberAccessException(SR.Format(SR.Acc_CreateInterfaceEx, declaringType)); } if (declaringType.IsAbstract) { throw new MemberAccessException(SR.Format(SR.Acc_CreateAbstEx, declaringType)); } if (declaringType.GetRootElementType() == typeof(ArgIterator)) { throw new NotSupportedException(); } if (isVarArg) { throw new NotSupportedException(); } if (declaringType.ContainsGenericParameters) { throw new MemberAccessException(SR.Format(SR.Acc_CreateGenericEx, declaringType)); } if (declaringType == typeof(void)) { throw new MemberAccessException(SR.Access_Void); } } [DoesNotReturn] internal void ThrowNoInvokeException() { CheckCanCreateInstance(DeclaringType, (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs); if ((Attributes & MethodAttributes.Static) == MethodAttributes.Static) { throw new MemberAccessException(SR.Acc_NotClassInit); } throw new TargetException(); } [DebuggerStepThrough] [DebuggerHidden] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2059:RunClassConstructor", Justification = "This ConstructorInfo instance represents the static constructor itself, so if this object was created, the static constructor exists.")] public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { INVOCATION_FLAGS invocationFlags = InvocationFlags; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) { ThrowNoInvokeException(); } CheckConsistency(obj); if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_RUN_CLASS_CONSTRUCTOR) != 0) { Type declaringType = DeclaringType; if (declaringType != null) { RuntimeHelpers.RunClassConstructor(declaringType.TypeHandle); } else { RuntimeHelpers.RunModuleConstructor(Module.ModuleHandle); } return null; } Signature signature = Signature; int num = signature.Arguments.Length; int num2 = ((parameters != null) ? parameters.Length : 0); if (num != num2) { throw new TargetParameterCountException(SR.Arg_ParmCnt); } bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0; StackAllocedArguments stackArgs = default(StackAllocedArguments); Span arguments = default(Span); if (num2 != 0) { arguments = CheckArguments(ref stackArgs, parameters, binder, invokeAttr, culture, signature); } object result = RuntimeMethodHandle.InvokeMethod(obj, in arguments, signature, constructor: false, wrapExceptions); for (int i = 0; i < arguments.Length; i++) { parameters[i] = arguments[i]; } return result; } [RequiresUnreferencedCode("Trimming may change method bodies. For example it can change some instructions, remove branches or local variables.")] public override MethodBody GetMethodBody() { RuntimeMethodBody methodBody = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); if (methodBody != null) { methodBody._methodBase = this; } return methodBody; } [DebuggerStepThrough] [DebuggerHidden] public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { INVOCATION_FLAGS invocationFlags = InvocationFlags; if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_NO_CTOR_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0) { ThrowNoInvokeException(); } Signature signature = Signature; int num = signature.Arguments.Length; int num2 = ((parameters != null) ? parameters.Length : 0); if (num != num2) { throw new TargetParameterCountException(SR.Arg_ParmCnt); } bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0; StackAllocedArguments stackArgs = default(StackAllocedArguments); Span arguments = default(Span); if (num2 != 0) { arguments = CheckArguments(ref stackArgs, parameters, binder, invokeAttr, culture, signature); } object result = RuntimeMethodHandle.InvokeMethod(null, in arguments, signature, constructor: true, wrapExceptions); for (int i = 0; i < arguments.Length; i++) { parameters[i] = arguments[i]; } return result; } } internal sealed class RuntimeCustomAttributeData : CustomAttributeData { private ConstructorInfo m_ctor; private readonly RuntimeModule m_scope; private readonly MemberInfo[] m_members; private readonly CustomAttributeCtorParameter[] m_ctorParams; private readonly CustomAttributeNamedParameter[] m_namedParams; private IList m_typedCtorArgs; private IList m_namedArgs; public override ConstructorInfo Constructor => m_ctor; public override IList ConstructorArguments { get { if (m_typedCtorArgs == null) { CustomAttributeTypedArgument[] array = new CustomAttributeTypedArgument[m_ctorParams.Length]; for (int i = 0; i < array.Length; i++) { CustomAttributeEncodedArgument customAttributeEncodedArgument = m_ctorParams[i].CustomAttributeEncodedArgument; array[i] = new CustomAttributeTypedArgument(m_scope, customAttributeEncodedArgument); } m_typedCtorArgs = Array.AsReadOnly(array); } return m_typedCtorArgs; } } public override IList NamedArguments { get { if (m_namedArgs == null) { if (m_namedParams == null) { return null; } int num = 0; for (int i = 0; i < m_namedParams.Length; i++) { if (m_namedParams[i].EncodedArgument.CustomAttributeType.EncodedType != 0) { num++; } } CustomAttributeNamedArgument[] array = new CustomAttributeNamedArgument[num]; int j = 0; int num2 = 0; for (; j < m_namedParams.Length; j++) { if (m_namedParams[j].EncodedArgument.CustomAttributeType.EncodedType != 0) { array[num2++] = new CustomAttributeNamedArgument(m_members[j], new CustomAttributeTypedArgument(m_scope, m_namedParams[j].EncodedArgument)); } } m_namedArgs = Array.AsReadOnly(array); } return m_namedArgs; } } internal static IList GetCustomAttributesInternal(RuntimeType target) { IList customAttributes = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); RuntimeType.ListBuilder pcas = default(RuntimeType.ListBuilder); PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), ref pcas); if (pcas.Count <= 0) { return customAttributes; } return GetCombinedList(customAttributes, ref pcas); } internal static IList GetCustomAttributesInternal(RuntimeFieldInfo target) { IList customAttributes = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); RuntimeType.ListBuilder pcas = default(RuntimeType.ListBuilder); PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), ref pcas); if (pcas.Count <= 0) { return customAttributes; } return GetCombinedList(customAttributes, ref pcas); } internal static IList GetCustomAttributesInternal(RuntimeMethodInfo target) { IList customAttributes = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); RuntimeType.ListBuilder pcas = default(RuntimeType.ListBuilder); PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), ref pcas); if (pcas.Count <= 0) { return customAttributes; } return GetCombinedList(customAttributes, ref pcas); } internal static IList GetCustomAttributesInternal(RuntimeConstructorInfo target) { return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); } internal static IList GetCustomAttributesInternal(RuntimeEventInfo target) { return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); } internal static IList GetCustomAttributesInternal(RuntimePropertyInfo target) { return GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); } internal static IList GetCustomAttributesInternal(RuntimeModule target) { if (target.IsResource()) { return new List(); } return GetCustomAttributes(target, target.MetadataToken); } internal static IList GetCustomAttributesInternal(RuntimeAssembly target) { return GetCustomAttributes((RuntimeModule)target.ManifestModule, RuntimeAssembly.GetToken(target.GetNativeHandle())); } internal static IList GetCustomAttributesInternal(RuntimeParameterInfo target) { RuntimeType.ListBuilder pcas = default(RuntimeType.ListBuilder); IList customAttributes = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken); PseudoCustomAttribute.GetCustomAttributes(target, (RuntimeType)typeof(object), ref pcas); if (pcas.Count <= 0) { return customAttributes; } return GetCombinedList(customAttributes, ref pcas); } private static IList GetCombinedList(IList customAttributes, ref RuntimeType.ListBuilder pseudoAttributes) { CustomAttributeData[] array = new CustomAttributeData[customAttributes.Count + pseudoAttributes.Count]; customAttributes.CopyTo(array, pseudoAttributes.Count); for (int i = 0; i < pseudoAttributes.Count; i++) { array[i] = new RuntimeCustomAttributeData(pseudoAttributes[i]); } return Array.AsReadOnly(array); } private static CustomAttributeEncoding TypeToCustomAttributeEncoding(RuntimeType type) { if (type == typeof(int)) { return CustomAttributeEncoding.Int32; } if (type.IsEnum) { return CustomAttributeEncoding.Enum; } if (type == typeof(string)) { return CustomAttributeEncoding.String; } if (type == typeof(Type)) { return CustomAttributeEncoding.Type; } if (type == typeof(object)) { return CustomAttributeEncoding.Object; } if (type.IsArray) { return CustomAttributeEncoding.Array; } if (type == typeof(char)) { return CustomAttributeEncoding.Char; } if (type == typeof(bool)) { return CustomAttributeEncoding.Boolean; } if (type == typeof(byte)) { return CustomAttributeEncoding.Byte; } if (type == typeof(sbyte)) { return CustomAttributeEncoding.SByte; } if (type == typeof(short)) { return CustomAttributeEncoding.Int16; } if (type == typeof(ushort)) { return CustomAttributeEncoding.UInt16; } if (type == typeof(uint)) { return CustomAttributeEncoding.UInt32; } if (type == typeof(long)) { return CustomAttributeEncoding.Int64; } if (type == typeof(ulong)) { return CustomAttributeEncoding.UInt64; } if (type == typeof(float)) { return CustomAttributeEncoding.Float; } if (type == typeof(double)) { return CustomAttributeEncoding.Double; } if (type == typeof(Enum)) { return CustomAttributeEncoding.Object; } if (type.IsClass) { return CustomAttributeEncoding.Object; } if (type.IsInterface) { return CustomAttributeEncoding.Object; } if (type.IsValueType) { return CustomAttributeEncoding.Undefined; } throw new ArgumentException(SR.Argument_InvalidKindOfTypeForCA, "type"); } private static CustomAttributeType InitCustomAttributeType(RuntimeType parameterType) { CustomAttributeEncoding customAttributeEncoding = TypeToCustomAttributeEncoding(parameterType); CustomAttributeEncoding customAttributeEncoding2 = CustomAttributeEncoding.Undefined; CustomAttributeEncoding encodedEnumType = CustomAttributeEncoding.Undefined; string enumName = null; if (customAttributeEncoding == CustomAttributeEncoding.Array) { parameterType = (RuntimeType)parameterType.GetElementType(); customAttributeEncoding2 = TypeToCustomAttributeEncoding(parameterType); } if (customAttributeEncoding == CustomAttributeEncoding.Enum || customAttributeEncoding2 == CustomAttributeEncoding.Enum) { encodedEnumType = TypeToCustomAttributeEncoding((RuntimeType)Enum.GetUnderlyingType(parameterType)); enumName = parameterType.AssemblyQualifiedName; } return new CustomAttributeType(customAttributeEncoding, customAttributeEncoding2, encodedEnumType, enumName); } private static IList GetCustomAttributes(RuntimeModule module, int tkTarget) { CustomAttributeRecord[] customAttributeRecords = GetCustomAttributeRecords(module, tkTarget); if (customAttributeRecords.Length == 0) { return Array.Empty(); } CustomAttributeData[] array = new CustomAttributeData[customAttributeRecords.Length]; for (int i = 0; i < customAttributeRecords.Length; i++) { array[i] = new RuntimeCustomAttributeData(module, customAttributeRecords[i].tkCtor, in customAttributeRecords[i].blob); } return Array.AsReadOnly(array); } internal static CustomAttributeRecord[] GetCustomAttributeRecords(RuntimeModule module, int targetToken) { MetadataImport metadataImport = module.MetadataImport; metadataImport.EnumCustomAttributes(targetToken, out var result); if (result.Length == 0) { return Array.Empty(); } CustomAttributeRecord[] array = new CustomAttributeRecord[result.Length]; for (int i = 0; i < array.Length; i++) { metadataImport.GetCustomAttributeProps(result[i], out array[i].tkCtor.Value, out array[i].blob); } return array; } internal static CustomAttributeTypedArgument Filter(IList attrs, Type caType, int parameter) { for (int i = 0; i < attrs.Count; i++) { if (attrs[i].Constructor.DeclaringType == caType) { return attrs[i].ConstructorArguments[parameter]; } } return default(CustomAttributeTypedArgument); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", Justification = "Property setters and fields which are accessed by any attribute instantiation which is present in the code linker has analyzed.As such enumerating all fields and properties may return different results after trimmingbut all those which are needed to actually have data will be there.")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:UnrecognizedReflectionPattern", Justification = "We're getting a MethodBase of a constructor that we found in the metadata. The attribute constructor won't be trimmed.")] private RuntimeCustomAttributeData(RuntimeModule scope, MetadataToken caCtorToken, in ConstArray blob) { m_scope = scope; m_ctor = (RuntimeConstructorInfo)RuntimeType.GetMethodBase(scope, caCtorToken); if (m_ctor.DeclaringType.IsGenericType) { Type type = scope.ResolveType(scope.MetadataImport.GetParentToken(caCtorToken), null, null); m_ctor = (RuntimeConstructorInfo)scope.ResolveMethod(caCtorToken, type.GenericTypeArguments, null).MethodHandle.GetMethodInfo(); } ParameterInfo[] parametersNoCopy = m_ctor.GetParametersNoCopy(); m_ctorParams = new CustomAttributeCtorParameter[parametersNoCopy.Length]; for (int i = 0; i < parametersNoCopy.Length; i++) { m_ctorParams[i] = new CustomAttributeCtorParameter(InitCustomAttributeType((RuntimeType)parametersNoCopy[i].ParameterType)); } FieldInfo[] fields = m_ctor.DeclaringType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); PropertyInfo[] properties = m_ctor.DeclaringType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); m_namedParams = new CustomAttributeNamedParameter[properties.Length + fields.Length]; for (int j = 0; j < fields.Length; j++) { m_namedParams[j] = new CustomAttributeNamedParameter(fields[j].Name, CustomAttributeEncoding.Field, InitCustomAttributeType((RuntimeType)fields[j].FieldType)); } for (int k = 0; k < properties.Length; k++) { m_namedParams[k + fields.Length] = new CustomAttributeNamedParameter(properties[k].Name, CustomAttributeEncoding.Property, InitCustomAttributeType((RuntimeType)properties[k].PropertyType)); } m_members = new MemberInfo[fields.Length + properties.Length]; fields.CopyTo(m_members, 0); properties.CopyTo(m_members, fields.Length); CustomAttributeEncodedArgument.ParseAttributeArguments(blob, ref m_ctorParams, ref m_namedParams, m_scope); } internal RuntimeCustomAttributeData(Attribute attribute) { if (attribute is DllImportAttribute dllImport) { Init(dllImport); } else if (attribute is FieldOffsetAttribute fieldOffset) { Init(fieldOffset); } else if (attribute is MarshalAsAttribute marshalAs) { Init(marshalAs); } else if (attribute is TypeForwardedToAttribute forwardedTo) { Init(forwardedTo); } else { Init(attribute); } } private void Init(DllImportAttribute dllImport) { Type typeFromHandle = typeof(DllImportAttribute); m_ctor = typeFromHandle.GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0]; m_typedCtorArgs = Array.AsReadOnly(new CustomAttributeTypedArgument[1] { new CustomAttributeTypedArgument(dllImport.Value) }); m_namedArgs = Array.AsReadOnly(new CustomAttributeNamedArgument[8] { new CustomAttributeNamedArgument(typeFromHandle.GetField("EntryPoint"), dllImport.EntryPoint), new CustomAttributeNamedArgument(typeFromHandle.GetField("CharSet"), dllImport.CharSet), new CustomAttributeNamedArgument(typeFromHandle.GetField("ExactSpelling"), dllImport.ExactSpelling), new CustomAttributeNamedArgument(typeFromHandle.GetField("SetLastError"), dllImport.SetLastError), new CustomAttributeNamedArgument(typeFromHandle.GetField("PreserveSig"), dllImport.PreserveSig), new CustomAttributeNamedArgument(typeFromHandle.GetField("CallingConvention"), dllImport.CallingConvention), new CustomAttributeNamedArgument(typeFromHandle.GetField("BestFitMapping"), dllImport.BestFitMapping), new CustomAttributeNamedArgument(typeFromHandle.GetField("ThrowOnUnmappableChar"), dllImport.ThrowOnUnmappableChar) }); } private void Init(FieldOffsetAttribute fieldOffset) { m_ctor = typeof(FieldOffsetAttribute).GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0]; m_typedCtorArgs = Array.AsReadOnly(new CustomAttributeTypedArgument[1] { new CustomAttributeTypedArgument(fieldOffset.Value) }); m_namedArgs = Array.AsReadOnly(Array.Empty()); } private void Init(MarshalAsAttribute marshalAs) { Type typeFromHandle = typeof(MarshalAsAttribute); m_ctor = typeFromHandle.GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0]; m_typedCtorArgs = Array.AsReadOnly(new CustomAttributeTypedArgument[1] { new CustomAttributeTypedArgument(marshalAs.Value) }); int num = 3; if (marshalAs.MarshalType != null) { num++; } if ((object)marshalAs.MarshalTypeRef != null) { num++; } if (marshalAs.MarshalCookie != null) { num++; } num++; num++; if ((object)marshalAs.SafeArrayUserDefinedSubType != null) { num++; } CustomAttributeNamedArgument[] array = new CustomAttributeNamedArgument[num]; num = 0; array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("ArraySubType"), marshalAs.ArraySubType); array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("SizeParamIndex"), marshalAs.SizeParamIndex); array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("SizeConst"), marshalAs.SizeConst); array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("IidParameterIndex"), marshalAs.IidParameterIndex); array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("SafeArraySubType"), marshalAs.SafeArraySubType); if (marshalAs.MarshalType != null) { array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("MarshalType"), marshalAs.MarshalType); } if ((object)marshalAs.MarshalTypeRef != null) { array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("MarshalTypeRef"), marshalAs.MarshalTypeRef); } if (marshalAs.MarshalCookie != null) { array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("MarshalCookie"), marshalAs.MarshalCookie); } if ((object)marshalAs.SafeArrayUserDefinedSubType != null) { array[num++] = new CustomAttributeNamedArgument(typeFromHandle.GetField("SafeArrayUserDefinedSubType"), marshalAs.SafeArrayUserDefinedSubType); } m_namedArgs = Array.AsReadOnly(array); } private void Init(TypeForwardedToAttribute forwardedTo) { Type typeFromHandle = typeof(TypeForwardedToAttribute); Type[] types = new Type[1] { typeof(Type) }; m_ctor = typeFromHandle.GetConstructor(BindingFlags.Instance | BindingFlags.Public, null, types, null); m_typedCtorArgs = Array.AsReadOnly(new CustomAttributeTypedArgument[1] { new CustomAttributeTypedArgument(typeof(Type), forwardedTo.Destination) }); CustomAttributeNamedArgument[] array = Array.Empty(); m_namedArgs = Array.AsReadOnly(array); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", Justification = "The pca object had to be created by the single ctor on the Type. So the ctor couldn't have been trimmed.")] private void Init(object pca) { Type type = pca.GetType(); m_ctor = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public)[0]; m_typedCtorArgs = Array.AsReadOnly(Array.Empty()); m_namedArgs = Array.AsReadOnly(Array.Empty()); } } public readonly struct CustomAttributeTypedArgument { private readonly object _value; private readonly Type _argumentType; public Type ArgumentType => _argumentType; public object? Value => _value; private static Type CustomAttributeEncodingToType(CustomAttributeEncoding encodedType) { return encodedType switch { CustomAttributeEncoding.Enum => typeof(Enum), CustomAttributeEncoding.Int32 => typeof(int), CustomAttributeEncoding.String => typeof(string), CustomAttributeEncoding.Type => typeof(Type), CustomAttributeEncoding.Array => typeof(Array), CustomAttributeEncoding.Char => typeof(char), CustomAttributeEncoding.Boolean => typeof(bool), CustomAttributeEncoding.SByte => typeof(sbyte), CustomAttributeEncoding.Byte => typeof(byte), CustomAttributeEncoding.Int16 => typeof(short), CustomAttributeEncoding.UInt16 => typeof(ushort), CustomAttributeEncoding.UInt32 => typeof(uint), CustomAttributeEncoding.Int64 => typeof(long), CustomAttributeEncoding.UInt64 => typeof(ulong), CustomAttributeEncoding.Float => typeof(float), CustomAttributeEncoding.Double => typeof(double), CustomAttributeEncoding.Object => typeof(object), _ => throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)encodedType), "encodedType"), }; } private unsafe static object EncodedValueToRawValue(long val, CustomAttributeEncoding encodedType) { return encodedType switch { CustomAttributeEncoding.Boolean => (byte)val != 0, CustomAttributeEncoding.Char => (char)val, CustomAttributeEncoding.Byte => (byte)val, CustomAttributeEncoding.SByte => (sbyte)val, CustomAttributeEncoding.Int16 => (short)val, CustomAttributeEncoding.UInt16 => (ushort)val, CustomAttributeEncoding.Int32 => (int)val, CustomAttributeEncoding.UInt32 => (uint)val, CustomAttributeEncoding.Int64 => val, CustomAttributeEncoding.UInt64 => (ulong)val, CustomAttributeEncoding.Float => *(float*)(&val), CustomAttributeEncoding.Double => *(double*)(&val), _ => throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)val), "val"), }; } private static RuntimeType ResolveType(RuntimeModule scope, string typeName) { RuntimeType typeByNameUsingCARules = RuntimeTypeHandle.GetTypeByNameUsingCARules(typeName, scope); if ((object)typeByNameUsingCARules == null) { throw new InvalidOperationException(SR.Format(SR.Arg_CATypeResolutionFailed, typeName)); } return typeByNameUsingCARules; } internal CustomAttributeTypedArgument(RuntimeModule scope, CustomAttributeEncodedArgument encodedArg) { CustomAttributeEncoding encodedType = encodedArg.CustomAttributeType.EncodedType; switch (encodedType) { case CustomAttributeEncoding.Undefined: throw new ArgumentException(null, "encodedArg"); case CustomAttributeEncoding.Enum: _argumentType = ResolveType(scope, encodedArg.CustomAttributeType.EnumName); _value = EncodedValueToRawValue(encodedArg.PrimitiveValue, encodedArg.CustomAttributeType.EncodedEnumType); break; case CustomAttributeEncoding.String: _argumentType = typeof(string); _value = encodedArg.StringValue; break; case CustomAttributeEncoding.Type: _argumentType = typeof(Type); _value = null; if (encodedArg.StringValue != null) { _value = ResolveType(scope, encodedArg.StringValue); } break; case CustomAttributeEncoding.Array: { encodedType = encodedArg.CustomAttributeType.EncodedArrayType; Type type = ((encodedType != CustomAttributeEncoding.Enum) ? CustomAttributeEncodingToType(encodedType) : ResolveType(scope, encodedArg.CustomAttributeType.EnumName)); _argumentType = type.MakeArrayType(); if (encodedArg.ArrayValue == null) { _value = null; break; } CustomAttributeTypedArgument[] array = new CustomAttributeTypedArgument[encodedArg.ArrayValue.Length]; for (int i = 0; i < array.Length; i++) { array[i] = new CustomAttributeTypedArgument(scope, encodedArg.ArrayValue[i]); } _value = Array.AsReadOnly(array); break; } default: _argumentType = CustomAttributeEncodingToType(encodedType); _value = EncodedValueToRawValue(encodedArg.PrimitiveValue, encodedType); break; } } public static bool operator ==(CustomAttributeTypedArgument left, CustomAttributeTypedArgument right) { return left.Equals(right); } public static bool operator !=(CustomAttributeTypedArgument left, CustomAttributeTypedArgument right) { return !left.Equals(right); } public CustomAttributeTypedArgument(Type argumentType, object? value) { if ((object)argumentType == null) { throw new ArgumentNullException("argumentType"); } _value = CanonicalizeValue(value); _argumentType = argumentType; } public CustomAttributeTypedArgument(object value) { if (value == null) { throw new ArgumentNullException("value"); } _value = CanonicalizeValue(value); _argumentType = value.GetType(); } public override string ToString() { return ToString(typed: false); } internal string ToString(bool typed) { if ((object)_argumentType == null) { return base.ToString(); } if (ArgumentType.IsEnum) { if (typed) { return $"{Value}"; } return $"({ArgumentType.FullName}){Value}"; } if (Value == null) { if (!typed) { return "(" + ArgumentType.Name + ")null"; } return "null"; } if (ArgumentType == typeof(string)) { return $"\"{Value}\""; } if (ArgumentType == typeof(char)) { return $"'{Value}'"; } if (ArgumentType == typeof(Type)) { return "typeof(" + ((Type)Value).FullName + ")"; } if (ArgumentType.IsArray) { IList list = (IList)Value; Type elementType = ArgumentType.GetElementType(); Span initialBuffer = stackalloc char[256]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); valueStringBuilder.Append("new "); valueStringBuilder.Append(elementType.IsEnum ? elementType.FullName : elementType.Name); valueStringBuilder.Append('['); int count = list.Count; valueStringBuilder.Append(count.ToString()); valueStringBuilder.Append("] { "); for (int i = 0; i < count; i++) { if (i != 0) { valueStringBuilder.Append(", "); } valueStringBuilder.Append(list[i].ToString(elementType != typeof(object))); } valueStringBuilder.Append(" }"); return valueStringBuilder.ToString(); } if (typed) { return $"{Value}"; } return $"({ArgumentType.Name}){Value}"; } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object? obj) { return obj == (object)this; } private static object CanonicalizeValue(object value) { if (!(value is Enum @enum)) { return value; } return @enum.GetValue(); } } [StructLayout(LayoutKind.Auto)] internal struct CustomAttributeRecord { internal ConstArray blob; internal MetadataToken tkCtor; } internal enum CustomAttributeEncoding { Undefined = 0, Boolean = 2, Char = 3, SByte = 4, Byte = 5, Int16 = 6, UInt16 = 7, Int32 = 8, UInt32 = 9, Int64 = 10, UInt64 = 11, Float = 12, Double = 13, String = 14, Array = 29, Type = 80, Object = 81, Field = 83, Property = 84, Enum = 85 } [StructLayout(LayoutKind.Auto)] internal readonly struct CustomAttributeEncodedArgument { private readonly long m_primitiveValue; private readonly CustomAttributeEncodedArgument[] m_arrayValue; private readonly string m_stringValue; private readonly CustomAttributeType m_type; public CustomAttributeType CustomAttributeType => m_type; public long PrimitiveValue => m_primitiveValue; public CustomAttributeEncodedArgument[] ArrayValue => m_arrayValue; public string StringValue => m_stringValue; [MethodImpl(MethodImplOptions.InternalCall)] private static extern void ParseAttributeArguments(IntPtr pCa, int cCa, ref CustomAttributeCtorParameter[] CustomAttributeCtorParameters, ref CustomAttributeNamedParameter[] CustomAttributeTypedArgument, RuntimeAssembly assembly); internal static void ParseAttributeArguments(ConstArray attributeBlob, ref CustomAttributeCtorParameter[] customAttributeCtorParameters, ref CustomAttributeNamedParameter[] customAttributeNamedParameters, RuntimeModule customAttributeModule) { if ((object)customAttributeModule == null) { throw new ArgumentNullException("customAttributeModule"); } if (customAttributeCtorParameters.Length != 0 || customAttributeNamedParameters.Length != 0) { ParseAttributeArguments(attributeBlob.Signature, attributeBlob.Length, ref customAttributeCtorParameters, ref customAttributeNamedParameters, (RuntimeAssembly)customAttributeModule.Assembly); } } } [StructLayout(LayoutKind.Auto)] internal readonly struct CustomAttributeNamedParameter { private readonly string m_argumentName; private readonly CustomAttributeEncoding m_fieldOrProperty; private readonly CustomAttributeEncoding m_padding; private readonly CustomAttributeType m_type; private readonly CustomAttributeEncodedArgument m_encodedArgument; public CustomAttributeEncodedArgument EncodedArgument => m_encodedArgument; public CustomAttributeNamedParameter(string argumentName, CustomAttributeEncoding fieldOrProperty, CustomAttributeType type) { if (argumentName == null) { throw new ArgumentNullException("argumentName"); } m_argumentName = argumentName; m_fieldOrProperty = fieldOrProperty; m_padding = fieldOrProperty; m_type = type; m_encodedArgument = default(CustomAttributeEncodedArgument); } } [StructLayout(LayoutKind.Auto)] internal readonly struct CustomAttributeCtorParameter { private readonly CustomAttributeType m_type; private readonly CustomAttributeEncodedArgument m_encodedArgument; public CustomAttributeEncodedArgument CustomAttributeEncodedArgument => m_encodedArgument; public CustomAttributeCtorParameter(CustomAttributeType type) { m_type = type; m_encodedArgument = default(CustomAttributeEncodedArgument); } } [StructLayout(LayoutKind.Auto)] internal readonly struct CustomAttributeType { private readonly string m_enumName; private readonly CustomAttributeEncoding m_encodedType; private readonly CustomAttributeEncoding m_encodedEnumType; private readonly CustomAttributeEncoding m_encodedArrayType; private readonly CustomAttributeEncoding m_padding; public CustomAttributeEncoding EncodedType => m_encodedType; public CustomAttributeEncoding EncodedEnumType => m_encodedEnumType; public CustomAttributeEncoding EncodedArrayType => m_encodedArrayType; public string EnumName => m_enumName; public CustomAttributeType(CustomAttributeEncoding encodedType, CustomAttributeEncoding encodedArrayType, CustomAttributeEncoding encodedEnumType, string enumName) { m_encodedType = encodedType; m_encodedArrayType = encodedArrayType; m_encodedEnumType = encodedEnumType; m_enumName = enumName; m_padding = m_encodedType; } } internal static class CustomAttribute { private static readonly RuntimeType Type_RuntimeType = (RuntimeType)typeof(RuntimeType); private static readonly RuntimeType Type_Type = (RuntimeType)typeof(Type); internal static bool IsDefined(RuntimeType type, RuntimeType caType, bool inherit) { if ((object)type.GetElementType() != null) { return false; } if (PseudoCustomAttribute.IsDefined(type, caType)) { return true; } if (IsCustomAttributeDefined(type.GetRuntimeModule(), type.MetadataToken, caType)) { return true; } if (!inherit) { return false; } type = type.BaseType as RuntimeType; while ((object)type != null) { if (IsCustomAttributeDefined(type.GetRuntimeModule(), type.MetadataToken, caType, 0, inherit)) { return true; } type = type.BaseType as RuntimeType; } return false; } internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType, bool inherit) { if (PseudoCustomAttribute.IsDefined(method, caType)) { return true; } if (IsCustomAttributeDefined(method.GetRuntimeModule(), method.MetadataToken, caType)) { return true; } if (!inherit) { return false; } method = method.GetParentDefinition(); while ((object)method != null) { if (IsCustomAttributeDefined(method.GetRuntimeModule(), method.MetadataToken, caType, 0, inherit)) { return true; } method = method.GetParentDefinition(); } return false; } internal static bool IsDefined(RuntimeConstructorInfo ctor, RuntimeType caType) { return IsCustomAttributeDefined(ctor.GetRuntimeModule(), ctor.MetadataToken, caType); } internal static bool IsDefined(RuntimePropertyInfo property, RuntimeType caType) { return IsCustomAttributeDefined(property.GetRuntimeModule(), property.MetadataToken, caType); } internal static bool IsDefined(RuntimeEventInfo e, RuntimeType caType) { return IsCustomAttributeDefined(e.GetRuntimeModule(), e.MetadataToken, caType); } internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType) { if (PseudoCustomAttribute.IsDefined(field, caType)) { return true; } return IsCustomAttributeDefined(field.GetRuntimeModule(), field.MetadataToken, caType); } internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType) { if (PseudoCustomAttribute.IsDefined(parameter, caType)) { return true; } return IsCustomAttributeDefined(parameter.GetRuntimeModule(), parameter.MetadataToken, caType); } internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType) { return IsCustomAttributeDefined(assembly.ManifestModule as RuntimeModule, RuntimeAssembly.GetToken(assembly.GetNativeHandle()), caType); } internal static bool IsDefined(RuntimeModule module, RuntimeType caType) { return IsCustomAttributeDefined(module, module.MetadataToken, caType); } internal static object[] GetCustomAttributes(RuntimeType type, RuntimeType caType, bool inherit) { if ((object)type.GetElementType() != null) { if (!caType.IsValueType) { return CreateAttributeArrayHelper(caType, 0); } return Array.Empty(); } if (type.IsGenericType && !type.IsGenericTypeDefinition) { type = type.GetGenericTypeDefinition() as RuntimeType; } RuntimeType.ListBuilder pcas = default(RuntimeType.ListBuilder); PseudoCustomAttribute.GetCustomAttributes(type, caType, ref pcas); if (!inherit || (caType.IsSealed && !GetAttributeUsage(caType).Inherited)) { object[] customAttributes = GetCustomAttributes(type.GetRuntimeModule(), type.MetadataToken, pcas.Count, caType); if (pcas.Count > 0) { pcas.CopyTo(customAttributes, customAttributes.Length - pcas.Count); } return customAttributes; } RuntimeType.ListBuilder attributes = default(RuntimeType.ListBuilder); bool mustBeInheritable = false; RuntimeType elementType = ((caType.IsValueType || caType.ContainsGenericParameters) ? ((RuntimeType)typeof(object)) : caType); for (int i = 0; i < pcas.Count; i++) { attributes.Add(pcas[i]); } while (type != (RuntimeType)typeof(object) && type != null) { AddCustomAttributes(ref attributes, type.GetRuntimeModule(), type.MetadataToken, caType, mustBeInheritable, attributes); mustBeInheritable = true; type = type.BaseType as RuntimeType; } object[] array = CreateAttributeArrayHelper(elementType, attributes.Count); for (int j = 0; j < attributes.Count; j++) { array[j] = attributes[j]; } return array; } internal static object[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, bool inherit) { if (method.IsGenericMethod && !method.IsGenericMethodDefinition) { method = method.GetGenericMethodDefinition() as RuntimeMethodInfo; } RuntimeType.ListBuilder pcas = default(RuntimeType.ListBuilder); PseudoCustomAttribute.GetCustomAttributes(method, caType, ref pcas); if (!inherit || (caType.IsSealed && !GetAttributeUsage(caType).Inherited)) { object[] customAttributes = GetCustomAttributes(method.GetRuntimeModule(), method.MetadataToken, pcas.Count, caType); if (pcas.Count > 0) { pcas.CopyTo(customAttributes, customAttributes.Length - pcas.Count); } return customAttributes; } RuntimeType.ListBuilder attributes = default(RuntimeType.ListBuilder); bool mustBeInheritable = false; RuntimeType elementType = ((caType.IsValueType || caType.ContainsGenericParameters) ? ((RuntimeType)typeof(object)) : caType); for (int i = 0; i < pcas.Count; i++) { attributes.Add(pcas[i]); } while (method != null) { AddCustomAttributes(ref attributes, method.GetRuntimeModule(), method.MetadataToken, caType, mustBeInheritable, attributes); mustBeInheritable = true; method = method.GetParentDefinition(); } object[] array = CreateAttributeArrayHelper(elementType, attributes.Count); for (int j = 0; j < attributes.Count; j++) { array[j] = attributes[j]; } return array; } internal static object[] GetCustomAttributes(RuntimeConstructorInfo ctor, RuntimeType caType) { return GetCustomAttributes(ctor.GetRuntimeModule(), ctor.MetadataToken, 0, caType); } internal static object[] GetCustomAttributes(RuntimePropertyInfo property, RuntimeType caType) { return GetCustomAttributes(property.GetRuntimeModule(), property.MetadataToken, 0, caType); } internal static object[] GetCustomAttributes(RuntimeEventInfo e, RuntimeType caType) { return GetCustomAttributes(e.GetRuntimeModule(), e.MetadataToken, 0, caType); } internal static object[] GetCustomAttributes(RuntimeFieldInfo field, RuntimeType caType) { RuntimeType.ListBuilder pcas = default(RuntimeType.ListBuilder); PseudoCustomAttribute.GetCustomAttributes(field, caType, ref pcas); object[] customAttributes = GetCustomAttributes(field.GetRuntimeModule(), field.MetadataToken, pcas.Count, caType); if (pcas.Count > 0) { pcas.CopyTo(customAttributes, customAttributes.Length - pcas.Count); } return customAttributes; } internal static object[] GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType) { RuntimeType.ListBuilder pcas = default(RuntimeType.ListBuilder); PseudoCustomAttribute.GetCustomAttributes(parameter, caType, ref pcas); object[] customAttributes = GetCustomAttributes(parameter.GetRuntimeModule(), parameter.MetadataToken, pcas.Count, caType); if (pcas.Count > 0) { pcas.CopyTo(customAttributes, customAttributes.Length - pcas.Count); } return customAttributes; } internal static object[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType) { int token = RuntimeAssembly.GetToken(assembly.GetNativeHandle()); return GetCustomAttributes(assembly.ManifestModule as RuntimeModule, token, 0, caType); } internal static object[] GetCustomAttributes(RuntimeModule module, RuntimeType caType) { return GetCustomAttributes(module, module.MetadataToken, 0, caType); } private static bool IsCustomAttributeDefined(RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType attributeFilterType) { return IsCustomAttributeDefined(decoratedModule, decoratedMetadataToken, attributeFilterType, 0, mustBeInheritable: false); } private static bool IsCustomAttributeDefined(RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType attributeFilterType, int attributeCtorToken, bool mustBeInheritable) { MetadataImport scope = decoratedModule.MetadataImport; scope.EnumCustomAttributes(decoratedMetadataToken, out var result); if (result.Length == 0) { return false; } CustomAttributeRecord customAttributeRecord = default(CustomAttributeRecord); if ((object)attributeFilterType != null) { RuntimeType.ListBuilder derivedAttributes = default(RuntimeType.ListBuilder); for (int i = 0; i < result.Length; i++) { scope.GetCustomAttributeProps(result[i], out customAttributeRecord.tkCtor.Value, out customAttributeRecord.blob); if (FilterCustomAttributeRecord(customAttributeRecord.tkCtor, in scope, decoratedModule, decoratedMetadataToken, attributeFilterType, mustBeInheritable, ref derivedAttributes, out var _, out var _, out var _)) { return true; } } } else { for (int j = 0; j < result.Length; j++) { scope.GetCustomAttributeProps(result[j], out customAttributeRecord.tkCtor.Value, out customAttributeRecord.blob); if ((int)customAttributeRecord.tkCtor == attributeCtorToken) { return true; } } } return false; } private static object[] GetCustomAttributes(RuntimeModule decoratedModule, int decoratedMetadataToken, int pcaCount, RuntimeType attributeFilterType) { RuntimeType.ListBuilder attributes = default(RuntimeType.ListBuilder); AddCustomAttributes(ref attributes, decoratedModule, decoratedMetadataToken, attributeFilterType, mustBeInheritable: false, default(RuntimeType.ListBuilder)); RuntimeType elementType = (((object)attributeFilterType == null || attributeFilterType.IsValueType || attributeFilterType.ContainsGenericParameters) ? ((RuntimeType)typeof(object)) : attributeFilterType); object[] array = CreateAttributeArrayHelper(elementType, attributes.Count + pcaCount); for (int i = 0; i < attributes.Count; i++) { array[i] = attributes[i]; } return array; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2065:UnrecognizedReflectionPattern", Justification = "Linker guarantees presence of all the constructor parameters, property setters and fields which are accessed by any attribute instantiation which is present in the code linker has analyzed.As such the reflection usage in this method will never fail as those methods/fields will be present.")] private unsafe static void AddCustomAttributes(ref RuntimeType.ListBuilder attributes, RuntimeModule decoratedModule, int decoratedMetadataToken, RuntimeType attributeFilterType, bool mustBeInheritable, RuntimeType.ListBuilder derivedAttributes) { CustomAttributeRecord[] customAttributeRecords = RuntimeCustomAttributeData.GetCustomAttributeRecords(decoratedModule, decoratedMetadataToken); if ((object)attributeFilterType == null && customAttributeRecords.Length == 0) { return; } MetadataImport scope = decoratedModule.MetadataImport; for (int i = 0; i < customAttributeRecords.Length; i++) { ref CustomAttributeRecord reference = ref customAttributeRecords[i]; IntPtr blob = reference.blob.Signature; IntPtr intPtr = (IntPtr)((byte*)(void*)blob + reference.blob.Length); if (!FilterCustomAttributeRecord(reference.tkCtor, in scope, decoratedModule, decoratedMetadataToken, attributeFilterType, mustBeInheritable, ref derivedAttributes, out var attributeType, out var ctorWithParameters, out var isVarArg)) { continue; } RuntimeConstructorInfo.CheckCanCreateInstance(attributeType, isVarArg); object obj; int namedArgs; if (ctorWithParameters != null) { obj = CreateCaObject(decoratedModule, attributeType, ctorWithParameters, ref blob, intPtr, out namedArgs); } else { obj = attributeType.CreateInstanceDefaultCtor(publicOnly: false, wrapExceptions: false); if ((int)((byte*)(void*)intPtr - (byte*)(void*)blob) == 0) { namedArgs = 0; } else { int num = Unsafe.ReadUnaligned((void*)blob); if ((num & 0xFFFF) != 1) { throw new CustomAttributeFormatException(); } namedArgs = num >> 16; blob = (IntPtr)((byte*)(void*)blob + 4); } } for (int j = 0; j < namedArgs; j++) { GetPropertyOrFieldData(decoratedModule, ref blob, intPtr, out var name, out var isProperty, out var type, out var value); try { if (isProperty) { if ((object)type == null && value != null) { type = (RuntimeType)value.GetType(); if (type == Type_RuntimeType) { type = Type_Type; } } PropertyInfo propertyInfo = (((object)type == null) ? attributeType.GetProperty(name) : attributeType.GetProperty(name, type, Type.EmptyTypes)); if ((object)propertyInfo == null) { throw new CustomAttributeFormatException(SR.Format(SR.RFLCT_InvalidPropFail, name)); } MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true); if (setMethod.IsPublic) { setMethod.Invoke(obj, BindingFlags.Default, null, new object[1] { value }, null); } } else { FieldInfo field = attributeType.GetField(name); field.SetValue(obj, value, BindingFlags.Default, Type.DefaultBinder, null); } } catch (Exception inner) { throw new CustomAttributeFormatException(SR.Format(isProperty ? SR.RFLCT_InvalidPropFail : SR.RFLCT_InvalidFieldFail, name), inner); } } if (blob != intPtr) { throw new CustomAttributeFormatException(); } attributes.Add(obj); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Module.ResolveMethod and Module.ResolveType are marked as RequiresUnreferencedCode because they rely on tokenswhich are not guaranteed to be stable across trimming. So if somebody hardcodes a token it could break.The usage here is not like that as all these tokens come from existing metadata loaded from some ILand so trimming has no effect (the tokens are read AFTER trimming occured).")] private static bool FilterCustomAttributeRecord(MetadataToken caCtorToken, in MetadataImport scope, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, bool mustBeInheritable, ref RuntimeType.ListBuilder derivedAttributes, out RuntimeType attributeType, out IRuntimeMethodInfo ctorWithParameters, out bool isVarArg) { ctorWithParameters = null; isVarArg = false; attributeType = decoratedModule.ResolveType(scope.GetParentToken(caCtorToken), null, null) as RuntimeType; if (!attributeFilterType.IsAssignableFrom(attributeType)) { return false; } if (!AttributeUsageCheck(attributeType, mustBeInheritable, ref derivedAttributes)) { return false; } if ((attributeType.Attributes & TypeAttributes.WindowsRuntime) == TypeAttributes.WindowsRuntime) { return false; } ConstArray methodSignature = scope.GetMethodSignature(caCtorToken); isVarArg = (methodSignature[0] & 5) != 0; if (methodSignature[1] != 0) { if (attributeType.IsGenericType) { ctorWithParameters = decoratedModule.ResolveMethod(caCtorToken, attributeType.GenericTypeArguments, null).MethodHandle.GetMethodInfo(); } else { ctorWithParameters = new ModuleHandle(decoratedModule).ResolveMethodHandle(caCtorToken).GetMethodInfo(); } } MetadataToken metadataToken = default(MetadataToken); if (decoratedToken.IsParamDef) { metadataToken = new MetadataToken(scope.GetParentToken(decoratedToken)); metadataToken = new MetadataToken(scope.GetParentToken(metadataToken)); } else if (decoratedToken.IsMethodDef || decoratedToken.IsProperty || decoratedToken.IsEvent || decoratedToken.IsFieldDef) { metadataToken = new MetadataToken(scope.GetParentToken(decoratedToken)); } else if (decoratedToken.IsTypeDef) { metadataToken = decoratedToken; } else if (decoratedToken.IsGenericPar) { metadataToken = new MetadataToken(scope.GetParentToken(decoratedToken)); if (metadataToken.IsMethodDef) { metadataToken = new MetadataToken(scope.GetParentToken(metadataToken)); } } RuntimeTypeHandle rth = (metadataToken.IsTypeDef ? decoratedModule.ModuleHandle.ResolveTypeHandle(metadataToken) : default(RuntimeTypeHandle)); RuntimeTypeHandle rth2 = attributeType.TypeHandle; bool result = RuntimeMethodHandle.IsCAVisibleFromDecoratedType(new QCallTypeHandle(ref rth2), (ctorWithParameters != null) ? ctorWithParameters.Value : RuntimeMethodHandleInternal.EmptyHandle, new QCallTypeHandle(ref rth), new QCallModule(ref decoratedModule)) != Interop.BOOL.FALSE; GC.KeepAlive(ctorWithParameters); return result; } private static bool AttributeUsageCheck(RuntimeType attributeType, bool mustBeInheritable, ref RuntimeType.ListBuilder derivedAttributes) { AttributeUsageAttribute attributeUsageAttribute = null; if (mustBeInheritable) { attributeUsageAttribute = GetAttributeUsage(attributeType); if (!attributeUsageAttribute.Inherited) { return false; } } if (derivedAttributes.Count == 0) { return true; } for (int i = 0; i < derivedAttributes.Count; i++) { if (derivedAttributes[i].GetType() == attributeType) { if (attributeUsageAttribute == null) { attributeUsageAttribute = GetAttributeUsage(attributeType); } return attributeUsageAttribute.AllowMultiple; } } return true; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Module.ResolveType is marked as RequiresUnreferencedCode because it relies on tokenswhich are not guaranteed to be stable across trimming. So if somebody hardcodes a token it could break.The usage here is not like that as all these tokens come from existing metadata loaded from some ILand so trimming has no effect (the tokens are read AFTER trimming occured).")] internal static AttributeUsageAttribute GetAttributeUsage(RuntimeType decoratedAttribute) { RuntimeModule runtimeModule = decoratedAttribute.GetRuntimeModule(); MetadataImport metadataImport = runtimeModule.MetadataImport; CustomAttributeRecord[] customAttributeRecords = RuntimeCustomAttributeData.GetCustomAttributeRecords(runtimeModule, decoratedAttribute.MetadataToken); AttributeUsageAttribute attributeUsageAttribute = null; for (int i = 0; i < customAttributeRecords.Length; i++) { ref CustomAttributeRecord reference = ref customAttributeRecords[i]; RuntimeType runtimeType = runtimeModule.ResolveType(metadataImport.GetParentToken(reference.tkCtor), null, null) as RuntimeType; if (!(runtimeType != (RuntimeType)typeof(AttributeUsageAttribute))) { if (attributeUsageAttribute != null) { throw new FormatException(SR.Format(SR.Format_AttributeUsage, runtimeType)); } ParseAttributeUsageAttribute(reference.blob, out var targets, out var inherited, out var allowMultiple); attributeUsageAttribute = new AttributeUsageAttribute(targets, allowMultiple, inherited); } } return attributeUsageAttribute ?? AttributeUsageAttribute.Default; } [MethodImpl(MethodImplOptions.InternalCall)] private static extern void _ParseAttributeUsageAttribute(IntPtr pCa, int cCa, out int targets, out bool inherited, out bool allowMultiple); private static void ParseAttributeUsageAttribute(ConstArray ca, out AttributeTargets targets, out bool inherited, out bool allowMultiple) { _ParseAttributeUsageAttribute(ca.Signature, ca.Length, out var targets2, out inherited, out allowMultiple); targets = (AttributeTargets)targets2; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern object _CreateCaObject(RuntimeModule pModule, RuntimeType type, IRuntimeMethodInfo pCtor, byte** ppBlob, byte* pEndBlob, int* pcNamedArgs); private unsafe static object CreateCaObject(RuntimeModule module, RuntimeType type, IRuntimeMethodInfo ctor, ref IntPtr blob, IntPtr blobEnd, out int namedArgs) { byte* ptr = (byte*)(void*)blob; byte* pEndBlob = (byte*)(void*)blobEnd; System.Runtime.CompilerServices.Unsafe.SkipInit(out int num); object result = _CreateCaObject(module, type, ctor, &ptr, pEndBlob, &num); blob = (IntPtr)ptr; namedArgs = num; return result; } [MethodImpl(MethodImplOptions.InternalCall)] private unsafe static extern void _GetPropertyOrFieldData(RuntimeModule pModule, byte** ppBlobStart, byte* pBlobEnd, out string name, out bool bIsProperty, out RuntimeType type, out object value); private unsafe static void GetPropertyOrFieldData(RuntimeModule module, ref IntPtr blobStart, IntPtr blobEnd, out string name, out bool isProperty, out RuntimeType type, out object value) { byte* ptr = (byte*)(void*)blobStart; _GetPropertyOrFieldData(module, &ptr, (byte*)(void*)blobEnd, out name, out isProperty, out type, out value); blobStart = (IntPtr)ptr; } private static object[] CreateAttributeArrayHelper(RuntimeType elementType, int elementCount) { if (elementCount == 0) { return elementType.GetEmptyArray(); } return (object[])Array.CreateInstance(elementType, elementCount); } } internal static class PseudoCustomAttribute { private static readonly HashSet s_pca = CreatePseudoCustomAttributeHashSet(); private static HashSet CreatePseudoCustomAttributeHashSet() { Type[] array = new Type[11] { typeof(FieldOffsetAttribute), typeof(SerializableAttribute), typeof(MarshalAsAttribute), typeof(ComImportAttribute), typeof(NonSerializedAttribute), typeof(InAttribute), typeof(OutAttribute), typeof(OptionalAttribute), typeof(DllImportAttribute), typeof(PreserveSigAttribute), typeof(TypeForwardedToAttribute) }; HashSet hashSet = new HashSet(array.Length); Type[] array2 = array; for (int i = 0; i < array2.Length; i++) { RuntimeType item = (RuntimeType)array2[i]; hashSet.Add(item); } return hashSet; } internal static void GetCustomAttributes(RuntimeType type, RuntimeType caType, ref RuntimeType.ListBuilder pcas) { bool flag = caType == typeof(object) || caType == typeof(Attribute); if (flag || s_pca.Contains(caType)) { if ((flag || caType == typeof(SerializableAttribute)) && (type.Attributes & TypeAttributes.Serializable) != 0) { pcas.Add(new SerializableAttribute()); } if ((flag || caType == typeof(ComImportAttribute)) && (type.Attributes & TypeAttributes.Import) != 0) { pcas.Add(new ComImportAttribute()); } } } internal static bool IsDefined(RuntimeType type, RuntimeType caType) { bool flag = caType == typeof(object) || caType == typeof(Attribute); if (!flag && !s_pca.Contains(caType)) { return false; } if ((flag || caType == typeof(SerializableAttribute)) && (type.Attributes & TypeAttributes.Serializable) != 0) { return true; } if ((flag || caType == typeof(ComImportAttribute)) && (type.Attributes & TypeAttributes.Import) != 0) { return true; } return false; } internal static void GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, ref RuntimeType.ListBuilder pcas) { bool flag = caType == typeof(object) || caType == typeof(Attribute); if (!flag && !s_pca.Contains(caType)) { return; } if (flag || caType == typeof(DllImportAttribute)) { Attribute dllImportCustomAttribute = GetDllImportCustomAttribute(method); if (dllImportCustomAttribute != null) { pcas.Add(dllImportCustomAttribute); } } if ((flag || caType == typeof(PreserveSigAttribute)) && (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0) { pcas.Add(new PreserveSigAttribute()); } } internal static bool IsDefined(RuntimeMethodInfo method, RuntimeType caType) { bool flag = caType == typeof(object) || caType == typeof(Attribute); if (!flag && !s_pca.Contains(caType)) { return false; } if ((flag || caType == typeof(DllImportAttribute)) && (method.Attributes & MethodAttributes.PinvokeImpl) != 0) { return true; } if ((flag || caType == typeof(PreserveSigAttribute)) && (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0) { return true; } return false; } internal static void GetCustomAttributes(RuntimeParameterInfo parameter, RuntimeType caType, ref RuntimeType.ListBuilder pcas) { bool flag = caType == typeof(object) || caType == typeof(Attribute); if (!flag && !s_pca.Contains(caType)) { return; } if ((flag || caType == typeof(InAttribute)) && parameter.IsIn) { pcas.Add(new InAttribute()); } if ((flag || caType == typeof(OutAttribute)) && parameter.IsOut) { pcas.Add(new OutAttribute()); } if ((flag || caType == typeof(OptionalAttribute)) && parameter.IsOptional) { pcas.Add(new OptionalAttribute()); } if (flag || caType == typeof(MarshalAsAttribute)) { Attribute marshalAsCustomAttribute = GetMarshalAsCustomAttribute(parameter); if (marshalAsCustomAttribute != null) { pcas.Add(marshalAsCustomAttribute); } } } internal static bool IsDefined(RuntimeParameterInfo parameter, RuntimeType caType) { bool flag = caType == typeof(object) || caType == typeof(Attribute); if (!flag && !s_pca.Contains(caType)) { return false; } if ((flag || caType == typeof(InAttribute)) && parameter.IsIn) { return true; } if ((flag || caType == typeof(OutAttribute)) && parameter.IsOut) { return true; } if ((flag || caType == typeof(OptionalAttribute)) && parameter.IsOptional) { return true; } if ((flag || caType == typeof(MarshalAsAttribute)) && GetMarshalAsCustomAttribute(parameter) != null) { return true; } return false; } internal static void GetCustomAttributes(RuntimeFieldInfo field, RuntimeType caType, ref RuntimeType.ListBuilder pcas) { bool flag = caType == typeof(object) || caType == typeof(Attribute); if (!flag && !s_pca.Contains(caType)) { return; } if (flag || caType == typeof(MarshalAsAttribute)) { Attribute marshalAsCustomAttribute = GetMarshalAsCustomAttribute(field); if (marshalAsCustomAttribute != null) { pcas.Add(marshalAsCustomAttribute); } } if (flag || caType == typeof(FieldOffsetAttribute)) { Attribute marshalAsCustomAttribute = GetFieldOffsetCustomAttribute(field); if (marshalAsCustomAttribute != null) { pcas.Add(marshalAsCustomAttribute); } } if ((flag || caType == typeof(NonSerializedAttribute)) && (field.Attributes & FieldAttributes.NotSerialized) != 0) { pcas.Add(new NonSerializedAttribute()); } } internal static bool IsDefined(RuntimeFieldInfo field, RuntimeType caType) { bool flag = caType == typeof(object) || caType == typeof(Attribute); if (!flag && !s_pca.Contains(caType)) { return false; } if ((flag || caType == typeof(MarshalAsAttribute)) && GetMarshalAsCustomAttribute(field) != null) { return true; } if ((flag || caType == typeof(FieldOffsetAttribute)) && GetFieldOffsetCustomAttribute(field) != null) { return true; } if ((flag || caType == typeof(NonSerializedAttribute)) && (field.Attributes & FieldAttributes.NotSerialized) != 0) { return true; } return false; } private static DllImportAttribute GetDllImportCustomAttribute(RuntimeMethodInfo method) { if ((method.Attributes & MethodAttributes.PinvokeImpl) == 0) { return null; } MetadataImport metadataImport = ModuleHandle.GetMetadataImport(method.Module.ModuleHandle.GetRuntimeModule()); int metadataToken = method.MetadataToken; metadataImport.GetPInvokeMap(metadataToken, out var attributes, out var importName, out var importDll); CharSet charSet = CharSet.None; switch (attributes & PInvokeAttributes.CharSetMask) { case PInvokeAttributes.CharSetNotSpec: charSet = CharSet.None; break; case PInvokeAttributes.CharSetAnsi: charSet = CharSet.Ansi; break; case PInvokeAttributes.CharSetUnicode: charSet = CharSet.Unicode; break; case PInvokeAttributes.CharSetMask: charSet = CharSet.Auto; break; } CallingConvention callingConvention = CallingConvention.Cdecl; switch (attributes & PInvokeAttributes.CallConvMask) { case PInvokeAttributes.CallConvWinapi: callingConvention = CallingConvention.Winapi; break; case PInvokeAttributes.CallConvCdecl: callingConvention = CallingConvention.Cdecl; break; case PInvokeAttributes.CallConvStdcall: callingConvention = CallingConvention.StdCall; break; case PInvokeAttributes.CallConvThiscall: callingConvention = CallingConvention.ThisCall; break; case PInvokeAttributes.CallConvFastcall: callingConvention = CallingConvention.FastCall; break; } DllImportAttribute dllImportAttribute = new DllImportAttribute(importDll); dllImportAttribute.EntryPoint = importName; dllImportAttribute.CharSet = charSet; dllImportAttribute.SetLastError = (attributes & PInvokeAttributes.SupportsLastError) != 0; dllImportAttribute.ExactSpelling = (attributes & PInvokeAttributes.NoMangle) != 0; dllImportAttribute.PreserveSig = (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0; dllImportAttribute.CallingConvention = callingConvention; dllImportAttribute.BestFitMapping = (attributes & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitEnabled; dllImportAttribute.ThrowOnUnmappableChar = (attributes & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharEnabled; return dllImportAttribute; } private static MarshalAsAttribute GetMarshalAsCustomAttribute(RuntimeParameterInfo parameter) { return GetMarshalAsCustomAttribute(parameter.MetadataToken, parameter.GetRuntimeModule()); } private static MarshalAsAttribute GetMarshalAsCustomAttribute(RuntimeFieldInfo field) { return GetMarshalAsCustomAttribute(field.MetadataToken, field.GetRuntimeModule()); } private static MarshalAsAttribute GetMarshalAsCustomAttribute(int token, RuntimeModule scope) { ConstArray fieldMarshal = ModuleHandle.GetMetadataImport(scope).GetFieldMarshal(token); if (fieldMarshal.Length == 0) { return null; } MetadataImport.GetMarshalAs(fieldMarshal, out var unmanagedType, out var safeArraySubType, out var safeArrayUserDefinedSubType, out var arraySubType, out var sizeParamIndex, out var sizeConst, out var marshalType, out var marshalCookie, out var iidParamIndex); RuntimeType safeArrayUserDefinedSubType2 = (string.IsNullOrEmpty(safeArrayUserDefinedSubType) ? null : RuntimeTypeHandle.GetTypeByNameUsingCARules(safeArrayUserDefinedSubType, scope)); RuntimeType marshalTypeRef = null; try { marshalTypeRef = ((marshalType == null) ? null : RuntimeTypeHandle.GetTypeByNameUsingCARules(marshalType, scope)); } catch (TypeLoadException) { } MarshalAsAttribute marshalAsAttribute = new MarshalAsAttribute(unmanagedType); marshalAsAttribute.SafeArraySubType = safeArraySubType; marshalAsAttribute.SafeArrayUserDefinedSubType = safeArrayUserDefinedSubType2; marshalAsAttribute.IidParameterIndex = iidParamIndex; marshalAsAttribute.ArraySubType = arraySubType; marshalAsAttribute.SizeParamIndex = (short)sizeParamIndex; marshalAsAttribute.SizeConst = sizeConst; marshalAsAttribute.MarshalType = marshalType; marshalAsAttribute.MarshalTypeRef = marshalTypeRef; marshalAsAttribute.MarshalCookie = marshalCookie; return marshalAsAttribute; } private static FieldOffsetAttribute GetFieldOffsetCustomAttribute(RuntimeFieldInfo field) { if ((object)field.DeclaringType != null && field.GetRuntimeModule().MetadataImport.GetFieldOffset(field.DeclaringType.MetadataToken, field.MetadataToken, out var offset)) { return new FieldOffsetAttribute(offset); } return null; } internal static StructLayoutAttribute GetStructLayoutCustomAttribute(RuntimeType type) { if (type.IsInterface || type.HasElementType || type.IsGenericParameter) { return null; } LayoutKind layoutKind = LayoutKind.Auto; switch (type.Attributes & TypeAttributes.LayoutMask) { case TypeAttributes.ExplicitLayout: layoutKind = LayoutKind.Explicit; break; case TypeAttributes.NotPublic: layoutKind = LayoutKind.Auto; break; case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break; } CharSet charSet = CharSet.None; switch (type.Attributes & TypeAttributes.StringFormatMask) { case TypeAttributes.NotPublic: charSet = CharSet.Ansi; break; case TypeAttributes.AutoClass: charSet = CharSet.Auto; break; case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break; } type.GetRuntimeModule().MetadataImport.GetClassLayout(type.MetadataToken, out var packSize, out var classSize); if (packSize == 0) { packSize = 8; } StructLayoutAttribute structLayoutAttribute = new StructLayoutAttribute(layoutKind); structLayoutAttribute.Pack = packSize; structLayoutAttribute.Size = classSize; structLayoutAttribute.CharSet = charSet; return structLayoutAttribute; } } internal sealed class RuntimeEventInfo : EventInfo { private int m_token; private EventAttributes m_flags; private string m_name; private unsafe void* m_utf8name; private RuntimeType.RuntimeTypeCache m_reflectedTypeCache; private RuntimeMethodInfo m_addMethod; private RuntimeMethodInfo m_removeMethod; private RuntimeMethodInfo m_raiseMethod; private MethodInfo[] m_otherMethod; private RuntimeType m_declaringType; private BindingFlags m_bindingFlags; internal BindingFlags BindingFlags => m_bindingFlags; public override MemberTypes MemberType => MemberTypes.Event; public unsafe override string Name => m_name ?? (m_name = new MdUtf8String(m_utf8name).ToString()); public override Type DeclaringType => m_declaringType; public override Type ReflectedType => ReflectedTypeInternal; private RuntimeType ReflectedTypeInternal => m_reflectedTypeCache.GetRuntimeType(); public override int MetadataToken => m_token; public override Module Module => GetRuntimeModule(); public override EventAttributes Attributes => m_flags; internal unsafe RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeType.RuntimeTypeCache reflectedTypeCache, out bool isPrivate) { MetadataImport metadataImport = declaredType.GetRuntimeModule().MetadataImport; m_token = tkEvent; m_reflectedTypeCache = reflectedTypeCache; m_declaringType = declaredType; RuntimeType runtimeType = reflectedTypeCache.GetRuntimeType(); metadataImport.GetEventProps(tkEvent, out m_utf8name, out m_flags); Associates.AssignAssociates(metadataImport, tkEvent, declaredType, runtimeType, out m_addMethod, out m_removeMethod, out m_raiseMethod, out var _, out var _, out m_otherMethod, out isPrivate, out m_bindingFlags); } internal override bool CacheEquals(object o) { if (o is RuntimeEventInfo runtimeEventInfo && runtimeEventInfo.m_token == m_token) { return RuntimeTypeHandle.GetModule(m_declaringType).Equals(RuntimeTypeHandle.GetModule(runtimeEventInfo.m_declaringType)); } return false; } public override string ToString() { if (m_addMethod == null || m_addMethod.GetParametersNoCopy().Length == 0) { throw new InvalidOperationException(SR.InvalidOperation_NoPublicAddMethod); } return m_addMethod.GetParametersNoCopy()[0].ParameterType.FormatTypeName() + " " + Name; } public override object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.GetCustomAttributes(this, runtimeType); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.IsDefined(this, runtimeType); } public override IList GetCustomAttributesData() { return RuntimeCustomAttributeData.GetCustomAttributesInternal(this); } public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) { return HasSameMetadataDefinitionAsCore(other); } internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } public override MethodInfo[] GetOtherMethods(bool nonPublic) { List list = new List(); if (m_otherMethod == null) { return Array.Empty(); } for (int i = 0; i < m_otherMethod.Length; i++) { if (Associates.IncludeAccessor(m_otherMethod[i], nonPublic)) { list.Add(m_otherMethod[i]); } } return list.ToArray(); } public override MethodInfo GetAddMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_addMethod, nonPublic)) { return null; } return m_addMethod; } public override MethodInfo GetRemoveMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_removeMethod, nonPublic)) { return null; } return m_removeMethod; } public override MethodInfo GetRaiseMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_raiseMethod, nonPublic)) { return null; } return m_raiseMethod; } } internal sealed class RuntimeExceptionHandlingClause : ExceptionHandlingClause { private RuntimeMethodBody _methodBody; private ExceptionHandlingClauseOptions _flags; private int _tryOffset; private int _tryLength; private int _handlerOffset; private int _handlerLength; private int _catchMetadataToken; private int _filterOffset; public override ExceptionHandlingClauseOptions Flags => _flags; public override int TryOffset => _tryOffset; public override int TryLength => _tryLength; public override int HandlerOffset => _handlerOffset; public override int HandlerLength => _handlerLength; public override int FilterOffset { get { if (_flags != ExceptionHandlingClauseOptions.Filter) { throw new InvalidOperationException(SR.Arg_EHClauseNotFilter); } return _filterOffset; } } public override Type CatchType { [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Module.ResolveType is marked as RequiresUnreferencedCode because it relies on tokenswhich are not guaranteed to be stable across trimming. So if somebody hardcodes a token it could break.The usage here is not like that as all these tokens come from existing metadata loaded from some ILand so trimming has no effect (the tokens are read AFTER trimming occured).")] get { if (_flags != 0) { throw new InvalidOperationException(SR.Arg_EHClauseNotClause); } Type result = null; if (!MetadataToken.IsNullToken(_catchMetadataToken)) { Type declaringType = _methodBody._methodBase.DeclaringType; Module module = ((declaringType == null) ? _methodBody._methodBase.Module : declaringType.Module); result = module.ResolveType(_catchMetadataToken, declaringType?.GetGenericArguments(), (_methodBody._methodBase is MethodInfo) ? _methodBody._methodBase.GetGenericArguments() : null); } return result; } } private RuntimeExceptionHandlingClause() { } public override string ToString() { if (Flags == ExceptionHandlingClauseOptions.Clause) { return string.Format(CultureInfo.CurrentUICulture, "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}, CatchType={5}", Flags, TryOffset, TryLength, HandlerOffset, HandlerLength, CatchType); } if (Flags == ExceptionHandlingClauseOptions.Filter) { return string.Format(CultureInfo.CurrentUICulture, "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}, FilterOffset={5}", Flags, TryOffset, TryLength, HandlerOffset, HandlerLength, FilterOffset); } return string.Format(CultureInfo.CurrentUICulture, "Flags={0}, TryOffset={1}, TryLength={2}, HandlerOffset={3}, HandlerLength={4}", Flags, TryOffset, TryLength, HandlerOffset, HandlerLength); } } internal abstract class RuntimeFieldInfo : FieldInfo { private BindingFlags m_bindingFlags; protected RuntimeType.RuntimeTypeCache m_reflectedTypeCache; protected RuntimeType m_declaringType; internal BindingFlags BindingFlags => m_bindingFlags; private RuntimeType ReflectedTypeInternal => m_reflectedTypeCache.GetRuntimeType(); public override MemberTypes MemberType => MemberTypes.Field; public override Type ReflectedType { get { if (!m_reflectedTypeCache.IsGlobal) { return ReflectedTypeInternal; } return null; } } public override Type DeclaringType { get { if (!m_reflectedTypeCache.IsGlobal) { return m_declaringType; } return null; } } public override Module Module => GetRuntimeModule(); public override bool IsCollectible => m_declaringType.IsCollectible; protected RuntimeFieldInfo(RuntimeType.RuntimeTypeCache reflectedTypeCache, RuntimeType declaringType, BindingFlags bindingFlags) { m_bindingFlags = bindingFlags; m_declaringType = declaringType; m_reflectedTypeCache = reflectedTypeCache; } internal RuntimeType GetDeclaringTypeInternal() { return m_declaringType; } internal RuntimeType GetRuntimeType() { return m_declaringType; } internal abstract RuntimeModule GetRuntimeModule(); public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) { return HasSameMetadataDefinitionAsCore(other); } public override string ToString() { return FieldType.FormatTypeName() + " " + Name; } public override object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.GetCustomAttributes(this, runtimeType); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.IsDefined(this, runtimeType); } public override IList GetCustomAttributesData() { return RuntimeCustomAttributeData.GetCustomAttributesInternal(this); } } internal sealed class RuntimeLocalVariableInfo : LocalVariableInfo { private RuntimeType _type; private int _localIndex; private bool _isPinned; public override Type LocalType => _type; public override int LocalIndex => _localIndex; public override bool IsPinned => _isPinned; private RuntimeLocalVariableInfo() { } } internal sealed class RuntimeMethodBody : MethodBody { private byte[] _IL; private ExceptionHandlingClause[] _exceptionHandlingClauses; private LocalVariableInfo[] _localVariables; internal MethodBase _methodBase; private int _localSignatureMetadataToken; private int _maxStackSize; private bool _initLocals; public override int LocalSignatureMetadataToken => _localSignatureMetadataToken; public override IList LocalVariables => Array.AsReadOnly(_localVariables); public override int MaxStackSize => _maxStackSize; public override bool InitLocals => _initLocals; public override IList ExceptionHandlingClauses => Array.AsReadOnly(_exceptionHandlingClauses); private RuntimeMethodBody() { _IL = null; _exceptionHandlingClauses = null; _localVariables = null; _methodBase = null; } public override byte[] GetILAsByteArray() { return _IL; } } internal sealed class RuntimeMethodInfo : MethodInfo, IRuntimeMethodInfo { private IntPtr m_handle; private RuntimeType.RuntimeTypeCache m_reflectedTypeCache; private string m_name; private string m_toString; private ParameterInfo[] m_parameters; private ParameterInfo m_returnParameter; private BindingFlags m_bindingFlags; private MethodAttributes m_methodAttributes; private Signature m_signature; private RuntimeType m_declaringType; private object m_keepalive; private INVOCATION_FLAGS m_invocationFlags; internal INVOCATION_FLAGS InvocationFlags { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { INVOCATION_FLAGS iNVOCATION_FLAGS = m_invocationFlags; if ((iNVOCATION_FLAGS & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) { iNVOCATION_FLAGS = LazyCreateInvocationFlags(); } return iNVOCATION_FLAGS; [MethodImpl(MethodImplOptions.NoInlining)] INVOCATION_FLAGS LazyCreateInvocationFlags() { INVOCATION_FLAGS iNVOCATION_FLAGS2 = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN; Type declaringType = DeclaringType; if (ContainsGenericParameters || IsDisallowedByRefType(ReturnType) || (declaringType != null && declaringType.ContainsGenericParameters) || (CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { iNVOCATION_FLAGS2 = INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; } else if ((declaringType != null && declaringType.IsByRefLike) || ReturnType.IsByRefLike) { iNVOCATION_FLAGS2 |= INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS; } return m_invocationFlags = iNVOCATION_FLAGS2 | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; } } } RuntimeMethodHandleInternal IRuntimeMethodInfo.Value => new RuntimeMethodHandleInternal(m_handle); private RuntimeType ReflectedTypeInternal => m_reflectedTypeCache.GetRuntimeType(); internal Signature Signature { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return m_signature ?? LazyCreateSignature(); [MethodImpl(MethodImplOptions.NoInlining)] Signature LazyCreateSignature() { Signature signature = new Signature(this, m_declaringType); Volatile.Write(ref m_signature, signature); return signature; } } } internal BindingFlags BindingFlags => m_bindingFlags; internal sealed override int GenericParameterCount => RuntimeMethodHandle.GetGenericParameterCount(this); public override string Name => m_name ?? (m_name = RuntimeMethodHandle.GetName(this)); public override Type DeclaringType { get { if (m_reflectedTypeCache.IsGlobal) { return null; } return m_declaringType; } } public override Type ReflectedType { get { if (m_reflectedTypeCache.IsGlobal) { return null; } return m_reflectedTypeCache.GetRuntimeType(); } } public override MemberTypes MemberType => MemberTypes.Method; public override int MetadataToken => RuntimeMethodHandle.GetMethodDef(this); public override Module Module => GetRuntimeModule(); public override bool IsSecurityCritical => true; public override bool IsSecuritySafeCritical => false; public override bool IsSecurityTransparent => false; public override RuntimeMethodHandle MethodHandle => new RuntimeMethodHandle(this); public override MethodAttributes Attributes => m_methodAttributes; public override CallingConventions CallingConvention => Signature.CallingConvention; public override Type ReturnType => Signature.ReturnType; public override ICustomAttributeProvider ReturnTypeCustomAttributes => ReturnParameter; public override ParameterInfo ReturnParameter => FetchReturnParameter(); public override bool IsCollectible => RuntimeMethodHandle.GetIsCollectible(new RuntimeMethodHandleInternal(m_handle)) != Interop.BOOL.FALSE; public override bool IsGenericMethod => RuntimeMethodHandle.HasMethodInstantiation(this); public override bool IsGenericMethodDefinition => RuntimeMethodHandle.IsGenericMethodDefinition(this); public override bool ContainsGenericParameters { get { if (DeclaringType != null && DeclaringType.ContainsGenericParameters) { return true; } if (!IsGenericMethod) { return false; } Type[] genericArguments = GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { if (genericArguments[i].ContainsGenericParameters) { return true; } } return false; } } private static bool IsDisallowedByRefType(Type type) { if (!type.IsByRef) { return false; } Type elementType = type.GetElementType(); if (!elementType.IsByRefLike) { return elementType == typeof(void); } return true; } internal RuntimeMethodInfo(RuntimeMethodHandleInternal handle, RuntimeType declaringType, RuntimeType.RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object keepalive) { m_bindingFlags = bindingFlags; m_declaringType = declaringType; m_keepalive = keepalive; m_handle = handle.Value; m_reflectedTypeCache = reflectedTypeCache; m_methodAttributes = methodAttributes; } private ParameterInfo[] FetchNonReturnParameters() { return m_parameters ?? (m_parameters = RuntimeParameterInfo.GetParameters(this, this, Signature)); } private ParameterInfo FetchReturnParameter() { return m_returnParameter ?? (m_returnParameter = RuntimeParameterInfo.GetReturnParameter(this, this, Signature)); } internal override bool CacheEquals(object o) { if (o is RuntimeMethodInfo runtimeMethodInfo) { return runtimeMethodInfo.m_handle == m_handle; } return false; } internal RuntimeMethodInfo GetParentDefinition() { if (!base.IsVirtual || m_declaringType.IsInterface) { return null; } RuntimeType runtimeType = (RuntimeType)m_declaringType.BaseType; if (runtimeType == null) { return null; } int slot = RuntimeMethodHandle.GetSlot(this); if (RuntimeTypeHandle.GetNumVirtuals(runtimeType) <= slot) { return null; } return (RuntimeMethodInfo)RuntimeType.GetMethodBase(runtimeType, RuntimeTypeHandle.GetMethodAt(runtimeType, slot)); } internal RuntimeType GetDeclaringTypeInternal() { return m_declaringType; } public override string ToString() { if (m_toString == null) { ValueStringBuilder sbParamList = new ValueStringBuilder(100); sbParamList.Append(ReturnType.FormatTypeName()); sbParamList.Append(' '); sbParamList.Append(Name); if (IsGenericMethod) { sbParamList.Append(RuntimeMethodHandle.ConstructInstantiation(this, TypeNameFormatFlags.FormatBasic)); } sbParamList.Append('('); MethodBase.AppendParameters(ref sbParamList, GetParameterTypes(), CallingConvention); sbParamList.Append(')'); m_toString = sbParamList.ToString(); } return m_toString; } public override int GetHashCode() { if (IsGenericMethod) { return ValueType.GetHashCodeOfPtr(m_handle); } return base.GetHashCode(); } public override bool Equals(object obj) { if (!IsGenericMethod) { return obj == this; } RuntimeMethodInfo runtimeMethodInfo = obj as RuntimeMethodInfo; if (runtimeMethodInfo == null || !runtimeMethodInfo.IsGenericMethod) { return false; } IRuntimeMethodInfo runtimeMethodInfo2 = RuntimeMethodHandle.StripMethodInstantiation(this); IRuntimeMethodInfo runtimeMethodInfo3 = RuntimeMethodHandle.StripMethodInstantiation(runtimeMethodInfo); if (runtimeMethodInfo2.Value.Value != runtimeMethodInfo3.Value.Value) { return false; } Type[] genericArguments = GetGenericArguments(); Type[] genericArguments2 = runtimeMethodInfo.GetGenericArguments(); if (genericArguments.Length != genericArguments2.Length) { return false; } for (int i = 0; i < genericArguments.Length; i++) { if (genericArguments[i] != genericArguments2[i]) { return false; } } if (DeclaringType != runtimeMethodInfo.DeclaringType) { return false; } if (ReflectedType != runtimeMethodInfo.ReflectedType) { return false; } return true; } public override object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType, inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.GetCustomAttributes(this, runtimeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.IsDefined(this, runtimeType, inherit); } public override IList GetCustomAttributesData() { return RuntimeCustomAttributeData.GetCustomAttributesInternal(this); } public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) { return HasSameMetadataDefinitionAsCore(other); } internal RuntimeType GetRuntimeType() { return m_declaringType; } internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } internal override ParameterInfo[] GetParametersNoCopy() { return FetchNonReturnParameters(); } public override ParameterInfo[] GetParameters() { ParameterInfo[] array = FetchNonReturnParameters(); if (array.Length == 0) { return array; } ParameterInfo[] array2 = new ParameterInfo[array.Length]; Array.Copy(array, array2, array.Length); return array2; } public override MethodImplAttributes GetMethodImplementationFlags() { return RuntimeMethodHandle.GetImplAttributes(this); } [RequiresUnreferencedCode("Trimming may change method bodies. For example it can change some instructions, remove branches or local variables.")] public override MethodBody GetMethodBody() { RuntimeMethodBody methodBody = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal); if (methodBody != null) { methodBody._methodBase = this; } return methodBody; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void CheckConsistency(object target) { if ((m_methodAttributes & MethodAttributes.Static) == 0 && !m_declaringType.IsInstanceOfType(target)) { if (target == null) { throw new TargetException(SR.RFLCT_Targ_StatMethReqTarg); } throw new TargetException(SR.RFLCT_Targ_ITargMismatch); } } [DoesNotReturn] private void ThrowNoInvokeException() { if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0) { throw new NotSupportedException(); } if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { throw new NotSupportedException(); } if (DeclaringType.ContainsGenericParameters || ContainsGenericParameters) { throw new InvalidOperationException(SR.Arg_UnboundGenParam); } if (base.IsAbstract) { throw new MemberAccessException(); } if (ReturnType.IsByRef) { Type elementType = ReturnType.GetElementType(); if (elementType.IsByRefLike) { throw new NotSupportedException(SR.NotSupported_ByRefToByRefLikeReturn); } if (elementType == typeof(void)) { throw new NotSupportedException(SR.NotSupported_ByRefToVoidReturn); } } throw new TargetException(); } [DebuggerStepThrough] [DebuggerHidden] public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { if ((InvocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0) { ThrowNoInvokeException(); } CheckConsistency(obj); Signature signature = Signature; int num = ((parameters != null) ? parameters.Length : 0); if (signature.Arguments.Length != num) { throw new TargetParameterCountException(SR.Arg_ParmCnt); } StackAllocedArguments stackArgs = default(StackAllocedArguments); Span arguments = default(Span); if (num != 0) { arguments = CheckArguments(ref stackArgs, parameters, binder, invokeAttr, culture, signature); } bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0; object result = RuntimeMethodHandle.InvokeMethod(obj, in arguments, Signature, constructor: false, wrapExceptions); for (int i = 0; i < arguments.Length; i++) { parameters[i] = arguments[i]; } return result; } [DebuggerStepThrough] [DebuggerHidden] internal object InvokeOneParameter(object obj, BindingFlags invokeAttr, Binder binder, object parameter, CultureInfo culture) { if ((InvocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0) { ThrowNoInvokeException(); } CheckConsistency(obj); Signature signature = Signature; if (signature.Arguments.Length != 1) { throw new TargetParameterCountException(SR.Arg_ParmCnt); } StackAllocedArguments stackArgs = default(StackAllocedArguments); Span arguments = CheckArguments(ref stackArgs, new ReadOnlySpan(ref parameter, 1), binder, invokeAttr, culture, signature); bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0; return RuntimeMethodHandle.InvokeMethod(obj, in arguments, Signature, constructor: false, wrapExceptions); } public override MethodInfo GetBaseDefinition() { if (!base.IsVirtual || base.IsStatic || m_declaringType == null || m_declaringType.IsInterface) { return this; } int slot = RuntimeMethodHandle.GetSlot(this); RuntimeType runtimeType = (RuntimeType)DeclaringType; RuntimeType reflectedType = runtimeType; RuntimeMethodHandleInternal methodHandle = default(RuntimeMethodHandleInternal); do { int numVirtuals = RuntimeTypeHandle.GetNumVirtuals(runtimeType); if (numVirtuals <= slot) { break; } methodHandle = RuntimeTypeHandle.GetMethodAt(runtimeType, slot); reflectedType = runtimeType; runtimeType = (RuntimeType)runtimeType.BaseType; } while (runtimeType != null); return (MethodInfo)RuntimeType.GetMethodBase(reflectedType, methodHandle); } public override Delegate CreateDelegate(Type delegateType) { return CreateDelegateInternal(delegateType, null, (DelegateBindingFlags)68); } public override Delegate CreateDelegate(Type delegateType, object target) { return CreateDelegateInternal(delegateType, target, DelegateBindingFlags.RelaxedSignature); } private Delegate CreateDelegateInternal(Type delegateType, object firstArgument, DelegateBindingFlags bindingFlags) { if (delegateType == null) { throw new ArgumentNullException("delegateType"); } RuntimeType runtimeType = delegateType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Argument_MustBeRuntimeType, "delegateType"); } if (!runtimeType.IsDelegate()) { throw new ArgumentException(SR.Arg_MustBeDelegate, "delegateType"); } Delegate @delegate = Delegate.CreateDelegateInternal(runtimeType, this, firstArgument, bindingFlags); if ((object)@delegate == null) { throw new ArgumentException(SR.Arg_DlgtTargMeth); } return @delegate; } [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation) { if (methodInstantiation == null) { throw new ArgumentNullException("methodInstantiation"); } RuntimeType[] array = new RuntimeType[methodInstantiation.Length]; if (!IsGenericMethodDefinition) { throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericMethodDefinition, this)); } for (int i = 0; i < methodInstantiation.Length; i++) { Type type = methodInstantiation[i]; if (type == null) { throw new ArgumentNullException(); } RuntimeType runtimeType = type as RuntimeType; if (runtimeType == null) { Type[] array2 = new Type[methodInstantiation.Length]; for (int j = 0; j < methodInstantiation.Length; j++) { array2[j] = methodInstantiation[j]; } methodInstantiation = array2; return MethodBuilderInstantiation.MakeGenericMethod(this, methodInstantiation); } array[i] = runtimeType; } RuntimeType[] genericArgumentsInternal = GetGenericArgumentsInternal(); RuntimeType.SanityCheckGenericArguments(array, genericArgumentsInternal); MethodInfo methodInfo = null; try { return RuntimeType.GetMethodBase(ReflectedTypeInternal, RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(m_handle), m_declaringType, array)) as MethodInfo; } catch (VerificationException e) { RuntimeType.ValidateGenericArguments(this, array, e); throw; } } internal RuntimeType[] GetGenericArgumentsInternal() { return RuntimeMethodHandle.GetMethodInstantiationInternal(this); } public override Type[] GetGenericArguments() { return RuntimeMethodHandle.GetMethodInstantiationPublic(this) ?? Type.EmptyTypes; } public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) { throw new InvalidOperationException(); } return RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo; } internal static MethodBase InternalGetCurrentMethod(ref StackCrawlMark stackMark) { IRuntimeMethodInfo currentMethod = RuntimeMethodHandle.GetCurrentMethod(ref stackMark); if (currentMethod == null) { return null; } return RuntimeType.GetMethodBase(currentMethod); } } internal class RuntimeModule : Module { private RuntimeType m_runtimeType; private RuntimeAssembly m_runtimeAssembly; private IntPtr m_pRefClass; private IntPtr m_pData; private IntPtr m_pGlobals; private IntPtr m_pFields; public override int MDStreamVersion => ModuleHandle.GetMDStreamVersion(this); internal RuntimeType RuntimeType => m_runtimeType ?? (m_runtimeType = ModuleHandle.GetModuleType(this)); internal MetadataImport MetadataImport => ModuleHandle.GetMetadataImport(this); [RequiresAssemblyFiles("Returns for modules with no file path")] public override string FullyQualifiedName => GetFullyQualifiedName(); public override Guid ModuleVersionId { get { MetadataImport.GetScopeProps(out var mvid); return mvid; } } public override int MetadataToken => ModuleHandle.GetToken(this); public override string ScopeName { get { string s = null; RuntimeModule module = this; GetScopeName(new QCallModule(ref module), new StringHandleOnStack(ref s)); return s; } } [RequiresAssemblyFiles("Returns for modules with no file path")] public override string Name { get { string fullyQualifiedName = GetFullyQualifiedName(); int num = fullyQualifiedName.LastIndexOf(Path.DirectorySeparatorChar); if (num == -1) { return fullyQualifiedName; } return fullyQualifiedName.Substring(num + 1); } } public override Assembly Assembly => GetRuntimeAssembly(); internal RuntimeModule() { throw new NotSupportedException(); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetType(QCallModule module, string className, bool throwOnError, bool ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetScopeName(QCallModule module, StringHandleOnStack retString); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void GetFullyQualifiedName(QCallModule module, StringHandleOnStack retString); [MethodImpl(MethodImplOptions.InternalCall)] private static extern RuntimeType[] GetTypes(RuntimeModule module); internal RuntimeType[] GetDefinedTypes() { return GetTypes(this); } [MethodImpl(MethodImplOptions.InternalCall)] private static extern bool IsResource(RuntimeModule module); private static RuntimeTypeHandle[] ConvertToTypeHandleArray(Type[] genericArguments) { if (genericArguments == null) { return null; } int num = genericArguments.Length; RuntimeTypeHandle[] array = new RuntimeTypeHandle[num]; for (int i = 0; i < num; i++) { Type type = genericArguments[i]; if (type == null) { throw new ArgumentException(SR.Argument_InvalidGenericInstArray); } type = type.UnderlyingSystemType; if (type == null) { throw new ArgumentException(SR.Argument_InvalidGenericInstArray); } if (!(type is RuntimeType)) { throw new ArgumentException(SR.Argument_InvalidGenericInstArray); } array[i] = type.GetTypeHandleInternal(); } return array; } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override byte[] ResolveSignature(int metadataToken) { MetadataToken metadataToken2 = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(metadataToken2)) { throw new ArgumentOutOfRangeException("metadataToken", SR.Format(SR.Argument_InvalidToken, metadataToken2, this)); } if (!metadataToken2.IsMemberRef && !metadataToken2.IsMethodDef && !metadataToken2.IsTypeSpec && !metadataToken2.IsSignature && !metadataToken2.IsFieldDef) { throw new ArgumentException(SR.Format(SR.Argument_InvalidToken, metadataToken2, this), "metadataToken"); } ConstArray constArray = ((!metadataToken2.IsMemberRef) ? MetadataImport.GetSignatureFromToken(metadataToken) : MetadataImport.GetMemberRefProps(metadataToken)); byte[] array = new byte[constArray.Length]; for (int i = 0; i < constArray.Length; i++) { array[i] = constArray[i]; } return array; } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public unsafe override MethodBase ResolveMethod(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { try { MetadataToken metadataToken2 = new MetadataToken(metadataToken); if (!metadataToken2.IsMethodDef && !metadataToken2.IsMethodSpec) { if (!metadataToken2.IsMemberRef) { throw new ArgumentException(SR.Format(SR.Argument_ResolveMethod, metadataToken2, this), "metadataToken"); } if (*(byte*)(void*)MetadataImport.GetMemberRefProps(metadataToken2).Signature == 6) { throw new ArgumentException(SR.Format(SR.Argument_ResolveMethod, metadataToken2, this), "metadataToken"); } } RuntimeTypeHandle[] typeInstantiationContext = null; RuntimeTypeHandle[] methodInstantiationContext = null; if (genericTypeArguments != null && genericTypeArguments.Length != 0) { typeInstantiationContext = ConvertToTypeHandleArray(genericTypeArguments); } if (genericMethodArguments != null && genericMethodArguments.Length != 0) { methodInstantiationContext = ConvertToTypeHandleArray(genericMethodArguments); } IRuntimeMethodInfo methodInfo = new ModuleHandle(this).ResolveMethodHandle(metadataToken2, typeInstantiationContext, methodInstantiationContext).GetMethodInfo(); Type type = RuntimeMethodHandle.GetDeclaringType(methodInfo); if (type.IsGenericType || type.IsArray) { MetadataToken metadataToken3 = new MetadataToken(MetadataImport.GetParentToken(metadataToken2)); if (metadataToken2.IsMethodSpec) { metadataToken3 = new MetadataToken(MetadataImport.GetParentToken(metadataToken3)); } type = ResolveType(metadataToken3, genericTypeArguments, genericMethodArguments); } return RuntimeType.GetMethodBase(type as RuntimeType, methodInfo); } catch (BadImageFormatException innerException) { throw new ArgumentException(SR.Argument_BadImageFormatExceptionResolve, innerException); } } [RequiresUnreferencedCode("Trimming changes metadata tokens")] private FieldInfo ResolveLiteralField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken metadataToken2 = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(metadataToken2) || !metadataToken2.IsFieldDef) { throw new ArgumentOutOfRangeException("metadataToken", SR.Format(SR.Argument_InvalidToken, metadataToken2, this)); } string name = MetadataImport.GetName(metadataToken2).ToString(); int parentToken = MetadataImport.GetParentToken(metadataToken2); Type type = ResolveType(parentToken, genericTypeArguments, genericMethodArguments); type.GetFields(); try { return type.GetField(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } catch { throw new ArgumentException(SR.Format(SR.Argument_ResolveField, metadataToken2, this), "metadataToken"); } } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public unsafe override FieldInfo ResolveField(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { try { MetadataToken metadataToken2 = new MetadataToken(metadataToken); if (!MetadataImport.IsValidToken(metadataToken2)) { throw new ArgumentOutOfRangeException("metadataToken", SR.Format(SR.Argument_InvalidToken, metadataToken2, this)); } RuntimeTypeHandle[] typeInstantiationContext = null; RuntimeTypeHandle[] methodInstantiationContext = null; if (genericTypeArguments != null && genericTypeArguments.Length != 0) { typeInstantiationContext = ConvertToTypeHandleArray(genericTypeArguments); } if (genericMethodArguments != null && genericMethodArguments.Length != 0) { methodInstantiationContext = ConvertToTypeHandleArray(genericMethodArguments); } ModuleHandle moduleHandle = new ModuleHandle(this); if (!metadataToken2.IsFieldDef) { if (!metadataToken2.IsMemberRef) { throw new ArgumentException(SR.Format(SR.Argument_ResolveField, metadataToken2, this), "metadataToken"); } if (*(byte*)(void*)MetadataImport.GetMemberRefProps(metadataToken2).Signature != 6) { throw new ArgumentException(SR.Format(SR.Argument_ResolveField, metadataToken2, this), "metadataToken"); } } IRuntimeFieldInfo runtimeFieldInfo = moduleHandle.ResolveFieldHandle(metadataToken, typeInstantiationContext, methodInstantiationContext).GetRuntimeFieldInfo(); RuntimeType runtimeType = RuntimeFieldHandle.GetApproxDeclaringType(runtimeFieldInfo.Value); if (runtimeType.IsGenericType || runtimeType.IsArray) { int parentToken = ModuleHandle.GetMetadataImport(this).GetParentToken(metadataToken); runtimeType = (RuntimeType)ResolveType(parentToken, genericTypeArguments, genericMethodArguments); } return RuntimeType.GetFieldInfo(runtimeType, runtimeFieldInfo); } catch (MissingFieldException) { return ResolveLiteralField(metadataToken, genericTypeArguments, genericMethodArguments); } catch (BadImageFormatException innerException) { throw new ArgumentException(SR.Argument_BadImageFormatExceptionResolve, innerException); } } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override Type ResolveType(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { try { MetadataToken metadataToken2 = new MetadataToken(metadataToken); if (metadataToken2.IsGlobalTypeDefToken) { throw new ArgumentException(SR.Format(SR.Argument_ResolveModuleType, metadataToken2), "metadataToken"); } if (!metadataToken2.IsTypeDef && !metadataToken2.IsTypeSpec && !metadataToken2.IsTypeRef) { throw new ArgumentException(SR.Format(SR.Argument_ResolveType, metadataToken2, this), "metadataToken"); } RuntimeTypeHandle[] typeInstantiationContext = null; RuntimeTypeHandle[] methodInstantiationContext = null; if (genericTypeArguments != null && genericTypeArguments.Length != 0) { typeInstantiationContext = ConvertToTypeHandleArray(genericTypeArguments); } if (genericMethodArguments != null && genericMethodArguments.Length != 0) { methodInstantiationContext = ConvertToTypeHandleArray(genericMethodArguments); } return GetModuleHandleImpl().ResolveTypeHandle(metadataToken, typeInstantiationContext, methodInstantiationContext).GetRuntimeType(); } catch (BadImageFormatException innerException) { throw new ArgumentException(SR.Argument_BadImageFormatExceptionResolve, innerException); } } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public unsafe override MemberInfo ResolveMember(int metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments) { MetadataToken metadataToken2 = new MetadataToken(metadataToken); if (metadataToken2.IsProperty) { throw new ArgumentException(SR.InvalidOperation_PropertyInfoNotAvailable); } if (metadataToken2.IsEvent) { throw new ArgumentException(SR.InvalidOperation_EventInfoNotAvailable); } if (metadataToken2.IsMethodSpec || metadataToken2.IsMethodDef) { return ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments); } if (metadataToken2.IsFieldDef) { return ResolveField(metadataToken, genericTypeArguments, genericMethodArguments); } if (metadataToken2.IsTypeRef || metadataToken2.IsTypeDef || metadataToken2.IsTypeSpec) { return ResolveType(metadataToken, genericTypeArguments, genericMethodArguments); } if (metadataToken2.IsMemberRef) { if (!MetadataImport.IsValidToken(metadataToken2)) { throw new ArgumentOutOfRangeException("metadataToken", SR.Format(SR.Argument_InvalidToken, metadataToken2, this)); } if (*(byte*)(void*)MetadataImport.GetMemberRefProps(metadataToken2).Signature == 6) { return ResolveField(metadataToken2, genericTypeArguments, genericMethodArguments); } return ResolveMethod(metadataToken2, genericTypeArguments, genericMethodArguments); } throw new ArgumentException(SR.Format(SR.Argument_ResolveMember, metadataToken2, this), "metadataToken"); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override string ResolveString(int metadataToken) { MetadataToken metadataToken2 = new MetadataToken(metadataToken); if (!metadataToken2.IsString) { throw new ArgumentException(SR.Format(SR.Argument_ResolveString, metadataToken, this)); } if (!MetadataImport.IsValidToken(metadataToken2)) { throw new ArgumentOutOfRangeException("metadataToken", SR.Format(SR.Argument_InvalidToken, metadataToken2, this)); } string userString = MetadataImport.GetUserString(metadataToken); if (userString == null) { throw new ArgumentException(SR.Format(SR.Argument_ResolveString, metadataToken, this)); } return userString; } public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) { ModuleHandle.GetPEKind(this, out peKind, out machine); } [RequiresUnreferencedCode("Methods might be removed because Module methods can't currently be annotated for dynamic access.")] protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { return GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers); } [RequiresUnreferencedCode("Methods might be removed because Module methods can't currently be annotated for dynamic access.")] internal MethodInfo GetMethodInternal(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { if (RuntimeType == null) { return null; } if (types == null) { return RuntimeType.GetMethod(name, bindingAttr); } return RuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); } public override object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.GetCustomAttributes(this, runtimeType); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.IsDefined(this, runtimeType); } public override IList GetCustomAttributesData() { return RuntimeCustomAttributeData.GetCustomAttributesInternal(this); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } [RequiresUnreferencedCode("Types might be removed")] public override Type GetType(string className, bool throwOnError, bool ignoreCase) { if (className == null) { throw new ArgumentNullException("className"); } RuntimeType o = null; object o2 = null; RuntimeModule module = this; GetType(new QCallModule(ref module), className, throwOnError, ignoreCase, ObjectHandleOnStack.Create(ref o), ObjectHandleOnStack.Create(ref o2)); GC.KeepAlive(o2); return o; } [RequiresAssemblyFiles("Returns for modules with no file path")] internal string GetFullyQualifiedName() { string s = null; RuntimeModule module = this; GetFullyQualifiedName(new QCallModule(ref module), new StringHandleOnStack(ref s)); return s; } [RequiresUnreferencedCode("Types might be removed")] public override Type[] GetTypes() { return GetTypes(this); } public override bool IsResource() { return IsResource(this); } [RequiresUnreferencedCode("Fields might be removed")] public override FieldInfo[] GetFields(BindingFlags bindingFlags) { if (RuntimeType == null) { return Array.Empty(); } return RuntimeType.GetFields(bindingFlags); } [RequiresUnreferencedCode("Fields might be removed")] public override FieldInfo GetField(string name, BindingFlags bindingAttr) { if (name == null) { throw new ArgumentNullException("name"); } if (RuntimeType == null) { return null; } return RuntimeType.GetField(name, bindingAttr); } [RequiresUnreferencedCode("Methods might be removed")] public override MethodInfo[] GetMethods(BindingFlags bindingFlags) { if (RuntimeType == null) { return Array.Empty(); } return RuntimeType.GetMethods(bindingFlags); } internal RuntimeAssembly GetRuntimeAssembly() { return m_runtimeAssembly; } protected override ModuleHandle GetModuleHandleImpl() { return new ModuleHandle(this); } internal IntPtr GetUnderlyingNativeHandle() { return m_pData; } } internal sealed class RuntimeParameterInfo : ParameterInfo { private static readonly Type s_DecimalConstantAttributeType = typeof(DecimalConstantAttribute); private static readonly Type s_CustomConstantAttributeType = typeof(CustomConstantAttribute); private int m_tkParamDef; private MetadataImport m_scope; private Signature m_signature; private volatile bool m_nameIsCached; private readonly bool m_noMetadata; private bool m_noDefaultValue; private MethodBase m_originalMember; public override Type ParameterType { get { if (ClassImpl == null) { RuntimeType classImpl = ((PositionImpl != -1) ? m_signature.Arguments[PositionImpl] : m_signature.ReturnType); ClassImpl = classImpl; } return ClassImpl; } } public override string Name { get { if (!m_nameIsCached) { if (!System.Reflection.MetadataToken.IsNullToken(m_tkParamDef)) { string nameImpl = m_scope.GetName(m_tkParamDef).ToString(); NameImpl = nameImpl; } m_nameIsCached = true; } return NameImpl; } } public override bool HasDefaultValue { get { if (m_noMetadata || m_noDefaultValue) { return false; } object defaultValueInternal = GetDefaultValueInternal(raw: false); return defaultValueInternal != DBNull.Value; } } public override object DefaultValue => GetDefaultValue(raw: false); public override object RawDefaultValue => GetDefaultValue(raw: true); public override int MetadataToken => m_tkParamDef; internal static ParameterInfo[] GetParameters(IRuntimeMethodInfo method, MemberInfo member, Signature sig) { ParameterInfo returnParameter; return GetParameters(method, member, sig, out returnParameter, fetchReturnParameter: false); } internal static ParameterInfo GetReturnParameter(IRuntimeMethodInfo method, MemberInfo member, Signature sig) { GetParameters(method, member, sig, out var returnParameter, fetchReturnParameter: true); return returnParameter; } private static ParameterInfo[] GetParameters(IRuntimeMethodInfo methodHandle, MemberInfo member, Signature sig, out ParameterInfo returnParameter, bool fetchReturnParameter) { returnParameter = null; int num = sig.Arguments.Length; ParameterInfo[] array = (fetchReturnParameter ? null : ((num == 0) ? Array.Empty() : new ParameterInfo[num])); int methodDef = RuntimeMethodHandle.GetMethodDef(methodHandle); int num2 = 0; if (!System.Reflection.MetadataToken.IsNullToken(methodDef)) { MetadataImport metadataImport = RuntimeTypeHandle.GetMetadataImport(RuntimeMethodHandle.GetDeclaringType(methodHandle)); metadataImport.EnumParams(methodDef, out var result); num2 = result.Length; if (num2 > num + 1) { throw new BadImageFormatException(SR.BadImageFormat_ParameterSignatureMismatch); } for (int i = 0; i < num2; i++) { int num3 = result[i]; metadataImport.GetParamDefProps(num3, out var sequence, out var attributes); sequence--; if (fetchReturnParameter && sequence == -1) { if (returnParameter != null) { throw new BadImageFormatException(SR.BadImageFormat_ParameterSignatureMismatch); } returnParameter = new RuntimeParameterInfo(sig, metadataImport, num3, sequence, attributes, member); } else if (!fetchReturnParameter && sequence >= 0) { if (sequence >= num) { throw new BadImageFormatException(SR.BadImageFormat_ParameterSignatureMismatch); } array[sequence] = new RuntimeParameterInfo(sig, metadataImport, num3, sequence, attributes, member); } } } if (fetchReturnParameter) { if (returnParameter == null) { returnParameter = new RuntimeParameterInfo(sig, MetadataImport.EmptyImport, 0, -1, ParameterAttributes.None, member); } } else if (num2 < array.Length + 1) { for (int j = 0; j < array.Length; j++) { if (array[j] == null) { array[j] = new RuntimeParameterInfo(sig, MetadataImport.EmptyImport, 0, j, ParameterAttributes.None, member); } } } return array; } internal void SetName(string name) { NameImpl = name; } internal void SetAttributes(ParameterAttributes attributes) { AttrsImpl = attributes; } internal RuntimeParameterInfo(RuntimeParameterInfo accessor, RuntimePropertyInfo property) : this(accessor, (MemberInfo)property) { m_signature = property.Signature; } private RuntimeParameterInfo(RuntimeParameterInfo accessor, MemberInfo member) { MemberImpl = member; m_originalMember = accessor.MemberImpl as MethodBase; NameImpl = accessor.Name; m_nameIsCached = true; ClassImpl = accessor.ParameterType; PositionImpl = accessor.Position; AttrsImpl = accessor.Attributes; m_tkParamDef = (System.Reflection.MetadataToken.IsNullToken(accessor.MetadataToken) ? 134217728 : accessor.MetadataToken); m_scope = accessor.m_scope; } private RuntimeParameterInfo(Signature signature, MetadataImport scope, int tkParamDef, int position, ParameterAttributes attributes, MemberInfo member) { PositionImpl = position; MemberImpl = member; m_signature = signature; m_tkParamDef = (System.Reflection.MetadataToken.IsNullToken(tkParamDef) ? 134217728 : tkParamDef); m_scope = scope; AttrsImpl = attributes; ClassImpl = null; NameImpl = null; } internal RuntimeParameterInfo(MethodInfo owner, string name, Type parameterType, int position) { MemberImpl = owner; NameImpl = name; m_nameIsCached = true; m_noMetadata = true; ClassImpl = parameterType; PositionImpl = position; AttrsImpl = ParameterAttributes.None; m_tkParamDef = 134217728; m_scope = MetadataImport.EmptyImport; } private object GetDefaultValue(bool raw) { if (m_noMetadata) { return null; } object obj = GetDefaultValueInternal(raw); if (obj == DBNull.Value && base.IsOptional) { obj = Type.Missing; } return obj; } private object GetDefaultValueInternal(bool raw) { if (m_noDefaultValue) { return DBNull.Value; } object obj = null; if (ParameterType == typeof(DateTime)) { if (raw) { CustomAttributeTypedArgument customAttributeTypedArgument = RuntimeCustomAttributeData.Filter(CustomAttributeData.GetCustomAttributes(this), typeof(DateTimeConstantAttribute), 0); if (customAttributeTypedArgument.ArgumentType != null) { return new DateTime((long)customAttributeTypedArgument.Value); } } else { object[] customAttributes = GetCustomAttributes(typeof(DateTimeConstantAttribute), inherit: false); if (customAttributes != null && customAttributes.Length != 0) { return ((DateTimeConstantAttribute)customAttributes[0]).Value; } } } if (!System.Reflection.MetadataToken.IsNullToken(m_tkParamDef)) { obj = MdConstant.GetValue(m_scope, m_tkParamDef, ParameterType.GetTypeHandleInternal(), raw); } if (obj == DBNull.Value) { if (raw) { foreach (CustomAttributeData customAttribute in CustomAttributeData.GetCustomAttributes(this)) { Type declaringType = customAttribute.Constructor.DeclaringType; if (declaringType == typeof(DateTimeConstantAttribute)) { obj = GetRawDateTimeConstant(customAttribute); } else if (declaringType == typeof(DecimalConstantAttribute)) { obj = GetRawDecimalConstant(customAttribute); } else if (declaringType.IsSubclassOf(s_CustomConstantAttributeType)) { obj = GetRawConstant(customAttribute); } } } else { object[] customAttributes2 = GetCustomAttributes(s_CustomConstantAttributeType, inherit: false); if (customAttributes2.Length != 0) { obj = ((CustomConstantAttribute)customAttributes2[0]).Value; } else { customAttributes2 = GetCustomAttributes(s_DecimalConstantAttributeType, inherit: false); if (customAttributes2.Length != 0) { obj = ((DecimalConstantAttribute)customAttributes2[0]).Value; } } } } if (obj == DBNull.Value) { m_noDefaultValue = true; } return obj; } private static decimal GetRawDecimalConstant(CustomAttributeData attr) { foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments) { if (namedArgument.MemberInfo.Name.Equals("Value")) { return (decimal)namedArgument.TypedValue.Value; } } ParameterInfo[] parameters = attr.Constructor.GetParameters(); IList constructorArguments = attr.ConstructorArguments; if (parameters[2].ParameterType == typeof(uint)) { int lo = (int)(uint)constructorArguments[4].Value; int mid = (int)(uint)constructorArguments[3].Value; int hi = (int)(uint)constructorArguments[2].Value; byte b = (byte)constructorArguments[1].Value; byte scale = (byte)constructorArguments[0].Value; return new decimal(lo, mid, hi, b != 0, scale); } int lo2 = (int)constructorArguments[4].Value; int mid2 = (int)constructorArguments[3].Value; int hi2 = (int)constructorArguments[2].Value; byte b2 = (byte)constructorArguments[1].Value; byte scale2 = (byte)constructorArguments[0].Value; return new decimal(lo2, mid2, hi2, b2 != 0, scale2); } private static DateTime GetRawDateTimeConstant(CustomAttributeData attr) { foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments) { if (namedArgument.MemberInfo.Name.Equals("Value")) { return new DateTime((long)namedArgument.TypedValue.Value); } } return new DateTime((long)attr.ConstructorArguments[0].Value); } private static object GetRawConstant(CustomAttributeData attr) { foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments) { if (namedArgument.MemberInfo.Name.Equals("Value")) { return namedArgument.TypedValue.Value; } } return DBNull.Value; } internal RuntimeModule GetRuntimeModule() { RuntimeMethodInfo runtimeMethodInfo = Member as RuntimeMethodInfo; RuntimeConstructorInfo runtimeConstructorInfo = Member as RuntimeConstructorInfo; RuntimePropertyInfo runtimePropertyInfo = Member as RuntimePropertyInfo; if (runtimeMethodInfo != null) { return runtimeMethodInfo.GetRuntimeModule(); } if (runtimeConstructorInfo != null) { return runtimeConstructorInfo.GetRuntimeModule(); } if (runtimePropertyInfo != null) { return runtimePropertyInfo.GetRuntimeModule(); } return null; } public override Type[] GetRequiredCustomModifiers() { if (m_signature != null) { return m_signature.GetCustomModifiers(PositionImpl + 1, required: true); } return Type.EmptyTypes; } public override Type[] GetOptionalCustomModifiers() { if (m_signature != null) { return m_signature.GetCustomModifiers(PositionImpl + 1, required: false); } return Type.EmptyTypes; } public override object[] GetCustomAttributes(bool inherit) { if (System.Reflection.MetadataToken.IsNullToken(m_tkParamDef)) { return Array.Empty(); } return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } if (System.Reflection.MetadataToken.IsNullToken(m_tkParamDef)) { return Array.Empty(); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.GetCustomAttributes(this, runtimeType); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } if (System.Reflection.MetadataToken.IsNullToken(m_tkParamDef)) { return false; } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.IsDefined(this, runtimeType); } public override IList GetCustomAttributesData() { return RuntimeCustomAttributeData.GetCustomAttributesInternal(this); } } internal sealed class RuntimePropertyInfo : PropertyInfo { private int m_token; private string m_name; private unsafe void* m_utf8name; private PropertyAttributes m_flags; private RuntimeType.RuntimeTypeCache m_reflectedTypeCache; private RuntimeMethodInfo m_getterMethod; private RuntimeMethodInfo m_setterMethod; private MethodInfo[] m_otherMethod; private RuntimeType m_declaringType; private BindingFlags m_bindingFlags; private Signature m_signature; private ParameterInfo[] m_parameters; internal unsafe Signature Signature { get { if (m_signature == null) { GetRuntimeModule().MetadataImport.GetPropertyProps(m_token, out var _, out var _, out var signature); m_signature = new Signature(signature.Signature.ToPointer(), signature.Length, m_declaringType); } return m_signature; } } internal BindingFlags BindingFlags => m_bindingFlags; public override MemberTypes MemberType => MemberTypes.Property; public unsafe override string Name => m_name ?? (m_name = new MdUtf8String(m_utf8name).ToString()); public override Type DeclaringType => m_declaringType; public override Type ReflectedType => ReflectedTypeInternal; private RuntimeType ReflectedTypeInternal => m_reflectedTypeCache.GetRuntimeType(); public override int MetadataToken => m_token; public override Module Module => GetRuntimeModule(); public override bool IsCollectible => m_declaringType.IsCollectible; public override Type PropertyType => Signature.ReturnType; public override PropertyAttributes Attributes => m_flags; public override bool CanRead => m_getterMethod != null; public override bool CanWrite => m_setterMethod != null; internal unsafe RuntimePropertyInfo(int tkProperty, RuntimeType declaredType, RuntimeType.RuntimeTypeCache reflectedTypeCache, out bool isPrivate) { MetadataImport metadataImport = declaredType.GetRuntimeModule().MetadataImport; m_token = tkProperty; m_reflectedTypeCache = reflectedTypeCache; m_declaringType = declaredType; metadataImport.GetPropertyProps(tkProperty, out m_utf8name, out m_flags, out var _); Associates.AssignAssociates(metadataImport, tkProperty, declaredType, reflectedTypeCache.GetRuntimeType(), out var _, out var _, out var _, out m_getterMethod, out m_setterMethod, out m_otherMethod, out isPrivate, out m_bindingFlags); } internal override bool CacheEquals(object o) { if (o is RuntimePropertyInfo runtimePropertyInfo && runtimePropertyInfo.m_token == m_token) { return RuntimeTypeHandle.GetModule(m_declaringType).Equals(RuntimeTypeHandle.GetModule(runtimePropertyInfo.m_declaringType)); } return false; } internal bool EqualsSig(RuntimePropertyInfo target) { return Signature.CompareSig(Signature, target.Signature); } public override string ToString() { ValueStringBuilder sbParamList = new ValueStringBuilder(100); sbParamList.Append(PropertyType.FormatTypeName()); sbParamList.Append(' '); sbParamList.Append(Name); RuntimeType[] arguments = Signature.Arguments; if (arguments.Length != 0) { sbParamList.Append(" ["); Type[] parameterTypes = arguments; MethodBase.AppendParameters(ref sbParamList, parameterTypes, Signature.CallingConvention); sbParamList.Append(']'); } return sbParamList.ToString(); } public override object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.GetCustomAttributes(this, runtimeType); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.IsDefined(this, runtimeType); } public override IList GetCustomAttributesData() { return RuntimeCustomAttributeData.GetCustomAttributesInternal(this); } public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) { return HasSameMetadataDefinitionAsCore(other); } internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } public override Type[] GetRequiredCustomModifiers() { return Signature.GetCustomModifiers(0, required: true); } public override Type[] GetOptionalCustomModifiers() { return Signature.GetCustomModifiers(0, required: false); } internal object GetConstantValue(bool raw) { object value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_token, PropertyType.GetTypeHandleInternal(), raw); if (value == DBNull.Value) { throw new InvalidOperationException(SR.Arg_EnumLitValueNotFound); } return value; } public override object GetConstantValue() { return GetConstantValue(raw: false); } public override object GetRawConstantValue() { return GetConstantValue(raw: true); } public override MethodInfo[] GetAccessors(bool nonPublic) { List list = new List(); if (Associates.IncludeAccessor(m_getterMethod, nonPublic)) { list.Add(m_getterMethod); } if (Associates.IncludeAccessor(m_setterMethod, nonPublic)) { list.Add(m_setterMethod); } if (m_otherMethod != null) { for (int i = 0; i < m_otherMethod.Length; i++) { if (Associates.IncludeAccessor(m_otherMethod[i], nonPublic)) { list.Add(m_otherMethod[i]); } } } return list.ToArray(); } public override RuntimeMethodInfo GetGetMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_getterMethod, nonPublic)) { return null; } return m_getterMethod; } public override RuntimeMethodInfo GetSetMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_setterMethod, nonPublic)) { return null; } return m_setterMethod; } public override ParameterInfo[] GetIndexParameters() { ParameterInfo[] indexParametersNoCopy = GetIndexParametersNoCopy(); int num = indexParametersNoCopy.Length; if (num == 0) { return indexParametersNoCopy; } ParameterInfo[] array = new ParameterInfo[num]; Array.Copy(indexParametersNoCopy, array, num); return array; } internal ParameterInfo[] GetIndexParametersNoCopy() { if (m_parameters == null) { int num = 0; ParameterInfo[] array = null; RuntimeMethodInfo getMethod = GetGetMethod(nonPublic: true); if (getMethod != null) { array = getMethod.GetParametersNoCopy(); num = array.Length; } else { getMethod = GetSetMethod(nonPublic: true); if (getMethod != null) { array = getMethod.GetParametersNoCopy(); num = array.Length - 1; } } ParameterInfo[] array2 = ((num != 0) ? new ParameterInfo[num] : Array.Empty()); for (int i = 0; i < array2.Length; i++) { array2[i] = new RuntimeParameterInfo((RuntimeParameterInfo)array[i], this); } m_parameters = array2; } return m_parameters; } [DebuggerStepThrough] [DebuggerHidden] public override object GetValue(object obj, object[] index) { return GetValue(obj, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, index, null); } [DebuggerStepThrough] [DebuggerHidden] public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { RuntimeMethodInfo getMethod = GetGetMethod(nonPublic: true); if (getMethod == null) { throw new ArgumentException(SR.Arg_GetMethNotFnd); } return getMethod.Invoke(obj, invokeAttr, binder, index, null); } [DebuggerStepThrough] [DebuggerHidden] public override void SetValue(object obj, object value, object[] index) { SetValue(obj, value, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, index, null); } [DebuggerStepThrough] [DebuggerHidden] public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { RuntimeMethodInfo setMethod = GetSetMethod(nonPublic: true); if (setMethod == null) { throw new ArgumentException(SR.Arg_SetMethNotFnd); } if (index == null) { setMethod.InvokeOneParameter(obj, invokeAttr, binder, value, culture); return; } object[] array = new object[index.Length + 1]; for (int i = 0; i < index.Length; i++) { array[i] = index[i]; } array[index.Length] = value; setMethod.Invoke(obj, invokeAttr, binder, array, culture); } } internal struct CerHashtable where K : class { private sealed class Table { internal K[] m_keys; internal V[] m_values; internal int m_count; internal Table(int size) { size = HashHelpers.GetPrime(size); m_keys = new K[size]; m_values = new V[size]; } internal void Insert(K key, V value) { int num = CerHashtable.GetHashCodeHelper(key); if (num < 0) { num = ~num; } K[] keys = m_keys; int num2 = num % keys.Length; while (true) { K val = keys[num2]; if (val == null) { break; } num2++; if (num2 >= keys.Length) { num2 -= keys.Length; } } m_count++; m_values[num2] = value; Volatile.Write(ref keys[num2], key); } } private Table m_Table; internal V this[K key] { get { Table table = Volatile.Read(ref m_Table); if (table == null) { return default(V); } int num = GetHashCodeHelper(key); if (num < 0) { num = ~num; } K[] keys = table.m_keys; int num2 = num % keys.Length; while (true) { K val = Volatile.Read(ref keys[num2]); if (val == null) { break; } if (val.Equals(key)) { return table.m_values[num2]; } num2++; if (num2 >= keys.Length) { num2 -= keys.Length; } } return default(V); } set { Table table = m_Table; if (table != null) { int num = 2 * (table.m_count + 1); if (num >= table.m_keys.Length) { Rehash(num); } } else { Rehash(7); } m_Table.Insert(key, value); } } private static int GetHashCodeHelper(K key) { if (!(key is string text)) { return key.GetHashCode(); } return text.GetNonRandomizedHashCode(); } private void Rehash(int newSize) { Table table = new Table(newSize); Table table2 = m_Table; if (table2 != null) { K[] keys = table2.m_keys; V[] values = table2.m_values; for (int i = 0; i < keys.Length; i++) { K val = keys[i]; if (val != null) { table.Insert(val, values[i]); } } } Volatile.Write(ref m_Table, table); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class AmbiguousMatchException : SystemException { public AmbiguousMatchException() : base(SR.RFLCT_Ambiguous) { base.HResult = -2147475171; } public AmbiguousMatchException(string? message) : base(message) { base.HResult = -2147475171; } public AmbiguousMatchException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2147475171; } private AmbiguousMatchException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyAlgorithmIdAttribute : Attribute { [CLSCompliant(false)] public uint AlgorithmId { get; } public AssemblyAlgorithmIdAttribute(AssemblyHashAlgorithm algorithmId) { AlgorithmId = (uint)algorithmId; } [CLSCompliant(false)] public AssemblyAlgorithmIdAttribute(uint algorithmId) { AlgorithmId = algorithmId; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyCompanyAttribute : Attribute { public string Company { get; } public AssemblyCompanyAttribute(string company) { Company = company; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyConfigurationAttribute : Attribute { public string Configuration { get; } public AssemblyConfigurationAttribute(string configuration) { Configuration = configuration; } } public enum AssemblyContentType { Default, WindowsRuntime } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyCopyrightAttribute : Attribute { public string Copyright { get; } public AssemblyCopyrightAttribute(string copyright) { Copyright = copyright; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyCultureAttribute : Attribute { public string Culture { get; } public AssemblyCultureAttribute(string culture) { Culture = culture; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyDefaultAliasAttribute : Attribute { public string DefaultAlias { get; } public AssemblyDefaultAliasAttribute(string defaultAlias) { DefaultAlias = defaultAlias; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyDelaySignAttribute : Attribute { public bool DelaySign { get; } public AssemblyDelaySignAttribute(bool delaySign) { DelaySign = delaySign; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyDescriptionAttribute : Attribute { public string Description { get; } public AssemblyDescriptionAttribute(string description) { Description = description; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyFileVersionAttribute : Attribute { public string Version { get; } public AssemblyFileVersionAttribute(string version) { Version = version ?? throw new ArgumentNullException("version"); } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyFlagsAttribute : Attribute { private readonly AssemblyNameFlags _flags; [Obsolete("AssemblyFlagsAttribute.Flags has been deprecated. Use AssemblyFlags instead.")] [CLSCompliant(false)] public uint Flags => (uint)_flags; public int AssemblyFlags => (int)_flags; [Obsolete("This constructor has been deprecated. Use AssemblyFlagsAttribute(AssemblyNameFlags) instead.")] [CLSCompliant(false)] public AssemblyFlagsAttribute(uint flags) { _flags = (AssemblyNameFlags)flags; } [Obsolete("This constructor has been deprecated. Use AssemblyFlagsAttribute(AssemblyNameFlags) instead.")] public AssemblyFlagsAttribute(int assemblyFlags) { _flags = (AssemblyNameFlags)assemblyFlags; } public AssemblyFlagsAttribute(AssemblyNameFlags assemblyFlags) { _flags = assemblyFlags; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyInformationalVersionAttribute : Attribute { public string InformationalVersion { get; } public AssemblyInformationalVersionAttribute(string informationalVersion) { InformationalVersion = informationalVersion; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyKeyFileAttribute : Attribute { public string KeyFile { get; } public AssemblyKeyFileAttribute(string keyFile) { KeyFile = keyFile; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyKeyNameAttribute : Attribute { public string KeyName { get; } public AssemblyKeyNameAttribute(string keyName) { KeyName = keyName; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)] public sealed class AssemblyMetadataAttribute : Attribute { public string Key { get; } public string? Value { get; } public AssemblyMetadataAttribute(string key, string? value) { Key = key; Value = value; } } [Flags] public enum AssemblyNameFlags { None = 0, PublicKey = 1, EnableJITcompileOptimizer = 0x4000, EnableJITcompileTracking = 0x8000, Retargetable = 0x100 } internal static class AssemblyNameFormatter { public static string ComputeDisplayName(string name, Version version, string cultureName, byte[] pkt, AssemblyNameFlags flags = AssemblyNameFlags.None, AssemblyContentType contentType = AssemblyContentType.Default) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendQuoted(name); if (version != null) { Version version2 = version.CanonicalizeVersion(); if (version2.Major != 65535) { stringBuilder.Append(", Version="); stringBuilder.Append(version2.Major); if (version2.Minor != 65535) { stringBuilder.Append('.'); stringBuilder.Append(version2.Minor); if (version2.Build != 65535) { stringBuilder.Append('.'); stringBuilder.Append(version2.Build); if (version2.Revision != 65535) { stringBuilder.Append('.'); stringBuilder.Append(version2.Revision); } } } } } if (cultureName != null) { if (cultureName.Length == 0) { cultureName = "neutral"; } stringBuilder.Append(", Culture="); stringBuilder.AppendQuoted(cultureName); } if (pkt != null) { if (pkt.Length > 8) { throw new ArgumentException(); } stringBuilder.Append(", PublicKeyToken="); if (pkt.Length == 0) { stringBuilder.Append("null"); } else { stringBuilder.Append(HexConverter.ToString(pkt, HexConverter.Casing.Lower)); } } if ((flags & AssemblyNameFlags.Retargetable) != 0) { stringBuilder.Append(", Retargetable=Yes"); } if (contentType == AssemblyContentType.WindowsRuntime) { stringBuilder.Append(", ContentType=WindowsRuntime"); } return stringBuilder.ToString(); } private static void AppendQuoted(this StringBuilder sb, string s) { bool flag = false; if (s != s.Trim() || s.Contains('"') || s.Contains('\'')) { flag = true; } if (flag) { sb.Append('"'); } for (int i = 0; i < s.Length; i++) { switch (s[i]) { case '"': case '\'': case ',': case '=': case '\\': sb.Append('\\'); break; case '\t': sb.Append("\\t"); continue; case '\r': sb.Append("\\r"); continue; case '\n': sb.Append("\\n"); continue; } sb.Append(s[i]); } if (flag) { sb.Append('"'); } } private static Version CanonicalizeVersion(this Version version) { ushort num = (ushort)version.Major; ushort num2 = (ushort)version.Minor; ushort num3 = (ushort)version.Build; ushort num4 = (ushort)version.Revision; if (num == version.Major && num2 == version.Minor && num3 == version.Build && num4 == version.Revision) { return version; } return new Version(num, num2, num3, num4); } } public class AssemblyNameProxy : MarshalByRefObject { public AssemblyName GetAssemblyName(string assemblyFile) { return AssemblyName.GetAssemblyName(assemblyFile); } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyProductAttribute : Attribute { public string Product { get; } public AssemblyProductAttribute(string product) { Product = product; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false, AllowMultiple = false)] public sealed class AssemblySignatureKeyAttribute : Attribute { public string PublicKey { get; } public string Countersignature { get; } public AssemblySignatureKeyAttribute(string publicKey, string countersignature) { PublicKey = publicKey; Countersignature = countersignature; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyTitleAttribute : Attribute { public string Title { get; } public AssemblyTitleAttribute(string title) { Title = title; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyTrademarkAttribute : Attribute { public string Trademark { get; } public AssemblyTrademarkAttribute(string trademark) { Trademark = trademark; } } [AttributeUsage(AttributeTargets.Assembly, Inherited = false)] public sealed class AssemblyVersionAttribute : Attribute { public string Version { get; } public AssemblyVersionAttribute(string version) { Version = version; } } public abstract class Binder { public abstract FieldInfo BindToField(BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo? culture); public abstract MethodBase BindToMethod(BindingFlags bindingAttr, MethodBase[] match, ref object?[] args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? names, out object? state); public abstract object ChangeType(object value, Type type, CultureInfo? culture); public abstract void ReorderArgumentArray(ref object?[] args, object state); public abstract MethodBase? SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[]? modifiers); public abstract PropertyInfo? SelectProperty(BindingFlags bindingAttr, PropertyInfo[] match, Type? returnType, Type[]? indexes, ParameterModifier[]? modifiers); } [Flags] public enum BindingFlags { Default = 0, IgnoreCase = 1, DeclaredOnly = 2, Instance = 4, Static = 8, Public = 0x10, NonPublic = 0x20, FlattenHierarchy = 0x40, InvokeMethod = 0x100, CreateInstance = 0x200, GetField = 0x400, SetField = 0x800, GetProperty = 0x1000, SetProperty = 0x2000, PutDispProperty = 0x4000, PutRefDispProperty = 0x8000, ExactBinding = 0x10000, SuppressChangeType = 0x20000, OptionalParamBinding = 0x40000, IgnoreReturn = 0x1000000, DoNotWrapExceptions = 0x2000000 } [Flags] public enum CallingConventions { Standard = 1, VarArgs = 2, Any = 3, HasThis = 0x20, ExplicitThis = 0x40 } internal enum CorElementType : byte { ELEMENT_TYPE_END = 0, ELEMENT_TYPE_VOID = 1, ELEMENT_TYPE_BOOLEAN = 2, ELEMENT_TYPE_CHAR = 3, ELEMENT_TYPE_I1 = 4, ELEMENT_TYPE_U1 = 5, ELEMENT_TYPE_I2 = 6, ELEMENT_TYPE_U2 = 7, ELEMENT_TYPE_I4 = 8, ELEMENT_TYPE_U4 = 9, ELEMENT_TYPE_I8 = 10, ELEMENT_TYPE_U8 = 11, ELEMENT_TYPE_R4 = 12, ELEMENT_TYPE_R8 = 13, ELEMENT_TYPE_STRING = 14, ELEMENT_TYPE_PTR = 15, ELEMENT_TYPE_BYREF = 16, ELEMENT_TYPE_VALUETYPE = 17, ELEMENT_TYPE_CLASS = 18, ELEMENT_TYPE_VAR = 19, ELEMENT_TYPE_ARRAY = 20, ELEMENT_TYPE_GENERICINST = 21, ELEMENT_TYPE_TYPEDBYREF = 22, ELEMENT_TYPE_I = 24, ELEMENT_TYPE_U = 25, ELEMENT_TYPE_FNPTR = 27, ELEMENT_TYPE_OBJECT = 28, ELEMENT_TYPE_SZARRAY = 29, ELEMENT_TYPE_MVAR = 30, ELEMENT_TYPE_CMOD_REQD = 31, ELEMENT_TYPE_CMOD_OPT = 32, ELEMENT_TYPE_INTERNAL = 33, ELEMENT_TYPE_MAX = 34, ELEMENT_TYPE_MODIFIER = 64, ELEMENT_TYPE_SENTINEL = 65, ELEMENT_TYPE_PINNED = 69 } public class CustomAttributeData { public virtual Type AttributeType => Constructor.DeclaringType; public virtual ConstructorInfo Constructor => null; public virtual IList ConstructorArguments => null; public virtual IList NamedArguments => null; public static IList GetCustomAttributes(MemberInfo target) { if ((object)target == null) { throw new ArgumentNullException("target"); } return target.GetCustomAttributesData(); } public static IList GetCustomAttributes(Module target) { if ((object)target == null) { throw new ArgumentNullException("target"); } return target.GetCustomAttributesData(); } public static IList GetCustomAttributes(Assembly target) { if ((object)target == null) { throw new ArgumentNullException("target"); } return target.GetCustomAttributesData(); } public static IList GetCustomAttributes(ParameterInfo target) { if (target == null) { throw new ArgumentNullException("target"); } return target.GetCustomAttributesData(); } protected CustomAttributeData() { } public override string ToString() { Span initialBuffer = stackalloc char[256]; ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer); valueStringBuilder.Append('['); valueStringBuilder.Append(Constructor.DeclaringType.FullName); valueStringBuilder.Append('('); bool flag = true; IList constructorArguments = ConstructorArguments; int count = constructorArguments.Count; for (int i = 0; i < count; i++) { if (!flag) { valueStringBuilder.Append(", "); } valueStringBuilder.Append(constructorArguments[i].ToString()); flag = false; } IList namedArguments = NamedArguments; int count2 = namedArguments.Count; for (int j = 0; j < count2; j++) { if (!flag) { valueStringBuilder.Append(", "); } valueStringBuilder.Append(namedArguments[j].ToString()); flag = false; } valueStringBuilder.Append(")]"); return valueStringBuilder.ToString(); } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object? obj) { return obj == this; } } public static class CustomAttributeExtensions { public static Attribute? GetCustomAttribute(this Assembly element, Type attributeType) { return Attribute.GetCustomAttribute(element, attributeType); } public static Attribute? GetCustomAttribute(this Module element, Type attributeType) { return Attribute.GetCustomAttribute(element, attributeType); } public static Attribute? GetCustomAttribute(this MemberInfo element, Type attributeType) { return Attribute.GetCustomAttribute(element, attributeType); } public static Attribute? GetCustomAttribute(this ParameterInfo element, Type attributeType) { return Attribute.GetCustomAttribute(element, attributeType); } public static T? GetCustomAttribute(this Assembly element) where T : Attribute { return (T)element.GetCustomAttribute(typeof(T)); } public static T? GetCustomAttribute(this Module element) where T : Attribute { return (T)element.GetCustomAttribute(typeof(T)); } public static T? GetCustomAttribute(this MemberInfo element) where T : Attribute { return (T)element.GetCustomAttribute(typeof(T)); } public static T? GetCustomAttribute(this ParameterInfo element) where T : Attribute { return (T)element.GetCustomAttribute(typeof(T)); } public static Attribute? GetCustomAttribute(this MemberInfo element, Type attributeType, bool inherit) { return Attribute.GetCustomAttribute(element, attributeType, inherit); } public static Attribute? GetCustomAttribute(this ParameterInfo element, Type attributeType, bool inherit) { return Attribute.GetCustomAttribute(element, attributeType, inherit); } public static T? GetCustomAttribute(this MemberInfo element, bool inherit) where T : Attribute { return (T)element.GetCustomAttribute(typeof(T), inherit); } public static T? GetCustomAttribute(this ParameterInfo element, bool inherit) where T : Attribute { return (T)element.GetCustomAttribute(typeof(T), inherit); } public static IEnumerable GetCustomAttributes(this Assembly element) { return Attribute.GetCustomAttributes(element); } public static IEnumerable GetCustomAttributes(this Module element) { return Attribute.GetCustomAttributes(element); } public static IEnumerable GetCustomAttributes(this MemberInfo element) { return Attribute.GetCustomAttributes(element); } public static IEnumerable GetCustomAttributes(this ParameterInfo element) { return Attribute.GetCustomAttributes(element); } public static IEnumerable GetCustomAttributes(this MemberInfo element, bool inherit) { return Attribute.GetCustomAttributes(element, inherit); } public static IEnumerable GetCustomAttributes(this ParameterInfo element, bool inherit) { return Attribute.GetCustomAttributes(element, inherit); } public static IEnumerable GetCustomAttributes(this Assembly element, Type attributeType) { return Attribute.GetCustomAttributes(element, attributeType); } public static IEnumerable GetCustomAttributes(this Module element, Type attributeType) { return Attribute.GetCustomAttributes(element, attributeType); } public static IEnumerable GetCustomAttributes(this MemberInfo element, Type attributeType) { return Attribute.GetCustomAttributes(element, attributeType); } public static IEnumerable GetCustomAttributes(this ParameterInfo element, Type attributeType) { return Attribute.GetCustomAttributes(element, attributeType); } public static IEnumerable GetCustomAttributes(this Assembly element) where T : Attribute { return (IEnumerable)element.GetCustomAttributes(typeof(T)); } public static IEnumerable GetCustomAttributes(this Module element) where T : Attribute { return (IEnumerable)element.GetCustomAttributes(typeof(T)); } public static IEnumerable GetCustomAttributes(this MemberInfo element) where T : Attribute { return (IEnumerable)element.GetCustomAttributes(typeof(T)); } public static IEnumerable GetCustomAttributes(this ParameterInfo element) where T : Attribute { return (IEnumerable)element.GetCustomAttributes(typeof(T)); } public static IEnumerable GetCustomAttributes(this MemberInfo element, Type attributeType, bool inherit) { return Attribute.GetCustomAttributes(element, attributeType, inherit); } public static IEnumerable GetCustomAttributes(this ParameterInfo element, Type attributeType, bool inherit) { return Attribute.GetCustomAttributes(element, attributeType, inherit); } public static IEnumerable GetCustomAttributes(this MemberInfo element, bool inherit) where T : Attribute { return (IEnumerable)GetCustomAttributes(element, typeof(T), inherit); } public static IEnumerable GetCustomAttributes(this ParameterInfo element, bool inherit) where T : Attribute { return (IEnumerable)GetCustomAttributes(element, typeof(T), inherit); } public static bool IsDefined(this Assembly element, Type attributeType) { return Attribute.IsDefined(element, attributeType); } public static bool IsDefined(this Module element, Type attributeType) { return Attribute.IsDefined(element, attributeType); } public static bool IsDefined(this MemberInfo element, Type attributeType) { return Attribute.IsDefined(element, attributeType); } public static bool IsDefined(this ParameterInfo element, Type attributeType) { return Attribute.IsDefined(element, attributeType); } public static bool IsDefined(this MemberInfo element, Type attributeType, bool inherit) { return Attribute.IsDefined(element, attributeType, inherit); } public static bool IsDefined(this ParameterInfo element, Type attributeType, bool inherit) { return Attribute.IsDefined(element, attributeType, inherit); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class CustomAttributeFormatException : FormatException { public CustomAttributeFormatException() : this(SR.Arg_CustomAttributeFormatException) { } public CustomAttributeFormatException(string? message) : this(message, null) { } public CustomAttributeFormatException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146232827; } protected CustomAttributeFormatException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public readonly struct CustomAttributeNamedArgument { private readonly MemberInfo _memberInfo; private readonly CustomAttributeTypedArgument _value; internal Type ArgumentType { get { if (!(_memberInfo is FieldInfo fieldInfo)) { return ((PropertyInfo)_memberInfo).PropertyType; } return fieldInfo.FieldType; } } public MemberInfo MemberInfo => _memberInfo; public CustomAttributeTypedArgument TypedValue => _value; public string MemberName => MemberInfo.Name; public bool IsField => MemberInfo is FieldInfo; public static bool operator ==(CustomAttributeNamedArgument left, CustomAttributeNamedArgument right) { return left.Equals(right); } public static bool operator !=(CustomAttributeNamedArgument left, CustomAttributeNamedArgument right) { return !left.Equals(right); } public CustomAttributeNamedArgument(MemberInfo memberInfo, object? value) { if ((object)memberInfo == null) { throw new ArgumentNullException("memberInfo"); } Type type; if (!(memberInfo is FieldInfo fieldInfo)) { if (!(memberInfo is PropertyInfo propertyInfo)) { throw new ArgumentException(SR.Argument_InvalidMemberForNamedArgument); } type = propertyInfo.PropertyType; } else { type = fieldInfo.FieldType; } Type argumentType = type; _memberInfo = memberInfo; _value = new CustomAttributeTypedArgument(argumentType, value); } public CustomAttributeNamedArgument(MemberInfo memberInfo, CustomAttributeTypedArgument typedArgument) { _memberInfo = memberInfo ?? throw new ArgumentNullException("memberInfo"); _value = typedArgument; } public override string ToString() { if ((object)_memberInfo == null) { return base.ToString(); } return MemberInfo.Name + " = " + TypedValue.ToString(ArgumentType != typeof(object)); } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object? obj) { return obj == (object)this; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] public sealed class DefaultMemberAttribute : Attribute { public string MemberName { get; } public DefaultMemberAttribute(string memberName) { MemberName = memberName; } } [Flags] public enum EventAttributes { None = 0, SpecialName = 0x200, RTSpecialName = 0x400, ReservedMask = 0x400 } public abstract class EventInfo : MemberInfo { public override MemberTypes MemberType => MemberTypes.Event; public abstract EventAttributes Attributes { get; } public bool IsSpecialName => (Attributes & EventAttributes.SpecialName) != 0; public virtual MethodInfo? AddMethod => GetAddMethod(nonPublic: true); public virtual MethodInfo? RemoveMethod => GetRemoveMethod(nonPublic: true); public virtual MethodInfo? RaiseMethod => GetRaiseMethod(nonPublic: true); public virtual bool IsMulticast { get { Type eventHandlerType = EventHandlerType; Type typeFromHandle = typeof(MulticastDelegate); return typeFromHandle.IsAssignableFrom(eventHandlerType); } } public virtual Type? EventHandlerType { get { MethodInfo addMethod = GetAddMethod(nonPublic: true); ParameterInfo[] parametersNoCopy = addMethod.GetParametersNoCopy(); Type typeFromHandle = typeof(Delegate); for (int i = 0; i < parametersNoCopy.Length; i++) { Type parameterType = parametersNoCopy[i].ParameterType; if (parameterType.IsSubclassOf(typeFromHandle)) { return parameterType; } } return null; } } public MethodInfo[] GetOtherMethods() { return GetOtherMethods(nonPublic: false); } public virtual MethodInfo[] GetOtherMethods(bool nonPublic) { throw NotImplemented.ByDesign; } public MethodInfo? GetAddMethod() { return GetAddMethod(nonPublic: false); } public MethodInfo? GetRemoveMethod() { return GetRemoveMethod(nonPublic: false); } public MethodInfo? GetRaiseMethod() { return GetRaiseMethod(nonPublic: false); } public abstract MethodInfo? GetAddMethod(bool nonPublic); public abstract MethodInfo? GetRemoveMethod(bool nonPublic); public abstract MethodInfo? GetRaiseMethod(bool nonPublic); [DebuggerHidden] [DebuggerStepThrough] public virtual void AddEventHandler(object? target, Delegate? handler) { MethodInfo addMethod = GetAddMethod(nonPublic: false); if (addMethod == null) { throw new InvalidOperationException(SR.InvalidOperation_NoPublicAddMethod); } addMethod.Invoke(target, new object[1] { handler }); } [DebuggerHidden] [DebuggerStepThrough] public virtual void RemoveEventHandler(object? target, Delegate? handler) { MethodInfo removeMethod = GetRemoveMethod(nonPublic: false); if (removeMethod == null) { throw new InvalidOperationException(SR.InvalidOperation_NoPublicRemoveMethod); } removeMethod.Invoke(target, new object[1] { handler }); } public override bool Equals(object? obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(EventInfo? left, EventInfo? right) { if ((object)right == null) { if ((object)left != null) { return false; } return true; } if ((object)left == right) { return true; } return left?.Equals(right) ?? false; } public static bool operator !=(EventInfo? left, EventInfo? right) { return !(left == right); } } public class ExceptionHandlingClause { public virtual ExceptionHandlingClauseOptions Flags => ExceptionHandlingClauseOptions.Clause; public virtual int TryOffset => 0; public virtual int TryLength => 0; public virtual int HandlerOffset => 0; public virtual int HandlerLength => 0; public virtual int FilterOffset { get { throw new InvalidOperationException(SR.Arg_EHClauseNotFilter); } } public virtual Type? CatchType => null; protected ExceptionHandlingClause() { } public override string ToString() { return $"Flags={Flags}, TryOffset={TryOffset}, TryLength={TryLength}, HandlerOffset={HandlerOffset}, HandlerLength={HandlerLength}, CatchType={CatchType}"; } } [Flags] public enum ExceptionHandlingClauseOptions { Clause = 0, Filter = 1, Finally = 2, Fault = 4 } [Flags] public enum FieldAttributes { FieldAccessMask = 7, PrivateScope = 0, Private = 1, FamANDAssem = 2, Assembly = 3, Family = 4, FamORAssem = 5, Public = 6, Static = 0x10, InitOnly = 0x20, Literal = 0x40, NotSerialized = 0x80, SpecialName = 0x200, PinvokeImpl = 0x2000, RTSpecialName = 0x400, HasFieldMarshal = 0x1000, HasDefault = 0x8000, HasFieldRVA = 0x100, ReservedMask = 0x9500 } [Flags] public enum GenericParameterAttributes { None = 0, VarianceMask = 3, Covariant = 1, Contravariant = 2, SpecialConstraintMask = 0x1C, ReferenceTypeConstraint = 4, NotNullableValueTypeConstraint = 8, DefaultConstructorConstraint = 0x10 } public interface ICustomAttributeProvider { object[] GetCustomAttributes(bool inherit); object[] GetCustomAttributes(Type attributeType, bool inherit); bool IsDefined(Type attributeType, bool inherit); } public enum ImageFileMachine { I386 = 332, IA64 = 512, AMD64 = 34404, ARM = 452 } public struct InterfaceMapping { public Type TargetType; public Type InterfaceType; public MethodInfo[] TargetMethods; public MethodInfo[] InterfaceMethods; } public static class IntrospectionExtensions { public static TypeInfo GetTypeInfo(this Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (type is IReflectableType reflectableType) { return reflectableType.GetTypeInfo(); } return new TypeDelegator(type); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class InvalidFilterCriteriaException : ApplicationException { public InvalidFilterCriteriaException() : this(SR.Arg_InvalidFilterCriteriaException) { } public InvalidFilterCriteriaException(string? message) : this(message, null) { } public InvalidFilterCriteriaException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146232831; } protected InvalidFilterCriteriaException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public interface IReflect { Type UnderlyingSystemType { get; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, Type[] types, ParameterModifier[]? modifiers); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] MethodInfo? GetMethod(string name, BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] MethodInfo[] GetMethods(BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] FieldInfo? GetField(string name, BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] FieldInfo[] GetFields(BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] PropertyInfo? GetProperty(string name, BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] PropertyInfo? GetProperty(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[] types, ParameterModifier[]? modifiers); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] PropertyInfo[] GetProperties(BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] MemberInfo[] GetMember(string name, BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] MemberInfo[] GetMembers(BindingFlags bindingAttr); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters); } public interface IReflectableType { TypeInfo GetTypeInfo(); } public class LocalVariableInfo { public virtual Type LocalType => null; public virtual int LocalIndex => 0; public virtual bool IsPinned => false; protected LocalVariableInfo() { } public override string ToString() { if (IsPinned) { return $"{LocalType} ({LocalIndex}) (pinned)"; } return $"{LocalType} ({LocalIndex})"; } } public class ManifestResourceInfo { public virtual Assembly? ReferencedAssembly { get; } public virtual string? FileName { get; } public virtual ResourceLocation ResourceLocation { get; } public ManifestResourceInfo(Assembly? containingAssembly, string? containingFileName, ResourceLocation resourceLocation) { ReferencedAssembly = containingAssembly; FileName = containingFileName; ResourceLocation = resourceLocation; } } public delegate bool MemberFilter(MemberInfo m, object? filterCriteria); [Flags] public enum MemberTypes { Constructor = 1, Event = 2, Field = 4, Method = 8, Property = 0x10, TypeInfo = 0x20, Custom = 0x40, NestedType = 0x80, All = 0xBF } [Flags] public enum MethodAttributes { MemberAccessMask = 7, PrivateScope = 0, Private = 1, FamANDAssem = 2, Assembly = 3, Family = 4, FamORAssem = 5, Public = 6, Static = 0x10, Final = 0x20, Virtual = 0x40, HideBySig = 0x80, CheckAccessOnOverride = 0x200, VtableLayoutMask = 0x100, ReuseSlot = 0, NewSlot = 0x100, Abstract = 0x400, SpecialName = 0x800, PinvokeImpl = 0x2000, UnmanagedExport = 8, RTSpecialName = 0x1000, HasSecurity = 0x4000, RequireSecObject = 0x8000, ReservedMask = 0xD000 } public class MethodBody { public virtual int LocalSignatureMetadataToken => 0; public virtual IList LocalVariables { get { throw new ArgumentNullException("array"); } } public virtual int MaxStackSize => 0; public virtual bool InitLocals => false; public virtual IList ExceptionHandlingClauses { get { throw new ArgumentNullException("array"); } } protected MethodBody() { } public virtual byte[]? GetILAsByteArray() { return null; } } public enum MethodImplAttributes { CodeTypeMask = 3, IL = 0, Native = 1, OPTIL = 2, Runtime = 3, ManagedMask = 4, Unmanaged = 4, Managed = 0, ForwardRef = 16, PreserveSig = 128, InternalCall = 4096, Synchronized = 32, NoInlining = 8, AggressiveInlining = 256, NoOptimization = 64, AggressiveOptimization = 512, MaxMethodImplVal = 65535 } public abstract class MethodInfo : MethodBase { public override MemberTypes MemberType => MemberTypes.Method; public virtual ParameterInfo ReturnParameter { get { throw NotImplemented.ByDesign; } } public virtual Type ReturnType { get { throw NotImplemented.ByDesign; } } public abstract ICustomAttributeProvider ReturnTypeCustomAttributes { get; } internal virtual int GenericParameterCount => GetGenericArguments().Length; public override Type[] GetGenericArguments() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } public virtual MethodInfo GetGenericMethodDefinition() { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public virtual MethodInfo MakeGenericMethod(params Type[] typeArguments) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } public abstract MethodInfo GetBaseDefinition(); public virtual Delegate CreateDelegate(Type delegateType) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } public virtual Delegate CreateDelegate(Type delegateType, object? target) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } public T CreateDelegate() where T : Delegate { return (T)CreateDelegate(typeof(T)); } public T CreateDelegate(object? target) where T : Delegate { return (T)CreateDelegate(typeof(T), target); } public override bool Equals(object? obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(MethodInfo? left, MethodInfo? right) { if ((object)right == null) { if ((object)left != null) { return false; } return true; } if ((object)left == right) { return true; } return left?.Equals(right) ?? false; } public static bool operator !=(MethodInfo? left, MethodInfo? right) { return !(left == right); } } public sealed class Missing : ISerializable { public static readonly Missing Value = new Missing(); private Missing() { } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } } public abstract class Module : ICustomAttributeProvider, ISerializable { public static readonly TypeFilter FilterTypeName = (Type m, object c) => FilterTypeNameImpl(m, c, StringComparison.Ordinal); public static readonly TypeFilter FilterTypeNameIgnoreCase = (Type m, object c) => FilterTypeNameImpl(m, c, StringComparison.OrdinalIgnoreCase); public virtual Assembly Assembly { get { throw NotImplemented.ByDesign; } } [RequiresAssemblyFiles("Returns for modules with no file path")] public virtual string FullyQualifiedName { get { throw NotImplemented.ByDesign; } } [RequiresAssemblyFiles("Returns for modules with no file path")] public virtual string Name { get { throw NotImplemented.ByDesign; } } public virtual int MDStreamVersion { get { throw NotImplemented.ByDesign; } } public virtual Guid ModuleVersionId { get { throw NotImplemented.ByDesign; } } public virtual string ScopeName { get { throw NotImplemented.ByDesign; } } public ModuleHandle ModuleHandle => GetModuleHandleImpl(); public virtual IEnumerable CustomAttributes => GetCustomAttributesData(); public virtual int MetadataToken { get { throw NotImplemented.ByDesign; } } protected virtual ModuleHandle GetModuleHandleImpl() { return ModuleHandle.EmptyHandle; } public virtual void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) { throw NotImplemented.ByDesign; } public virtual bool IsResource() { throw NotImplemented.ByDesign; } public virtual bool IsDefined(Type attributeType, bool inherit) { throw NotImplemented.ByDesign; } public virtual IList GetCustomAttributesData() { throw NotImplemented.ByDesign; } public virtual object[] GetCustomAttributes(bool inherit) { throw NotImplemented.ByDesign; } public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Methods might be removed")] public MethodInfo? GetMethod(string name) { if (name == null) { throw new ArgumentNullException("name"); } return GetMethodImpl(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any, null, null); } [RequiresUnreferencedCode("Methods might be removed")] public MethodInfo? GetMethod(string name, Type[] types) { return GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Any, types, null); } [RequiresUnreferencedCode("Methods might be removed")] public MethodInfo? GetMethod(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { if (name == null) { throw new ArgumentNullException("name"); } if (types == null) { throw new ArgumentNullException("types"); } for (int i = 0; i < types.Length; i++) { if (types[i] == null) { throw new ArgumentNullException("types"); } } return GetMethodImpl(name, bindingAttr, binder, callConvention, types, modifiers); } [RequiresUnreferencedCode("Methods might be removed")] protected virtual MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Methods might be removed")] public MethodInfo[] GetMethods() { return GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [RequiresUnreferencedCode("Methods might be removed")] public virtual MethodInfo[] GetMethods(BindingFlags bindingFlags) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Fields might be removed")] public FieldInfo? GetField(string name) { return GetField(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [RequiresUnreferencedCode("Fields might be removed")] public virtual FieldInfo? GetField(string name, BindingFlags bindingAttr) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Fields might be removed")] public FieldInfo[] GetFields() { return GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public); } [RequiresUnreferencedCode("Fields might be removed")] public virtual FieldInfo[] GetFields(BindingFlags bindingFlags) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Types might be removed")] public virtual Type[] GetTypes() { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Types might be removed")] public virtual Type? GetType(string className) { return GetType(className, throwOnError: false, ignoreCase: false); } [RequiresUnreferencedCode("Types might be removed")] public virtual Type? GetType(string className, bool ignoreCase) { return GetType(className, throwOnError: false, ignoreCase); } [RequiresUnreferencedCode("Types might be removed")] public virtual Type? GetType(string className, bool throwOnError, bool ignoreCase) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Types might be removed")] public virtual Type[] FindTypes(TypeFilter? filter, object? filterCriteria) { Type[] types = GetTypes(); int num = 0; for (int i = 0; i < types.Length; i++) { if (filter != null && !filter(types[i], filterCriteria)) { types[i] = null; } else { num++; } } if (num == types.Length) { return types; } Type[] array = new Type[num]; num = 0; for (int j = 0; j < types.Length; j++) { if (types[j] != null) { array[num++] = types[j]; } } return array; } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public FieldInfo? ResolveField(int metadataToken) { return ResolveField(metadataToken, null, null); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public virtual FieldInfo? ResolveField(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public MemberInfo? ResolveMember(int metadataToken) { return ResolveMember(metadataToken, null, null); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public virtual MemberInfo? ResolveMember(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public MethodBase? ResolveMethod(int metadataToken) { return ResolveMethod(metadataToken, null, null); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public virtual MethodBase? ResolveMethod(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public virtual byte[] ResolveSignature(int metadataToken) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public virtual string ResolveString(int metadataToken) { throw NotImplemented.ByDesign; } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public Type ResolveType(int metadataToken) { return ResolveType(metadataToken, null, null); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public virtual Type ResolveType(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { throw NotImplemented.ByDesign; } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw NotImplemented.ByDesign; } public override bool Equals(object? o) { return base.Equals(o); } public override int GetHashCode() { return base.GetHashCode(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Module? left, Module? right) { if ((object)right == null) { if ((object)left != null) { return false; } return true; } if ((object)left == right) { return true; } return left?.Equals(right) ?? false; } public static bool operator !=(Module? left, Module? right) { return !(left == right); } public override string ToString() { return ScopeName; } private static bool FilterTypeNameImpl(Type cls, object filterCriteria, StringComparison comparison) { if (!(filterCriteria is string text)) { throw new InvalidFilterCriteriaException(SR.InvalidFilterCriteriaException_CritString); } if (text.Length > 0 && text[^1] == '*') { ReadOnlySpan value = text.AsSpan(0, text.Length - 1); return cls.Name.AsSpan().StartsWith(value, comparison); } return cls.Name.Equals(text, comparison); } } public delegate Module ModuleResolveEventHandler(object sender, ResolveEventArgs e); public 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; } } public enum NullabilityState { Unknown, NotNull, Nullable } public sealed class NullabilityInfoContext { [Flags] private enum NotAnnotatedStatus { None = 0, Private = 1, Internal = 2 } private readonly Dictionary _publicOnlyModules = new Dictionary(); private readonly Dictionary _context = new Dictionary(); internal static bool IsSupported { get; } = !AppContext.TryGetSwitch("System.Reflection.NullabilityInfoContext.IsSupported", out var isEnabled) || isEnabled; 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 NullabilityState.Unknown; } public NullabilityInfo Create(ParameterInfo parameterInfo) { if (parameterInfo == null) { throw new ArgumentNullException("parameterInfo"); } EnsureIsSupported(); if (parameterInfo.Member is MethodInfo method && IsPrivateOrInternalMethodAndAnnotationDisabled(method)) { return new NullabilityInfo(parameterInfo.ParameterType, NullabilityState.Unknown, NullabilityState.Unknown, null, Array.Empty()); } IList customAttributesData = parameterInfo.GetCustomAttributesData(); NullabilityInfo nullabilityInfo = GetNullabilityInfo(parameterInfo.Member, parameterInfo.ParameterType, customAttributesData); if (nullabilityInfo.ReadState != 0) { CheckParameterMetadataType(parameterInfo, nullabilityInfo); } CheckNullabilityAttributes(nullabilityInfo, customAttributesData); return nullabilityInfo; } private void CheckParameterMetadataType(ParameterInfo parameter, NullabilityInfo nullability) { if (!(parameter.Member is MethodInfo method)) { return; } MethodInfo methodMetadataDefinition = GetMethodMetadataDefinition(method); ParameterInfo parameterInfo = null; if (string.IsNullOrEmpty(parameter.Name)) { parameterInfo = methodMetadataDefinition.ReturnParameter; } else { ParameterInfo[] parameters = methodMetadataDefinition.GetParameters(); for (int i = 0; i < parameters.Length; i++) { if (parameter.Position == i && parameter.Name == parameters[i].Name) { parameterInfo = parameters[i]; break; } } } if (parameterInfo != null) { CheckGenericParameters(nullability, methodMetadataDefinition, parameterInfo.ParameterType); } } private static MethodInfo GetMethodMetadataDefinition(MethodInfo method) { if (method.IsGenericMethod && !method.IsGenericMethodDefinition) { method = method.GetGenericMethodDefinition(); } return (MethodInfo)GetMemberMetadataDefinition(method); } private void CheckNullabilityAttributes(NullabilityInfo nullability, IList attributes) { foreach (CustomAttributeData attribute in attributes) { if (attribute.AttributeType.Namespace == "System.Diagnostics.CodeAnalysis") { if (attribute.AttributeType.Name == "NotNullAttribute" && nullability.ReadState == NullabilityState.Nullable) { nullability.ReadState = NullabilityState.NotNull; break; } if ((attribute.AttributeType.Name == "MaybeNullAttribute" || attribute.AttributeType.Name == "MaybeNullWhenAttribute") && nullability.ReadState == NullabilityState.NotNull && !nullability.Type.IsValueType) { nullability.ReadState = NullabilityState.Nullable; break; } if (attribute.AttributeType.Name == "DisallowNullAttribute" && nullability.WriteState == NullabilityState.Nullable) { nullability.WriteState = NullabilityState.NotNull; break; } if (attribute.AttributeType.Name == "AllowNullAttribute" && nullability.WriteState == NullabilityState.NotNull && !nullability.Type.IsValueType) { nullability.WriteState = NullabilityState.Nullable; break; } } } } public NullabilityInfo Create(PropertyInfo propertyInfo) { if ((object)propertyInfo == null) { throw new ArgumentNullException("propertyInfo"); } EnsureIsSupported(); NullabilityInfo nullabilityInfo = GetNullabilityInfo(propertyInfo, propertyInfo.PropertyType, propertyInfo.GetCustomAttributesData()); MethodInfo getMethod = propertyInfo.GetGetMethod(nonPublic: true); MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true); if (getMethod != null) { if (IsPrivateOrInternalMethodAndAnnotationDisabled(getMethod)) { nullabilityInfo.ReadState = NullabilityState.Unknown; } CheckNullabilityAttributes(nullabilityInfo, getMethod.ReturnParameter.GetCustomAttributesData()); } else { nullabilityInfo.ReadState = NullabilityState.Unknown; } if (setMethod != null) { if (IsPrivateOrInternalMethodAndAnnotationDisabled(setMethod)) { nullabilityInfo.WriteState = NullabilityState.Unknown; } CheckNullabilityAttributes(nullabilityInfo, setMethod.GetParameters()[0].GetCustomAttributesData()); } else { nullabilityInfo.WriteState = NullabilityState.Unknown; } return nullabilityInfo; } private bool IsPrivateOrInternalMethodAndAnnotationDisabled(MethodInfo 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) { if ((object)eventInfo == null) { throw new ArgumentNullException("eventInfo"); } EnsureIsSupported(); return GetNullabilityInfo(eventInfo, eventInfo.EventHandlerType, eventInfo.GetCustomAttributesData()); } public NullabilityInfo Create(FieldInfo fieldInfo) { if ((object)fieldInfo == null) { throw new ArgumentNullException("fieldInfo"); } EnsureIsSupported(); if (IsPrivateOrInternalFieldAndAnnotationDisabled(fieldInfo)) { return new NullabilityInfo(fieldInfo.FieldType, NullabilityState.Unknown, NullabilityState.Unknown, null, Array.Empty()); } IList customAttributesData = fieldInfo.GetCustomAttributesData(); NullabilityInfo nullabilityInfo = GetNullabilityInfo(fieldInfo, fieldInfo.FieldType, customAttributesData); CheckNullabilityAttributes(nullabilityInfo, customAttributesData); return nullabilityInfo; } private static void EnsureIsSupported() { if (!IsSupported) { throw new InvalidOperationException(SR.NullabilityInfoContext_NotSupported); } } 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 NotAnnotatedStatus PopulateAnnotationInfo(IList customAttributes) { System.Runtime.CompilerServices.Unsafe.SkipInit(out bool flag); 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, IList customAttributes) { return GetNullabilityInfo(memberInfo, type, customAttributes, 0); } private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, IList customAttributes, int index) { NullabilityState state = NullabilityState.Unknown; NullabilityInfo elementType = null; NullabilityInfo[] array = Array.Empty(); Type type2 = type; if (type.IsValueType) { type2 = Nullable.GetUnderlyingType(type); if (type2 != null) { state = NullabilityState.Nullable; } else { type2 = type; state = NullabilityState.NotNull; } } else { if (!ParseNullableState(customAttributes, index, ref state)) { state = GetNullableContext(memberInfo); } if (type.IsArray) { elementType = GetNullabilityInfo(memberInfo, type.GetElementType(), customAttributes, index + 1); } } if (type2.IsGenericType) { Type[] genericArguments = type2.GetGenericArguments(); array = new NullabilityInfo[genericArguments.Length]; int i = 0; int num = 0; for (; i < genericArguments.Length; i++) { Type type3 = Nullable.GetUnderlyingType(genericArguments[i]) ?? genericArguments[i]; if (!type3.IsValueType || type3.IsGenericType) { num++; } array[i] = GetNullabilityInfo(memberInfo, genericArguments[i], customAttributes, index + num); } } NullabilityInfo nullabilityInfo = new NullabilityInfo(type, state, state, elementType, array); if (!type.IsValueType && state != 0) { TryLoadGenericMetaTypeNullability(memberInfo, nullabilityInfo); } return nullabilityInfo; } private static bool ParseNullableState(IList customAttributes, int index, ref NullabilityState state) { foreach (CustomAttributeData customAttribute in customAttributes) { if (customAttribute.AttributeType.Name == "NullableAttribute" && customAttribute.AttributeType.Namespace == "System.Runtime.CompilerServices" && customAttribute.ConstructorArguments.Count == 1) { object value = customAttribute.ConstructorArguments[0].Value; if (value is byte b) { state = TranslateByte(b); return true; } if (value is ReadOnlyCollection readOnlyCollection && index < readOnlyCollection.Count) { object value2 = readOnlyCollection[index].Value; if (value2 is byte) { byte b2 = (byte)value2; state = TranslateByte(b2); return true; } break; } break; } } return false; } 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); } } private static MemberInfo GetMemberMetadataDefinition(MemberInfo member) { Type declaringType = member.DeclaringType; if (declaringType != null && declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition) { return declaringType.GetGenericTypeDefinition().GetMemberWithSameMetadataDefinitionAs(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).GetParameters()[0].ParameterType; } private void CheckGenericParameters(NullabilityInfo nullability, MemberInfo metaMember, Type metaType) { if (metaType.IsGenericParameter) { NullabilityState state = nullability.ReadState; if (state == NullabilityState.NotNull && !ParseNullableState(metaType.GetCustomAttributesData(), 0, ref state)) { state = GetNullableContext(metaType); } nullability.ReadState = state; nullability.WriteState = state; } else { if (!metaType.ContainsGenericParameters) { return; } if (nullability.GenericTypeArguments.Length != 0) { Type[] genericArguments = metaType.GetGenericArguments(); for (int i = 0; i < genericArguments.Length; i++) { if (genericArguments[i].IsGenericParameter) { NullabilityInfo nullabilityInfo = GetNullabilityInfo(metaMember, genericArguments[i], genericArguments[i].GetCustomAttributesData(), i + 1); nullability.GenericTypeArguments[i].ReadState = nullabilityInfo.ReadState; nullability.GenericTypeArguments[i].WriteState = nullabilityInfo.WriteState; } else { UpdateGenericArrayElements(nullability.GenericTypeArguments[i].ElementType, metaMember, genericArguments[i]); } } } else { UpdateGenericArrayElements(nullability.ElementType, metaMember, metaType); } } } private void UpdateGenericArrayElements(NullabilityInfo elementState, MemberInfo metaMember, Type metaType) { if (metaType.IsArray && elementState != null && metaType.GetElementType().IsGenericParameter) { Type elementType = metaType.GetElementType(); NullabilityInfo nullabilityInfo = GetNullabilityInfo(metaMember, elementType, elementType.GetCustomAttributesData(), 0); elementState.ReadState = nullabilityInfo.ReadState; elementState.WriteState = nullabilityInfo.WriteState; } } 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, }; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)] public sealed class ObfuscateAssemblyAttribute : Attribute { public bool AssemblyIsPrivate { get; } public bool StripAfterObfuscation { get; set; } = true; public ObfuscateAssemblyAttribute(bool assemblyIsPrivate) { AssemblyIsPrivate = assemblyIsPrivate; } } [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate, AllowMultiple = true, Inherited = false)] public sealed class ObfuscationAttribute : Attribute { public bool StripAfterObfuscation { get; set; } = true; public bool Exclude { get; set; } = true; public bool ApplyToMembers { get; set; } = true; public string? Feature { get; set; } = "all"; } [Flags] public enum ParameterAttributes { None = 0, In = 1, Out = 2, Lcid = 4, Retval = 8, Optional = 0x10, HasDefault = 0x1000, HasFieldMarshal = 0x2000, Reserved3 = 0x4000, Reserved4 = 0x8000, ReservedMask = 0xF000 } public class ParameterInfo : ICustomAttributeProvider, IObjectReference { protected ParameterAttributes AttrsImpl; protected Type? ClassImpl; protected object? DefaultValueImpl; protected MemberInfo MemberImpl; protected string? NameImpl; protected int PositionImpl; public virtual ParameterAttributes Attributes => AttrsImpl; public virtual MemberInfo Member => MemberImpl; public virtual string? Name => NameImpl; public virtual Type ParameterType => ClassImpl; public virtual int Position => PositionImpl; public bool IsIn => (Attributes & ParameterAttributes.In) != 0; public bool IsLcid => (Attributes & ParameterAttributes.Lcid) != 0; public bool IsOptional => (Attributes & ParameterAttributes.Optional) != 0; public bool IsOut => (Attributes & ParameterAttributes.Out) != 0; public bool IsRetval => (Attributes & ParameterAttributes.Retval) != 0; public virtual object? DefaultValue { get { throw NotImplemented.ByDesign; } } public virtual object? RawDefaultValue { get { throw NotImplemented.ByDesign; } } public virtual bool HasDefaultValue { get { throw NotImplemented.ByDesign; } } public virtual IEnumerable CustomAttributes => GetCustomAttributesData(); public virtual int MetadataToken => 134217728; protected ParameterInfo() { } public virtual bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } return false; } public virtual IList GetCustomAttributesData() { throw NotImplemented.ByDesign; } public virtual object[] GetCustomAttributes(bool inherit) { return Array.Empty(); } public virtual object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } return Array.Empty(); } public virtual Type[] GetOptionalCustomModifiers() { return Type.EmptyTypes; } public virtual Type[] GetRequiredCustomModifiers() { return Type.EmptyTypes; } public object GetRealObject(StreamingContext context) { if (MemberImpl == null) { throw new SerializationException(SR.Serialization_InsufficientState); } switch (MemberImpl.MemberType) { case MemberTypes.Constructor: case MemberTypes.Method: { if (PositionImpl == -1) { if (MemberImpl.MemberType == MemberTypes.Method) { return ((MethodInfo)MemberImpl).ReturnParameter; } throw new SerializationException(SR.Serialization_BadParameterInfo); } ParameterInfo[] indexParameters = ((MethodBase)MemberImpl).GetParametersNoCopy(); if (indexParameters != null && PositionImpl < indexParameters.Length) { return indexParameters[PositionImpl]; } throw new SerializationException(SR.Serialization_BadParameterInfo); } case MemberTypes.Property: { ParameterInfo[] indexParameters = ((PropertyInfo)MemberImpl).GetIndexParameters(); if (indexParameters != null && PositionImpl > -1 && PositionImpl < indexParameters.Length) { return indexParameters[PositionImpl]; } throw new SerializationException(SR.Serialization_BadParameterInfo); } default: throw new SerializationException(SR.Serialization_NoParameterInfo); } } public override string ToString() { string text = ParameterType.FormatTypeName(); string name = Name; if (name != null) { return text + " " + name; } return text; } } public readonly struct ParameterModifier { private readonly bool[] _byRef; public bool this[int index] { get { return _byRef[index]; } set { _byRef[index] = value; } } internal bool[] IsByRefArray => _byRef; public ParameterModifier(int parameterCount) { if (parameterCount <= 0) { throw new ArgumentException(SR.Arg_ParmArraySize); } _byRef = new bool[parameterCount]; } } [CLSCompliant(false)] public sealed class Pointer : ISerializable { private unsafe readonly void* _ptr; private readonly Type _ptrType; private unsafe Pointer(void* ptr, Type ptrType) { _ptr = ptr; _ptrType = ptrType; } public unsafe static object Box(void* ptr, Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (!type.IsPointer) { throw new ArgumentException(SR.Arg_MustBePointer, "ptr"); } if (!type.IsRuntimeImplemented()) { throw new ArgumentException(SR.Arg_MustBeType, "ptr"); } return new Pointer(ptr, type); } public unsafe static void* Unbox(object ptr) { if (!(ptr is Pointer)) { throw new ArgumentException(SR.Arg_MustBePointer, "ptr"); } return ((Pointer)ptr)._ptr; } public unsafe override bool Equals([NotNullWhen(true)] object? obj) { if (obj is Pointer pointer) { return _ptr == pointer._ptr; } return false; } public unsafe override int GetHashCode() { UIntPtr ptr = (UIntPtr)_ptr; return ptr.GetHashCode(); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } internal Type GetPointerType() { return _ptrType; } internal unsafe IntPtr GetPointerValue() { return (IntPtr)_ptr; } } [Flags] public enum PortableExecutableKinds { NotAPortableExecutableImage = 0, ILOnly = 1, Required32Bit = 2, PE32Plus = 4, Unmanaged32Bit = 8, Preferred32Bit = 0x10 } public enum ProcessorArchitecture { None, MSIL, X86, IA64, Amd64, Arm } [Flags] public enum PropertyAttributes { None = 0, SpecialName = 0x200, RTSpecialName = 0x400, HasDefault = 0x1000, Reserved2 = 0x2000, Reserved3 = 0x4000, Reserved4 = 0x8000, ReservedMask = 0xF400 } public abstract class PropertyInfo : MemberInfo { public override MemberTypes MemberType => MemberTypes.Property; public abstract Type PropertyType { get; } public abstract PropertyAttributes Attributes { get; } public bool IsSpecialName => (Attributes & PropertyAttributes.SpecialName) != 0; public abstract bool CanRead { get; } public abstract bool CanWrite { get; } public virtual MethodInfo? GetMethod => GetGetMethod(nonPublic: true); public virtual MethodInfo? SetMethod => GetSetMethod(nonPublic: true); public abstract ParameterInfo[] GetIndexParameters(); public MethodInfo[] GetAccessors() { return GetAccessors(nonPublic: false); } public abstract MethodInfo[] GetAccessors(bool nonPublic); public MethodInfo? GetGetMethod() { return GetGetMethod(nonPublic: false); } public abstract MethodInfo? GetGetMethod(bool nonPublic); public MethodInfo? GetSetMethod() { return GetSetMethod(nonPublic: false); } public abstract MethodInfo? GetSetMethod(bool nonPublic); public virtual Type[] GetOptionalCustomModifiers() { return Type.EmptyTypes; } public virtual Type[] GetRequiredCustomModifiers() { return Type.EmptyTypes; } [DebuggerHidden] [DebuggerStepThrough] public object? GetValue(object? obj) { return GetValue(obj, null); } [DebuggerHidden] [DebuggerStepThrough] public virtual object? GetValue(object? obj, object?[]? index) { return GetValue(obj, BindingFlags.Default, null, index, null); } public abstract object? GetValue(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture); public virtual object? GetConstantValue() { throw NotImplemented.ByDesign; } public virtual object? GetRawConstantValue() { throw NotImplemented.ByDesign; } [DebuggerHidden] [DebuggerStepThrough] public void SetValue(object? obj, object? value) { SetValue(obj, value, null); } [DebuggerHidden] [DebuggerStepThrough] public virtual void SetValue(object? obj, object? value, object?[]? index) { SetValue(obj, value, BindingFlags.Default, null, index, null); } public abstract void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture); public override bool Equals(object? obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(PropertyInfo? left, PropertyInfo? right) { if ((object)right == null) { if ((object)left != null) { return false; } return true; } if ((object)left == right) { return true; } return left?.Equals(right) ?? false; } public static bool operator !=(PropertyInfo? left, PropertyInfo? right) { return !(left == right); } } public abstract class ReflectionContext { public abstract Assembly MapAssembly(Assembly assembly); public abstract TypeInfo MapType(TypeInfo type); public virtual TypeInfo GetTypeForObject(object value) { if (value == null) { throw new ArgumentNullException("value"); } return MapType(value.GetType().GetTypeInfo()); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class ReflectionTypeLoadException : SystemException, ISerializable { public Type?[] Types { get; } public Exception?[] LoaderExceptions { get; } public override string Message => CreateString(isMessage: true); public ReflectionTypeLoadException(Type?[]? classes, Exception?[]? exceptions) : this(classes, exceptions, null) { } public ReflectionTypeLoadException(Type?[]? classes, Exception?[]? exceptions, string? message) : base(message) { Types = classes ?? Type.EmptyTypes; LoaderExceptions = exceptions ?? Array.Empty(); base.HResult = -2146232830; } private ReflectionTypeLoadException(SerializationInfo info, StreamingContext context) : base(info, context) { Types = Type.EmptyTypes; LoaderExceptions = ((Exception[])info.GetValue("Exceptions", typeof(Exception[]))) ?? Array.Empty(); } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Types", null, typeof(Type[])); info.AddValue("Exceptions", LoaderExceptions, typeof(Exception[])); } public override string ToString() { return CreateString(isMessage: false); } private string CreateString(bool isMessage) { string text = (isMessage ? base.Message : base.ToString()); Exception[] loaderExceptions = LoaderExceptions; if (loaderExceptions.Length == 0) { return text; } StringBuilder stringBuilder = new StringBuilder(text); Exception[] array = loaderExceptions; foreach (Exception ex in array) { if (ex != null) { stringBuilder.AppendLine().Append(isMessage ? ex.Message : ex.ToString()); } } return stringBuilder.ToString(); } } [Flags] public enum ResourceAttributes { Public = 1, Private = 2 } [Flags] public enum ResourceLocation { ContainedInAnotherAssembly = 2, ContainedInManifestFile = 4, Embedded = 1 } public static class RuntimeReflectionExtensions { public static IEnumerable GetRuntimeFields([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] this Type type) { if (type == null) { throw new ArgumentNullException("type"); } return type.GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } public static IEnumerable GetRuntimeMethods([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] this Type type) { if (type == null) { throw new ArgumentNullException("type"); } return type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } public static IEnumerable GetRuntimeProperties([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] this Type type) { if (type == null) { throw new ArgumentNullException("type"); } return type.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } public static IEnumerable GetRuntimeEvents([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] this Type type) { if (type == null) { throw new ArgumentNullException("type"); } return type.GetEvents(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } public static FieldInfo? GetRuntimeField([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] this Type type, string name) { if (type == null) { throw new ArgumentNullException("type"); } return type.GetField(name); } public static MethodInfo? GetRuntimeMethod([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] this Type type, string name, Type[] parameters) { if (type == null) { throw new ArgumentNullException("type"); } return type.GetMethod(name, parameters); } public static PropertyInfo? GetRuntimeProperty([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] this Type type, string name) { if (type == null) { throw new ArgumentNullException("type"); } return type.GetProperty(name); } public static EventInfo? GetRuntimeEvent([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] this Type type, string name) { if (type == null) { throw new ArgumentNullException("type"); } return type.GetEvent(name); } public static MethodInfo? GetRuntimeBaseDefinition(this MethodInfo method) { if (method == null) { throw new ArgumentNullException("method"); } return method.GetBaseDefinition(); } public static InterfaceMapping GetRuntimeInterfaceMap(this TypeInfo typeInfo, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type interfaceType) { if (typeInfo == null) { throw new ArgumentNullException("typeInfo"); } return typeInfo.GetInterfaceMap(interfaceType); } public static MethodInfo GetMethodInfo(this Delegate del) { if ((object)del == null) { throw new ArgumentNullException("del"); } return del.Method; } } internal sealed class SignatureArrayType : SignatureHasElementType { private readonly int _rank; private readonly bool _isMultiDim; public sealed override bool IsSZArray => !_isMultiDim; public sealed override bool IsVariableBoundArray => _isMultiDim; protected sealed override string Suffix { get { if (!_isMultiDim) { return "[]"; } if (_rank == 1) { return "[*]"; } return "[" + new string(',', _rank - 1) + "]"; } } internal SignatureArrayType(SignatureType elementType, int rank, bool isMultiDim) : base(elementType) { _rank = rank; _isMultiDim = isMultiDim; } protected sealed override bool IsArrayImpl() { return true; } protected sealed override bool IsByRefImpl() { return false; } protected sealed override bool IsPointerImpl() { return false; } public sealed override int GetArrayRank() { return _rank; } } internal sealed class SignatureByRefType : SignatureHasElementType { public sealed override bool IsSZArray => false; public sealed override bool IsVariableBoundArray => false; protected sealed override string Suffix => "&"; internal SignatureByRefType(SignatureType elementType) : base(elementType) { } protected sealed override bool IsArrayImpl() { return false; } protected sealed override bool IsByRefImpl() { return true; } protected sealed override bool IsPointerImpl() { return false; } public sealed override int GetArrayRank() { throw new ArgumentException(SR.Argument_HasToBeArrayClass); } } internal sealed class SignatureConstructedGenericType : SignatureType { private readonly Type _genericTypeDefinition; private readonly Type[] _genericTypeArguments; public sealed override bool IsTypeDefinition => false; public sealed override bool IsGenericTypeDefinition => false; public sealed override bool IsByRefLike => _genericTypeDefinition.IsByRefLike; public sealed override bool IsSZArray => false; public sealed override bool IsVariableBoundArray => false; public sealed override bool IsConstructedGenericType => true; public sealed override bool IsGenericParameter => false; public sealed override bool IsGenericTypeParameter => false; public sealed override bool IsGenericMethodParameter => false; public sealed override bool ContainsGenericParameters { get { for (int i = 0; i < _genericTypeArguments.Length; i++) { if (_genericTypeArguments[i].ContainsGenericParameters) { return true; } } return false; } } internal sealed override SignatureType ElementType => null; public sealed override Type[] GenericTypeArguments => (Type[])_genericTypeArguments.Clone(); public sealed override int GenericParameterPosition { get { throw new InvalidOperationException(SR.Arg_NotGenericParameter); } } public sealed override string Name => _genericTypeDefinition.Name; public sealed override string Namespace => _genericTypeDefinition.Namespace; internal SignatureConstructedGenericType(Type genericTypeDefinition, Type[] typeArguments) { if ((object)genericTypeDefinition == null) { throw new ArgumentNullException("genericTypeDefinition"); } if (typeArguments == null) { throw new ArgumentNullException("typeArguments"); } typeArguments = (Type[])typeArguments.Clone(); for (int i = 0; i < typeArguments.Length; i++) { if ((object)typeArguments[i] == null) { throw new ArgumentNullException("typeArguments"); } } _genericTypeDefinition = genericTypeDefinition; _genericTypeArguments = typeArguments; } protected sealed override bool HasElementTypeImpl() { return false; } protected sealed override bool IsArrayImpl() { return false; } protected sealed override bool IsByRefImpl() { return false; } protected sealed override bool IsPointerImpl() { return false; } public sealed override int GetArrayRank() { throw new ArgumentException(SR.Argument_HasToBeArrayClass); } public sealed override Type GetGenericTypeDefinition() { return _genericTypeDefinition; } public sealed override Type[] GetGenericArguments() { return GenericTypeArguments; } public sealed override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(_genericTypeDefinition.ToString()); stringBuilder.Append('['); for (int i = 0; i < _genericTypeArguments.Length; i++) { if (i != 0) { stringBuilder.Append(','); } stringBuilder.Append(_genericTypeArguments[i].ToString()); } stringBuilder.Append(']'); return stringBuilder.ToString(); } } internal sealed class SignatureGenericMethodParameterType : SignatureGenericParameterType { public sealed override bool IsGenericTypeParameter => false; public sealed override bool IsGenericMethodParameter => true; public sealed override string Name => "!!" + GenericParameterPosition; internal SignatureGenericMethodParameterType(int position) : base(position) { } } internal abstract class SignatureGenericParameterType : SignatureType { private readonly int _position; public sealed override bool IsTypeDefinition => false; public sealed override bool IsGenericTypeDefinition => false; public sealed override bool IsByRefLike => false; public sealed override bool IsSZArray => false; public sealed override bool IsVariableBoundArray => false; public sealed override bool IsConstructedGenericType => false; public sealed override bool IsGenericParameter => true; public abstract override bool IsGenericMethodParameter { get; } public sealed override bool ContainsGenericParameters => true; internal sealed override SignatureType ElementType => null; public sealed override Type[] GenericTypeArguments => Type.EmptyTypes; public sealed override int GenericParameterPosition => _position; public abstract override string Name { get; } public sealed override string Namespace => null; protected SignatureGenericParameterType(int position) { _position = position; } protected sealed override bool HasElementTypeImpl() { return false; } protected sealed override bool IsArrayImpl() { return false; } protected sealed override bool IsByRefImpl() { return false; } protected sealed override bool IsPointerImpl() { return false; } public sealed override int GetArrayRank() { throw new ArgumentException(SR.Argument_HasToBeArrayClass); } public sealed override Type GetGenericTypeDefinition() { throw new InvalidOperationException(SR.InvalidOperation_NotGenericType); } public sealed override Type[] GetGenericArguments() { return Type.EmptyTypes; } public sealed override string ToString() { return Name; } } internal abstract class SignatureHasElementType : SignatureType { private readonly SignatureType _elementType; public sealed override bool IsTypeDefinition => false; public sealed override bool IsGenericTypeDefinition => false; public sealed override bool IsByRefLike => false; public abstract override bool IsSZArray { get; } public abstract override bool IsVariableBoundArray { get; } public sealed override bool IsConstructedGenericType => false; public sealed override bool IsGenericParameter => false; public sealed override bool IsGenericTypeParameter => false; public sealed override bool IsGenericMethodParameter => false; public sealed override bool ContainsGenericParameters => _elementType.ContainsGenericParameters; internal sealed override SignatureType ElementType => _elementType; public sealed override Type[] GenericTypeArguments => Type.EmptyTypes; public sealed override int GenericParameterPosition { get { throw new InvalidOperationException(SR.Arg_NotGenericParameter); } } public sealed override string Name => _elementType.Name + Suffix; public sealed override string Namespace => _elementType.Namespace; protected abstract string Suffix { get; } protected SignatureHasElementType(SignatureType elementType) { _elementType = elementType; } protected sealed override bool HasElementTypeImpl() { return true; } protected abstract override bool IsArrayImpl(); protected abstract override bool IsByRefImpl(); protected abstract override bool IsPointerImpl(); public abstract override int GetArrayRank(); public sealed override Type GetGenericTypeDefinition() { throw new InvalidOperationException(SR.InvalidOperation_NotGenericType); } public sealed override Type[] GetGenericArguments() { return Type.EmptyTypes; } public sealed override string ToString() { return _elementType.ToString() + Suffix; } } internal sealed class SignaturePointerType : SignatureHasElementType { public sealed override bool IsSZArray => false; public sealed override bool IsVariableBoundArray => false; protected sealed override string Suffix => "*"; internal SignaturePointerType(SignatureType elementType) : base(elementType) { } protected sealed override bool IsArrayImpl() { return false; } protected sealed override bool IsByRefImpl() { return false; } protected sealed override bool IsPointerImpl() { return true; } public sealed override int GetArrayRank() { throw new ArgumentException(SR.Argument_HasToBeArrayClass); } } internal abstract class SignatureType : Type { public sealed override bool IsSignatureType => true; public abstract override bool IsTypeDefinition { get; } public abstract override bool IsSZArray { get; } public abstract override bool IsVariableBoundArray { get; } public abstract override bool IsByRefLike { get; } public sealed override bool IsGenericType { get { if (!IsGenericTypeDefinition) { return IsConstructedGenericType; } return true; } } public abstract override bool IsGenericTypeDefinition { get; } public abstract override bool IsConstructedGenericType { get; } public abstract override bool IsGenericParameter { get; } public abstract override bool IsGenericTypeParameter { get; } public abstract override bool IsGenericMethodParameter { get; } public abstract override bool ContainsGenericParameters { get; } public sealed override MemberTypes MemberType => MemberTypes.TypeInfo; public abstract override Type[] GenericTypeArguments { get; } public abstract override int GenericParameterPosition { get; } internal abstract SignatureType ElementType { get; } public sealed override Type UnderlyingSystemType => this; public abstract override string Name { get; } public abstract override string Namespace { get; } public sealed override string FullName => null; public sealed override string AssemblyQualifiedName => null; public sealed override Assembly Assembly { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override Module Module { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override Type ReflectedType { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override Type BaseType { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override int MetadataToken { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override Type DeclaringType { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override MethodBase DeclaringMethod { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override GenericParameterAttributes GenericParameterAttributes { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override Guid GUID { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override IEnumerable CustomAttributes { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override bool IsEnum { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override bool IsSecurityCritical { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override bool IsSecuritySafeCritical { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override bool IsSecurityTransparent { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override bool IsSerializable { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override StructLayoutAttribute StructLayoutAttribute { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } public sealed override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(SR.NotSupported_SignatureType); } } protected abstract override bool HasElementTypeImpl(); protected abstract override bool IsArrayImpl(); protected abstract override bool IsByRefImpl(); protected abstract override bool IsPointerImpl(); public sealed override Type MakeArrayType() { return new SignatureArrayType(this, 1, isMultiDim: false); } public sealed override Type MakeArrayType(int rank) { if (rank <= 0) { throw new IndexOutOfRangeException(); } return new SignatureArrayType(this, rank, isMultiDim: true); } public sealed override Type MakeByRefType() { return new SignatureByRefType(this); } public sealed override Type MakePointerType() { return new SignaturePointerType(this); } [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public sealed override Type MakeGenericType(params Type[] typeArguments) { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override Type GetElementType() { return ElementType; } public abstract override int GetArrayRank(); public abstract override Type GetGenericTypeDefinition(); public abstract override Type[] GetGenericArguments(); public abstract override string ToString(); [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public sealed override Type[] GetInterfaces() { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override bool IsAssignableFrom([NotNullWhen(true)] Type c) { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override Type[] GetGenericParameterConstraints() { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override bool IsEnumDefined(object value) { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override string GetEnumName(object value) { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override string[] GetEnumNames() { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override Type GetEnumUnderlyingType() { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override Array GetEnumValues() { throw new NotSupportedException(SR.NotSupported_SignatureType); } protected sealed override TypeCode GetTypeCodeImpl() { throw new NotSupportedException(SR.NotSupported_SignatureType); } protected sealed override TypeAttributes GetAttributeFlagsImpl() { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] public sealed override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public sealed override EventInfo GetEvent(string name, BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public sealed override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public sealed override FieldInfo GetField(string name, BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public sealed override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public sealed override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public sealed override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public sealed override Type GetNestedType(string name, BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public sealed override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] public sealed override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public sealed override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] protected sealed override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] protected sealed override MethodInfo GetMethodImpl(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] protected sealed override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public sealed override MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public sealed override MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public sealed override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicEvents)] public sealed override MemberInfo[] GetDefaultMembers() { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] public sealed override EventInfo[] GetEvents() { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override IList GetCustomAttributesData() { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2063:UnrecognizedReflectionPattern", Justification = "Linker doesn't recognize always throwing method. https://github.com/mono/linker/issues/2025")] [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public sealed override Type GetInterface(string name, bool ignoreCase) { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] protected sealed override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(SR.NotSupported_SignatureType); } protected sealed override bool IsCOMObjectImpl() { throw new NotSupportedException(SR.NotSupported_SignatureType); } protected sealed override bool IsPrimitiveImpl() { throw new NotSupportedException(SR.NotSupported_SignatureType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public sealed override Type[] FindInterfaces(TypeFilter filter, object filterCriteria) { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type interfaceType) { throw new NotSupportedException(SR.NotSupported_SignatureType); } protected sealed override bool IsContextfulImpl() { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override bool IsEquivalentTo([NotNullWhen(true)] Type other) { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override bool IsInstanceOfType([NotNullWhen(true)] object o) { throw new NotSupportedException(SR.NotSupported_SignatureType); } protected sealed override bool IsMarshalByRefImpl() { throw new NotSupportedException(SR.NotSupported_SignatureType); } public sealed override bool IsSubclassOf(Type c) { throw new NotSupportedException(SR.NotSupported_SignatureType); } protected sealed override bool IsValueTypeImpl() { throw new NotSupportedException(SR.NotSupported_SignatureType); } } internal static class SignatureTypeExtensions { public static bool MatchesParameterTypeExactly(this Type pattern, ParameterInfo parameter) { if (pattern is SignatureType pattern2) { return pattern2.MatchesExactly(parameter.ParameterType); } return (object)pattern == parameter.ParameterType; } internal static bool MatchesExactly(this SignatureType pattern, Type actual) { if (pattern.IsSZArray) { if (actual.IsSZArray) { return pattern.ElementType.MatchesExactly(actual.GetElementType()); } return false; } if (pattern.IsVariableBoundArray) { if (actual.IsVariableBoundArray && pattern.GetArrayRank() == actual.GetArrayRank()) { return pattern.ElementType.MatchesExactly(actual.GetElementType()); } return false; } if (pattern.IsByRef) { if (actual.IsByRef) { return pattern.ElementType.MatchesExactly(actual.GetElementType()); } return false; } if (pattern.IsPointer) { if (actual.IsPointer) { return pattern.ElementType.MatchesExactly(actual.GetElementType()); } return false; } if (pattern.IsConstructedGenericType) { if (!actual.IsConstructedGenericType) { return false; } if (!(pattern.GetGenericTypeDefinition() == actual.GetGenericTypeDefinition())) { return false; } Type[] genericTypeArguments = pattern.GenericTypeArguments; Type[] genericTypeArguments2 = actual.GenericTypeArguments; int num = genericTypeArguments.Length; if (num != genericTypeArguments2.Length) { return false; } for (int i = 0; i < num; i++) { Type type = genericTypeArguments[i]; if (type is SignatureType pattern2) { if (!pattern2.MatchesExactly(genericTypeArguments2[i])) { return false; } } else if (type != genericTypeArguments2[i]) { return false; } } return true; } if (pattern.IsGenericMethodParameter) { if (!actual.IsGenericMethodParameter) { return false; } if (pattern.GenericParameterPosition != actual.GenericParameterPosition) { return false; } return true; } return false; } internal static Type TryResolveAgainstGenericMethod(this SignatureType signatureType, MethodInfo genericMethod) { return signatureType.TryResolve(genericMethod.GetGenericArguments()); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Used to find matching method overloads. Only used for assignability checks.")] private static Type TryResolve(this SignatureType signatureType, Type[] genericMethodParameters) { if (signatureType.IsSZArray) { Type type = signatureType.ElementType.TryResolve(genericMethodParameters); if ((object)type == null) { return null; } return type.TryMakeArrayType(); } if (signatureType.IsVariableBoundArray) { Type type2 = signatureType.ElementType.TryResolve(genericMethodParameters); if ((object)type2 == null) { return null; } return type2.TryMakeArrayType(signatureType.GetArrayRank()); } if (signatureType.IsByRef) { Type type3 = signatureType.ElementType.TryResolve(genericMethodParameters); if ((object)type3 == null) { return null; } return type3.TryMakeByRefType(); } if (signatureType.IsPointer) { Type type4 = signatureType.ElementType.TryResolve(genericMethodParameters); if ((object)type4 == null) { return null; } return type4.TryMakePointerType(); } if (signatureType.IsConstructedGenericType) { Type[] genericTypeArguments = signatureType.GenericTypeArguments; int num = genericTypeArguments.Length; Type[] array = new Type[num]; for (int i = 0; i < num; i++) { Type type5 = genericTypeArguments[i]; if (type5 is SignatureType signatureType2) { array[i] = signatureType2.TryResolve(genericMethodParameters); if (array[i] == null) { return null; } } else { array[i] = type5; } } return signatureType.GetGenericTypeDefinition().TryMakeGenericType(array); } if (signatureType.IsGenericMethodParameter) { int genericParameterPosition = signatureType.GenericParameterPosition; if (genericParameterPosition >= genericMethodParameters.Length) { return null; } return genericMethodParameters[genericParameterPosition]; } return null; } private static Type TryMakeArrayType(this Type type) { try { return type.MakeArrayType(); } catch { return null; } } private static Type TryMakeArrayType(this Type type, int rank) { try { return type.MakeArrayType(rank); } catch { return null; } } private static Type TryMakeByRefType(this Type type) { try { return type.MakeByRefType(); } catch { return null; } } private static Type TryMakePointerType(this Type type) { try { return type.MakePointerType(); } catch { return null; } } [RequiresUnreferencedCode("Wrapper around MakeGenericType which itself has RequiresUnreferencedCode")] private static Type TryMakeGenericType(this Type type, Type[] instantiation) { try { return type.MakeGenericType(instantiation); } catch { return null; } } } [Obsolete("Strong name signing is not supported and throws PlatformNotSupportedException.", DiagnosticId = "SYSLIB0017", UrlFormat = "https://aka.ms/dotnet-warnings/{0}")] public class StrongNameKeyPair : IDeserializationCallback, ISerializable { public byte[] PublicKey { get { throw new PlatformNotSupportedException(SR.PlatformNotSupported_StrongNameSigning); } } public StrongNameKeyPair(FileStream keyPairFile) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_StrongNameSigning); } public StrongNameKeyPair(byte[] keyPairArray) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_StrongNameSigning); } protected StrongNameKeyPair(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public StrongNameKeyPair(string keyPairContainer) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_StrongNameSigning); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } void IDeserializationCallback.OnDeserialization(object sender) { throw new PlatformNotSupportedException(); } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class TargetException : ApplicationException { public TargetException() : this(null) { } public TargetException(string? message) : this(message, null) { } public TargetException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146232829; } protected TargetException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class TargetInvocationException : ApplicationException { public TargetInvocationException(Exception? inner) : base(SR.Arg_TargetInvocationException, inner) { base.HResult = -2146232828; } public TargetInvocationException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2146232828; } private TargetInvocationException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Serializable] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class TargetParameterCountException : ApplicationException { public TargetParameterCountException() : base(SR.Arg_TargetParameterCountException) { base.HResult = -2147352562; } public TargetParameterCountException(string? message) : base(message) { base.HResult = -2147352562; } public TargetParameterCountException(string? message, Exception? inner) : base(message, inner) { base.HResult = -2147352562; } private TargetParameterCountException(SerializationInfo info, StreamingContext context) : base(info, context) { } } [Flags] public enum TypeAttributes { VisibilityMask = 7, NotPublic = 0, Public = 1, NestedPublic = 2, NestedPrivate = 3, NestedFamily = 4, NestedAssembly = 5, NestedFamANDAssem = 6, NestedFamORAssem = 7, LayoutMask = 0x18, AutoLayout = 0, SequentialLayout = 8, ExplicitLayout = 0x10, ClassSemanticsMask = 0x20, Class = 0, Interface = 0x20, Abstract = 0x80, Sealed = 0x100, SpecialName = 0x400, Import = 0x1000, Serializable = 0x2000, WindowsRuntime = 0x4000, StringFormatMask = 0x30000, AnsiClass = 0, UnicodeClass = 0x10000, AutoClass = 0x20000, CustomFormatClass = 0x30000, CustomFormatMask = 0xC00000, BeforeFieldInit = 0x100000, RTSpecialName = 0x800, HasSecurity = 0x40000, ReservedMask = 0x40800 } public class TypeDelegator : TypeInfo { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] protected Type typeImpl; public override Guid GUID => typeImpl.GUID; public override int MetadataToken => typeImpl.MetadataToken; public override Module Module => typeImpl.Module; public override Assembly Assembly => typeImpl.Assembly; public override RuntimeTypeHandle TypeHandle => typeImpl.TypeHandle; public override string Name => typeImpl.Name; public override string? FullName => typeImpl.FullName; public override string? Namespace => typeImpl.Namespace; public override string? AssemblyQualifiedName => typeImpl.AssemblyQualifiedName; public override Type? BaseType => typeImpl.BaseType; public override bool IsTypeDefinition => typeImpl.IsTypeDefinition; public override bool IsSZArray => typeImpl.IsSZArray; public override bool IsVariableBoundArray => typeImpl.IsVariableBoundArray; public override bool IsGenericTypeParameter => typeImpl.IsGenericTypeParameter; public override bool IsGenericMethodParameter => typeImpl.IsGenericMethodParameter; public override bool IsByRefLike => typeImpl.IsByRefLike; public override bool IsConstructedGenericType => typeImpl.IsConstructedGenericType; public override bool IsCollectible => typeImpl.IsCollectible; public override Type UnderlyingSystemType => typeImpl.UnderlyingSystemType; public override bool IsAssignableFrom([NotNullWhen(true)] TypeInfo? typeInfo) { if (typeInfo == null) { return false; } return IsAssignableFrom(typeInfo.AsType()); } protected TypeDelegator() { } public TypeDelegator([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type delegatingType) { if ((object)delegatingType == null) { throw new ArgumentNullException("delegatingType"); } typeImpl = delegatingType; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public override object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) { return typeImpl.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] protected override ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { return typeImpl.GetConstructor(bindingAttr, binder, callConvention, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return typeImpl.GetConstructors(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { if (types == null) { return typeImpl.GetMethod(name, bindingAttr); } return typeImpl.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { return typeImpl.GetMethods(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { return typeImpl.GetField(name, bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo[] GetFields(BindingFlags bindingAttr) { return typeImpl.GetFields(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type? GetInterface(string name, bool ignoreCase) { return typeImpl.GetInterface(name, ignoreCase); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type[] GetInterfaces() { return typeImpl.GetInterfaces(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo? GetEvent(string name, BindingFlags bindingAttr) { return typeImpl.GetEvent(name, bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] public override EventInfo[] GetEvents() { return typeImpl.GetEvents(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] protected override PropertyInfo? GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { if (returnType == null && types == null) { return typeImpl.GetProperty(name, bindingAttr); } return typeImpl.GetProperty(name, bindingAttr, binder, returnType, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { return typeImpl.GetProperties(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo[] GetEvents(BindingFlags bindingAttr) { return typeImpl.GetEvents(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type[] GetNestedTypes(BindingFlags bindingAttr) { return typeImpl.GetNestedTypes(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type? GetNestedType(string name, BindingFlags bindingAttr) { return typeImpl.GetNestedType(name, bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { return typeImpl.GetMember(name, type, bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return typeImpl.GetMembers(bindingAttr); } public override MemberInfo GetMemberWithSameMetadataDefinitionAs(MemberInfo member) { return typeImpl.GetMemberWithSameMetadataDefinitionAs(member); } protected override TypeAttributes GetAttributeFlagsImpl() { return typeImpl.Attributes; } protected override bool IsArrayImpl() { return typeImpl.IsArray; } protected override bool IsPrimitiveImpl() { return typeImpl.IsPrimitive; } protected override bool IsByRefImpl() { return typeImpl.IsByRef; } protected override bool IsPointerImpl() { return typeImpl.IsPointer; } protected override bool IsValueTypeImpl() { return typeImpl.IsValueType; } protected override bool IsCOMObjectImpl() { return typeImpl.IsCOMObject; } public override Type? GetElementType() { return typeImpl.GetElementType(); } protected override bool HasElementTypeImpl() { return typeImpl.HasElementType; } public override object[] GetCustomAttributes(bool inherit) { return typeImpl.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return typeImpl.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return typeImpl.IsDefined(attributeType, inherit); } public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type interfaceType) { return typeImpl.GetInterfaceMap(interfaceType); } } public delegate bool TypeFilter(Type m, object? filterCriteria); public abstract class TypeInfo : Type, IReflectableType { public virtual Type[] GenericTypeParameters { get { if (!IsGenericTypeDefinition) { return Type.EmptyTypes; } return GetGenericArguments(); } } public virtual IEnumerable DeclaredConstructors { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] get { return GetConstructors(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } } public virtual IEnumerable DeclaredEvents { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] get { return GetEvents(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } } public virtual IEnumerable DeclaredFields { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] get { return GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } } public virtual IEnumerable DeclaredMembers { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] get { return GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } } public virtual IEnumerable DeclaredMethods { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] get { return GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } } public virtual IEnumerable DeclaredNestedTypes { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] get { Type[] array = GetDeclaredOnlyNestedTypes(this); foreach (Type type2 in array) { yield return type2.GetTypeInfo(); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "The yield return state machine doesn't propagate annotations")] static Type[] GetDeclaredOnlyNestedTypes(Type type) { return type.GetNestedTypes(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } } } public virtual IEnumerable DeclaredProperties { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] get { return GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } } public virtual IEnumerable ImplementedInterfaces { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] get { return GetInterfaces(); } } TypeInfo IReflectableType.GetTypeInfo() { return this; } public virtual Type AsType() { return this; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public virtual EventInfo? GetDeclaredEvent(string name) { return GetEvent(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public virtual FieldInfo? GetDeclaredField(string name) { return GetField(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public virtual MethodInfo? GetDeclaredMethod(string name) { return GetMethod(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public virtual TypeInfo? GetDeclaredNestedType(string name) { return GetNestedType(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetTypeInfo(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] public virtual PropertyInfo? GetDeclaredProperty(string name) { return GetProperty(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public virtual IEnumerable GetDeclaredMethods(string name) { MethodInfo[] array = GetDeclaredOnlyMethods(this); foreach (MethodInfo methodInfo in array) { if (methodInfo.Name == name) { yield return methodInfo; } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "The yield return state machine doesn't propagate annotations")] static MethodInfo[] GetDeclaredOnlyMethods(Type type) { return type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } } public virtual bool IsAssignableFrom([NotNullWhen(true)] TypeInfo? typeInfo) { if (typeInfo == null) { return false; } if (this == typeInfo) { return true; } if (typeInfo.IsSubclassOf(this)) { return true; } if (base.IsInterface) { return typeInfo.ImplementInterface(this); } if (IsGenericParameter) { Type[] genericParameterConstraints = GetGenericParameterConstraints(); for (int i = 0; i < genericParameterConstraints.Length; i++) { if (!genericParameterConstraints[i].IsAssignableFrom(typeInfo)) { return false; } } return true; } return false; } internal static string GetRankString(int rank) { if (rank <= 0) { throw new IndexOutOfRangeException(); } if (rank != 1) { return "[" + new string(',', rank - 1) + "]"; } return "[*]"; } } } namespace System.Reflection.Metadata { public static class AssemblyExtensions { [DllImport("QCall")] [return: MarshalAs(UnmanagedType.Bool)] private unsafe static extern bool InternalTryGetRawMetadata(QCallAssembly assembly, ref byte* blob, ref int length); [CLSCompliant(false)] public unsafe static bool TryGetRawMetadata(this Assembly assembly, out byte* blob, out int length) { if (assembly == null) { throw new ArgumentNullException("assembly"); } blob = null; length = 0; RuntimeAssembly runtimeAssembly = assembly as RuntimeAssembly; if (runtimeAssembly == null) { return false; } RuntimeAssembly assembly2 = runtimeAssembly; return InternalTryGetRawMetadata(new QCallAssembly(ref assembly2), ref blob, ref length); } } public static class MetadataUpdater { public static bool IsSupported { get; } = IsApplyUpdateSupported(); [DllImport("QCall")] private unsafe static extern void ApplyUpdate(QCallAssembly assembly, byte* metadataDelta, int metadataDeltaLength, byte* ilDelta, int ilDeltaLength, byte* pdbDelta, int pdbDeltaLength); [DllImport("QCall")] private static extern bool IsApplyUpdateSupported(); public unsafe static void ApplyUpdate(Assembly assembly, ReadOnlySpan metadataDelta, ReadOnlySpan ilDelta, ReadOnlySpan pdbDelta) { if (!(assembly is RuntimeAssembly runtimeAssembly)) { if ((object)assembly == null) { throw new ArgumentNullException("assembly"); } throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); } RuntimeAssembly assembly2 = runtimeAssembly; fixed (byte* metadataDelta2 = metadataDelta) { fixed (byte* ilDelta2 = ilDelta) { fixed (byte* pdbDelta2 = pdbDelta) { ApplyUpdate(new QCallAssembly(ref assembly2), metadataDelta2, metadataDelta.Length, ilDelta2, ilDelta.Length, pdbDelta2, pdbDelta.Length); } } } } internal static string GetCapabilities() { return "Baseline AddMethodToExistingType AddStaticFieldToExistingType AddInstanceFieldToExistingType NewTypeDefinition ChangeCustomAttributes UpdateParameters"; } } internal static class RuntimeTypeMetadataUpdateHandler { [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Clearing the caches on a Type isn't affected if a Type is trimmed, or has any of its members trimmed.")] public static void ClearCache(Type[] types) { if (RequiresClearingAllTypes(types)) { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { if (SkipAssembly(assembly)) { continue; } try { Type[] types2 = assembly.GetTypes(); foreach (Type type in types2) { ClearCache(type); } } catch (ReflectionTypeLoadException) { } } } else { foreach (Type type2 in types) { ClearCache(type2); } } } private static bool SkipAssembly(Assembly assembly) { return typeof(object).Assembly == assembly; } private static void ClearCache(Type type) { (type as RuntimeType)?.ClearCache(); } private static bool RequiresClearingAllTypes([NotNullWhen(false)] Type[] types) { if (types == null) { return true; } foreach (Type type in types) { if (!type.IsSealed) { return true; } } return false; } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public sealed class MetadataUpdateHandlerAttribute : Attribute { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public Type HandlerType { get; } public MetadataUpdateHandlerAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type handlerType) { HandlerType = handlerType; } } } namespace System.Reflection.Emit { internal sealed class InternalAssemblyBuilder : RuntimeAssembly { public override string Location { get { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } } [RequiresAssemblyFiles("This member throws an exception for assemblies embedded in a single-file app")] public override string CodeBase { get { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } } public override string ImageRuntimeVersion => Assembly.GetExecutingAssembly().ImageRuntimeVersion; private InternalAssemblyBuilder() { } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is InternalAssemblyBuilder) { return this == obj; } return obj.Equals(this); } public override int GetHashCode() { return base.GetHashCode(); } public override string[] GetManifestResourceNames() { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } [RequiresAssemblyFiles("This member throws an exception for assemblies embedded in a single-file app")] public override FileStream GetFile(string name) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } [RequiresAssemblyFiles("This member throws an exception for assemblies embedded in a single-file app")] public override FileStream[] GetFiles(bool getResourceModules) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override Stream GetManifestResourceStream(Type type, string name) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override Stream GetManifestResourceStream(string name) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override ManifestResourceInfo GetManifestResourceInfo(string resourceName) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } [RequiresUnreferencedCode("Types might be removed")] public override Type[] GetExportedTypes() { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } } public sealed class AssemblyBuilder : Assembly { internal AssemblyBuilderData _assemblyData; private readonly InternalAssemblyBuilder _internalAssemblyBuilder; private ModuleBuilder _manifestModuleBuilder; private bool _isManifestModuleUsedAsDefinedModule; private static readonly object s_assemblyBuilderLock = new object(); internal object SyncRoot => InternalAssembly.SyncRoot; internal InternalAssemblyBuilder InternalAssembly => _internalAssemblyBuilder; public override string? FullName => InternalAssembly.FullName; public override Module ManifestModule => _manifestModuleBuilder.InternalModule; public override bool ReflectionOnly => InternalAssembly.ReflectionOnly; public override long HostContext => InternalAssembly.HostContext; public override bool IsCollectible => InternalAssembly.IsCollectible; [RequiresAssemblyFiles("This member throws an exception for assemblies embedded in a single-file app")] public override string? CodeBase { get { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } } public override string Location { get { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } } public override MethodInfo? EntryPoint => null; public override bool IsDynamic => true; [MethodImpl(MethodImplOptions.InternalCall)] private static extern RuntimeModule GetInMemoryAssemblyModule(RuntimeAssembly assembly); internal ModuleBuilder GetModuleBuilder(InternalModuleBuilder module) { lock (SyncRoot) { if (_manifestModuleBuilder.InternalModule == module) { return _manifestModuleBuilder; } throw new ArgumentException(null, "module"); } } internal AssemblyBuilder(AssemblyName name, AssemblyBuilderAccess access, ref StackCrawlMark stackMark, AssemblyLoadContext assemblyLoadContext, IEnumerable unsafeAssemblyAttributes) { if (name == null) { throw new ArgumentNullException("name"); } if (access != AssemblyBuilderAccess.Run && access != AssemblyBuilderAccess.RunAndCollect) { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)access), "access"); } name = (AssemblyName)name.Clone(); List list = null; if (unsafeAssemblyAttributes != null) { list = new List(unsafeAssemblyAttributes); } Assembly o = null; CreateDynamicAssembly(ObjectHandleOnStack.Create(ref name), new StackCrawlMarkHandle(ref stackMark), (int)access, ObjectHandleOnStack.Create(ref assemblyLoadContext), ObjectHandleOnStack.Create(ref o)); _internalAssemblyBuilder = (InternalAssemblyBuilder)o; _assemblyData = new AssemblyBuilderData(access); InitManifestModule(); if (list == null) { return; } foreach (CustomAttributeBuilder item in list) { SetCustomAttribute(item); } } [MemberNotNull("_manifestModuleBuilder")] private void InitManifestModule() { InternalModuleBuilder internalModuleBuilder = (InternalModuleBuilder)GetInMemoryAssemblyModule(InternalAssembly); _manifestModuleBuilder = new ModuleBuilder(this, internalModuleBuilder); _manifestModuleBuilder.Init("RefEmit_InMemoryManifestModule"); _isManifestModuleUsedAsDefinedModule = false; } public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalDefineDynamicAssembly(name, access, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext, null); } public static AssemblyBuilder DefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, IEnumerable? assemblyAttributes) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalDefineDynamicAssembly(name, access, ref stackMark, AssemblyLoadContext.CurrentContextualReflectionContext, assemblyAttributes); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void CreateDynamicAssembly(ObjectHandleOnStack name, StackCrawlMarkHandle stackMark, int access, ObjectHandleOnStack assemblyLoadContext, ObjectHandleOnStack retAssembly); internal static AssemblyBuilder InternalDefineDynamicAssembly(AssemblyName name, AssemblyBuilderAccess access, ref StackCrawlMark stackMark, AssemblyLoadContext assemblyLoadContext, IEnumerable unsafeAssemblyAttributes) { lock (s_assemblyBuilderLock) { return new AssemblyBuilder(name, access, ref stackMark, assemblyLoadContext, unsafeAssemblyAttributes); } } public ModuleBuilder DefineDynamicModule(string name) { lock (SyncRoot) { return DefineDynamicModuleInternalNoLock(name); } } private ModuleBuilder DefineDynamicModuleInternalNoLock(string name) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "name"); } if (name[0] == '\0') { throw new ArgumentException(SR.Argument_InvalidName, "name"); } if (_isManifestModuleUsedAsDefinedModule) { throw new InvalidOperationException(SR.InvalidOperation_NoMultiModuleAssembly); } ModuleBuilder manifestModuleBuilder = _manifestModuleBuilder; _assemblyData._moduleBuilderList.Add(manifestModuleBuilder); if (manifestModuleBuilder == _manifestModuleBuilder) { _isManifestModuleUsedAsDefinedModule = true; } return manifestModuleBuilder; } internal static void CheckContext(params Type[][] typess) { if (typess == null) { return; } foreach (Type[] array in typess) { if (array != null) { CheckContext(array); } } } internal static void CheckContext(params Type[] types) { if (types == null) { return; } foreach (Type type in types) { if (!(type == null)) { if (type.Module == null || type.Module.Assembly == null) { throw new ArgumentException(SR.Argument_TypeNotValid); } _ = type.Module.Assembly == typeof(object).Module.Assembly; } } } public override bool Equals(object? obj) { return InternalAssembly.Equals(obj); } public override int GetHashCode() { return InternalAssembly.GetHashCode(); } public override object[] GetCustomAttributes(bool inherit) { return InternalAssembly.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return InternalAssembly.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return InternalAssembly.IsDefined(attributeType, inherit); } public override IList GetCustomAttributesData() { return InternalAssembly.GetCustomAttributesData(); } public override AssemblyName GetName(bool copiedName) { return InternalAssembly.GetName(copiedName); } [RequiresUnreferencedCode("Types might be removed")] public override Type? GetType(string name, bool throwOnError, bool ignoreCase) { return InternalAssembly.GetType(name, throwOnError, ignoreCase); } public override Module? GetModule(string name) { return InternalAssembly.GetModule(name); } [RequiresUnreferencedCode("Assembly references might be removed")] public override AssemblyName[] GetReferencedAssemblies() { return InternalAssembly.GetReferencedAssemblies(); } public override Module[] GetModules(bool getResourceModules) { return InternalAssembly.GetModules(getResourceModules); } public override Module[] GetLoadedModules(bool getResourceModules) { return InternalAssembly.GetLoadedModules(getResourceModules); } public override Assembly GetSatelliteAssembly(CultureInfo culture) { return InternalAssembly.GetSatelliteAssembly(culture, null); } public override Assembly GetSatelliteAssembly(CultureInfo culture, Version? version) { return InternalAssembly.GetSatelliteAssembly(culture, version); } public ModuleBuilder? GetDynamicModule(string name) { lock (SyncRoot) { return GetDynamicModuleNoLock(name); } } private ModuleBuilder GetDynamicModuleNoLock(string name) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "name"); } for (int i = 0; i < _assemblyData._moduleBuilderList.Count; i++) { ModuleBuilder moduleBuilder = _assemblyData._moduleBuilderList[i]; if (moduleBuilder._moduleData._moduleName.Equals(name)) { return moduleBuilder; } } return null; } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) { throw new ArgumentNullException("con"); } if (binaryAttribute == null) { throw new ArgumentNullException("binaryAttribute"); } lock (SyncRoot) { TypeBuilder.DefineCustomAttribute(_manifestModuleBuilder, 536870913, _manifestModuleBuilder.GetConstructorToken(con), binaryAttribute); } } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { throw new ArgumentNullException("customBuilder"); } lock (SyncRoot) { customBuilder.CreateCustomAttribute(_manifestModuleBuilder, 536870913); } } [RequiresUnreferencedCode("Types might be removed")] public override Type[] GetExportedTypes() { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } [RequiresAssemblyFiles("This member throws an exception for assemblies embedded in a single-file app")] public override FileStream GetFile(string name) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } [RequiresAssemblyFiles("This member throws an exception for assemblies embedded in a single-file app")] public override FileStream[] GetFiles(bool getResourceModules) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override ManifestResourceInfo? GetManifestResourceInfo(string resourceName) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override string[] GetManifestResourceNames() { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override Stream? GetManifestResourceStream(string name) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } public override Stream? GetManifestResourceStream(Type type, string name) { throw new NotSupportedException(SR.NotSupported_DynamicAssembly); } } internal sealed class AssemblyBuilderData { public readonly List _moduleBuilderList; public readonly AssemblyBuilderAccess _access; internal AssemblyBuilderData(AssemblyBuilderAccess access) { _access = access; _moduleBuilderList = new List(); } public void CheckTypeNameConflict(string strTypeName, TypeBuilder enclosingType) { for (int i = 0; i < _moduleBuilderList.Count; i++) { ModuleBuilder moduleBuilder = _moduleBuilderList[i]; moduleBuilder.CheckTypeNameConflict(strTypeName, enclosingType); } } } public sealed class ConstructorBuilder : ConstructorInfo { private readonly MethodBuilder m_methodBuilder; internal bool m_isDefaultConstructor; public override int MetadataToken => m_methodBuilder.MetadataToken; public override Module Module => m_methodBuilder.Module; public override Type? ReflectedType => m_methodBuilder.ReflectedType; public override Type? DeclaringType => m_methodBuilder.DeclaringType; public override string Name => m_methodBuilder.Name; public override MethodAttributes Attributes => m_methodBuilder.Attributes; public override RuntimeMethodHandle MethodHandle => m_methodBuilder.MethodHandle; public override CallingConventions CallingConvention { get { if (DeclaringType.IsGenericType) { return CallingConventions.HasThis; } return CallingConventions.Standard; } } public bool InitLocals { get { return m_methodBuilder.InitLocals; } set { m_methodBuilder.InitLocals = value; } } internal ConstructorBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, ModuleBuilder mod, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TypeBuilder type) { m_methodBuilder = new MethodBuilder(name, attributes, callingConvention, null, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers, mod, type); type.m_listMethods.Add(m_methodBuilder); m_methodBuilder.GetMethodSignature().InternalGetSignature(out var _); int metadataToken = m_methodBuilder.MetadataToken; } internal ConstructorBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, ModuleBuilder mod, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TypeBuilder type) : this(name, attributes, callingConvention, parameterTypes, null, null, mod, type) { } internal override Type[] GetParameterTypes() { return m_methodBuilder.GetParameterTypes(); } [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] private TypeBuilder GetTypeBuilder() { return m_methodBuilder.GetTypeBuilder(); } internal SignatureHelper GetMethodSignature() { return m_methodBuilder.GetMethodSignature(); } public override string ToString() { return m_methodBuilder.ToString(); } public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override ParameterInfo[] GetParameters() { ConstructorInfo constructor = GetTypeBuilder().GetConstructor(m_methodBuilder.m_parameterTypes); return constructor.GetParameters(); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_methodBuilder.GetMethodImplementationFlags(); } public override object Invoke(BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override object[] GetCustomAttributes(bool inherit) { return m_methodBuilder.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_methodBuilder.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_methodBuilder.IsDefined(attributeType, inherit); } public ParameterBuilder DefineParameter(int iSequence, ParameterAttributes attributes, string? strParamName) { attributes &= ~ParameterAttributes.ReservedMask; return m_methodBuilder.DefineParameter(iSequence, attributes, strParamName); } public ILGenerator GetILGenerator() { if (m_isDefaultConstructor) { throw new InvalidOperationException(SR.InvalidOperation_DefaultConstructorILGen); } return m_methodBuilder.GetILGenerator(); } public ILGenerator GetILGenerator(int streamSize) { if (m_isDefaultConstructor) { throw new InvalidOperationException(SR.InvalidOperation_DefaultConstructorILGen); } return m_methodBuilder.GetILGenerator(streamSize); } internal override Type GetReturnType() { return m_methodBuilder.ReturnType; } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { m_methodBuilder.SetCustomAttribute(con, binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { m_methodBuilder.SetCustomAttribute(customBuilder); } public void SetImplementationFlags(MethodImplAttributes attributes) { m_methodBuilder.SetImplementationFlags(attributes); } } public class CustomAttributeBuilder { internal ConstructorInfo m_con; private object[] m_constructorArgs; private byte[] m_blob; public CustomAttributeBuilder(ConstructorInfo con, object?[] constructorArgs) : this(con, constructorArgs, Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty()) { } public CustomAttributeBuilder(ConstructorInfo con, object?[] constructorArgs, PropertyInfo[] namedProperties, object?[] propertyValues) : this(con, constructorArgs, namedProperties, propertyValues, Array.Empty(), Array.Empty()) { } public CustomAttributeBuilder(ConstructorInfo con, object?[] constructorArgs, FieldInfo[] namedFields, object?[] fieldValues) : this(con, constructorArgs, Array.Empty(), Array.Empty(), namedFields, fieldValues) { } public CustomAttributeBuilder(ConstructorInfo con, object?[] constructorArgs, PropertyInfo[] namedProperties, object?[] propertyValues, FieldInfo[] namedFields, object?[] fieldValues) { if (con == null) { throw new ArgumentNullException("con"); } if (constructorArgs == null) { throw new ArgumentNullException("constructorArgs"); } if (namedProperties == null) { throw new ArgumentNullException("namedProperties"); } if (propertyValues == null) { throw new ArgumentNullException("propertyValues"); } if (namedFields == null) { throw new ArgumentNullException("namedFields"); } if (fieldValues == null) { throw new ArgumentNullException("fieldValues"); } if (namedProperties.Length != propertyValues.Length) { throw new ArgumentException(SR.Arg_ArrayLengthsDiffer, "namedProperties, propertyValues"); } if (namedFields.Length != fieldValues.Length) { throw new ArgumentException(SR.Arg_ArrayLengthsDiffer, "namedFields, fieldValues"); } if ((con.Attributes & MethodAttributes.Static) == MethodAttributes.Static || (con.Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) { throw new ArgumentException(SR.Argument_BadConstructor); } if ((con.CallingConvention & CallingConventions.Standard) != CallingConventions.Standard) { throw new ArgumentException(SR.Argument_BadConstructorCallConv); } m_con = con; m_constructorArgs = new object[constructorArgs.Length]; Array.Copy(constructorArgs, m_constructorArgs, constructorArgs.Length); Type[] parameterTypes = con.GetParameterTypes(); if (parameterTypes.Length != constructorArgs.Length) { throw new ArgumentException(SR.Argument_BadParameterCountsForConstructor); } for (int i = 0; i < parameterTypes.Length; i++) { if (!ValidateType(parameterTypes[i])) { throw new ArgumentException(SR.Argument_BadTypeInCustomAttribute); } } for (int i = 0; i < parameterTypes.Length; i++) { object obj = constructorArgs[i]; if (obj == null) { if (parameterTypes[i].IsValueType) { throw new ArgumentNullException($"{"constructorArgs"}[{i}]"); } } else { VerifyTypeAndPassedObjectType(parameterTypes[i], obj.GetType(), $"{"constructorArgs"}[{i}]"); } } MemoryStream output = new MemoryStream(); BinaryWriter binaryWriter = new BinaryWriter(output); binaryWriter.Write((ushort)1); for (int i = 0; i < constructorArgs.Length; i++) { EmitValue(binaryWriter, parameterTypes[i], constructorArgs[i]); } binaryWriter.Write((ushort)(namedProperties.Length + namedFields.Length)); for (int i = 0; i < namedProperties.Length; i++) { PropertyInfo propertyInfo = namedProperties[i]; if (propertyInfo == null) { throw new ArgumentNullException("namedProperties[" + i + "]"); } Type propertyType = propertyInfo.PropertyType; object obj2 = propertyValues[i]; if (obj2 == null && propertyType.IsValueType) { throw new ArgumentNullException("propertyValues[" + i + "]"); } if (!ValidateType(propertyType)) { throw new ArgumentException(SR.Argument_BadTypeInCustomAttribute); } if (!propertyInfo.CanWrite) { throw new ArgumentException(SR.Argument_NotAWritableProperty); } if (propertyInfo.DeclaringType != con.DeclaringType && !(con.DeclaringType is TypeBuilderInstantiation) && !con.DeclaringType.IsSubclassOf(propertyInfo.DeclaringType) && !TypeBuilder.IsTypeEqual(propertyInfo.DeclaringType, con.DeclaringType) && (!(propertyInfo.DeclaringType is TypeBuilder) || !con.DeclaringType.IsSubclassOf(((TypeBuilder)propertyInfo.DeclaringType).BakedRuntimeType))) { throw new ArgumentException(SR.Argument_BadPropertyForConstructorBuilder); } if (obj2 != null) { VerifyTypeAndPassedObjectType(propertyType, obj2.GetType(), $"{"propertyValues"}[{i}]"); } binaryWriter.Write((byte)84); EmitType(binaryWriter, propertyType); EmitString(binaryWriter, namedProperties[i].Name); EmitValue(binaryWriter, propertyType, obj2); } for (int i = 0; i < namedFields.Length; i++) { FieldInfo fieldInfo = namedFields[i]; if (fieldInfo == null) { throw new ArgumentNullException("namedFields[" + i + "]"); } Type fieldType = fieldInfo.FieldType; object obj3 = fieldValues[i]; if (obj3 == null && fieldType.IsValueType) { throw new ArgumentNullException("fieldValues[" + i + "]"); } if (!ValidateType(fieldType)) { throw new ArgumentException(SR.Argument_BadTypeInCustomAttribute); } if (fieldInfo.DeclaringType != con.DeclaringType && !(con.DeclaringType is TypeBuilderInstantiation) && !con.DeclaringType.IsSubclassOf(fieldInfo.DeclaringType) && !TypeBuilder.IsTypeEqual(fieldInfo.DeclaringType, con.DeclaringType) && (!(fieldInfo.DeclaringType is TypeBuilder) || !con.DeclaringType.IsSubclassOf(((TypeBuilder)namedFields[i].DeclaringType).BakedRuntimeType))) { throw new ArgumentException(SR.Argument_BadFieldForConstructorBuilder); } if (obj3 != null) { VerifyTypeAndPassedObjectType(fieldType, obj3.GetType(), $"{"fieldValues"}[{i}]"); } binaryWriter.Write((byte)83); EmitType(binaryWriter, fieldType); EmitString(binaryWriter, fieldInfo.Name); EmitValue(binaryWriter, fieldType, obj3); } m_blob = ((MemoryStream)binaryWriter.BaseStream).ToArray(); } private bool ValidateType(Type t) { if (t.IsPrimitive) { if (t != typeof(IntPtr)) { return t != typeof(UIntPtr); } return false; } if (t == typeof(string) || t == typeof(Type)) { return true; } if (t.IsEnum) { TypeCode typeCode = Type.GetTypeCode(Enum.GetUnderlyingType(t)); if ((uint)(typeCode - 5) <= 7u) { return true; } return false; } if (t.IsArray) { if (t.GetArrayRank() == 1) { return ValidateType(t.GetElementType()); } return false; } return t == typeof(object); } private static void VerifyTypeAndPassedObjectType(Type type, Type passedType, string paramName) { if (type != typeof(object) && Type.GetTypeCode(passedType) != Type.GetTypeCode(type)) { throw new ArgumentException(SR.Argument_ConstantDoesntMatch); } if (passedType == typeof(IntPtr) || passedType == typeof(UIntPtr)) { throw new ArgumentException(SR.Format(SR.Argument_BadParameterTypeForCAB, passedType), paramName); } } private static void EmitType(BinaryWriter writer, Type type) { if (type.IsPrimitive) { switch (Type.GetTypeCode(type)) { case TypeCode.SByte: writer.Write((byte)4); break; case TypeCode.Byte: writer.Write((byte)5); break; case TypeCode.Char: writer.Write((byte)3); break; case TypeCode.Boolean: writer.Write((byte)2); break; case TypeCode.Int16: writer.Write((byte)6); break; case TypeCode.UInt16: writer.Write((byte)7); break; case TypeCode.Int32: writer.Write((byte)8); break; case TypeCode.UInt32: writer.Write((byte)9); break; case TypeCode.Int64: writer.Write((byte)10); break; case TypeCode.UInt64: writer.Write((byte)11); break; case TypeCode.Single: writer.Write((byte)12); break; case TypeCode.Double: writer.Write((byte)13); break; } } else if (type.IsEnum) { writer.Write((byte)85); EmitString(writer, type.AssemblyQualifiedName); } else if (type == typeof(string)) { writer.Write((byte)14); } else if (type == typeof(Type)) { writer.Write((byte)80); } else if (type.IsArray) { writer.Write((byte)29); EmitType(writer, type.GetElementType()); } else { writer.Write((byte)81); } } private static void EmitString(BinaryWriter writer, string str) { byte[] bytes = Encoding.UTF8.GetBytes(str); uint num = (uint)bytes.Length; if (num <= 127) { writer.Write((byte)num); } else if (num <= 16383) { writer.Write(BinaryPrimitives.ReverseEndianness((short)(num | 0x8000))); } else { writer.Write(BinaryPrimitives.ReverseEndianness(num | 0xC0000000u)); } writer.Write(bytes); } private static void EmitValue(BinaryWriter writer, Type type, object value) { if (type.IsEnum) { switch (Type.GetTypeCode(Enum.GetUnderlyingType(type))) { case TypeCode.SByte: writer.Write((sbyte)value); break; case TypeCode.Byte: writer.Write((byte)value); break; case TypeCode.Int16: writer.Write((short)value); break; case TypeCode.UInt16: writer.Write((ushort)value); break; case TypeCode.Int32: writer.Write((int)value); break; case TypeCode.UInt32: writer.Write((uint)value); break; case TypeCode.Int64: writer.Write((long)value); break; case TypeCode.UInt64: writer.Write((ulong)value); break; } return; } if (type == typeof(string)) { if (value == null) { writer.Write(byte.MaxValue); } else { EmitString(writer, (string)value); } return; } if (type == typeof(Type)) { if (value == null) { writer.Write(byte.MaxValue); return; } string text = TypeNameBuilder.ToString((Type)value, TypeNameBuilder.Format.AssemblyQualifiedName); if (text == null) { throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeForCA, value.GetType())); } EmitString(writer, text); return; } if (type.IsArray) { if (value == null) { writer.Write(uint.MaxValue); return; } Array array = (Array)value; Type elementType = type.GetElementType(); writer.Write(array.Length); for (int i = 0; i < array.Length; i++) { EmitValue(writer, elementType, array.GetValue(i)); } return; } if (type.IsPrimitive) { switch (Type.GetTypeCode(type)) { case TypeCode.SByte: writer.Write((sbyte)value); break; case TypeCode.Byte: writer.Write((byte)value); break; case TypeCode.Char: writer.Write(Convert.ToUInt16((char)value)); break; case TypeCode.Boolean: writer.Write((byte)(((bool)value) ? 1u : 0u)); break; case TypeCode.Int16: writer.Write((short)value); break; case TypeCode.UInt16: writer.Write((ushort)value); break; case TypeCode.Int32: writer.Write((int)value); break; case TypeCode.UInt32: writer.Write((uint)value); break; case TypeCode.Int64: writer.Write((long)value); break; case TypeCode.UInt64: writer.Write((ulong)value); break; case TypeCode.Single: writer.Write((float)value); break; case TypeCode.Double: writer.Write((double)value); break; } return; } if (type == typeof(object)) { Type type2 = ((value == null) ? typeof(string) : ((value is Type) ? typeof(Type) : value.GetType())); if (type2 == typeof(object)) { throw new ArgumentException(SR.Format(SR.Argument_BadParameterTypeForCAB, type2)); } EmitType(writer, type2); EmitValue(writer, type2, value); return; } string p = "null"; if (value != null) { p = value.GetType().ToString(); } throw new ArgumentException(SR.Format(SR.Argument_BadParameterTypeForCAB, p)); } internal void CreateCustomAttribute(ModuleBuilder mod, int tkOwner) { TypeBuilder.DefineCustomAttribute(mod, tkOwner, mod.GetConstructorToken(m_con), m_blob); } } internal sealed class DynamicILGenerator : ILGenerator { internal DynamicScope m_scope; private int m_methodSigToken; internal DynamicILGenerator(DynamicMethod method, byte[] methodSignature, int size) : base(method, size) { m_scope = new DynamicScope(); m_methodSigToken = m_scope.GetTokenFor(methodSignature); } internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm) { dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm, module, m_methodBuilder.Name, (byte[])m_scope[m_methodSigToken], new DynamicResolver(this)); } public override LocalBuilder DeclareLocal(Type localType, bool pinned) { if (localType == null) { throw new ArgumentNullException("localType"); } RuntimeType runtimeType = localType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Argument_MustBeRuntimeType); } LocalBuilder result = new LocalBuilder(m_localCount, localType, m_methodBuilder); m_localSignature.AddArgument(localType, pinned); m_localCount++; return result; } public override void Emit(OpCode opcode, MethodInfo meth) { if (meth == null) { throw new ArgumentNullException("meth"); } int num = 0; int num2 = 0; DynamicMethod dynamicMethod = meth as DynamicMethod; if (dynamicMethod == null) { RuntimeMethodInfo runtimeMethodInfo = meth as RuntimeMethodInfo; if (runtimeMethodInfo == null) { throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, "meth"); } RuntimeType runtimeType = runtimeMethodInfo.GetRuntimeType(); num2 = ((!(runtimeType != null) || (!runtimeType.IsGenericType && !runtimeType.IsArray)) ? GetTokenFor(runtimeMethodInfo) : GetTokenFor(runtimeMethodInfo, runtimeType)); } else { if (opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn) || opcode.Equals(OpCodes.Ldvirtftn)) { throw new ArgumentException(SR.Argument_InvalidOpCodeOnDynamicMethod); } num2 = GetTokenFor(dynamicMethod); } EnsureCapacity(7); InternalEmit(opcode); if (opcode.StackBehaviourPush == StackBehaviour.Varpush && meth.ReturnType != typeof(void)) { num++; } if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { num -= meth.GetParametersNoCopy().Length; } if (!meth.IsStatic && !opcode.Equals(OpCodes.Newobj) && !opcode.Equals(OpCodes.Ldtoken) && !opcode.Equals(OpCodes.Ldftn)) { num--; } UpdateStackSize(opcode, num); PutInteger4(num2); } public override void Emit(OpCode opcode, ConstructorInfo con) { if (con == null) { throw new ArgumentNullException("con"); } RuntimeConstructorInfo runtimeConstructorInfo = con as RuntimeConstructorInfo; if (runtimeConstructorInfo == null) { throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, "con"); } RuntimeType runtimeType = runtimeConstructorInfo.GetRuntimeType(); int value = ((!(runtimeType != null) || (!runtimeType.IsGenericType && !runtimeType.IsArray)) ? GetTokenFor(runtimeConstructorInfo) : GetTokenFor(runtimeConstructorInfo, runtimeType)); EnsureCapacity(7); InternalEmit(opcode); UpdateStackSize(opcode, 1); PutInteger4(value); } public override void Emit(OpCode opcode, Type type) { if (type == null) { throw new ArgumentNullException("type"); } RuntimeType runtimeType = type as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Argument_MustBeRuntimeType); } int tokenFor = GetTokenFor(runtimeType); EnsureCapacity(7); InternalEmit(opcode); PutInteger4(tokenFor); } public override void Emit(OpCode opcode, FieldInfo field) { if (field == null) { throw new ArgumentNullException("field"); } RuntimeFieldInfo runtimeFieldInfo = field as RuntimeFieldInfo; if (runtimeFieldInfo == null) { throw new ArgumentException(SR.Argument_MustBeRuntimeFieldInfo, "field"); } int value = ((!(field.DeclaringType == null)) ? GetTokenFor(runtimeFieldInfo, runtimeFieldInfo.GetRuntimeType()) : GetTokenFor(runtimeFieldInfo)); EnsureCapacity(7); InternalEmit(opcode); PutInteger4(value); } public override void Emit(OpCode opcode, string str) { if (str == null) { throw new ArgumentNullException("str"); } int tokenForString = GetTokenForString(str); EnsureCapacity(7); InternalEmit(opcode); PutInteger4(tokenForString); } public override void EmitCalli(OpCode opcode, CallingConventions callingConvention, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) { int num = 0; if (optionalParameterTypes != null && (callingConvention & CallingConventions.VarArgs) == 0) { throw new InvalidOperationException(SR.InvalidOperation_NotAVarArgCallingConvention); } SignatureHelper memberRefSignature = GetMemberRefSignature(callingConvention, returnType, parameterTypes, optionalParameterTypes); EnsureCapacity(7); Emit(OpCodes.Calli); if (returnType != typeof(void)) { num++; } if (parameterTypes != null) { num -= parameterTypes.Length; } if (optionalParameterTypes != null) { num -= optionalParameterTypes.Length; } if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis) { num--; } num--; UpdateStackSize(OpCodes.Calli, num); int tokenForSig = GetTokenForSig(memberRefSignature.GetSignature(appendEndOfSig: true)); PutInteger4(tokenForSig); } public override void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] parameterTypes) { int num = 0; int num2 = 0; if (parameterTypes != null) { num2 = parameterTypes.Length; } SignatureHelper methodSigHelper = SignatureHelper.GetMethodSigHelper(unmanagedCallConv, returnType); if (parameterTypes != null) { for (int i = 0; i < num2; i++) { methodSigHelper.AddArgument(parameterTypes[i]); } } if (returnType != typeof(void)) { num++; } if (parameterTypes != null) { num -= num2; } num--; UpdateStackSize(OpCodes.Calli, num); EnsureCapacity(7); Emit(OpCodes.Calli); int tokenForSig = GetTokenForSig(methodSigHelper.GetSignature(appendEndOfSig: true)); PutInteger4(tokenForSig); } public override void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[] optionalParameterTypes) { if (methodInfo == null) { throw new ArgumentNullException("methodInfo"); } if (!opcode.Equals(OpCodes.Call) && !opcode.Equals(OpCodes.Callvirt) && !opcode.Equals(OpCodes.Newobj)) { throw new ArgumentException(SR.Argument_NotMethodCallOpcode, "opcode"); } if (methodInfo.ContainsGenericParameters) { throw new ArgumentException(SR.Argument_GenericsInvalid, "methodInfo"); } if (methodInfo.DeclaringType != null && methodInfo.DeclaringType.ContainsGenericParameters) { throw new ArgumentException(SR.Argument_GenericsInvalid, "methodInfo"); } int num = 0; int memberRefToken = GetMemberRefToken(methodInfo, optionalParameterTypes); EnsureCapacity(7); InternalEmit(opcode); if (methodInfo.ReturnType != typeof(void)) { num++; } num -= methodInfo.GetParameterTypes().Length; if (!(methodInfo is SymbolMethod) && !methodInfo.IsStatic && !opcode.Equals(OpCodes.Newobj)) { num--; } if (optionalParameterTypes != null) { num -= optionalParameterTypes.Length; } UpdateStackSize(opcode, num); PutInteger4(memberRefToken); } public override void Emit(OpCode opcode, SignatureHelper signature) { if (signature == null) { throw new ArgumentNullException("signature"); } int num = 0; EnsureCapacity(7); InternalEmit(opcode); if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { num -= signature.ArgumentCount; num--; UpdateStackSize(opcode, num); } int tokenForSig = GetTokenForSig(signature.GetSignature(appendEndOfSig: true)); PutInteger4(tokenForSig); } public override void BeginExceptFilterBlock() { if (base.CurrExcStackCount == 0) { throw new NotSupportedException(SR.Argument_NotInExceptionBlock); } __ExceptionInfo _ExceptionInfo = base.CurrExcStack[base.CurrExcStackCount - 1]; Label endLabel = _ExceptionInfo.GetEndLabel(); Emit(OpCodes.Leave, endLabel); UpdateStackSize(OpCodes.Nop, 1); _ExceptionInfo.MarkFilterAddr(ILOffset); } public override void BeginCatchBlock(Type exceptionType) { if (base.CurrExcStackCount == 0) { throw new NotSupportedException(SR.Argument_NotInExceptionBlock); } __ExceptionInfo _ExceptionInfo = base.CurrExcStack[base.CurrExcStackCount - 1]; RuntimeType runtimeType = exceptionType as RuntimeType; if (_ExceptionInfo.GetCurrentState() == 1) { if (exceptionType != null) { throw new ArgumentException(SR.Argument_ShouldNotSpecifyExceptionType); } Emit(OpCodes.Endfilter); _ExceptionInfo.MarkCatchAddr(ILOffset, null); return; } if (exceptionType == null) { throw new ArgumentNullException("exceptionType"); } if (runtimeType == null) { throw new ArgumentException(SR.Argument_MustBeRuntimeType); } Label endLabel = _ExceptionInfo.GetEndLabel(); Emit(OpCodes.Leave, endLabel); UpdateStackSize(OpCodes.Nop, 1); _ExceptionInfo.MarkCatchAddr(ILOffset, exceptionType); _ExceptionInfo.m_filterAddr[_ExceptionInfo.m_currentCatch - 1] = GetTokenFor(runtimeType); } public override void UsingNamespace(string ns) { throw new NotSupportedException(SR.InvalidOperation_NotAllowedInDynamicMethod); } public override void BeginScope() { throw new NotSupportedException(SR.InvalidOperation_NotAllowedInDynamicMethod); } public override void EndScope() { throw new NotSupportedException(SR.InvalidOperation_NotAllowedInDynamicMethod); } private int GetMemberRefToken(MethodBase methodInfo, Type[] optionalParameterTypes) { if (optionalParameterTypes != null && (methodInfo.CallingConvention & CallingConventions.VarArgs) == 0) { throw new InvalidOperationException(SR.InvalidOperation_NotAVarArgCallingConvention); } RuntimeMethodInfo runtimeMethodInfo = methodInfo as RuntimeMethodInfo; DynamicMethod dynamicMethod = methodInfo as DynamicMethod; if (runtimeMethodInfo == null && dynamicMethod == null) { throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, "methodInfo"); } ParameterInfo[] parametersNoCopy = methodInfo.GetParametersNoCopy(); Type[] array; Type[][] array2; Type[][] array3; if (parametersNoCopy != null && parametersNoCopy.Length != 0) { array = new Type[parametersNoCopy.Length]; array2 = new Type[array.Length][]; array3 = new Type[array.Length][]; for (int i = 0; i < parametersNoCopy.Length; i++) { array[i] = parametersNoCopy[i].ParameterType; array2[i] = parametersNoCopy[i].GetRequiredCustomModifiers(); array3[i] = parametersNoCopy[i].GetOptionalCustomModifiers(); } } else { array = null; array2 = null; array3 = null; } SignatureHelper memberRefSignature = GetMemberRefSignature(methodInfo.CallingConvention, MethodBuilder.GetMethodBaseReturnType(methodInfo), array, array2, array3, optionalParameterTypes); if (runtimeMethodInfo != null) { return GetTokenForVarArgMethod(runtimeMethodInfo, memberRefSignature); } return GetTokenForVarArgMethod(dynamicMethod, memberRefSignature); } internal override SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, Type[] optionalParameterTypes) { SignatureHelper methodSigHelper = SignatureHelper.GetMethodSigHelper(null, call, returnType, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers); if (optionalParameterTypes != null && optionalParameterTypes.Length != 0) { methodSigHelper.AddSentinel(); methodSigHelper.AddArguments(optionalParameterTypes, null, null); } return methodSigHelper; } internal override void RecordTokenFixup() { } private int GetTokenFor(RuntimeType rtType) { return m_scope.GetTokenFor(rtType.TypeHandle); } private int GetTokenFor(RuntimeFieldInfo runtimeField) { return m_scope.GetTokenFor(runtimeField.FieldHandle); } private int GetTokenFor(RuntimeFieldInfo runtimeField, RuntimeType rtType) { return m_scope.GetTokenFor(runtimeField.FieldHandle, rtType.TypeHandle); } private int GetTokenFor(RuntimeConstructorInfo rtMeth) { return m_scope.GetTokenFor(rtMeth.MethodHandle); } private int GetTokenFor(RuntimeConstructorInfo rtMeth, RuntimeType rtType) { return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle); } private int GetTokenFor(RuntimeMethodInfo rtMeth) { return m_scope.GetTokenFor(rtMeth.MethodHandle); } private int GetTokenFor(RuntimeMethodInfo rtMeth, RuntimeType rtType) { return m_scope.GetTokenFor(rtMeth.MethodHandle, rtType.TypeHandle); } private int GetTokenFor(DynamicMethod dm) { return m_scope.GetTokenFor(dm); } private int GetTokenForVarArgMethod(RuntimeMethodInfo rtMeth, SignatureHelper sig) { VarArgMethod varArgMethod = new VarArgMethod(rtMeth, sig); return m_scope.GetTokenFor(varArgMethod); } private int GetTokenForVarArgMethod(DynamicMethod dm, SignatureHelper sig) { VarArgMethod varArgMethod = new VarArgMethod(dm, sig); return m_scope.GetTokenFor(varArgMethod); } private int GetTokenForString(string s) { return m_scope.GetTokenFor(s); } private int GetTokenForSig(byte[] sig) { return m_scope.GetTokenFor(sig); } } internal sealed class DynamicResolver : Resolver { private sealed class DestroyScout { internal RuntimeMethodHandleInternal m_methodHandle; ~DestroyScout() { if (!m_methodHandle.IsNullHandle()) { if (RuntimeMethodHandle.GetResolver(m_methodHandle) != null) { GC.ReRegisterForFinalize(this); } else { RuntimeMethodHandle.Destroy(m_methodHandle); } } } } [Flags] internal enum SecurityControlFlags { Default = 0, SkipVisibilityChecks = 1, RestrictedSkipVisibilityChecks = 2, HasCreationContext = 4, CanSkipCSEvaluation = 8 } private __ExceptionInfo[] m_exceptions; private byte[] m_exceptionHeader; private DynamicMethod m_method; private byte[] m_code; private byte[] m_localSignature; private int m_stackSize; private DynamicScope m_scope; internal DynamicResolver(DynamicILGenerator ilGenerator) { m_stackSize = ilGenerator.GetMaxStackSize(); m_exceptions = ilGenerator.GetExceptions(); m_code = ilGenerator.BakeByteArray(); m_localSignature = ilGenerator.m_localSignature.InternalGetSignatureArray(); m_scope = ilGenerator.m_scope; m_method = (DynamicMethod)ilGenerator.m_methodBuilder; m_method.m_resolver = this; } internal DynamicResolver(DynamicILInfo dynamicILInfo) { m_stackSize = dynamicILInfo.MaxStackSize; m_code = dynamicILInfo.Code; m_localSignature = dynamicILInfo.LocalSignature; m_exceptionHeader = dynamicILInfo.Exceptions; m_scope = dynamicILInfo.DynamicScope; m_method = dynamicILInfo.DynamicMethod; m_method.m_resolver = this; } ~DynamicResolver() { DynamicMethod method = m_method; if (!(method == null) && method.m_methodHandle != null) { DestroyScout destroyScout; try { destroyScout = new DestroyScout(); } catch { GC.ReRegisterForFinalize(this); return; } destroyScout.m_methodHandle = method.m_methodHandle.Value; } } internal override RuntimeType GetJitContext(out int securityControlFlags) { SecurityControlFlags securityControlFlags2 = SecurityControlFlags.Default; if (m_method.m_restrictedSkipVisibility) { securityControlFlags2 |= SecurityControlFlags.RestrictedSkipVisibilityChecks; } else if (m_method.m_skipVisibility) { securityControlFlags2 |= SecurityControlFlags.SkipVisibilityChecks; } RuntimeType typeOwner = m_method.m_typeOwner; securityControlFlags = (int)securityControlFlags2; return typeOwner; } private static int CalculateNumberOfExceptions(__ExceptionInfo[] excp) { int num = 0; if (excp == null) { return 0; } for (int i = 0; i < excp.Length; i++) { num += excp[i].GetNumberOfCatches(); } return num; } internal override byte[] GetCodeInfo(out int stackSize, out int initLocals, out int EHCount) { stackSize = m_stackSize; if (m_exceptionHeader != null && m_exceptionHeader.Length != 0) { if (m_exceptionHeader.Length < 4) { throw new FormatException(); } byte b = m_exceptionHeader[0]; if ((b & 0x40u) != 0) { int num = m_exceptionHeader[3] << 16; num |= m_exceptionHeader[2] << 8; num |= m_exceptionHeader[1]; EHCount = (num - 4) / 24; } else { EHCount = (m_exceptionHeader[1] - 2) / 12; } } else { EHCount = CalculateNumberOfExceptions(m_exceptions); } initLocals = (m_method.InitLocals ? 1 : 0); return m_code; } internal override byte[] GetLocalsSignature() { return m_localSignature; } internal override byte[] GetRawEHInfo() { return m_exceptionHeader; } internal unsafe override void GetEHInfo(int excNumber, void* exc) { for (int i = 0; i < m_exceptions.Length; i++) { int numberOfCatches = m_exceptions[i].GetNumberOfCatches(); if (excNumber < numberOfCatches) { ((CORINFO_EH_CLAUSE*)exc)->Flags = m_exceptions[i].GetExceptionTypes()[excNumber]; ((CORINFO_EH_CLAUSE*)exc)->TryOffset = m_exceptions[i].GetStartAddress(); if ((((CORINFO_EH_CLAUSE*)exc)->Flags & 2) != 2) { ((CORINFO_EH_CLAUSE*)exc)->TryLength = m_exceptions[i].GetEndAddress() - ((CORINFO_EH_CLAUSE*)exc)->TryOffset; } else { ((CORINFO_EH_CLAUSE*)exc)->TryLength = m_exceptions[i].GetFinallyEndAddress() - ((CORINFO_EH_CLAUSE*)exc)->TryOffset; } ((CORINFO_EH_CLAUSE*)exc)->HandlerOffset = m_exceptions[i].GetCatchAddresses()[excNumber]; ((CORINFO_EH_CLAUSE*)exc)->HandlerLength = m_exceptions[i].GetCatchEndAddresses()[excNumber] - ((CORINFO_EH_CLAUSE*)exc)->HandlerOffset; ((CORINFO_EH_CLAUSE*)exc)->ClassTokenOrFilterOffset = m_exceptions[i].GetFilterAddresses()[excNumber]; break; } excNumber -= numberOfCatches; } } internal override string GetStringLiteral(int token) { return m_scope.GetString(token); } internal override void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle) { typeHandle = default(IntPtr); methodHandle = default(IntPtr); fieldHandle = default(IntPtr); object obj = m_scope[token]; if (obj == null) { throw new InvalidProgramException(); } if (obj is RuntimeTypeHandle) { typeHandle = ((RuntimeTypeHandle)obj).Value; return; } if (obj is RuntimeMethodHandle) { methodHandle = ((RuntimeMethodHandle)obj).Value; return; } if (obj is RuntimeFieldHandle) { fieldHandle = ((RuntimeFieldHandle)obj).Value; return; } DynamicMethod dynamicMethod = obj as DynamicMethod; if (dynamicMethod != null) { methodHandle = dynamicMethod.GetMethodDescriptor().Value; } else if (obj is GenericMethodInfo genericMethodInfo) { methodHandle = genericMethodInfo.m_methodHandle.Value; typeHandle = genericMethodInfo.m_context.Value; } else if (obj is GenericFieldInfo genericFieldInfo) { fieldHandle = genericFieldInfo.m_fieldHandle.Value; typeHandle = genericFieldInfo.m_context.Value; } else if (obj is VarArgMethod varArgMethod) { if (varArgMethod.m_dynamicMethod == null) { methodHandle = varArgMethod.m_method.MethodHandle.Value; typeHandle = varArgMethod.m_method.GetDeclaringTypeInternal().GetTypeHandleInternal().Value; } else { methodHandle = varArgMethod.m_dynamicMethod.GetMethodDescriptor().Value; } } } internal override byte[] ResolveSignature(int token, int fromMethod) { return m_scope.ResolveSignature(token, fromMethod); } internal override MethodInfo GetDynamicMethod() { return m_method.GetMethodInfo(); } } public class DynamicILInfo { private DynamicMethod m_method; private DynamicScope m_scope; private byte[] m_exceptions; private byte[] m_code; private byte[] m_localSignature; private int m_maxStackSize; private int m_methodSignature; internal byte[] LocalSignature => m_localSignature ?? (m_localSignature = SignatureHelper.GetLocalVarSigHelper().InternalGetSignatureArray()); internal byte[] Exceptions => m_exceptions; internal byte[] Code => m_code; internal int MaxStackSize => m_maxStackSize; public DynamicMethod DynamicMethod => m_method; internal DynamicScope DynamicScope => m_scope; internal DynamicILInfo(DynamicMethod method, byte[] methodSignature) { m_scope = new DynamicScope(); m_method = method; m_methodSignature = m_scope.GetTokenFor(methodSignature); m_exceptions = Array.Empty(); m_code = Array.Empty(); m_localSignature = Array.Empty(); } internal void GetCallableMethod(RuntimeModule module, DynamicMethod dm) { dm.m_methodHandle = ModuleHandle.GetDynamicMethod(dm, module, m_method.Name, (byte[])m_scope[m_methodSignature], new DynamicResolver(this)); } public void SetCode(byte[]? code, int maxStackSize) { m_code = ((code != null) ? ((byte[])code.Clone()) : Array.Empty()); m_maxStackSize = maxStackSize; } [CLSCompliant(false)] public unsafe void SetCode(byte* code, int codeSize, int maxStackSize) { if (codeSize < 0) { throw new ArgumentOutOfRangeException("codeSize", SR.ArgumentOutOfRange_GenericPositive); } if (codeSize > 0 && code == null) { throw new ArgumentNullException("code"); } m_code = new Span(code, codeSize).ToArray(); m_maxStackSize = maxStackSize; } public void SetExceptions(byte[]? exceptions) { m_exceptions = ((exceptions != null) ? ((byte[])exceptions.Clone()) : Array.Empty()); } [CLSCompliant(false)] public unsafe void SetExceptions(byte* exceptions, int exceptionsSize) { if (exceptionsSize < 0) { throw new ArgumentOutOfRangeException("exceptionsSize", SR.ArgumentOutOfRange_GenericPositive); } if (exceptionsSize > 0 && exceptions == null) { throw new ArgumentNullException("exceptions"); } m_exceptions = new Span(exceptions, exceptionsSize).ToArray(); } public void SetLocalSignature(byte[]? localSignature) { m_localSignature = ((localSignature != null) ? ((byte[])localSignature.Clone()) : Array.Empty()); } [CLSCompliant(false)] public unsafe void SetLocalSignature(byte* localSignature, int signatureSize) { if (signatureSize < 0) { throw new ArgumentOutOfRangeException("signatureSize", SR.ArgumentOutOfRange_GenericPositive); } if (signatureSize > 0 && localSignature == null) { throw new ArgumentNullException("localSignature"); } m_localSignature = new Span(localSignature, signatureSize).ToArray(); } public int GetTokenFor(RuntimeMethodHandle method) { return DynamicScope.GetTokenFor(method); } public int GetTokenFor(DynamicMethod method) { return DynamicScope.GetTokenFor(method); } public int GetTokenFor(RuntimeMethodHandle method, RuntimeTypeHandle contextType) { return DynamicScope.GetTokenFor(method, contextType); } public int GetTokenFor(RuntimeFieldHandle field) { return DynamicScope.GetTokenFor(field); } public int GetTokenFor(RuntimeFieldHandle field, RuntimeTypeHandle contextType) { return DynamicScope.GetTokenFor(field, contextType); } public int GetTokenFor(RuntimeTypeHandle type) { return DynamicScope.GetTokenFor(type); } public int GetTokenFor(string literal) { return DynamicScope.GetTokenFor(literal); } public int GetTokenFor(byte[] signature) { return DynamicScope.GetTokenFor(signature); } } internal sealed class DynamicScope { internal readonly List m_tokens = new List { null }; internal object this[int token] { get { token &= 0xFFFFFF; if (token < 0 || token > m_tokens.Count) { return null; } return m_tokens[token]; } } internal int GetTokenFor(VarArgMethod varArgMethod) { m_tokens.Add(varArgMethod); return (m_tokens.Count - 1) | 0xA000000; } internal string GetString(int token) { return this[token] as string; } internal byte[] ResolveSignature(int token, int fromMethod) { if (fromMethod == 0) { return (byte[])this[token]; } if (!(this[token] is VarArgMethod varArgMethod)) { return null; } return varArgMethod.m_signature.GetSignature(appendEndOfSig: true); } public int GetTokenFor(RuntimeMethodHandle method) { IRuntimeMethodInfo methodInfo = method.GetMethodInfo(); if (methodInfo != null) { RuntimeMethodHandleInternal value = methodInfo.Value; if (!RuntimeMethodHandle.IsDynamicMethod(value)) { RuntimeType declaringType = RuntimeMethodHandle.GetDeclaringType(value); if (declaringType != null && RuntimeTypeHandle.HasInstantiation(declaringType)) { MethodBase methodBase = RuntimeType.GetMethodBase(methodInfo); Type genericTypeDefinition = methodBase.DeclaringType.GetGenericTypeDefinition(); throw new ArgumentException(SR.Format(SR.Argument_MethodDeclaringTypeGenericLcg, methodBase, genericTypeDefinition)); } } } m_tokens.Add(method); return (m_tokens.Count - 1) | 0x6000000; } public int GetTokenFor(RuntimeMethodHandle method, RuntimeTypeHandle typeContext) { m_tokens.Add(new GenericMethodInfo(method, typeContext)); return (m_tokens.Count - 1) | 0x6000000; } public int GetTokenFor(DynamicMethod method) { m_tokens.Add(method); return (m_tokens.Count - 1) | 0x6000000; } public int GetTokenFor(RuntimeFieldHandle field) { m_tokens.Add(field); return (m_tokens.Count - 1) | 0x4000000; } public int GetTokenFor(RuntimeFieldHandle field, RuntimeTypeHandle typeContext) { m_tokens.Add(new GenericFieldInfo(field, typeContext)); return (m_tokens.Count - 1) | 0x4000000; } public int GetTokenFor(RuntimeTypeHandle type) { m_tokens.Add(type); return (m_tokens.Count - 1) | 0x2000000; } public int GetTokenFor(string literal) { m_tokens.Add(literal); return (m_tokens.Count - 1) | 0x70000000; } public int GetTokenFor(byte[] signature) { m_tokens.Add(signature); return (m_tokens.Count - 1) | 0x11000000; } } internal sealed class GenericMethodInfo { internal RuntimeMethodHandle m_methodHandle; internal RuntimeTypeHandle m_context; internal GenericMethodInfo(RuntimeMethodHandle methodHandle, RuntimeTypeHandle context) { m_methodHandle = methodHandle; m_context = context; } } internal sealed class GenericFieldInfo { internal RuntimeFieldHandle m_fieldHandle; internal RuntimeTypeHandle m_context; internal GenericFieldInfo(RuntimeFieldHandle fieldHandle, RuntimeTypeHandle context) { m_fieldHandle = fieldHandle; m_context = context; } } internal sealed class VarArgMethod { internal RuntimeMethodInfo m_method; internal DynamicMethod m_dynamicMethod; internal SignatureHelper m_signature; internal VarArgMethod(DynamicMethod dm, SignatureHelper signature) { m_dynamicMethod = dm; m_signature = signature; } internal VarArgMethod(RuntimeMethodInfo method, SignatureHelper signature) { m_method = method; m_signature = signature; } } public sealed class DynamicMethod : MethodInfo { internal sealed class RTDynamicMethod : MethodInfo { internal DynamicMethod m_owner; private RuntimeParameterInfo[] m_parameters; private string m_name; private MethodAttributes m_attributes; private CallingConventions m_callingConvention; public override string Name => m_name; public override Type DeclaringType => null; public override Type ReflectedType => null; public override Module Module => m_owner.m_module; public override RuntimeMethodHandle MethodHandle { get { throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInDynamicMethod); } } public override MethodAttributes Attributes => m_attributes; public override CallingConventions CallingConvention => m_callingConvention; public override bool IsSecurityCritical => m_owner.IsSecurityCritical; public override bool IsSecuritySafeCritical => m_owner.IsSecuritySafeCritical; public override bool IsSecurityTransparent => m_owner.IsSecurityTransparent; public override Type ReturnType => m_owner.m_returnType; public override ParameterInfo ReturnParameter => new RuntimeParameterInfo(this, null, m_owner.m_returnType, -1); public override ICustomAttributeProvider ReturnTypeCustomAttributes => new EmptyCAHolder(); internal RTDynamicMethod(DynamicMethod owner, string name, MethodAttributes attributes, CallingConventions callingConvention) { m_owner = owner; m_name = name; m_attributes = attributes; m_callingConvention = callingConvention; } public override string ToString() { ValueStringBuilder sbParamList = new ValueStringBuilder(100); sbParamList.Append(ReturnType.FormatTypeName()); sbParamList.Append(' '); sbParamList.Append(Name); sbParamList.Append('('); MethodBase.AppendParameters(ref sbParamList, GetParameterTypes(), CallingConvention); sbParamList.Append(')'); return sbParamList.ToString(); } public override MethodInfo GetBaseDefinition() { return this; } public override ParameterInfo[] GetParameters() { ParameterInfo[] array = LoadParameters(); ParameterInfo[] array2 = array; ParameterInfo[] array3 = new ParameterInfo[array2.Length]; Array.Copy(array2, array3, array2.Length); return array3; } public override MethodImplAttributes GetMethodImplementationFlags() { return MethodImplAttributes.NoInlining; } public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { throw new ArgumentException(SR.Argument_MustBeRuntimeMethodInfo, "this"); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) { return new object[1] { new MethodImplAttribute((MethodImplOptions)GetMethodImplementationFlags()) }; } return Array.Empty(); } public override object[] GetCustomAttributes(bool inherit) { return new object[1] { new MethodImplAttribute((MethodImplOptions)GetMethodImplementationFlags()) }; } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) { throw new ArgumentNullException("attributeType"); } if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute))) { return true; } return false; } internal RuntimeParameterInfo[] LoadParameters() { if (m_parameters == null) { Type[] parameterTypes = m_owner.m_parameterTypes; Type[] array = parameterTypes; RuntimeParameterInfo[] array2 = new RuntimeParameterInfo[array.Length]; for (int i = 0; i < array.Length; i++) { array2[i] = new RuntimeParameterInfo(this, null, array[i], i); } if (m_parameters == null) { m_parameters = array2; } } return m_parameters; } } private RuntimeType[] m_parameterTypes; internal IRuntimeMethodInfo m_methodHandle; private RuntimeType m_returnType; private DynamicILGenerator m_ilGenerator; private DynamicILInfo m_DynamicILInfo; private bool m_fInitLocals; private RuntimeModule m_module; internal bool m_skipVisibility; internal RuntimeType m_typeOwner; private RTDynamicMethod m_dynMethod; internal DynamicResolver m_resolver; internal bool m_restrictedSkipVisibility; private static volatile InternalModuleBuilder s_anonymouslyHostedDynamicMethodsModule; private static readonly object s_anonymouslyHostedDynamicMethodsModuleLock = new object(); public override string Name => m_dynMethod.Name; public override Type? DeclaringType => m_dynMethod.DeclaringType; public override Type? ReflectedType => m_dynMethod.ReflectedType; public override Module Module => m_dynMethod.Module; public override RuntimeMethodHandle MethodHandle { get { throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInDynamicMethod); } } public override MethodAttributes Attributes => m_dynMethod.Attributes; public override CallingConventions CallingConvention => m_dynMethod.CallingConvention; public override bool IsSecurityCritical => true; public override bool IsSecuritySafeCritical => false; public override bool IsSecurityTransparent => false; public override Type ReturnType => m_dynMethod.ReturnType; public override ParameterInfo ReturnParameter => m_dynMethod.ReturnParameter; public override ICustomAttributeProvider ReturnTypeCustomAttributes => m_dynMethod.ReturnTypeCustomAttributes; public bool InitLocals { get { return m_fInitLocals; } set { m_fInitLocals = value; } } public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes) { Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, null, skipVisibility: false, transparentMethod: true); } public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, bool restrictedSkipVisibility) { Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, null, restrictedSkipVisibility, transparentMethod: true); } public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, Module m) { if (m == null) { throw new ArgumentNullException("m"); } Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, m, skipVisibility: false, transparentMethod: false); } public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, Module m, bool skipVisibility) { if (m == null) { throw new ArgumentNullException("m"); } Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, null, m, skipVisibility, transparentMethod: false); } public DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, Module m, bool skipVisibility) { if (m == null) { throw new ArgumentNullException("m"); } Init(name, attributes, callingConvention, returnType, parameterTypes, null, m, skipVisibility, transparentMethod: false); } public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, Type owner) { if (owner == null) { throw new ArgumentNullException("owner"); } Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, owner, null, skipVisibility: false, transparentMethod: false); } public DynamicMethod(string name, Type? returnType, Type[]? parameterTypes, Type owner, bool skipVisibility) { if (owner == null) { throw new ArgumentNullException("owner"); } Init(name, MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, returnType, parameterTypes, owner, null, skipVisibility, transparentMethod: false); } public DynamicMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, Type owner, bool skipVisibility) { if (owner == null) { throw new ArgumentNullException("owner"); } Init(name, attributes, callingConvention, returnType, parameterTypes, owner, null, skipVisibility, transparentMethod: false); } private static void CheckConsistency(MethodAttributes attributes, CallingConventions callingConvention) { if ((attributes & ~MethodAttributes.MemberAccessMask) != MethodAttributes.Static) { throw new NotSupportedException(SR.NotSupported_DynamicMethodFlags); } if ((attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public) { throw new NotSupportedException(SR.NotSupported_DynamicMethodFlags); } if (callingConvention != CallingConventions.Standard && callingConvention != CallingConventions.VarArgs) { throw new NotSupportedException(SR.NotSupported_DynamicMethodFlags); } if (callingConvention == CallingConventions.VarArgs) { throw new NotSupportedException(SR.NotSupported_DynamicMethodFlags); } } private static RuntimeModule GetDynamicMethodsModule() { if (s_anonymouslyHostedDynamicMethodsModule != null) { return s_anonymouslyHostedDynamicMethodsModule; } lock (s_anonymouslyHostedDynamicMethodsModuleLock) { if (s_anonymouslyHostedDynamicMethodsModule != null) { return s_anonymouslyHostedDynamicMethodsModule; } AssemblyName name = new AssemblyName("Anonymously Hosted DynamicMethods Assembly"); StackCrawlMark stackMark = StackCrawlMark.LookForMe; AssemblyBuilder assemblyBuilder = AssemblyBuilder.InternalDefineDynamicAssembly(name, AssemblyBuilderAccess.Run, ref stackMark, null, null); s_anonymouslyHostedDynamicMethodsModule = (InternalModuleBuilder)assemblyBuilder.ManifestModule; } return s_anonymouslyHostedDynamicMethodsModule; } [MemberNotNull("m_parameterTypes")] [MemberNotNull("m_returnType")] [MemberNotNull("m_dynMethod")] private void Init(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] signature, Type owner, Module m, bool skipVisibility, bool transparentMethod) { CheckConsistency(attributes, callingConvention); if (signature != null) { m_parameterTypes = new RuntimeType[signature.Length]; for (int i = 0; i < signature.Length; i++) { if (signature[i] == null) { throw new ArgumentException(SR.Arg_InvalidTypeInSignature); } m_parameterTypes[i] = signature[i].UnderlyingSystemType as RuntimeType; if (m_parameterTypes[i] == null || m_parameterTypes[i] == typeof(void)) { throw new ArgumentException(SR.Arg_InvalidTypeInSignature); } } } else { m_parameterTypes = Array.Empty(); } m_returnType = ((returnType == null) ? ((RuntimeType)typeof(void)) : (returnType.UnderlyingSystemType as RuntimeType)); if (m_returnType == null) { throw new NotSupportedException(SR.Arg_InvalidTypeInRetType); } if (transparentMethod) { m_module = GetDynamicMethodsModule(); if (skipVisibility) { m_restrictedSkipVisibility = true; } } else { if (m != null) { m_module = m.ModuleHandle.GetRuntimeModule(); } else { RuntimeType runtimeType = null; if (owner != null) { runtimeType = owner.UnderlyingSystemType as RuntimeType; } if (runtimeType != null) { if (runtimeType.HasElementType || runtimeType.ContainsGenericParameters || runtimeType.IsGenericParameter || runtimeType.IsInterface) { throw new ArgumentException(SR.Argument_InvalidTypeForDynamicMethod); } m_typeOwner = runtimeType; m_module = runtimeType.GetRuntimeModule(); } } m_skipVisibility = skipVisibility; } m_ilGenerator = null; m_fInitLocals = true; m_methodHandle = null; if (name == null) { throw new ArgumentNullException("name"); } m_dynMethod = new RTDynamicMethod(this, name, attributes, callingConvention); } public sealed override Delegate CreateDelegate(Type delegateType) { if (m_restrictedSkipVisibility) { GetMethodDescriptor(); IRuntimeMethodInfo methodHandle = m_methodHandle; RuntimeHelpers.CompileMethod(methodHandle?.Value ?? RuntimeMethodHandleInternal.EmptyHandle); GC.KeepAlive(methodHandle); } MulticastDelegate multicastDelegate = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, null, GetMethodDescriptor()); multicastDelegate.StoreDynamicMethod(GetMethodInfo()); return multicastDelegate; } public sealed override Delegate CreateDelegate(Type delegateType, object? target) { if (m_restrictedSkipVisibility) { GetMethodDescriptor(); IRuntimeMethodInfo methodHandle = m_methodHandle; RuntimeHelpers.CompileMethod(methodHandle?.Value ?? RuntimeMethodHandleInternal.EmptyHandle); GC.KeepAlive(methodHandle); } MulticastDelegate multicastDelegate = (MulticastDelegate)Delegate.CreateDelegateNoSecurityCheck(delegateType, target, GetMethodDescriptor()); multicastDelegate.StoreDynamicMethod(GetMethodInfo()); return multicastDelegate; } internal RuntimeMethodHandle GetMethodDescriptor() { if (m_methodHandle == null) { lock (this) { if (m_methodHandle == null) { if (m_DynamicILInfo != null) { m_DynamicILInfo.GetCallableMethod(m_module, this); } else { if (m_ilGenerator == null || m_ilGenerator.ILOffset == 0) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_BadEmptyMethodBody, Name)); } m_ilGenerator.GetCallableMethod(m_module, this); } } } } return new RuntimeMethodHandle(m_methodHandle); } public override string ToString() { return m_dynMethod.ToString(); } public override MethodInfo GetBaseDefinition() { return this; } public override ParameterInfo[] GetParameters() { return m_dynMethod.GetParameters(); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_dynMethod.GetMethodImplementationFlags(); } public override object? Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { throw new NotSupportedException(SR.NotSupported_CallToVarArg); } GetMethodDescriptor(); Signature signature = new Signature(m_methodHandle, m_parameterTypes, m_returnType, CallingConvention); int num = signature.Arguments.Length; int num2 = ((parameters != null) ? parameters.Length : 0); if (num != num2) { throw new TargetParameterCountException(SR.Arg_ParmCnt); } bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0; StackAllocedArguments stackArgs = default(StackAllocedArguments); Span arguments = default(Span); if (num2 != 0) { arguments = CheckArguments(ref stackArgs, parameters, binder, invokeAttr, culture, signature); } object result = RuntimeMethodHandle.InvokeMethod(null, in arguments, signature, constructor: false, wrapExceptions); for (int i = 0; i < arguments.Length; i++) { parameters[i] = arguments[i]; } GC.KeepAlive(this); return result; } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_dynMethod.GetCustomAttributes(attributeType, inherit); } public override object[] GetCustomAttributes(bool inherit) { return m_dynMethod.GetCustomAttributes(inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_dynMethod.IsDefined(attributeType, inherit); } public ParameterBuilder? DefineParameter(int position, ParameterAttributes attributes, string? parameterName) { if (position < 0 || position > m_parameterTypes.Length) { throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); } position--; if (position >= 0) { RuntimeParameterInfo[] array = m_dynMethod.LoadParameters(); array[position].SetName(parameterName); array[position].SetAttributes(attributes); } return null; } public DynamicILInfo GetDynamicILInfo() { if (m_DynamicILInfo == null) { CallingConventions callingConvention = CallingConvention; Type returnType = ReturnType; Type[] parameterTypes = m_parameterTypes; byte[] signature = SignatureHelper.GetMethodSigHelper(null, callingConvention, returnType, null, null, parameterTypes, null, null).GetSignature(appendEndOfSig: true); m_DynamicILInfo = new DynamicILInfo(this, signature); } return m_DynamicILInfo; } public ILGenerator GetILGenerator() { return GetILGenerator(64); } public ILGenerator GetILGenerator(int streamSize) { if (m_ilGenerator == null) { CallingConventions callingConvention = CallingConvention; Type returnType = ReturnType; Type[] parameterTypes = m_parameterTypes; byte[] signature = SignatureHelper.GetMethodSigHelper(null, callingConvention, returnType, null, null, parameterTypes, null, null).GetSignature(appendEndOfSig: true); m_ilGenerator = new DynamicILGenerator(this, signature, streamSize); } return m_ilGenerator; } internal MethodInfo GetMethodInfo() { return m_dynMethod; } } public sealed class EnumBuilder : TypeInfo { [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] internal TypeBuilder m_typeBuilder; private FieldBuilder m_underlyingField; public FieldBuilder UnderlyingField => m_underlyingField; public override string Name => m_typeBuilder.Name; public override Guid GUID => m_typeBuilder.GUID; public override Module Module => m_typeBuilder.Module; public override Assembly Assembly => m_typeBuilder.Assembly; public override RuntimeTypeHandle TypeHandle => m_typeBuilder.TypeHandle; public override string? FullName => m_typeBuilder.FullName; public override string? AssemblyQualifiedName => m_typeBuilder.AssemblyQualifiedName; public override string? Namespace => m_typeBuilder.Namespace; public override Type? BaseType => m_typeBuilder.BaseType; public override bool IsByRefLike => false; public override bool IsTypeDefinition => true; public override bool IsSZArray => false; public override bool IsConstructedGenericType => false; public override Type UnderlyingSystemType => GetEnumUnderlyingType(); public override Type? DeclaringType => m_typeBuilder.DeclaringType; public override Type? ReflectedType => m_typeBuilder.ReflectedType; public override bool IsAssignableFrom([NotNullWhen(true)] TypeInfo? typeInfo) { if (typeInfo == null) { return false; } return IsAssignableFrom(typeInfo.AsType()); } public FieldBuilder DefineLiteral(string literalName, object? literalValue) { FieldBuilder fieldBuilder = m_typeBuilder.DefineField(literalName, this, FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal); fieldBuilder.SetConstant(literalValue); return fieldBuilder; } [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public TypeInfo? CreateTypeInfo() { return m_typeBuilder.CreateTypeInfo(); } [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public Type? CreateType() { return m_typeBuilder.CreateType(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public override object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) { return m_typeBuilder.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] protected override ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { return m_typeBuilder.GetConstructor(bindingAttr, binder, callConvention, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return m_typeBuilder.GetConstructors(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { if (types == null) { return m_typeBuilder.GetMethod(name, bindingAttr); } return m_typeBuilder.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { return m_typeBuilder.GetMethods(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { return m_typeBuilder.GetField(name, bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo[] GetFields(BindingFlags bindingAttr) { return m_typeBuilder.GetFields(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type? GetInterface(string name, bool ignoreCase) { return m_typeBuilder.GetInterface(name, ignoreCase); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type[] GetInterfaces() { return m_typeBuilder.GetInterfaces(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo? GetEvent(string name, BindingFlags bindingAttr) { return m_typeBuilder.GetEvent(name, bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] public override EventInfo[] GetEvents() { return m_typeBuilder.GetEvents(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { return m_typeBuilder.GetProperties(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type[] GetNestedTypes(BindingFlags bindingAttr) { return m_typeBuilder.GetNestedTypes(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type? GetNestedType(string name, BindingFlags bindingAttr) { return m_typeBuilder.GetNestedType(name, bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { return m_typeBuilder.GetMember(name, type, bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return m_typeBuilder.GetMembers(bindingAttr); } public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type interfaceType) { return m_typeBuilder.GetInterfaceMap(interfaceType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo[] GetEvents(BindingFlags bindingAttr) { return m_typeBuilder.GetEvents(bindingAttr); } protected override TypeAttributes GetAttributeFlagsImpl() { return m_typeBuilder.Attributes; } protected override bool IsArrayImpl() { return false; } protected override bool IsPrimitiveImpl() { return false; } protected override bool IsValueTypeImpl() { return true; } protected override bool IsByRefImpl() { return false; } protected override bool IsPointerImpl() { return false; } protected override bool IsCOMObjectImpl() { return false; } public override Type? GetElementType() { return m_typeBuilder.GetElementType(); } protected override bool HasElementTypeImpl() { return m_typeBuilder.HasElementType; } public override Type GetEnumUnderlyingType() { return m_underlyingField.FieldType; } public override object[] GetCustomAttributes(bool inherit) { return m_typeBuilder.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_typeBuilder.GetCustomAttributes(attributeType, inherit); } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { m_typeBuilder.SetCustomAttribute(con, binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { m_typeBuilder.SetCustomAttribute(customBuilder); } public override bool IsDefined(Type attributeType, bool inherit) { return m_typeBuilder.IsDefined(attributeType, inherit); } public override Type MakePointerType() { return SymbolType.FormCompoundType("*", this, 0); } public override Type MakeByRefType() { return SymbolType.FormCompoundType("&", this, 0); } public override Type MakeArrayType() { return SymbolType.FormCompoundType("[]", this, 0); } public override Type MakeArrayType(int rank) { string rankString = TypeInfo.GetRankString(rank); return SymbolType.FormCompoundType(rankString, this, 0); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2064:UnrecognizedReflectionPattern", Justification = "Reflection.Emit is not subject to trimming")] internal EnumBuilder(string name, Type underlyingType, TypeAttributes visibility, ModuleBuilder module) { if (((uint)visibility & 0xFFFFFFF8u) != 0) { throw new ArgumentException(SR.Argument_ShouldOnlySetVisibilityFlags, "name"); } m_typeBuilder = new TypeBuilder(name, visibility | TypeAttributes.Sealed, typeof(Enum), null, module, PackingSize.Unspecified, 0, null); m_underlyingField = m_typeBuilder.DefineField("value__", underlyingType, FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName); } } public sealed class EventBuilder { private string m_name; private int m_evToken; private ModuleBuilder m_module; private EventAttributes m_attributes; private TypeBuilder m_type; internal EventBuilder(ModuleBuilder mod, string name, EventAttributes attr, TypeBuilder type, int evToken) { m_name = name; m_module = mod; m_attributes = attr; m_evToken = evToken; m_type = type; } private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttributes semantics) { if (mdBuilder == null) { throw new ArgumentNullException("mdBuilder"); } m_type.ThrowIfCreated(); ModuleBuilder module = m_module; TypeBuilder.DefineMethodSemantics(new QCallModule(ref module), m_evToken, semantics, mdBuilder.MetadataToken); } public void SetAddOnMethod(MethodBuilder mdBuilder) { SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.AddOn); } public void SetRemoveOnMethod(MethodBuilder mdBuilder) { SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.RemoveOn); } public void SetRaiseMethod(MethodBuilder mdBuilder) { SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Fire); } public void AddOtherMethod(MethodBuilder mdBuilder) { SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Other); } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) { throw new ArgumentNullException("con"); } if (binaryAttribute == null) { throw new ArgumentNullException("binaryAttribute"); } m_type.ThrowIfCreated(); TypeBuilder.DefineCustomAttribute(m_module, m_evToken, m_module.GetConstructorToken(con), binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { throw new ArgumentNullException("customBuilder"); } m_type.ThrowIfCreated(); customBuilder.CreateCustomAttribute(m_module, m_evToken); } } public sealed class FieldBuilder : FieldInfo { private int m_fieldTok; private TypeBuilder m_typeBuilder; private string m_fieldName; private FieldAttributes m_Attributes; private Type m_fieldType; public override int MetadataToken => m_fieldTok; public override Module Module => m_typeBuilder.Module; public override string Name => m_fieldName; public override Type? DeclaringType { get { if (m_typeBuilder.m_isHiddenGlobalType) { return null; } return m_typeBuilder; } } public override Type? ReflectedType { get { if (m_typeBuilder.m_isHiddenGlobalType) { return null; } return m_typeBuilder; } } public override Type FieldType => m_fieldType; public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(SR.NotSupported_DynamicModule); } } public override FieldAttributes Attributes => m_Attributes; internal FieldBuilder(TypeBuilder typeBuilder, string fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes) { if (fieldName == null) { throw new ArgumentNullException("fieldName"); } if (fieldName.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "fieldName"); } if (fieldName[0] == '\0') { throw new ArgumentException(SR.Argument_IllegalName, "fieldName"); } if (type == null) { throw new ArgumentNullException("type"); } if (type == typeof(void)) { throw new ArgumentException(SR.Argument_BadFieldType); } m_fieldName = fieldName; m_typeBuilder = typeBuilder; m_fieldType = type; m_Attributes = attributes & ~FieldAttributes.ReservedMask; SignatureHelper fieldSigHelper = SignatureHelper.GetFieldSigHelper(m_typeBuilder.Module); fieldSigHelper.AddArgument(type, requiredCustomModifiers, optionalCustomModifiers); int length; byte[] signature = fieldSigHelper.InternalGetSignature(out length); ModuleBuilder module = m_typeBuilder.GetModuleBuilder(); m_fieldTok = TypeBuilder.DefineField(new QCallModule(ref module), typeBuilder.TypeToken, fieldName, signature, length, m_Attributes); } internal void SetData(byte[] data, int size) { ModuleBuilder module = m_typeBuilder.GetModuleBuilder(); ModuleBuilder.SetFieldRVAContent(new QCallModule(ref module), m_fieldTok, data, size); } public override object? GetValue(object? obj) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override void SetValue(object? obj, object? val, BindingFlags invokeAttr, Binder? binder, CultureInfo? culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public void SetOffset(int iOffset) { m_typeBuilder.ThrowIfCreated(); ModuleBuilder module = m_typeBuilder.GetModuleBuilder(); TypeBuilder.SetFieldLayoutOffset(new QCallModule(ref module), m_fieldTok, iOffset); } public void SetConstant(object? defaultValue) { m_typeBuilder.ThrowIfCreated(); if (defaultValue == null && m_fieldType.IsValueType && (!m_fieldType.IsGenericType || !(m_fieldType.GetGenericTypeDefinition() == typeof(Nullable<>)))) { throw new ArgumentException(SR.Argument_ConstantNull); } TypeBuilder.SetConstantValue(m_typeBuilder.GetModuleBuilder(), m_fieldTok, m_fieldType, defaultValue); } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) { throw new ArgumentNullException("con"); } if (binaryAttribute == null) { throw new ArgumentNullException("binaryAttribute"); } ModuleBuilder moduleBuilder = m_typeBuilder.Module as ModuleBuilder; m_typeBuilder.ThrowIfCreated(); TypeBuilder.DefineCustomAttribute(moduleBuilder, m_fieldTok, moduleBuilder.GetConstructorToken(con), binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { throw new ArgumentNullException("customBuilder"); } m_typeBuilder.ThrowIfCreated(); ModuleBuilder mod = m_typeBuilder.Module as ModuleBuilder; customBuilder.CreateCustomAttribute(mod, m_fieldTok); } } public sealed class GenericTypeParameterBuilder : TypeInfo { internal TypeBuilder m_type; public override Type? DeclaringType => m_type.DeclaringType; public override Type? ReflectedType => m_type.ReflectedType; public override string Name => m_type.Name; public override Module Module => m_type.Module; public override bool IsByRefLike => false; public override int MetadataToken => m_type.MetadataToken; public override Guid GUID { get { throw new NotSupportedException(); } } public override Assembly Assembly => m_type.Assembly; public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } } public override string? FullName => null; public override string? Namespace => null; public override string? AssemblyQualifiedName => null; public override Type? BaseType => m_type.BaseType; public override bool IsTypeDefinition => false; public override bool IsSZArray => false; public override Type UnderlyingSystemType => this; public override bool IsGenericTypeDefinition => false; public override bool IsGenericType => false; public override bool IsGenericParameter => true; public override bool IsConstructedGenericType => false; public override int GenericParameterPosition => m_type.GenericParameterPosition; public override bool ContainsGenericParameters => m_type.ContainsGenericParameters; public override GenericParameterAttributes GenericParameterAttributes => m_type.GenericParameterAttributes; public override MethodBase? DeclaringMethod => m_type.DeclaringMethod; public override bool IsAssignableFrom([NotNullWhen(true)] TypeInfo? typeInfo) { if (typeInfo == null) { return false; } return IsAssignableFrom(typeInfo.AsType()); } internal GenericTypeParameterBuilder(TypeBuilder type) { m_type = type; } public override string ToString() { return m_type.Name; } public override bool Equals(object? o) { GenericTypeParameterBuilder genericTypeParameterBuilder = o as GenericTypeParameterBuilder; if (genericTypeParameterBuilder == null) { return false; } return (object)genericTypeParameterBuilder.m_type == m_type; } public override int GetHashCode() { return m_type.GetHashCode(); } public override Type MakePointerType() { return SymbolType.FormCompoundType("*", this, 0); } public override Type MakeByRefType() { return SymbolType.FormCompoundType("&", this, 0); } public override Type MakeArrayType() { return SymbolType.FormCompoundType("[]", this, 0); } public override Type MakeArrayType(int rank) { string rankString = TypeInfo.GetRankString(rank); return SymbolType.FormCompoundType(rankString, this, 0) as SymbolType; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public override object InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo GetField(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2063:UnrecognizedReflectionPattern", Justification = "Linker doesn't recognize always throwing method. https://github.com/mono/linker/issues/2025")] [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type GetInterface(string name, bool ignoreCase) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type[] GetInterfaces() { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo GetEvent(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] public override EventInfo[] GetEvents() { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type GetNestedType(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type interfaceType) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); } protected override TypeAttributes GetAttributeFlagsImpl() { return TypeAttributes.Public; } protected override bool IsArrayImpl() { return false; } protected override bool IsByRefImpl() { return false; } protected override bool IsPointerImpl() { return false; } protected override bool IsPrimitiveImpl() { return false; } protected override bool IsCOMObjectImpl() { return false; } public override Type GetElementType() { throw new NotSupportedException(); } protected override bool HasElementTypeImpl() { return false; } public override Type[] GetGenericArguments() { throw new InvalidOperationException(); } public override Type GetGenericTypeDefinition() { throw new InvalidOperationException(); } [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public override Type MakeGenericType(params Type[] typeArguments) { throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this)); } protected override bool IsValueTypeImpl() { return false; } public override bool IsAssignableFrom([NotNullWhen(true)] Type? c) { throw new NotSupportedException(); } public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); } public override object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { m_type.SetGenParamCustomAttribute(con, binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { m_type.SetGenParamCustomAttribute(customBuilder); } public void SetBaseTypeConstraint([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? baseTypeConstraint) { AssemblyBuilder.CheckContext(baseTypeConstraint); m_type.SetParent(baseTypeConstraint); } public void SetInterfaceConstraints(params Type[]? interfaceConstraints) { AssemblyBuilder.CheckContext(interfaceConstraints); m_type.SetInterfaces(interfaceConstraints); } public void SetGenericParameterAttributes(GenericParameterAttributes genericParameterAttributes) { m_type.SetGenParamAttributes(genericParameterAttributes); } } public class ILGenerator { private int m_length; private byte[] m_ILStream; private int[] m_labelList; private int m_labelCount; private __FixupData[] m_fixupData; private int m_fixupCount; private int[] m_RelocFixupList; private int m_RelocFixupCount; private int m_exceptionCount; private int m_currExcStackCount; private __ExceptionInfo[] m_exceptions; private __ExceptionInfo[] m_currExcStack; internal ScopeTree m_ScopeTree; internal MethodInfo m_methodBuilder; internal int m_localCount; internal SignatureHelper m_localSignature; private int m_maxStackSize; private int m_maxMidStack; private int m_maxMidStackCur; internal int CurrExcStackCount => m_currExcStackCount; internal __ExceptionInfo[]? CurrExcStack => m_currExcStack; public virtual int ILOffset => m_length; internal static T[] EnlargeArray(T[] incoming) { return EnlargeArray(incoming, incoming.Length * 2); } internal static T[] EnlargeArray(T[] incoming, int requiredSize) { T[] array = new T[requiredSize]; Array.Copy(incoming, array, incoming.Length); return array; } internal ILGenerator(MethodInfo methodBuilder) : this(methodBuilder, 64) { } internal ILGenerator(MethodInfo methodBuilder, int size) { m_ILStream = new byte[Math.Max(size, 16)]; m_ScopeTree = new ScopeTree(); m_methodBuilder = methodBuilder; m_localSignature = SignatureHelper.GetLocalVarSigHelper((m_methodBuilder as MethodBuilder)?.GetTypeBuilder().Module); } internal virtual void RecordTokenFixup() { if (m_RelocFixupList == null) { m_RelocFixupList = new int[8]; } else if (m_RelocFixupList.Length <= m_RelocFixupCount) { m_RelocFixupList = EnlargeArray(m_RelocFixupList); } m_RelocFixupList[m_RelocFixupCount++] = m_length; } internal void InternalEmit(OpCode opcode) { short value = opcode.Value; if (opcode.Size != 1) { BinaryPrimitives.WriteInt16BigEndian(m_ILStream.AsSpan(m_length), value); m_length += 2; } else { m_ILStream[m_length++] = (byte)value; } UpdateStackSize(opcode, opcode.StackChange()); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void UpdateStackSize(OpCode opcode, int stackchange) { m_maxMidStackCur += stackchange; if (m_maxMidStackCur > m_maxMidStack) { m_maxMidStack = m_maxMidStackCur; } else if (m_maxMidStackCur < 0) { m_maxMidStackCur = 0; } if (opcode.EndsUncondJmpBlk()) { m_maxStackSize += m_maxMidStack; m_maxMidStack = 0; m_maxMidStackCur = 0; } } private int GetMethodToken(MethodBase method, Type[] optionalParameterTypes, bool useMethodDef) { return ((ModuleBuilder)m_methodBuilder.Module).GetMethodTokenInternal(method, optionalParameterTypes, useMethodDef); } internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, Type[] parameterTypes, Type[] optionalParameterTypes) { return GetMemberRefSignature(call, returnType, parameterTypes, null, null, optionalParameterTypes); } internal virtual SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, Type[] optionalParameterTypes) { return GetMemberRefSignature(call, returnType, parameterTypes, requiredCustomModifiers, optionalCustomModifiers, optionalParameterTypes, 0); } private SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, Type[] optionalParameterTypes, int cGenericParameters) { return ((ModuleBuilder)m_methodBuilder.Module).GetMemberRefSignature(call, returnType, parameterTypes, requiredCustomModifiers, optionalCustomModifiers, optionalParameterTypes, cGenericParameters); } internal byte[] BakeByteArray() { if (m_currExcStackCount != 0) { throw new ArgumentException(SR.Argument_UnclosedExceptionBlock); } if (m_length == 0) { return null; } byte[] array = new byte[m_length]; Array.Copy(m_ILStream, array, m_length); for (int i = 0; i < m_fixupCount; i++) { __FixupData _FixupData = m_fixupData[i]; int num = GetLabelPos(_FixupData.m_fixupLabel) - (_FixupData.m_fixupPos + _FixupData.m_fixupInstSize); if (_FixupData.m_fixupInstSize == 1) { if (num < -128 || num > 127) { throw new NotSupportedException(SR.Format(SR.NotSupported_IllegalOneByteBranch, _FixupData.m_fixupPos, num)); } array[_FixupData.m_fixupPos] = (byte)num; } else { BinaryPrimitives.WriteInt32LittleEndian(array.AsSpan(_FixupData.m_fixupPos), num); } } return array; } internal __ExceptionInfo[] GetExceptions() { if (m_currExcStackCount != 0) { throw new NotSupportedException(SR.Argument_UnclosedExceptionBlock); } if (m_exceptionCount == 0) { return null; } __ExceptionInfo[] array = new __ExceptionInfo[m_exceptionCount]; Array.Copy(m_exceptions, array, m_exceptionCount); SortExceptions(array); return array; } internal void EnsureCapacity(int size) { if (m_length + size >= m_ILStream.Length) { IncreaseCapacity(size); } } private void IncreaseCapacity(int size) { byte[] array = new byte[Math.Max(m_ILStream.Length * 2, m_length + size)]; Array.Copy(m_ILStream, array, m_ILStream.Length); m_ILStream = array; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void PutInteger4(int value) { BinaryPrimitives.WriteInt32LittleEndian(m_ILStream.AsSpan(m_length), value); m_length += 4; } private int GetLabelPos(Label lbl) { int labelValue = lbl.GetLabelValue(); if (labelValue < 0 || labelValue >= m_labelCount || m_labelList == null) { throw new ArgumentException(SR.Argument_BadLabel); } if (m_labelList[labelValue] < 0) { throw new ArgumentException(SR.Argument_BadLabelContent); } return m_labelList[labelValue]; } private void AddFixup(Label lbl, int pos, int instSize) { if (m_fixupData == null) { m_fixupData = new __FixupData[8]; } else if (m_fixupData.Length <= m_fixupCount) { m_fixupData = EnlargeArray(m_fixupData); } m_fixupData[m_fixupCount++] = new __FixupData { m_fixupPos = pos, m_fixupLabel = lbl, m_fixupInstSize = instSize }; } internal int GetMaxStackSize() { return m_maxStackSize; } private static void SortExceptions(__ExceptionInfo[] exceptions) { for (int i = 0; i < exceptions.Length; i++) { int num = i; for (int j = i + 1; j < exceptions.Length; j++) { if (exceptions[num].IsInner(exceptions[j])) { num = j; } } __ExceptionInfo _ExceptionInfo = exceptions[i]; exceptions[i] = exceptions[num]; exceptions[num] = _ExceptionInfo; } } internal int[] GetTokenFixups() { if (m_RelocFixupCount == 0) { return null; } int[] array = new int[m_RelocFixupCount]; Array.Copy(m_RelocFixupList, array, m_RelocFixupCount); return array; } public virtual void Emit(OpCode opcode) { EnsureCapacity(3); InternalEmit(opcode); } public virtual void Emit(OpCode opcode, byte arg) { EnsureCapacity(4); InternalEmit(opcode); m_ILStream[m_length++] = arg; } [CLSCompliant(false)] public void Emit(OpCode opcode, sbyte arg) { EnsureCapacity(4); InternalEmit(opcode); m_ILStream[m_length++] = (byte)arg; } public virtual void Emit(OpCode opcode, short arg) { EnsureCapacity(5); InternalEmit(opcode); BinaryPrimitives.WriteInt16LittleEndian(m_ILStream.AsSpan(m_length), arg); m_length += 2; } public virtual void Emit(OpCode opcode, int arg) { if (opcode.Equals(OpCodes.Ldc_I4)) { OpCode opCode; switch (arg) { case -1: opCode = OpCodes.Ldc_I4_M1; goto IL_009b; case 0: opCode = OpCodes.Ldc_I4_0; goto IL_009b; case 1: opCode = OpCodes.Ldc_I4_1; goto IL_009b; case 2: opCode = OpCodes.Ldc_I4_2; goto IL_009b; case 3: opCode = OpCodes.Ldc_I4_3; goto IL_009b; case 4: opCode = OpCodes.Ldc_I4_4; goto IL_009b; case 5: opCode = OpCodes.Ldc_I4_5; goto IL_009b; case 6: opCode = OpCodes.Ldc_I4_6; goto IL_009b; case 7: opCode = OpCodes.Ldc_I4_7; goto IL_009b; case 8: { opCode = OpCodes.Ldc_I4_8; goto IL_009b; } IL_009b: opcode = opCode; Emit(opcode); return; } if (arg >= -128 && arg <= 127) { Emit(OpCodes.Ldc_I4_S, (sbyte)arg); return; } } else if (opcode.Equals(OpCodes.Ldarg)) { if ((uint)arg <= 3u) { Emit(arg switch { 0 => OpCodes.Ldarg_0, 1 => OpCodes.Ldarg_1, 2 => OpCodes.Ldarg_2, _ => OpCodes.Ldarg_3, }); return; } if ((uint)arg <= 255u) { Emit(OpCodes.Ldarg_S, (byte)arg); return; } if ((uint)arg <= 65535u) { Emit(OpCodes.Ldarg, (short)arg); return; } } else if (opcode.Equals(OpCodes.Ldarga)) { if ((uint)arg <= 255u) { Emit(OpCodes.Ldarga_S, (byte)arg); return; } if ((uint)arg <= 65535u) { Emit(OpCodes.Ldarga, (short)arg); return; } } else if (opcode.Equals(OpCodes.Starg)) { if ((uint)arg <= 255u) { Emit(OpCodes.Starg_S, (byte)arg); return; } if ((uint)arg <= 65535u) { Emit(OpCodes.Starg, (short)arg); return; } } EnsureCapacity(7); InternalEmit(opcode); PutInteger4(arg); } public virtual void Emit(OpCode opcode, MethodInfo meth) { if (meth == null) { throw new ArgumentNullException("meth"); } if (opcode.Equals(OpCodes.Call) || opcode.Equals(OpCodes.Callvirt) || opcode.Equals(OpCodes.Newobj)) { EmitCall(opcode, meth, null); return; } bool useMethodDef = opcode.Equals(OpCodes.Ldtoken) || opcode.Equals(OpCodes.Ldftn) || opcode.Equals(OpCodes.Ldvirtftn); int methodToken = GetMethodToken(meth, null, useMethodDef); EnsureCapacity(7); InternalEmit(opcode); UpdateStackSize(opcode, 0); RecordTokenFixup(); PutInteger4(methodToken); } public virtual void EmitCalli(OpCode opcode, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, Type[]? optionalParameterTypes) { int num = 0; if (optionalParameterTypes != null && (callingConvention & CallingConventions.VarArgs) == 0) { throw new InvalidOperationException(SR.InvalidOperation_NotAVarArgCallingConvention); } ModuleBuilder moduleBuilder = (ModuleBuilder)m_methodBuilder.Module; SignatureHelper memberRefSignature = GetMemberRefSignature(callingConvention, returnType, parameterTypes, optionalParameterTypes); EnsureCapacity(7); Emit(OpCodes.Calli); if (returnType != typeof(void)) { num++; } if (parameterTypes != null) { num -= parameterTypes.Length; } if (optionalParameterTypes != null) { num -= optionalParameterTypes.Length; } if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis) { num--; } num--; UpdateStackSize(OpCodes.Calli, num); RecordTokenFixup(); PutInteger4(moduleBuilder.GetSignatureToken(memberRefSignature)); } public virtual void EmitCalli(OpCode opcode, CallingConvention unmanagedCallConv, Type? returnType, Type[]? parameterTypes) { int num = 0; int num2 = 0; ModuleBuilder moduleBuilder = (ModuleBuilder)m_methodBuilder.Module; if (parameterTypes != null) { num2 = parameterTypes.Length; } SignatureHelper methodSigHelper = SignatureHelper.GetMethodSigHelper(moduleBuilder, unmanagedCallConv, returnType); if (parameterTypes != null) { for (int i = 0; i < num2; i++) { methodSigHelper.AddArgument(parameterTypes[i]); } } if (returnType != typeof(void)) { num++; } if (parameterTypes != null) { num -= num2; } num--; UpdateStackSize(OpCodes.Calli, num); EnsureCapacity(7); Emit(OpCodes.Calli); RecordTokenFixup(); PutInteger4(moduleBuilder.GetSignatureToken(methodSigHelper)); } public virtual void EmitCall(OpCode opcode, MethodInfo methodInfo, Type[]? optionalParameterTypes) { if (methodInfo == null) { throw new ArgumentNullException("methodInfo"); } if (!opcode.Equals(OpCodes.Call) && !opcode.Equals(OpCodes.Callvirt) && !opcode.Equals(OpCodes.Newobj)) { throw new ArgumentException(SR.Argument_NotMethodCallOpcode, "opcode"); } int num = 0; int methodToken = GetMethodToken(methodInfo, optionalParameterTypes, useMethodDef: false); EnsureCapacity(7); InternalEmit(opcode); if (methodInfo.ReturnType != typeof(void)) { num++; } Type[] parameterTypes = methodInfo.GetParameterTypes(); if (parameterTypes != null) { num -= parameterTypes.Length; } if (!(methodInfo is SymbolMethod) && !methodInfo.IsStatic && !opcode.Equals(OpCodes.Newobj)) { num--; } if (optionalParameterTypes != null) { num -= optionalParameterTypes.Length; } UpdateStackSize(opcode, num); RecordTokenFixup(); PutInteger4(methodToken); } public virtual void Emit(OpCode opcode, SignatureHelper signature) { if (signature == null) { throw new ArgumentNullException("signature"); } int num = 0; ModuleBuilder moduleBuilder = (ModuleBuilder)m_methodBuilder.Module; int signatureToken = moduleBuilder.GetSignatureToken(signature); int value = signatureToken; EnsureCapacity(7); InternalEmit(opcode); if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { num -= signature.ArgumentCount; num--; UpdateStackSize(opcode, num); } RecordTokenFixup(); PutInteger4(value); } public virtual void Emit(OpCode opcode, ConstructorInfo con) { if (con == null) { throw new ArgumentNullException("con"); } int num = 0; int methodToken = GetMethodToken(con, null, useMethodDef: true); EnsureCapacity(7); InternalEmit(opcode); if (opcode.StackBehaviourPush == StackBehaviour.Varpush) { num++; } if (opcode.StackBehaviourPop == StackBehaviour.Varpop) { Type[] parameterTypes = con.GetParameterTypes(); if (parameterTypes != null) { num -= parameterTypes.Length; } } UpdateStackSize(opcode, num); RecordTokenFixup(); PutInteger4(methodToken); } public virtual void Emit(OpCode opcode, Type cls) { ModuleBuilder moduleBuilder = (ModuleBuilder)m_methodBuilder.Module; int value = ((!(opcode == OpCodes.Ldtoken) || !(cls != null) || !cls.IsGenericTypeDefinition) ? moduleBuilder.GetTypeTokenInternal(cls) : moduleBuilder.GetTypeToken(cls)); EnsureCapacity(7); InternalEmit(opcode); RecordTokenFixup(); PutInteger4(value); } public virtual void Emit(OpCode opcode, long arg) { EnsureCapacity(11); InternalEmit(opcode); BinaryPrimitives.WriteInt64LittleEndian(m_ILStream.AsSpan(m_length), arg); m_length += 8; } public virtual void Emit(OpCode opcode, float arg) { EnsureCapacity(7); InternalEmit(opcode); BinaryPrimitives.WriteInt32LittleEndian(m_ILStream.AsSpan(m_length), BitConverter.SingleToInt32Bits(arg)); m_length += 4; } public virtual void Emit(OpCode opcode, double arg) { EnsureCapacity(11); InternalEmit(opcode); BinaryPrimitives.WriteInt64LittleEndian(m_ILStream.AsSpan(m_length), BitConverter.DoubleToInt64Bits(arg)); m_length += 8; } public virtual void Emit(OpCode opcode, Label label) { EnsureCapacity(7); InternalEmit(opcode); if (OpCodes.TakesSingleByteArgument(opcode)) { AddFixup(label, m_length++, 1); return; } AddFixup(label, m_length, 4); m_length += 4; } public virtual void Emit(OpCode opcode, Label[] labels) { if (labels == null) { throw new ArgumentNullException("labels"); } int num = labels.Length; EnsureCapacity(num * 4 + 7); InternalEmit(opcode); PutInteger4(num); int num2 = num * 4; int num3 = 0; while (num2 > 0) { AddFixup(labels[num3], m_length, num2); m_length += 4; num2 -= 4; num3++; } } public virtual void Emit(OpCode opcode, FieldInfo field) { ModuleBuilder moduleBuilder = (ModuleBuilder)m_methodBuilder.Module; int fieldToken = moduleBuilder.GetFieldToken(field); EnsureCapacity(7); InternalEmit(opcode); RecordTokenFixup(); PutInteger4(fieldToken); } public virtual void Emit(OpCode opcode, string str) { ModuleBuilder moduleBuilder = (ModuleBuilder)m_methodBuilder.Module; int stringConstant = moduleBuilder.GetStringConstant(str); EnsureCapacity(7); InternalEmit(opcode); PutInteger4(stringConstant); } public virtual void Emit(OpCode opcode, LocalBuilder local) { if (local == null) { throw new ArgumentNullException("local"); } int localIndex = local.GetLocalIndex(); if (local.GetMethodBuilder() != m_methodBuilder) { throw new ArgumentException(SR.Argument_UnmatchedMethodForLocal, "local"); } if (opcode.Equals(OpCodes.Ldloc)) { switch (localIndex) { case 0: opcode = OpCodes.Ldloc_0; break; case 1: opcode = OpCodes.Ldloc_1; break; case 2: opcode = OpCodes.Ldloc_2; break; case 3: opcode = OpCodes.Ldloc_3; break; default: if (localIndex <= 255) { opcode = OpCodes.Ldloc_S; } break; } } else if (opcode.Equals(OpCodes.Stloc)) { switch (localIndex) { case 0: opcode = OpCodes.Stloc_0; break; case 1: opcode = OpCodes.Stloc_1; break; case 2: opcode = OpCodes.Stloc_2; break; case 3: opcode = OpCodes.Stloc_3; break; default: if (localIndex <= 255) { opcode = OpCodes.Stloc_S; } break; } } else if (opcode.Equals(OpCodes.Ldloca) && localIndex <= 255) { opcode = OpCodes.Ldloca_S; } EnsureCapacity(7); InternalEmit(opcode); if (opcode.OperandType == OperandType.InlineNone) { return; } if (!OpCodes.TakesSingleByteArgument(opcode)) { BinaryPrimitives.WriteInt16LittleEndian(m_ILStream.AsSpan(m_length), (short)localIndex); m_length += 2; return; } if (localIndex > 255) { throw new InvalidOperationException(SR.InvalidOperation_BadInstructionOrIndexOutOfBound); } m_ILStream[m_length++] = (byte)localIndex; } public virtual Label BeginExceptionBlock() { if (m_exceptions == null) { m_exceptions = new __ExceptionInfo[2]; } if (m_currExcStack == null) { m_currExcStack = new __ExceptionInfo[2]; } if (m_exceptionCount >= m_exceptions.Length) { m_exceptions = EnlargeArray(m_exceptions); } if (m_currExcStackCount >= m_currExcStack.Length) { m_currExcStack = EnlargeArray(m_currExcStack); } Label label = DefineLabel(); __ExceptionInfo _ExceptionInfo = new __ExceptionInfo(m_length, label); m_exceptions[m_exceptionCount++] = _ExceptionInfo; m_currExcStack[m_currExcStackCount++] = _ExceptionInfo; return label; } public virtual void EndExceptionBlock() { if (m_currExcStackCount == 0) { throw new NotSupportedException(SR.Argument_NotInExceptionBlock); } __ExceptionInfo _ExceptionInfo = m_currExcStack[m_currExcStackCount - 1]; m_currExcStack[--m_currExcStackCount] = null; Label endLabel = _ExceptionInfo.GetEndLabel(); switch (_ExceptionInfo.GetCurrentState()) { case 0: case 1: throw new InvalidOperationException(SR.Argument_BadExceptionCodeGen); case 2: Emit(OpCodes.Leave, endLabel); break; case 3: case 4: Emit(OpCodes.Endfinally); break; } Label loc = ((m_labelList[endLabel.GetLabelValue()] != -1) ? _ExceptionInfo.m_finallyEndLabel : endLabel); MarkLabel(loc); _ExceptionInfo.Done(m_length); } public virtual void BeginExceptFilterBlock() { if (m_currExcStackCount == 0) { throw new NotSupportedException(SR.Argument_NotInExceptionBlock); } __ExceptionInfo _ExceptionInfo = m_currExcStack[m_currExcStackCount - 1]; Emit(OpCodes.Leave, _ExceptionInfo.GetEndLabel()); _ExceptionInfo.MarkFilterAddr(m_length); } public virtual void BeginCatchBlock(Type exceptionType) { if (m_currExcStackCount == 0) { throw new NotSupportedException(SR.Argument_NotInExceptionBlock); } __ExceptionInfo _ExceptionInfo = m_currExcStack[m_currExcStackCount - 1]; if (_ExceptionInfo.GetCurrentState() == 1) { if (exceptionType != null) { throw new ArgumentException(SR.Argument_ShouldNotSpecifyExceptionType); } Emit(OpCodes.Endfilter); } else { if (exceptionType == null) { throw new ArgumentNullException("exceptionType"); } Emit(OpCodes.Leave, _ExceptionInfo.GetEndLabel()); } _ExceptionInfo.MarkCatchAddr(m_length, exceptionType); } public virtual void BeginFaultBlock() { if (m_currExcStackCount == 0) { throw new NotSupportedException(SR.Argument_NotInExceptionBlock); } __ExceptionInfo _ExceptionInfo = m_currExcStack[m_currExcStackCount - 1]; Emit(OpCodes.Leave, _ExceptionInfo.GetEndLabel()); _ExceptionInfo.MarkFaultAddr(m_length); } public virtual void BeginFinallyBlock() { if (m_currExcStackCount == 0) { throw new NotSupportedException(SR.Argument_NotInExceptionBlock); } __ExceptionInfo _ExceptionInfo = m_currExcStack[m_currExcStackCount - 1]; int currentState = _ExceptionInfo.GetCurrentState(); Label endLabel = _ExceptionInfo.GetEndLabel(); int num = 0; if (currentState != 0) { Emit(OpCodes.Leave, endLabel); num = m_length; } MarkLabel(endLabel); Label label = DefineLabel(); _ExceptionInfo.SetFinallyEndLabel(label); Emit(OpCodes.Leave, label); if (num == 0) { num = m_length; } _ExceptionInfo.MarkFinallyAddr(m_length, num); } public virtual Label DefineLabel() { if (m_labelList == null) { m_labelList = new int[4]; } if (m_labelCount >= m_labelList.Length) { m_labelList = EnlargeArray(m_labelList); } m_labelList[m_labelCount] = -1; return new Label(m_labelCount++); } public virtual void MarkLabel(Label loc) { int labelValue = loc.GetLabelValue(); if (m_labelList == null || labelValue < 0 || labelValue >= m_labelList.Length) { throw new ArgumentException(SR.Argument_InvalidLabel); } if (m_labelList[labelValue] != -1) { throw new ArgumentException(SR.Argument_RedefinedLabel); } m_labelList[labelValue] = m_length; } public virtual void ThrowException([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] Type excType) { if (excType == null) { throw new ArgumentNullException("excType"); } if (!excType.IsSubclassOf(typeof(Exception)) && excType != typeof(Exception)) { throw new ArgumentException(SR.Argument_NotExceptionType); } ConstructorInfo constructor = excType.GetConstructor(Type.EmptyTypes); if (constructor == null) { throw new ArgumentException(SR.Argument_MissingDefaultConstructor); } Emit(OpCodes.Newobj, constructor); Emit(OpCodes.Throw); } public virtual void EmitWriteLine(string value) { Emit(OpCodes.Ldstr, value); Type[] types = new Type[1] { typeof(string) }; Type type = Type.GetType("System.Console, System.Console", throwOnError: true); MethodInfo method = type.GetMethod("WriteLine", types); Emit(OpCodes.Call, method); } public virtual void EmitWriteLine(LocalBuilder localBuilder) { if (m_methodBuilder == null) { throw new ArgumentException(SR.InvalidOperation_BadILGeneratorUsage); } Type type = Type.GetType("System.Console, System.Console", throwOnError: true); MethodInfo method = type.GetMethod("get_Out"); Emit(OpCodes.Call, method); Emit(OpCodes.Ldloc, localBuilder); Type[] array = new Type[1]; Type localType = localBuilder.LocalType; if (localType is TypeBuilder || localType is EnumBuilder) { throw new ArgumentException(SR.NotSupported_OutputStreamUsingTypeBuilder); } array[0] = localType; MethodInfo method2 = typeof(TextWriter).GetMethod("WriteLine", array); if (method2 == null) { throw new ArgumentException(SR.Argument_EmitWriteLineType, "localBuilder"); } Emit(OpCodes.Callvirt, method2); } public virtual void EmitWriteLine(FieldInfo fld) { if (fld == null) { throw new ArgumentNullException("fld"); } Type type = Type.GetType("System.Console, System.Console", throwOnError: true); MethodInfo method = type.GetMethod("get_Out"); Emit(OpCodes.Call, method); if ((fld.Attributes & FieldAttributes.Static) != 0) { Emit(OpCodes.Ldsfld, fld); } else { Emit(OpCodes.Ldarg, (short)0); Emit(OpCodes.Ldfld, fld); } Type[] array = new Type[1]; Type fieldType = fld.FieldType; if (fieldType is TypeBuilder || fieldType is EnumBuilder) { throw new NotSupportedException(SR.NotSupported_OutputStreamUsingTypeBuilder); } array[0] = fieldType; MethodInfo method2 = typeof(TextWriter).GetMethod("WriteLine", array); if (method2 == null) { throw new ArgumentException(SR.Argument_EmitWriteLineType, "fld"); } Emit(OpCodes.Callvirt, method2); } public virtual LocalBuilder DeclareLocal(Type localType) { return DeclareLocal(localType, pinned: false); } public virtual LocalBuilder DeclareLocal(Type localType, bool pinned) { MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder; if (methodBuilder == null) { throw new NotSupportedException(); } if (methodBuilder.IsTypeCreated()) { throw new InvalidOperationException(SR.InvalidOperation_TypeHasBeenCreated); } if (localType == null) { throw new ArgumentNullException("localType"); } if (methodBuilder.m_bIsBaked) { throw new InvalidOperationException(SR.InvalidOperation_MethodBaked); } m_localSignature.AddArgument(localType, pinned); return new LocalBuilder(m_localCount++, localType, methodBuilder, pinned); } public virtual void UsingNamespace(string usingNamespace) { if (usingNamespace == null) { throw new ArgumentNullException("usingNamespace"); } if (usingNamespace.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "usingNamespace"); } MethodBuilder methodBuilder = m_methodBuilder as MethodBuilder; if (methodBuilder == null) { throw new NotSupportedException(); } int currentActiveScopeIndex = methodBuilder.GetILGenerator().m_ScopeTree.GetCurrentActiveScopeIndex(); if (currentActiveScopeIndex == -1) { methodBuilder.m_localSymInfo.AddUsingNamespace(usingNamespace); } else { m_ScopeTree.AddUsingNamespaceToCurrentScope(usingNamespace); } } public virtual void BeginScope() { m_ScopeTree.AddScopeInfo(ScopeAction.Open, m_length); } public virtual void EndScope() { m_ScopeTree.AddScopeInfo(ScopeAction.Close, m_length); } } internal struct __FixupData { internal Label m_fixupLabel; internal int m_fixupPos; internal int m_fixupInstSize; } internal sealed class __ExceptionInfo { internal int m_startAddr; internal int[] m_filterAddr; internal int[] m_catchAddr; internal int[] m_catchEndAddr; internal int[] m_type; internal Type[] m_catchClass; internal Label m_endLabel; internal Label m_finallyEndLabel; internal int m_endAddr; internal int m_endFinally; internal int m_currentCatch; private int m_currentState; internal __ExceptionInfo(int startAddr, Label endLabel) { m_startAddr = startAddr; m_endAddr = -1; m_filterAddr = new int[4]; m_catchAddr = new int[4]; m_catchEndAddr = new int[4]; m_catchClass = new Type[4]; m_currentCatch = 0; m_endLabel = endLabel; m_type = new int[4]; m_endFinally = -1; m_currentState = 0; } private void MarkHelper(int catchorfilterAddr, int catchEndAddr, Type catchClass, int type) { int currentCatch = m_currentCatch; if (currentCatch >= m_catchAddr.Length) { m_filterAddr = ILGenerator.EnlargeArray(m_filterAddr); m_catchAddr = ILGenerator.EnlargeArray(m_catchAddr); m_catchEndAddr = ILGenerator.EnlargeArray(m_catchEndAddr); m_catchClass = ILGenerator.EnlargeArray(m_catchClass); m_type = ILGenerator.EnlargeArray(m_type); } if (type == 1) { m_type[currentCatch] = type; m_filterAddr[currentCatch] = catchorfilterAddr; m_catchAddr[currentCatch] = -1; if (currentCatch > 0) { m_catchEndAddr[currentCatch - 1] = catchorfilterAddr; } } else { m_catchClass[currentCatch] = catchClass; if (m_type[currentCatch] != 1) { m_type[currentCatch] = type; } m_catchAddr[currentCatch] = catchorfilterAddr; if (currentCatch > 0 && m_type[currentCatch] != 1) { m_catchEndAddr[currentCatch - 1] = catchEndAddr; } m_catchEndAddr[currentCatch] = -1; m_currentCatch++; } if (m_endAddr == -1) { m_endAddr = catchorfilterAddr; } } internal void MarkFilterAddr(int filterAddr) { m_currentState = 1; MarkHelper(filterAddr, filterAddr, null, 1); } internal void MarkFaultAddr(int faultAddr) { m_currentState = 4; MarkHelper(faultAddr, faultAddr, null, 4); } internal void MarkCatchAddr(int catchAddr, Type catchException) { m_currentState = 2; MarkHelper(catchAddr, catchAddr, catchException, 0); } internal void MarkFinallyAddr(int finallyAddr, int endCatchAddr) { if (m_endFinally != -1) { throw new ArgumentException(SR.Argument_TooManyFinallyClause); } m_currentState = 3; m_endFinally = finallyAddr; MarkHelper(finallyAddr, endCatchAddr, null, 2); } internal void Done(int endAddr) { m_catchEndAddr[m_currentCatch - 1] = endAddr; m_currentState = 5; } internal int GetStartAddress() { return m_startAddr; } internal int GetEndAddress() { return m_endAddr; } internal int GetFinallyEndAddress() { return m_endFinally; } internal Label GetEndLabel() { return m_endLabel; } internal int[] GetFilterAddresses() { return m_filterAddr; } internal int[] GetCatchAddresses() { return m_catchAddr; } internal int[] GetCatchEndAddresses() { return m_catchEndAddr; } internal Type[] GetCatchClass() { return m_catchClass; } internal int GetNumberOfCatches() { return m_currentCatch; } internal int[] GetExceptionTypes() { return m_type; } internal void SetFinallyEndLabel(Label lbl) { m_finallyEndLabel = lbl; } internal bool IsInner(__ExceptionInfo exc) { int num = exc.m_currentCatch - 1; int num2 = m_currentCatch - 1; if (exc.m_catchEndAddr[num] < m_catchEndAddr[num2]) { return true; } if (exc.m_catchEndAddr[num] != m_catchEndAddr[num2]) { return false; } return exc.GetEndAddress() > GetEndAddress(); } internal int GetCurrentState() { return m_currentState; } } internal enum ScopeAction : sbyte { Open = -1, Close = 1 } internal sealed class ScopeTree { internal int[] m_iOffsets; internal ScopeAction[] m_ScopeActions; internal int m_iCount; internal int m_iOpenScopeCount; internal LocalSymInfo[] m_localSymInfos; internal ScopeTree() { m_iOpenScopeCount = 0; m_iCount = 0; } internal int GetCurrentActiveScopeIndex() { if (m_iCount == 0) { return -1; } int num = m_iCount - 1; int num2 = 0; while (num2 > 0 || m_ScopeActions[num] == ScopeAction.Close) { num2 += (int)m_ScopeActions[num]; num--; } return num; } internal void AddUsingNamespaceToCurrentScope(string strNamespace) { int currentActiveScopeIndex = GetCurrentActiveScopeIndex(); ref LocalSymInfo reference = ref m_localSymInfos[currentActiveScopeIndex]; if (reference == null) { reference = new LocalSymInfo(); } m_localSymInfos[currentActiveScopeIndex].AddUsingNamespace(strNamespace); } internal void AddScopeInfo(ScopeAction sa, int iOffset) { if (sa == ScopeAction.Close && m_iOpenScopeCount <= 0) { throw new ArgumentException(SR.Argument_UnmatchingSymScope); } EnsureCapacity(); m_ScopeActions[m_iCount] = sa; m_iOffsets[m_iCount] = iOffset; m_localSymInfos[m_iCount] = null; checked { m_iCount++; } m_iOpenScopeCount += 0 - sa; } internal void EnsureCapacity() { if (m_iCount == 0) { m_iOffsets = new int[16]; m_ScopeActions = new ScopeAction[16]; m_localSymInfos = new LocalSymInfo[16]; } else if (m_iCount == m_iOffsets.Length) { int num = checked(m_iCount * 2); int[] array = new int[num]; Array.Copy(m_iOffsets, array, m_iCount); m_iOffsets = array; ScopeAction[] array2 = new ScopeAction[num]; Array.Copy(m_ScopeActions, array2, m_iCount); m_ScopeActions = array2; LocalSymInfo[] array3 = new LocalSymInfo[num]; Array.Copy(m_localSymInfos, array3, m_iCount); m_localSymInfos = array3; } } } public sealed class LocalBuilder : LocalVariableInfo { private int m_localIndex; private Type m_localType; private MethodInfo m_methodBuilder; private bool m_isPinned; public override bool IsPinned => m_isPinned; public override Type LocalType => m_localType; public override int LocalIndex => m_localIndex; internal LocalBuilder(int localIndex, Type localType, MethodInfo methodBuilder) : this(localIndex, localType, methodBuilder, isPinned: false) { } internal LocalBuilder(int localIndex, Type localType, MethodInfo methodBuilder, bool isPinned) { m_isPinned = isPinned; m_localIndex = localIndex; m_localType = localType; m_methodBuilder = methodBuilder; } internal int GetLocalIndex() { return m_localIndex; } internal MethodInfo GetMethodBuilder() { return m_methodBuilder; } } public sealed class MethodBuilder : MethodInfo { internal string m_strName; private int m_token; private readonly ModuleBuilder m_module; [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] internal TypeBuilder m_containingType; private int[] m_mdMethodFixups; private byte[] m_localSignature; internal LocalSymInfo m_localSymInfo; internal ILGenerator m_ilGenerator; private byte[] m_ubBody; private ExceptionHandler[] m_exceptions; internal bool m_bIsBaked; private bool m_fInitLocals; private readonly MethodAttributes m_iAttributes; private readonly CallingConventions m_callingConvention; private MethodImplAttributes m_dwMethodImplFlags; private SignatureHelper m_signature; internal Type[] m_parameterTypes; private Type m_returnType; private Type[] m_returnTypeRequiredCustomModifiers; private Type[] m_returnTypeOptionalCustomModifiers; private Type[][] m_parameterTypeRequiredCustomModifiers; private Type[][] m_parameterTypeOptionalCustomModifiers; private GenericTypeParameterBuilder[] m_inst; private bool m_bIsGenMethDef; internal bool m_canBeRuntimeImpl; internal bool m_isDllImport; internal int ExceptionHandlerCount { get { if (m_exceptions == null) { return 0; } return m_exceptions.Length; } } public override string Name => m_strName; public override int MetadataToken => GetToken(); public override Module Module => m_containingType.Module; public override Type? DeclaringType { get { if (m_containingType.m_isHiddenGlobalType) { return null; } return m_containingType; } } public override ICustomAttributeProvider ReturnTypeCustomAttributes => new EmptyCAHolder(); public override Type? ReflectedType => DeclaringType; public override MethodAttributes Attributes => m_iAttributes; public override CallingConventions CallingConvention => m_callingConvention; public override RuntimeMethodHandle MethodHandle { get { throw new NotSupportedException(SR.NotSupported_DynamicModule); } } public override bool IsSecurityCritical => true; public override bool IsSecuritySafeCritical => false; public override bool IsSecurityTransparent => false; public override Type ReturnType => m_returnType; public override ParameterInfo ReturnParameter { get { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) { throw new InvalidOperationException(SR.InvalidOperation_TypeNotCreated); } MethodInfo method = m_containingType.GetMethod(m_strName, m_parameterTypes); return method.ReturnParameter; } } public override bool IsGenericMethodDefinition => m_bIsGenMethDef; public override bool ContainsGenericParameters { get { throw new NotSupportedException(); } } public override bool IsGenericMethod => m_inst != null; public bool InitLocals { get { ThrowIfGeneric(); return m_fInitLocals; } set { ThrowIfGeneric(); m_fInitLocals = value; } } internal MethodBuilder(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, ModuleBuilder mod, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TypeBuilder type) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "name"); } if (name[0] == '\0') { throw new ArgumentException(SR.Argument_IllegalName, "name"); } if (mod == null) { throw new ArgumentNullException("mod"); } if (parameterTypes != null) { foreach (Type type2 in parameterTypes) { if (type2 == null) { throw new ArgumentNullException("parameterTypes"); } } } m_strName = name; m_module = mod; m_containingType = type; m_returnType = returnType ?? typeof(void); if ((attributes & MethodAttributes.Static) == 0) { callingConvention |= CallingConventions.HasThis; } else if ((attributes & MethodAttributes.Virtual) != 0 && (attributes & MethodAttributes.Abstract) == 0) { throw new ArgumentException(SR.Arg_NoStaticVirtual); } m_callingConvention = callingConvention; if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy(parameterTypes, m_parameterTypes, parameterTypes.Length); } else { m_parameterTypes = null; } m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers; m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers; m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers; m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers; m_iAttributes = attributes; m_bIsBaked = false; m_fInitLocals = true; m_localSymInfo = new LocalSymInfo(); m_ubBody = null; m_ilGenerator = null; m_dwMethodImplFlags = MethodImplAttributes.IL; } internal void CreateMethodBodyHelper(ILGenerator il) { if (il == null) { throw new ArgumentNullException("il"); } int num = 0; ModuleBuilder module = m_module; m_containingType.ThrowIfCreated(); if (m_bIsBaked) { throw new InvalidOperationException(SR.InvalidOperation_MethodHasBody); } if (il.m_methodBuilder != this && il.m_methodBuilder != null) { throw new InvalidOperationException(SR.InvalidOperation_BadILGeneratorUsage); } ThrowIfShouldNotHaveBody(); if (il.m_ScopeTree.m_iOpenScopeCount != 0) { throw new InvalidOperationException(SR.InvalidOperation_OpenLocalVariableScope); } m_ubBody = il.BakeByteArray(); m_mdMethodFixups = il.GetTokenFixups(); __ExceptionInfo[] exceptions = il.GetExceptions(); int num2 = CalculateNumberOfExceptions(exceptions); if (num2 > 0) { m_exceptions = new ExceptionHandler[num2]; for (int i = 0; i < exceptions.Length; i++) { int[] filterAddresses = exceptions[i].GetFilterAddresses(); int[] catchAddresses = exceptions[i].GetCatchAddresses(); int[] catchEndAddresses = exceptions[i].GetCatchEndAddresses(); Type[] catchClass = exceptions[i].GetCatchClass(); int numberOfCatches = exceptions[i].GetNumberOfCatches(); int startAddress = exceptions[i].GetStartAddress(); int endAddress = exceptions[i].GetEndAddress(); int[] exceptionTypes = exceptions[i].GetExceptionTypes(); for (int j = 0; j < numberOfCatches; j++) { int exceptionTypeToken = 0; if (catchClass[j] != null) { exceptionTypeToken = module.GetTypeTokenInternal(catchClass[j]); } switch (exceptionTypes[j]) { case 0: case 1: case 4: m_exceptions[num++] = new ExceptionHandler(startAddress, endAddress, filterAddresses[j], catchAddresses[j], catchEndAddresses[j], exceptionTypes[j], exceptionTypeToken); break; case 2: m_exceptions[num++] = new ExceptionHandler(startAddress, exceptions[i].GetFinallyEndAddress(), filterAddresses[j], catchAddresses[j], catchEndAddresses[j], exceptionTypes[j], exceptionTypeToken); break; } } } } m_bIsBaked = true; } internal void ReleaseBakedStructures() { if (m_bIsBaked) { m_ubBody = null; m_localSymInfo = null; m_mdMethodFixups = null; m_localSignature = null; m_exceptions = null; } } internal override Type[] GetParameterTypes() { return m_parameterTypes ?? (m_parameterTypes = Type.EmptyTypes); } internal static Type GetMethodBaseReturnType(MethodBase method) { if (method is MethodInfo methodInfo) { return methodInfo.ReturnType; } if (method is ConstructorInfo constructorInfo) { return constructorInfo.GetReturnType(); } return null; } internal void SetToken(int token) { m_token = token; } internal byte[] GetBody() { return m_ubBody; } internal int[] GetTokenFixups() { return m_mdMethodFixups; } internal SignatureHelper GetMethodSignature() { if (m_parameterTypes == null) { m_parameterTypes = Type.EmptyTypes; } m_signature = SignatureHelper.GetMethodSigHelper(m_module, m_callingConvention, (m_inst != null) ? m_inst.Length : 0, m_returnType, m_returnTypeRequiredCustomModifiers, m_returnTypeOptionalCustomModifiers, m_parameterTypes, m_parameterTypeRequiredCustomModifiers, m_parameterTypeOptionalCustomModifiers); return m_signature; } internal byte[] GetLocalSignature(out int signatureLength) { if (m_localSignature != null) { signatureLength = m_localSignature.Length; return m_localSignature; } if (m_ilGenerator != null && m_ilGenerator.m_localCount != 0) { return m_ilGenerator.m_localSignature.InternalGetSignature(out signatureLength); } return SignatureHelper.GetLocalVarSigHelper(m_module).InternalGetSignature(out signatureLength); } internal int GetMaxStack() { if (m_ilGenerator != null) { return m_ilGenerator.GetMaxStackSize() + ExceptionHandlerCount; } return 16; } internal ExceptionHandler[] GetExceptionHandlers() { return m_exceptions; } internal static int CalculateNumberOfExceptions(__ExceptionInfo[] excp) { int num = 0; if (excp == null) { return 0; } for (int i = 0; i < excp.Length; i++) { num += excp[i].GetNumberOfCatches(); } return num; } internal bool IsTypeCreated() { if (m_containingType != null) { return m_containingType.IsCreated(); } return false; } [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] internal TypeBuilder GetTypeBuilder() { return m_containingType; } internal ModuleBuilder GetModuleBuilder() { return m_module; } public override bool Equals(object? obj) { if (!(obj is MethodBuilder)) { return false; } if (!m_strName.Equals(((MethodBuilder)obj).m_strName)) { return false; } if (m_iAttributes != ((MethodBuilder)obj).m_iAttributes) { return false; } SignatureHelper methodSignature = ((MethodBuilder)obj).GetMethodSignature(); if (methodSignature.Equals(GetMethodSignature())) { return true; } return false; } public override int GetHashCode() { return m_strName.GetHashCode(); } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(1000); stringBuilder.Append("Name: ").Append(m_strName).AppendLine(" "); stringBuilder.Append("Attributes: ").Append((int)m_iAttributes).AppendLine(); stringBuilder.Append("Method Signature: ").Append(GetMethodSignature()).AppendLine(); stringBuilder.AppendLine(); return stringBuilder.ToString(); } public override object Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_dwMethodImplFlags; } public override MethodInfo GetBaseDefinition() { return this; } public override ParameterInfo[] GetParameters() { if (!m_bIsBaked || m_containingType == null || m_containingType.BakedRuntimeType == null) { throw new NotSupportedException(SR.InvalidOperation_TypeNotCreated); } MethodInfo method = m_containingType.GetMethod(m_strName, m_parameterTypes); return method.GetParameters(); } public override object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override MethodInfo GetGenericMethodDefinition() { if (!IsGenericMethod) { throw new InvalidOperationException(); } return this; } public override Type[] GetGenericArguments() { Type[] inst = m_inst; return inst ?? Type.EmptyTypes; } [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public override MethodInfo MakeGenericMethod(params Type[] typeArguments) { return MethodBuilderInstantiation.MakeGenericMethod(this, typeArguments); } public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { if (names == null) { throw new ArgumentNullException("names"); } if (names.Length == 0) { throw new ArgumentException(SR.Arg_EmptyArray, "names"); } if (m_inst != null) { throw new InvalidOperationException(SR.InvalidOperation_GenericParametersAlreadySet); } for (int i = 0; i < names.Length; i++) { if (names[i] == null) { throw new ArgumentNullException("names"); } } if (m_token != 0) { throw new InvalidOperationException(SR.InvalidOperation_MethodBuilderBaked); } m_bIsGenMethDef = true; m_inst = new GenericTypeParameterBuilder[names.Length]; for (int j = 0; j < names.Length; j++) { m_inst[j] = new GenericTypeParameterBuilder(new TypeBuilder(names[j], j, this)); } return m_inst; } internal void ThrowIfGeneric() { if (IsGenericMethod && !IsGenericMethodDefinition) { throw new InvalidOperationException(); } } private int GetToken() { if (m_token != 0) { return m_token; } MethodBuilder methodBuilder = null; int result = 0; lock (m_containingType.m_listMethods) { if (m_token != 0) { return m_token; } int i; for (i = m_containingType.m_lastTokenizedMethod + 1; i < m_containingType.m_listMethods.Count; i++) { methodBuilder = m_containingType.m_listMethods[i]; result = methodBuilder.GetTokenNoLock(); if (methodBuilder == this) { break; } } m_containingType.m_lastTokenizedMethod = i; return result; } } private int GetTokenNoLock() { int length; byte[] signature = GetMethodSignature().InternalGetSignature(out length); ModuleBuilder module = m_module; int tkMethod = (m_token = TypeBuilder.DefineMethod(new QCallModule(ref module), m_containingType.MetadataToken, m_strName, signature, length, Attributes)); if (m_inst != null) { GenericTypeParameterBuilder[] inst = m_inst; foreach (GenericTypeParameterBuilder genericTypeParameterBuilder in inst) { if (!genericTypeParameterBuilder.m_type.IsCreated()) { genericTypeParameterBuilder.m_type.CreateType(); } } } TypeBuilder.SetMethodImpl(new QCallModule(ref module), tkMethod, m_dwMethodImplFlags); return m_token; } public void SetParameters(params Type[] parameterTypes) { AssemblyBuilder.CheckContext(parameterTypes); SetSignature(null, null, null, parameterTypes, null, null); } public void SetReturnType(Type? returnType) { AssemblyBuilder.CheckContext(returnType); SetSignature(returnType, null, null, null, null, null); } public void SetSignature(Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers) { if (m_token == 0) { AssemblyBuilder.CheckContext(returnType); AssemblyBuilder.CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes); AssemblyBuilder.CheckContext(parameterTypeRequiredCustomModifiers); AssemblyBuilder.CheckContext(parameterTypeOptionalCustomModifiers); ThrowIfGeneric(); if (returnType != null) { m_returnType = returnType; } if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy(parameterTypes, m_parameterTypes, parameterTypes.Length); } m_returnTypeRequiredCustomModifiers = returnTypeRequiredCustomModifiers; m_returnTypeOptionalCustomModifiers = returnTypeOptionalCustomModifiers; m_parameterTypeRequiredCustomModifiers = parameterTypeRequiredCustomModifiers; m_parameterTypeOptionalCustomModifiers = parameterTypeOptionalCustomModifiers; } } public ParameterBuilder DefineParameter(int position, ParameterAttributes attributes, string? strParamName) { if (position < 0) { throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); } ThrowIfGeneric(); m_containingType.ThrowIfCreated(); if (position > 0 && (m_parameterTypes == null || position > m_parameterTypes.Length)) { throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_ParamSequence); } attributes &= ~ParameterAttributes.ReservedMask; return new ParameterBuilder(this, position, attributes, strParamName); } public void SetImplementationFlags(MethodImplAttributes attributes) { ThrowIfGeneric(); m_containingType.ThrowIfCreated(); m_dwMethodImplFlags = attributes; m_canBeRuntimeImpl = true; ModuleBuilder module = m_module; TypeBuilder.SetMethodImpl(new QCallModule(ref module), MetadataToken, attributes); } public ILGenerator GetILGenerator() { ThrowIfGeneric(); ThrowIfShouldNotHaveBody(); return m_ilGenerator ?? (m_ilGenerator = new ILGenerator(this)); } public ILGenerator GetILGenerator(int size) { ThrowIfGeneric(); ThrowIfShouldNotHaveBody(); return m_ilGenerator ?? (m_ilGenerator = new ILGenerator(this, size)); } private void ThrowIfShouldNotHaveBody() { if ((m_dwMethodImplFlags & MethodImplAttributes.CodeTypeMask) != 0 || (m_dwMethodImplFlags & MethodImplAttributes.ManagedMask) != 0 || (m_iAttributes & MethodAttributes.PinvokeImpl) != 0 || m_isDllImport) { throw new InvalidOperationException(SR.InvalidOperation_ShouldNotHaveMethodBody); } } internal Module GetModule() { return GetModuleBuilder(); } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if ((object)con == null) { throw new ArgumentNullException("con"); } if (binaryAttribute == null) { throw new ArgumentNullException("binaryAttribute"); } ThrowIfGeneric(); TypeBuilder.DefineCustomAttribute(m_module, MetadataToken, m_module.GetConstructorToken(con), binaryAttribute); if (IsKnownCA(con)) { ParseCA(con); } } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { throw new ArgumentNullException("customBuilder"); } ThrowIfGeneric(); customBuilder.CreateCustomAttribute(m_module, MetadataToken); if (IsKnownCA(customBuilder.m_con)) { ParseCA(customBuilder.m_con); } } private static bool IsKnownCA(ConstructorInfo con) { Type declaringType = con.DeclaringType; if (!(declaringType == typeof(MethodImplAttribute))) { return declaringType == typeof(DllImportAttribute); } return true; } private void ParseCA(ConstructorInfo con) { Type declaringType = con.DeclaringType; if (declaringType == typeof(MethodImplAttribute)) { m_canBeRuntimeImpl = true; } else if (declaringType == typeof(DllImportAttribute)) { m_canBeRuntimeImpl = true; m_isDllImport = true; } } } internal sealed class LocalSymInfo { internal int m_iLocalSymCount; internal string[] m_namespace; internal int m_iNameSpaceCount; internal LocalSymInfo() { m_iLocalSymCount = 0; m_iNameSpaceCount = 0; } private void EnsureCapacityNamespace() { if (m_iNameSpaceCount == 0) { m_namespace = new string[16]; } else if (m_iNameSpaceCount == m_namespace.Length) { string[] array = new string[checked(m_iNameSpaceCount * 2)]; Array.Copy(m_namespace, array, m_iNameSpaceCount); m_namespace = array; } } internal void AddUsingNamespace(string strNamespace) { EnsureCapacityNamespace(); m_namespace[m_iNameSpaceCount] = strNamespace; checked { m_iNameSpaceCount++; } } } internal readonly struct ExceptionHandler : IEquatable { internal readonly int m_exceptionClass; internal readonly int m_tryStartOffset; internal readonly int m_tryEndOffset; internal readonly int m_filterOffset; internal readonly int m_handlerStartOffset; internal readonly int m_handlerEndOffset; internal readonly ExceptionHandlingClauseOptions m_kind; internal ExceptionHandler(int tryStartOffset, int tryEndOffset, int filterOffset, int handlerStartOffset, int handlerEndOffset, int kind, int exceptionTypeToken) { m_tryStartOffset = tryStartOffset; m_tryEndOffset = tryEndOffset; m_filterOffset = filterOffset; m_handlerStartOffset = handlerStartOffset; m_handlerEndOffset = handlerEndOffset; m_kind = (ExceptionHandlingClauseOptions)kind; m_exceptionClass = exceptionTypeToken; } public override int GetHashCode() { return m_exceptionClass ^ m_tryStartOffset ^ m_tryEndOffset ^ m_filterOffset ^ m_handlerStartOffset ^ m_handlerEndOffset ^ (int)m_kind; } public override bool Equals(object obj) { if (obj is ExceptionHandler) { return Equals((ExceptionHandler)obj); } return false; } public bool Equals(ExceptionHandler other) { if (other.m_exceptionClass == m_exceptionClass && other.m_tryStartOffset == m_tryStartOffset && other.m_tryEndOffset == m_tryEndOffset && other.m_filterOffset == m_filterOffset && other.m_handlerStartOffset == m_handlerStartOffset && other.m_handlerEndOffset == m_handlerEndOffset) { return other.m_kind == m_kind; } return false; } } internal sealed class MethodBuilderInstantiation : MethodInfo { internal MethodInfo m_method; private Type[] m_inst; public override MemberTypes MemberType => m_method.MemberType; public override string Name => m_method.Name; public override Type DeclaringType => m_method.DeclaringType; public override Type ReflectedType => m_method.ReflectedType; public override Module Module => m_method.Module; public override RuntimeMethodHandle MethodHandle { get { throw new NotSupportedException(SR.NotSupported_DynamicModule); } } public override MethodAttributes Attributes => m_method.Attributes; public override CallingConventions CallingConvention => m_method.CallingConvention; public override bool IsGenericMethodDefinition => false; public override bool ContainsGenericParameters { get { for (int i = 0; i < m_inst.Length; i++) { if (m_inst[i].ContainsGenericParameters) { return true; } } if (DeclaringType != null && DeclaringType.ContainsGenericParameters) { return true; } return false; } } public override bool IsGenericMethod => true; public override Type ReturnType => m_method.ReturnType; public override ParameterInfo ReturnParameter { get { throw new NotSupportedException(); } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } } internal static MethodInfo MakeGenericMethod(MethodInfo method, Type[] inst) { if (!method.IsGenericMethodDefinition) { throw new InvalidOperationException(); } return new MethodBuilderInstantiation(method, inst); } internal MethodBuilderInstantiation(MethodInfo method, Type[] inst) { m_method = method; m_inst = inst; } internal override Type[] GetParameterTypes() { return m_method.GetParameterTypes(); } public override object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); } public override ParameterInfo[] GetParameters() { throw new NotSupportedException(); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); } public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { throw new NotSupportedException(); } public override Type[] GetGenericArguments() { return m_inst; } public override MethodInfo GetGenericMethodDefinition() { return m_method; } [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public override MethodInfo MakeGenericMethod(params Type[] arguments) { throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericMethodDefinition, this)); } public override MethodInfo GetBaseDefinition() { throw new NotSupportedException(); } } internal sealed class InternalModuleBuilder : RuntimeModule { private InternalModuleBuilder() { } public override bool Equals(object obj) { if (obj == null) { return false; } if (obj is InternalModuleBuilder) { return this == obj; } return obj.Equals(this); } public override int GetHashCode() { return base.GetHashCode(); } } public class ModuleBuilder : Module { private Dictionary _typeBuilderDict; internal ModuleBuilderData _moduleData; internal InternalModuleBuilder _internalModuleBuilder; private readonly AssemblyBuilder _assemblyBuilder; internal AssemblyBuilder ContainingAssemblyBuilder => _assemblyBuilder; internal object SyncRoot => ContainingAssemblyBuilder.SyncRoot; internal InternalModuleBuilder InternalModule => _internalModuleBuilder; [RequiresAssemblyFiles("Returns for modules with no file path")] public override string FullyQualifiedName => _moduleData._moduleName; public override int MDStreamVersion => InternalModule.MDStreamVersion; public override Guid ModuleVersionId => InternalModule.ModuleVersionId; public override int MetadataToken => InternalModule.MetadataToken; public override string ScopeName => InternalModule.ScopeName; [RequiresAssemblyFiles("Returns for modules with no file path")] public override string Name => InternalModule.Name; public override Assembly Assembly => _assemblyBuilder; internal static string UnmangleTypeName(string typeName) { int startIndex = typeName.Length - 1; while (true) { startIndex = typeName.LastIndexOf('+', startIndex); if (startIndex == -1) { break; } bool flag = true; int num = startIndex; while (typeName[--num] == '\\') { flag = !flag; } if (flag) { break; } startIndex = num; } return typeName.Substring(startIndex + 1); } internal ModuleBuilder(AssemblyBuilder assemblyBuilder, InternalModuleBuilder internalModuleBuilder) { _internalModuleBuilder = internalModuleBuilder; _assemblyBuilder = assemblyBuilder; } internal void AddType(string name, Type type) { _typeBuilderDict.Add(name, type); } internal void CheckTypeNameConflict(string strTypeName, Type enclosingType) { if (_typeBuilderDict.TryGetValue(strTypeName, out var value) && (object)value.DeclaringType == enclosingType) { throw new ArgumentException(SR.Argument_DuplicateTypeName); } } private static Type GetType(string strFormat, Type baseType) { if (string.IsNullOrEmpty(strFormat)) { return baseType; } return SymbolType.FormCompoundType(strFormat, baseType, 0); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern int GetTypeRef(QCallModule module, string strFullName, QCallModule refedModule, string strRefedModuleFileName, int tkResolution); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern int GetMemberRef(QCallModule module, QCallModule refedModule, int tr, int defToken); private int GetMemberRef(Module refedModule, int tr, int defToken) { ModuleBuilder module = this; RuntimeModule module2 = GetRuntimeModuleFromModule(refedModule); return GetMemberRef(new QCallModule(ref module), new QCallModule(ref module2), tr, defToken); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern int GetMemberRefFromSignature(QCallModule module, int tr, string methodName, byte[] signature, int length); private int GetMemberRefFromSignature(int tr, string methodName, byte[] signature, int length) { ModuleBuilder module = this; return GetMemberRefFromSignature(new QCallModule(ref module), tr, methodName, signature, length); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern int GetMemberRefOfMethodInfo(QCallModule module, int tr, RuntimeMethodHandleInternal method); private int GetMemberRefOfMethodInfo(int tr, RuntimeMethodInfo method) { ModuleBuilder module = this; int memberRefOfMethodInfo = GetMemberRefOfMethodInfo(new QCallModule(ref module), tr, ((IRuntimeMethodInfo)method).Value); GC.KeepAlive(method); return memberRefOfMethodInfo; } private int GetMemberRefOfMethodInfo(int tr, RuntimeConstructorInfo method) { ModuleBuilder module = this; int memberRefOfMethodInfo = GetMemberRefOfMethodInfo(new QCallModule(ref module), tr, ((IRuntimeMethodInfo)method).Value); GC.KeepAlive(method); return memberRefOfMethodInfo; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern int GetMemberRefOfFieldInfo(QCallModule module, int tkType, QCallTypeHandle declaringType, int tkField); private int GetMemberRefOfFieldInfo(int tkType, RuntimeTypeHandle declaringType, RuntimeFieldInfo runtimeField) { ModuleBuilder module = this; return GetMemberRefOfFieldInfo(new QCallModule(ref module), tkType, new QCallTypeHandle(ref declaringType), runtimeField.MetadataToken); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern int GetTokenFromTypeSpec(QCallModule pModule, byte[] signature, int length); private int GetTokenFromTypeSpec(byte[] signature, int length) { ModuleBuilder module = this; return GetTokenFromTypeSpec(new QCallModule(ref module), signature, length); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern int GetArrayMethodToken(QCallModule module, int tkTypeSpec, string methodName, byte[] signature, int sigLength); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern int GetStringConstant(QCallModule module, string str, int length); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern void SetFieldRVAContent(QCallModule module, int fdToken, byte[] data, int length); internal virtual Type FindTypeBuilderWithName(string strTypeName, bool ignoreCase) { Type value; if (ignoreCase) { foreach (string key in _typeBuilderDict.Keys) { if (string.Equals(key, strTypeName, StringComparison.OrdinalIgnoreCase)) { return _typeBuilderDict[key]; } } } else if (_typeBuilderDict.TryGetValue(strTypeName, out value)) { return value; } return null; } private int GetTypeRefNested(Type type, Module refedModule, string strRefedModuleFileName) { Type declaringType = type.DeclaringType; int tkResolution = 0; string text = type.FullName; if (declaringType != null) { tkResolution = GetTypeRefNested(declaringType, refedModule, strRefedModuleFileName); text = UnmangleTypeName(text); } ModuleBuilder module = this; RuntimeModule module2 = GetRuntimeModuleFromModule(refedModule); return GetTypeRef(new QCallModule(ref module), text, new QCallModule(ref module2), strRefedModuleFileName, tkResolution); } internal int InternalGetConstructorToken(ConstructorInfo con, bool usingRef) { if (con == null) { throw new ArgumentNullException("con"); } int typeTokenInternal; if (con is ConstructorBuilder constructorBuilder) { if (!usingRef && constructorBuilder.Module.Equals(this)) { return constructorBuilder.MetadataToken; } typeTokenInternal = GetTypeTokenInternal(con.ReflectedType); return GetMemberRef(con.ReflectedType.Module, typeTokenInternal, constructorBuilder.MetadataToken); } if (con is ConstructorOnTypeBuilderInstantiation constructorOnTypeBuilderInstantiation) { if (usingRef) { throw new InvalidOperationException(); } typeTokenInternal = GetTypeTokenInternal(con.DeclaringType); return GetMemberRef(con.DeclaringType.Module, typeTokenInternal, constructorOnTypeBuilderInstantiation.MetadataToken); } if (con is RuntimeConstructorInfo method && !con.ReflectedType.IsArray) { typeTokenInternal = GetTypeTokenInternal(con.ReflectedType); return GetMemberRefOfMethodInfo(typeTokenInternal, method); } ParameterInfo[] parameters = con.GetParameters(); if (parameters == null) { throw new ArgumentException(SR.Argument_InvalidConstructorInfo); } Type[] array = new Type[parameters.Length]; Type[][] array2 = new Type[parameters.Length][]; Type[][] array3 = new Type[parameters.Length][]; for (int i = 0; i < parameters.Length; i++) { if (parameters[i] == null) { throw new ArgumentException(SR.Argument_InvalidConstructorInfo); } array[i] = parameters[i].ParameterType; array2[i] = parameters[i].GetRequiredCustomModifiers(); array3[i] = parameters[i].GetOptionalCustomModifiers(); } typeTokenInternal = GetTypeTokenInternal(con.ReflectedType); SignatureHelper methodSigHelper = SignatureHelper.GetMethodSigHelper(this, con.CallingConvention, null, null, null, array, array2, array3); int length; byte[] signature = methodSigHelper.InternalGetSignature(out length); return GetMemberRefFromSignature(typeTokenInternal, con.Name, signature, length); } internal void Init(string strModuleName) { _moduleData = new ModuleBuilderData(this, strModuleName); _typeBuilderDict = new Dictionary(); } protected override ModuleHandle GetModuleHandleImpl() { return new ModuleHandle(InternalModule); } private static RuntimeModule GetRuntimeModuleFromModule(Module m) { ModuleBuilder moduleBuilder = m as ModuleBuilder; if (moduleBuilder != null) { return moduleBuilder.InternalModule; } return m as RuntimeModule; } private int GetMemberRefToken(MethodBase method, Type[] optionalParameterTypes) { int cGenericParameters = 0; if (method.IsGenericMethod) { if (!method.IsGenericMethodDefinition) { throw new InvalidOperationException(); } cGenericParameters = method.GetGenericArguments().Length; } if (optionalParameterTypes != null && (method.CallingConvention & CallingConventions.VarArgs) == 0) { throw new InvalidOperationException(SR.InvalidOperation_NotAVarArgCallingConvention); } MethodInfo methodInfo = method as MethodInfo; SignatureHelper memberRefSignature; if (method.DeclaringType.IsGenericType) { MethodBase genericMethodBaseDefinition = GetGenericMethodBaseDefinition(method); memberRefSignature = GetMemberRefSignature(genericMethodBaseDefinition, cGenericParameters); } else { memberRefSignature = GetMemberRefSignature(method, cGenericParameters); } if (optionalParameterTypes != null && optionalParameterTypes.Length != 0) { memberRefSignature.AddSentinel(); memberRefSignature.AddArguments(optionalParameterTypes, null, null); } int length; byte[] signature = memberRefSignature.InternalGetSignature(out length); int tr; if (!method.DeclaringType.IsGenericType) { tr = ((!method.Module.Equals(this)) ? GetTypeToken(method.DeclaringType) : ((!(methodInfo != null)) ? GetConstructorToken(method as ConstructorInfo) : GetMethodToken(methodInfo))); } else { int length2; byte[] signature2 = SignatureHelper.GetTypeSigToken(this, method.DeclaringType).InternalGetSignature(out length2); tr = GetTokenFromTypeSpec(signature2, length2); } return GetMemberRefFromSignature(tr, method.Name, signature, length); } internal SignatureHelper GetMemberRefSignature(CallingConventions call, Type returnType, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers, Type[] optionalParameterTypes, int cGenericParameters) { SignatureHelper methodSigHelper = SignatureHelper.GetMethodSigHelper(this, call, cGenericParameters, returnType, null, null, parameterTypes, requiredCustomModifiers, optionalCustomModifiers); if (optionalParameterTypes != null && optionalParameterTypes.Length != 0) { methodSigHelper.AddSentinel(); methodSigHelper.AddArguments(optionalParameterTypes, null, null); } return methodSigHelper; } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Module.ResolveMethod is marked as RequiresUnreferencedCode because it relies on tokens which are not guaranteed to be stable across trimming. So if somebody hardcodes a token it could break. The usage here is not like that as all these tokens come from existing metadata loaded from some IL and so trimming has no effect (the tokens are read AFTER trimming occured).")] private static MethodBase GetGenericMethodBaseDefinition(MethodBase methodBase) { MethodInfo methodInfo = methodBase as MethodInfo; if (methodBase is MethodOnTypeBuilderInstantiation methodOnTypeBuilderInstantiation) { return methodOnTypeBuilderInstantiation.m_method; } if (methodBase is ConstructorOnTypeBuilderInstantiation constructorOnTypeBuilderInstantiation) { return constructorOnTypeBuilderInstantiation.m_ctor; } if (methodBase is MethodBuilder || methodBase is ConstructorBuilder) { return methodBase; } if (methodBase.IsGenericMethod) { MethodBase genericMethodDefinition = methodInfo.GetGenericMethodDefinition(); return genericMethodDefinition.Module.ResolveMethod(methodBase.MetadataToken, genericMethodDefinition.DeclaringType?.GetGenericArguments(), genericMethodDefinition.GetGenericArguments()); } return methodBase.Module.ResolveMethod(methodBase.MetadataToken, methodBase.DeclaringType?.GetGenericArguments(), null); } internal SignatureHelper GetMemberRefSignature(MethodBase method, int cGenericParameters) { MethodBase methodBase = method; if (!(methodBase is MethodBuilder methodBuilder)) { if (!(methodBase is ConstructorBuilder constructorBuilder)) { if (!(methodBase is MethodOnTypeBuilderInstantiation methodOnTypeBuilderInstantiation)) { if (methodBase is ConstructorOnTypeBuilderInstantiation constructorOnTypeBuilderInstantiation) { if (constructorOnTypeBuilderInstantiation.m_ctor is ConstructorBuilder constructorBuilder2) { return constructorBuilder2.GetMethodSignature(); } ConstructorOnTypeBuilderInstantiation constructorOnTypeBuilderInstantiation2 = constructorOnTypeBuilderInstantiation; method = constructorOnTypeBuilderInstantiation2.m_ctor; } } else { if (methodOnTypeBuilderInstantiation.m_method is MethodBuilder methodBuilder2) { return methodBuilder2.GetMethodSignature(); } MethodOnTypeBuilderInstantiation methodOnTypeBuilderInstantiation2 = methodOnTypeBuilderInstantiation; method = methodOnTypeBuilderInstantiation2.m_method; } ParameterInfo[] parametersNoCopy = method.GetParametersNoCopy(); Type[] array = new Type[parametersNoCopy.Length]; Type[][] array2 = new Type[array.Length][]; Type[][] array3 = new Type[array.Length][]; for (int i = 0; i < parametersNoCopy.Length; i++) { array[i] = parametersNoCopy[i].ParameterType; array2[i] = parametersNoCopy[i].GetRequiredCustomModifiers(); array3[i] = parametersNoCopy[i].GetOptionalCustomModifiers(); } ParameterInfo parameterInfo = ((method is MethodInfo methodInfo) ? methodInfo.ReturnParameter : null); return SignatureHelper.GetMethodSigHelper(this, method.CallingConvention, cGenericParameters, parameterInfo?.ParameterType, parameterInfo?.GetRequiredCustomModifiers(), parameterInfo?.GetOptionalCustomModifiers(), array, array2, array3); } return constructorBuilder.GetMethodSignature(); } return methodBuilder.GetMethodSignature(); } public override bool Equals(object? obj) { return InternalModule.Equals(obj); } public override int GetHashCode() { return InternalModule.GetHashCode(); } public override object[] GetCustomAttributes(bool inherit) { return InternalModule.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return InternalModule.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return InternalModule.IsDefined(attributeType, inherit); } public override IList GetCustomAttributesData() { return InternalModule.GetCustomAttributesData(); } [RequiresUnreferencedCode("Types might be removed")] public override Type[] GetTypes() { lock (SyncRoot) { return GetTypesNoLock(); } } internal Type[] GetTypesNoLock() { Type[] array = new Type[_typeBuilderDict.Count]; int num = 0; foreach (Type value in _typeBuilderDict.Values) { EnumBuilder enumBuilder = value as EnumBuilder; TypeBuilder typeBuilder = ((!(enumBuilder != null)) ? ((TypeBuilder)value) : enumBuilder.m_typeBuilder); if (typeBuilder.IsCreated()) { array[num++] = typeBuilder.UnderlyingSystemType; } else { array[num++] = value; } } return array; } [RequiresUnreferencedCode("Types might be removed")] public override Type? GetType(string className) { return GetType(className, throwOnError: false, ignoreCase: false); } [RequiresUnreferencedCode("Types might be removed")] public override Type? GetType(string className, bool ignoreCase) { return GetType(className, throwOnError: false, ignoreCase); } [RequiresUnreferencedCode("Types might be removed")] public override Type? GetType(string className, bool throwOnError, bool ignoreCase) { lock (SyncRoot) { return GetTypeNoLock(className, throwOnError, ignoreCase); } } [RequiresUnreferencedCode("Types might be removed")] private Type GetTypeNoLock(string className, bool throwOnError, bool ignoreCase) { Type type = InternalModule.GetType(className, throwOnError, ignoreCase); if (type != null) { return type; } string text = null; string text2 = null; int num = 0; while (num <= className.Length) { int num2 = className.AsSpan(num).IndexOfAny('[', '*', '&'); if (num2 == -1) { text = className; text2 = null; break; } num2 += num; int num3 = 0; int num4 = num2 - 1; while (num4 >= 0 && className[num4] == '\\') { num3++; num4--; } if (num3 % 2 == 1) { num = num2 + 1; continue; } text = className.Substring(0, num2); text2 = className.Substring(num2); break; } if (text == null) { text = className; text2 = null; } text = text.Replace("\\\\", "\\").Replace("\\[", "[").Replace("\\*", "*") .Replace("\\&", "&"); if (text2 != null) { type = InternalModule.GetType(text, throwOnError: false, ignoreCase); } if (type == null) { type = FindTypeBuilderWithName(text, ignoreCase); if (type == null && Assembly is AssemblyBuilder) { List moduleBuilderList = ContainingAssemblyBuilder._assemblyData._moduleBuilderList; int count = moduleBuilderList.Count; for (int i = 0; i < count; i++) { if (!(type == null)) { break; } ModuleBuilder moduleBuilder = moduleBuilderList[i]; type = moduleBuilder.FindTypeBuilderWithName(text, ignoreCase); } } if (type == null) { return null; } } if (text2 == null) { return type; } return GetType(text2, type); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override byte[] ResolveSignature(int metadataToken) { return InternalModule.ResolveSignature(metadataToken); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override MethodBase? ResolveMethod(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveMethod(metadataToken, genericTypeArguments, genericMethodArguments); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override FieldInfo? ResolveField(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveField(metadataToken, genericTypeArguments, genericMethodArguments); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override Type ResolveType(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveType(metadataToken, genericTypeArguments, genericMethodArguments); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override MemberInfo? ResolveMember(int metadataToken, Type[]? genericTypeArguments, Type[]? genericMethodArguments) { return InternalModule.ResolveMember(metadataToken, genericTypeArguments, genericMethodArguments); } [RequiresUnreferencedCode("Trimming changes metadata tokens")] public override string ResolveString(int metadataToken) { return InternalModule.ResolveString(metadataToken); } public override void GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine) { InternalModule.GetPEKind(out peKind, out machine); } public override bool IsResource() { return InternalModule.IsResource(); } [RequiresUnreferencedCode("Fields might be removed")] public override FieldInfo[] GetFields(BindingFlags bindingFlags) { return InternalModule.GetFields(bindingFlags); } [RequiresUnreferencedCode("Fields might be removed")] public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { return InternalModule.GetField(name, bindingAttr); } [RequiresUnreferencedCode("Methods might be removed")] public override MethodInfo[] GetMethods(BindingFlags bindingFlags) { return InternalModule.GetMethods(bindingFlags); } [RequiresUnreferencedCode("Methods might be removed")] protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { return InternalModule.GetMethodInternal(name, bindingAttr, binder, callConvention, types, modifiers); } public TypeBuilder DefineType(string name) { lock (SyncRoot) { return DefineTypeNoLock(name, TypeAttributes.NotPublic, null, null, PackingSize.Unspecified, 0); } } public TypeBuilder DefineType(string name, TypeAttributes attr) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, null, null, PackingSize.Unspecified, 0); } } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent) { lock (SyncRoot) { AssemblyBuilder.CheckContext(parent); return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, 0); } } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, int typesize) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, typesize); } } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, PackingSize packingSize, int typesize) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, null, packingSize, typesize); } } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, Type[]? interfaces) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, interfaces, PackingSize.Unspecified, 0); } } private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type parent, Type[] interfaces, PackingSize packingSize, int typesize) { return new TypeBuilder(name, attr, parent, interfaces, this, packingSize, typesize, null); } public TypeBuilder DefineType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, PackingSize packsize) { lock (SyncRoot) { return DefineTypeNoLock(name, attr, parent, packsize); } } private TypeBuilder DefineTypeNoLock(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type parent, PackingSize packsize) { return new TypeBuilder(name, attr, parent, null, this, packsize, 0, null); } public EnumBuilder DefineEnum(string name, TypeAttributes visibility, Type underlyingType) { AssemblyBuilder.CheckContext(underlyingType); lock (SyncRoot) { EnumBuilder enumBuilder = DefineEnumNoLock(name, visibility, underlyingType); _typeBuilderDict[name] = enumBuilder; return enumBuilder; } } private EnumBuilder DefineEnumNoLock(string name, TypeAttributes visibility, Type underlyingType) { return new EnumBuilder(name, underlyingType, visibility, this); } [RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")] public MethodBuilder DefinePInvokeMethod(string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { return DefinePInvokeMethod(name, dllName, name, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); } [RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")] public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { lock (SyncRoot) { if ((attributes & MethodAttributes.Static) == 0) { throw new ArgumentException(SR.Argument_GlobalFunctionHasToBeStatic); } AssemblyBuilder.CheckContext(returnType); AssemblyBuilder.CheckContext(parameterTypes); return _moduleData._globalTypeBuilder.DefinePInvokeMethod(name, dllName, entryName, attributes, callingConvention, returnType, parameterTypes, nativeCallConv, nativeCharSet); } } public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, Type? returnType, Type[]? parameterTypes) { return DefineGlobalMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes); } public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes) { return DefineGlobalMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null); } public MethodBuilder DefineGlobalMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { lock (SyncRoot) { return DefineGlobalMethodNoLock(name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } } private MethodBuilder DefineGlobalMethodNoLock(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) { if (_moduleData._hasGlobalBeenCreated) { throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated); } if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "name"); } if ((attributes & MethodAttributes.Static) == 0) { throw new ArgumentException(SR.Argument_GlobalFunctionHasToBeStatic); } AssemblyBuilder.CheckContext(returnType); AssemblyBuilder.CheckContext(requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes); AssemblyBuilder.CheckContext(requiredParameterTypeCustomModifiers); AssemblyBuilder.CheckContext(optionalParameterTypeCustomModifiers); return _moduleData._globalTypeBuilder.DefineMethod(name, attributes, callingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } public void CreateGlobalFunctions() { lock (SyncRoot) { CreateGlobalFunctionsNoLock(); } } private void CreateGlobalFunctionsNoLock() { if (_moduleData._hasGlobalBeenCreated) { throw new InvalidOperationException(SR.InvalidOperation_NotADebugModule); } _moduleData._globalTypeBuilder.CreateType(); _moduleData._hasGlobalBeenCreated = true; } public FieldBuilder DefineInitializedData(string name, byte[] data, FieldAttributes attributes) { lock (SyncRoot) { return DefineInitializedDataNoLock(name, data, attributes); } } private FieldBuilder DefineInitializedDataNoLock(string name, byte[] data, FieldAttributes attributes) { if (_moduleData._hasGlobalBeenCreated) { throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated); } return _moduleData._globalTypeBuilder.DefineInitializedData(name, data, attributes); } public FieldBuilder DefineUninitializedData(string name, int size, FieldAttributes attributes) { lock (SyncRoot) { return DefineUninitializedDataNoLock(name, size, attributes); } } private FieldBuilder DefineUninitializedDataNoLock(string name, int size, FieldAttributes attributes) { if (_moduleData._hasGlobalBeenCreated) { throw new InvalidOperationException(SR.InvalidOperation_GlobalsHaveBeenCreated); } return _moduleData._globalTypeBuilder.DefineUninitializedData(name, size, attributes); } internal int GetTypeTokenInternal(Type type) { return GetTypeTokenInternal(type, getGenericDefinition: false); } private int GetTypeTokenInternal(Type type, bool getGenericDefinition) { lock (SyncRoot) { return GetTypeTokenWorkerNoLock(type, getGenericDefinition); } } internal int GetTypeToken(Type type) { return GetTypeTokenInternal(type, getGenericDefinition: true); } private int GetTypeTokenWorkerNoLock(Type type, bool getGenericDefinition) { if (type == null) { throw new ArgumentNullException("type"); } AssemblyBuilder.CheckContext(type); if (type.IsByRef) { throw new ArgumentException(SR.Argument_CannotGetTypeTokenForByRef); } if ((type.IsGenericType && (!type.IsGenericTypeDefinition || !getGenericDefinition)) || type.IsGenericParameter || type.IsArray || type.IsPointer) { int length; byte[] signature = SignatureHelper.GetTypeSigToken(this, type).InternalGetSignature(out length); return GetTokenFromTypeSpec(signature, length); } Module module = type.Module; if (module.Equals(this)) { TypeBuilder typeBuilder = null; EnumBuilder enumBuilder = type as EnumBuilder; typeBuilder = ((enumBuilder != null) ? enumBuilder.m_typeBuilder : (type as TypeBuilder)); if (typeBuilder != null) { return typeBuilder.TypeToken; } if (type is GenericTypeParameterBuilder genericTypeParameterBuilder) { return genericTypeParameterBuilder.MetadataToken; } return GetTypeRefNested(type, this, string.Empty); } ModuleBuilder moduleBuilder = module as ModuleBuilder; string strRefedModuleFileName = string.Empty; if (module.Assembly.Equals(Assembly)) { if (moduleBuilder == null) { moduleBuilder = ContainingAssemblyBuilder.GetModuleBuilder((InternalModuleBuilder)module); } strRefedModuleFileName = moduleBuilder._moduleData._moduleName; } return GetTypeRefNested(type, module, strRefedModuleFileName); } internal int GetMethodToken(MethodInfo method) { lock (SyncRoot) { return GetMethodTokenNoLock(method, getGenericTypeDefinition: false); } } private int GetMethodTokenNoLock(MethodInfo method, bool getGenericTypeDefinition) { if (method == null) { throw new ArgumentNullException("method"); } int num = 0; int tr; if (method is MethodBuilder methodBuilder) { int metadataToken = methodBuilder.MetadataToken; if (method.Module.Equals(this)) { return metadataToken; } if (method.DeclaringType == null) { throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); } tr = (getGenericTypeDefinition ? GetTypeToken(method.DeclaringType) : GetTypeTokenInternal(method.DeclaringType)); return GetMemberRef(method.DeclaringType.Module, tr, metadataToken); } if (method is MethodOnTypeBuilderInstantiation) { return GetMemberRefToken(method, null); } if (method is SymbolMethod symbolMethod) { if (symbolMethod.GetModule() == this) { return symbolMethod.MetadataToken; } return symbolMethod.GetToken(this); } Type declaringType = method.DeclaringType; if (declaringType == null) { throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); } if (declaringType.IsArray) { ParameterInfo[] parameters = method.GetParameters(); Type[] array = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { array[i] = parameters[i].ParameterType; } return GetArrayMethodToken(declaringType, method.Name, method.CallingConvention, method.ReturnType, array); } if (method is RuntimeMethodInfo method2) { tr = (getGenericTypeDefinition ? GetTypeToken(declaringType) : GetTypeTokenInternal(declaringType)); return GetMemberRefOfMethodInfo(tr, method2); } ParameterInfo[] parameters2 = method.GetParameters(); Type[] array2 = new Type[parameters2.Length]; Type[][] array3 = new Type[array2.Length][]; Type[][] array4 = new Type[array2.Length][]; for (int j = 0; j < parameters2.Length; j++) { array2[j] = parameters2[j].ParameterType; array3[j] = parameters2[j].GetRequiredCustomModifiers(); array4[j] = parameters2[j].GetOptionalCustomModifiers(); } tr = (getGenericTypeDefinition ? GetTypeToken(declaringType) : GetTypeTokenInternal(declaringType)); SignatureHelper methodSigHelper; try { methodSigHelper = SignatureHelper.GetMethodSigHelper(this, method.CallingConvention, method.ReturnType, method.ReturnParameter.GetRequiredCustomModifiers(), method.ReturnParameter.GetOptionalCustomModifiers(), array2, array3, array4); } catch (NotImplementedException) { methodSigHelper = SignatureHelper.GetMethodSigHelper(this, method.ReturnType, array2); } int length; byte[] signature = methodSigHelper.InternalGetSignature(out length); return GetMemberRefFromSignature(tr, method.Name, signature, length); } internal int GetMethodTokenInternal(MethodBase method, Type[] optionalParameterTypes, bool useMethodDef) { MethodInfo methodInfo = method as MethodInfo; if (method.IsGenericMethod) { MethodInfo methodInfo2 = methodInfo; bool isGenericMethodDefinition = methodInfo.IsGenericMethodDefinition; if (!isGenericMethodDefinition) { methodInfo2 = methodInfo.GetGenericMethodDefinition(); } int num = ((Equals(methodInfo2.Module) && (!(methodInfo2.DeclaringType != null) || !methodInfo2.DeclaringType.IsGenericType)) ? GetMethodToken(methodInfo2) : GetMemberRefToken(methodInfo2, null)); if (isGenericMethodDefinition && useMethodDef) { return num; } int length; byte[] signature = SignatureHelper.GetMethodSpecSigHelper(this, methodInfo.GetGenericArguments()).InternalGetSignature(out length); ModuleBuilder module = this; return TypeBuilder.DefineMethodSpec(new QCallModule(ref module), num, signature, length); } if ((method.CallingConvention & CallingConventions.VarArgs) == 0 && (method.DeclaringType == null || !method.DeclaringType.IsGenericType)) { if (methodInfo != null) { return GetMethodToken(methodInfo); } return GetConstructorToken(method as ConstructorInfo); } return GetMemberRefToken(method, optionalParameterTypes); } internal int GetArrayMethodToken(Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { lock (SyncRoot) { return GetArrayMethodTokenNoLock(arrayClass, methodName, callingConvention, returnType, parameterTypes); } } private int GetArrayMethodTokenNoLock(Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { if (arrayClass == null) { throw new ArgumentNullException("arrayClass"); } if (methodName == null) { throw new ArgumentNullException("methodName"); } if (methodName.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "methodName"); } if (!arrayClass.IsArray) { throw new ArgumentException(SR.Argument_HasToBeArrayClass); } AssemblyBuilder.CheckContext(returnType, arrayClass); AssemblyBuilder.CheckContext(parameterTypes); SignatureHelper methodSigHelper = SignatureHelper.GetMethodSigHelper(this, callingConvention, returnType, null, null, parameterTypes, null, null); int length; byte[] signature = methodSigHelper.InternalGetSignature(out length); int typeTokenInternal = GetTypeTokenInternal(arrayClass); ModuleBuilder module = this; return GetArrayMethodToken(new QCallModule(ref module), typeTokenInternal, methodName, signature, length); } public MethodInfo GetArrayMethod(Type arrayClass, string methodName, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes) { AssemblyBuilder.CheckContext(returnType, arrayClass); AssemblyBuilder.CheckContext(parameterTypes); int arrayMethodToken = GetArrayMethodToken(arrayClass, methodName, callingConvention, returnType, parameterTypes); return new SymbolMethod(this, arrayMethodToken, arrayClass, methodName, callingConvention, returnType, parameterTypes); } internal int GetConstructorToken(ConstructorInfo con) { return InternalGetConstructorToken(con, usingRef: false); } internal int GetFieldToken(FieldInfo field) { lock (SyncRoot) { return GetFieldTokenNoLock(field); } } private int GetFieldTokenNoLock(FieldInfo field) { if (field == null) { throw new ArgumentNullException("field"); } int num = 0; int tokenFromTypeSpec; if (field is FieldBuilder fieldBuilder) { if (field.DeclaringType != null && field.DeclaringType.IsGenericType) { int length; byte[] signature = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out length); tokenFromTypeSpec = GetTokenFromTypeSpec(signature, length); return GetMemberRef(this, tokenFromTypeSpec, fieldBuilder.MetadataToken); } if (fieldBuilder.Module.Equals(this)) { return fieldBuilder.MetadataToken; } if (field.DeclaringType == null) { throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); } tokenFromTypeSpec = GetTypeTokenInternal(field.DeclaringType); return GetMemberRef(field.ReflectedType.Module, tokenFromTypeSpec, fieldBuilder.MetadataToken); } if (field is RuntimeFieldInfo runtimeField) { if (field.DeclaringType == null) { throw new InvalidOperationException(SR.InvalidOperation_CannotImportGlobalFromDifferentModule); } if (field.DeclaringType != null && field.DeclaringType.IsGenericType) { int length2; byte[] signature2 = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out length2); tokenFromTypeSpec = GetTokenFromTypeSpec(signature2, length2); return GetMemberRefOfFieldInfo(tokenFromTypeSpec, field.DeclaringType.GetTypeHandleInternal(), runtimeField); } tokenFromTypeSpec = GetTypeTokenInternal(field.DeclaringType); return GetMemberRefOfFieldInfo(tokenFromTypeSpec, field.DeclaringType.GetTypeHandleInternal(), runtimeField); } if (field is FieldOnTypeBuilderInstantiation fieldOnTypeBuilderInstantiation) { FieldInfo fieldInfo = fieldOnTypeBuilderInstantiation.FieldInfo; int length3; byte[] signature3 = SignatureHelper.GetTypeSigToken(this, field.DeclaringType).InternalGetSignature(out length3); tokenFromTypeSpec = GetTokenFromTypeSpec(signature3, length3); return GetMemberRef(fieldInfo.ReflectedType.Module, tokenFromTypeSpec, fieldOnTypeBuilderInstantiation.MetadataToken); } tokenFromTypeSpec = GetTypeTokenInternal(field.ReflectedType); SignatureHelper fieldSigHelper = SignatureHelper.GetFieldSigHelper(this); fieldSigHelper.AddArgument(field.FieldType, field.GetRequiredCustomModifiers(), field.GetOptionalCustomModifiers()); int length4; byte[] signature4 = fieldSigHelper.InternalGetSignature(out length4); return GetMemberRefFromSignature(tokenFromTypeSpec, field.Name, signature4, length4); } internal int GetStringConstant(string str) { if (str == null) { throw new ArgumentNullException("str"); } ModuleBuilder module = this; return GetStringConstant(new QCallModule(ref module), str, str.Length); } internal int GetSignatureToken(SignatureHelper sigHelper) { if (sigHelper == null) { throw new ArgumentNullException("sigHelper"); } int length; byte[] signature = sigHelper.InternalGetSignature(out length); ModuleBuilder module = this; return TypeBuilder.GetTokenFromSig(new QCallModule(ref module), signature, length); } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) { throw new ArgumentNullException("con"); } if (binaryAttribute == null) { throw new ArgumentNullException("binaryAttribute"); } TypeBuilder.DefineCustomAttribute(this, 1, GetConstructorToken(con), binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { throw new ArgumentNullException("customBuilder"); } customBuilder.CreateCustomAttribute(this, 1); } } internal sealed class ModuleBuilderData { public readonly TypeBuilder _globalTypeBuilder; public readonly string _moduleName; public bool _hasGlobalBeenCreated; internal ModuleBuilderData(ModuleBuilder module, string moduleName) { _globalTypeBuilder = new TypeBuilder(module); _moduleName = moduleName; } } public class ParameterBuilder { private readonly string _name; private readonly int _position; private readonly ParameterAttributes _attributes; private MethodBuilder _methodBuilder; private int _token; public virtual string? Name => _name; public virtual int Position => _position; public virtual int Attributes => (int)_attributes; public bool IsIn => (_attributes & ParameterAttributes.In) != 0; public bool IsOut => (_attributes & ParameterAttributes.Out) != 0; public bool IsOptional => (_attributes & ParameterAttributes.Optional) != 0; public virtual void SetConstant(object? defaultValue) { TypeBuilder.SetConstantValue(_methodBuilder.GetModuleBuilder(), _token, (_position == 0) ? _methodBuilder.ReturnType : _methodBuilder.m_parameterTypes[_position - 1], defaultValue); } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) { throw new ArgumentNullException("con"); } if (binaryAttribute == null) { throw new ArgumentNullException("binaryAttribute"); } TypeBuilder.DefineCustomAttribute(_methodBuilder.GetModuleBuilder(), _token, ((ModuleBuilder)_methodBuilder.GetModule()).GetConstructorToken(con), binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { throw new ArgumentNullException("customBuilder"); } customBuilder.CreateCustomAttribute((ModuleBuilder)_methodBuilder.GetModule(), _token); } internal ParameterBuilder(MethodBuilder methodBuilder, int sequence, ParameterAttributes attributes, string paramName) { _position = sequence; _name = paramName; _methodBuilder = methodBuilder; _attributes = attributes; ModuleBuilder module = _methodBuilder.GetModuleBuilder(); _token = TypeBuilder.SetParamInfo(new QCallModule(ref module), _methodBuilder.MetadataToken, sequence, attributes, paramName); } } public sealed class PropertyBuilder : PropertyInfo { private string m_name; private int m_tkProperty; private ModuleBuilder m_moduleBuilder; private PropertyAttributes m_attributes; private Type m_returnType; private MethodInfo m_getMethod; private MethodInfo m_setMethod; private TypeBuilder m_containingType; public override Module Module => m_containingType.Module; public override Type PropertyType => m_returnType; public override PropertyAttributes Attributes => m_attributes; public override bool CanRead { get { if (m_getMethod != null) { return true; } return false; } } public override bool CanWrite { get { if (m_setMethod != null) { return true; } return false; } } public override string Name => m_name; public override Type? DeclaringType => m_containingType; public override Type? ReflectedType => m_containingType; internal PropertyBuilder(ModuleBuilder mod, string name, SignatureHelper sig, PropertyAttributes attr, Type returnType, int prToken, TypeBuilder containingType) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "name"); } if (name[0] == '\0') { throw new ArgumentException(SR.Argument_IllegalName, "name"); } m_name = name; m_moduleBuilder = mod; m_attributes = attr; m_returnType = returnType; m_tkProperty = prToken; m_containingType = containingType; } public void SetConstant(object? defaultValue) { m_containingType.ThrowIfCreated(); TypeBuilder.SetConstantValue(m_moduleBuilder, m_tkProperty, m_returnType, defaultValue); } private void SetMethodSemantics(MethodBuilder mdBuilder, MethodSemanticsAttributes semantics) { if (mdBuilder == null) { throw new ArgumentNullException("mdBuilder"); } m_containingType.ThrowIfCreated(); ModuleBuilder module = m_moduleBuilder; TypeBuilder.DefineMethodSemantics(new QCallModule(ref module), m_tkProperty, semantics, mdBuilder.MetadataToken); } public void SetGetMethod(MethodBuilder mdBuilder) { SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Getter); m_getMethod = mdBuilder; } public void SetSetMethod(MethodBuilder mdBuilder) { SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Setter); m_setMethod = mdBuilder; } public void AddOtherMethod(MethodBuilder mdBuilder) { SetMethodSemantics(mdBuilder, MethodSemanticsAttributes.Other); } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) { throw new ArgumentNullException("con"); } if (binaryAttribute == null) { throw new ArgumentNullException("binaryAttribute"); } m_containingType.ThrowIfCreated(); TypeBuilder.DefineCustomAttribute(m_moduleBuilder, m_tkProperty, m_moduleBuilder.GetConstructorToken(con), binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { throw new ArgumentNullException("customBuilder"); } m_containingType.ThrowIfCreated(); customBuilder.CreateCustomAttribute(m_moduleBuilder, m_tkProperty); } public override object GetValue(object? obj, object?[]? index) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override object GetValue(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override void SetValue(object? obj, object? value, object?[]? index) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override void SetValue(object? obj, object? value, BindingFlags invokeAttr, Binder? binder, object?[]? index, CultureInfo? culture) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override MethodInfo[] GetAccessors(bool nonPublic) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override MethodInfo? GetGetMethod(bool nonPublic) { if (nonPublic || m_getMethod == null) { return m_getMethod; } if ((m_getMethod.Attributes & MethodAttributes.Public) == MethodAttributes.Public) { return m_getMethod; } return null; } public override MethodInfo? GetSetMethod(bool nonPublic) { if (nonPublic || m_setMethod == null) { return m_setMethod; } if ((m_setMethod.Attributes & MethodAttributes.Public) == MethodAttributes.Public) { return m_setMethod; } return null; } public override ParameterInfo[] GetIndexParameters() { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } } public sealed class SignatureHelper { private byte[] m_signature; private int m_currSig; private int m_sizeLoc; private ModuleBuilder m_module; private bool m_sigDone; private int m_argCount; internal int ArgumentCount => m_argCount; public static SignatureHelper GetMethodSigHelper(Module? mod, Type? returnType, Type[]? parameterTypes) { return GetMethodSigHelper(mod, CallingConventions.Standard, returnType, null, null, parameterTypes, null, null); } public static SignatureHelper GetMethodSigHelper(Module? mod, CallingConventions callingConvention, Type? returnType) { return GetMethodSigHelper(mod, callingConvention, returnType, null, null, null, null, null); } internal static SignatureHelper GetMethodSpecSigHelper(Module scope, Type[] inst) { SignatureHelper signatureHelper = new SignatureHelper(scope, MdSigCallingConvention.GenericInst); signatureHelper.AddData(inst.Length); foreach (Type clsArgument in inst) { signatureHelper.AddArgument(clsArgument); } return signatureHelper; } internal static SignatureHelper GetMethodSigHelper(Module scope, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) { return GetMethodSigHelper(scope, callingConvention, 0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } internal static SignatureHelper GetMethodSigHelper(Module scope, CallingConventions callingConvention, int cGenericParam, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) { if (returnType == null) { returnType = typeof(void); } MdSigCallingConvention mdSigCallingConvention = MdSigCallingConvention.Default; if ((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { mdSigCallingConvention = MdSigCallingConvention.Vararg; } if (cGenericParam > 0) { mdSigCallingConvention |= MdSigCallingConvention.Generic; } if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis) { mdSigCallingConvention |= MdSigCallingConvention.HasThis; } SignatureHelper signatureHelper = new SignatureHelper(scope, mdSigCallingConvention, cGenericParam, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers); signatureHelper.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); return signatureHelper; } internal static SignatureHelper GetMethodSigHelper(Module mod, CallingConvention unmanagedCallConv, Type returnType) { if ((object)returnType == null) { returnType = typeof(void); } MdSigCallingConvention callingConvention; switch (unmanagedCallConv) { case CallingConvention.Cdecl: callingConvention = MdSigCallingConvention.C; break; case CallingConvention.Winapi: case CallingConvention.StdCall: callingConvention = MdSigCallingConvention.StdCall; break; case CallingConvention.ThisCall: callingConvention = MdSigCallingConvention.ThisCall; break; case CallingConvention.FastCall: callingConvention = MdSigCallingConvention.FastCall; break; default: throw new ArgumentException(SR.Argument_UnknownUnmanagedCallConv, "unmanagedCallConv"); } return new SignatureHelper(mod, callingConvention, returnType, null, null); } public static SignatureHelper GetLocalVarSigHelper() { return GetLocalVarSigHelper(null); } public static SignatureHelper GetMethodSigHelper(CallingConventions callingConvention, Type? returnType) { return GetMethodSigHelper(null, callingConvention, returnType); } internal static SignatureHelper GetMethodSigHelper(CallingConvention unmanagedCallingConvention, Type returnType) { return GetMethodSigHelper(null, unmanagedCallingConvention, returnType); } public static SignatureHelper GetLocalVarSigHelper(Module? mod) { return new SignatureHelper(mod, MdSigCallingConvention.LocalSig); } public static SignatureHelper GetFieldSigHelper(Module? mod) { return new SignatureHelper(mod, MdSigCallingConvention.Field); } public static SignatureHelper GetPropertySigHelper(Module? mod, Type? returnType, Type[]? parameterTypes) { return GetPropertySigHelper(mod, returnType, null, null, parameterTypes, null, null); } public static SignatureHelper GetPropertySigHelper(Module? mod, Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { return GetPropertySigHelper(mod, (CallingConventions)0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } public static SignatureHelper GetPropertySigHelper(Module? mod, CallingConventions callingConvention, Type? returnType, Type[]? requiredReturnTypeCustomModifiers, Type[]? optionalReturnTypeCustomModifiers, Type[]? parameterTypes, Type[][]? requiredParameterTypeCustomModifiers, Type[][]? optionalParameterTypeCustomModifiers) { if (returnType == null) { returnType = typeof(void); } MdSigCallingConvention mdSigCallingConvention = MdSigCallingConvention.Property; if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis) { mdSigCallingConvention |= MdSigCallingConvention.HasThis; } SignatureHelper signatureHelper = new SignatureHelper(mod, mdSigCallingConvention, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers); signatureHelper.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); return signatureHelper; } internal static SignatureHelper GetTypeSigToken(Module module, Type type) { if (module == null) { throw new ArgumentNullException("module"); } if (type == null) { throw new ArgumentNullException("type"); } return new SignatureHelper(module, type); } private SignatureHelper(Module mod, MdSigCallingConvention callingConvention) { Init(mod, callingConvention); } private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, int cGenericParameters, Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) { Init(mod, callingConvention, cGenericParameters); if (callingConvention == MdSigCallingConvention.Field) { throw new ArgumentException(SR.Argument_BadFieldSig); } AddOneArgTypeHelper(returnType, requiredCustomModifiers, optionalCustomModifiers); } private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) : this(mod, callingConvention, 0, returnType, requiredCustomModifiers, optionalCustomModifiers) { } private SignatureHelper(Module mod, Type type) { Init(mod); AddOneArgTypeHelper(type); } [MemberNotNull("m_signature")] private void Init(Module mod) { m_signature = new byte[32]; m_currSig = 0; m_module = mod as ModuleBuilder; m_argCount = 0; m_sigDone = false; m_sizeLoc = -1; if (m_module == null && mod != null) { throw new ArgumentException(SR.NotSupported_MustBeModuleBuilder); } } [MemberNotNull("m_signature")] private void Init(Module mod, MdSigCallingConvention callingConvention) { Init(mod, callingConvention, 0); } [MemberNotNull("m_signature")] private void Init(Module mod, MdSigCallingConvention callingConvention, int cGenericParam) { Init(mod); AddData((int)callingConvention); if (callingConvention == MdSigCallingConvention.Field || callingConvention == MdSigCallingConvention.GenericInst) { m_sizeLoc = -1; return; } if (cGenericParam > 0) { AddData(cGenericParam); } m_sizeLoc = m_currSig++; } private void AddOneArgTypeHelper(Type argument, bool pinned) { if (pinned) { AddElementType(CorElementType.ELEMENT_TYPE_PINNED); } AddOneArgTypeHelper(argument); } private void AddOneArgTypeHelper(Type clsArgument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) { if (optionalCustomModifiers != null) { foreach (Type type in optionalCustomModifiers) { if (type == null) { throw new ArgumentNullException("optionalCustomModifiers"); } if (type.HasElementType) { throw new ArgumentException(SR.Argument_ArraysInvalid, "optionalCustomModifiers"); } if (type.ContainsGenericParameters) { throw new ArgumentException(SR.Argument_GenericsInvalid, "optionalCustomModifiers"); } AddElementType(CorElementType.ELEMENT_TYPE_CMOD_OPT); int typeToken = m_module.GetTypeToken(type); AddToken(typeToken); } } if (requiredCustomModifiers != null) { foreach (Type type2 in requiredCustomModifiers) { if (type2 == null) { throw new ArgumentNullException("requiredCustomModifiers"); } if (type2.HasElementType) { throw new ArgumentException(SR.Argument_ArraysInvalid, "requiredCustomModifiers"); } if (type2.ContainsGenericParameters) { throw new ArgumentException(SR.Argument_GenericsInvalid, "requiredCustomModifiers"); } AddElementType(CorElementType.ELEMENT_TYPE_CMOD_REQD); int typeToken2 = m_module.GetTypeToken(type2); AddToken(typeToken2); } } AddOneArgTypeHelper(clsArgument); } private void AddOneArgTypeHelper(Type clsArgument) { AddOneArgTypeHelperWorker(clsArgument, lastWasGenericInst: false); } private void AddOneArgTypeHelperWorker(Type clsArgument, bool lastWasGenericInst) { if (clsArgument.IsGenericParameter) { if (clsArgument.DeclaringMethod != null) { AddElementType(CorElementType.ELEMENT_TYPE_MVAR); } else { AddElementType(CorElementType.ELEMENT_TYPE_VAR); } AddData(clsArgument.GenericParameterPosition); return; } if (clsArgument.IsGenericType && (!clsArgument.IsGenericTypeDefinition || !lastWasGenericInst)) { AddElementType(CorElementType.ELEMENT_TYPE_GENERICINST); AddOneArgTypeHelperWorker(clsArgument.GetGenericTypeDefinition(), lastWasGenericInst: true); Type[] genericArguments = clsArgument.GetGenericArguments(); AddData(genericArguments.Length); Type[] array = genericArguments; foreach (Type clsArgument2 in array) { AddOneArgTypeHelper(clsArgument2); } return; } if (clsArgument is TypeBuilder) { TypeBuilder typeBuilder = (TypeBuilder)clsArgument; int clsToken = ((!typeBuilder.Module.Equals(m_module)) ? m_module.GetTypeToken(clsArgument) : typeBuilder.TypeToken); if (clsArgument.IsValueType) { InternalAddTypeToken(clsToken, CorElementType.ELEMENT_TYPE_VALUETYPE); } else { InternalAddTypeToken(clsToken, CorElementType.ELEMENT_TYPE_CLASS); } return; } if (clsArgument is EnumBuilder) { TypeBuilder typeBuilder2 = ((EnumBuilder)clsArgument).m_typeBuilder; int clsToken2 = ((!typeBuilder2.Module.Equals(m_module)) ? m_module.GetTypeToken(clsArgument) : typeBuilder2.TypeToken); if (clsArgument.IsValueType) { InternalAddTypeToken(clsToken2, CorElementType.ELEMENT_TYPE_VALUETYPE); } else { InternalAddTypeToken(clsToken2, CorElementType.ELEMENT_TYPE_CLASS); } return; } if (clsArgument.IsByRef) { AddElementType(CorElementType.ELEMENT_TYPE_BYREF); clsArgument = clsArgument.GetElementType(); AddOneArgTypeHelper(clsArgument); return; } if (clsArgument.IsPointer) { AddElementType(CorElementType.ELEMENT_TYPE_PTR); AddOneArgTypeHelper(clsArgument.GetElementType()); return; } if (clsArgument.IsArray) { if (clsArgument.IsSZArray) { AddElementType(CorElementType.ELEMENT_TYPE_SZARRAY); AddOneArgTypeHelper(clsArgument.GetElementType()); return; } AddElementType(CorElementType.ELEMENT_TYPE_ARRAY); AddOneArgTypeHelper(clsArgument.GetElementType()); int arrayRank = clsArgument.GetArrayRank(); AddData(arrayRank); AddData(0); AddData(arrayRank); for (int j = 0; j < arrayRank; j++) { AddData(0); } return; } CorElementType corElementType = CorElementType.ELEMENT_TYPE_MAX; if (clsArgument is RuntimeType) { corElementType = RuntimeTypeHandle.GetCorElementType((RuntimeType)clsArgument); if (corElementType == CorElementType.ELEMENT_TYPE_CLASS) { if (clsArgument == typeof(object)) { corElementType = CorElementType.ELEMENT_TYPE_OBJECT; } else if (clsArgument == typeof(string)) { corElementType = CorElementType.ELEMENT_TYPE_STRING; } } } if (IsSimpleType(corElementType)) { AddElementType(corElementType); } else if (m_module == null) { InternalAddRuntimeType(clsArgument); } else if (clsArgument.IsValueType) { InternalAddTypeToken(m_module.GetTypeToken(clsArgument), CorElementType.ELEMENT_TYPE_VALUETYPE); } else { InternalAddTypeToken(m_module.GetTypeToken(clsArgument), CorElementType.ELEMENT_TYPE_CLASS); } } private void AddData(int data) { if (m_currSig + 4 > m_signature.Length) { m_signature = ExpandArray(m_signature); } if (data <= 127) { m_signature[m_currSig++] = (byte)data; return; } if (data <= 16383) { BinaryPrimitives.WriteInt16BigEndian(m_signature.AsSpan(m_currSig), (short)(data | 0x8000)); m_currSig += 2; return; } if (data <= 536870911) { BinaryPrimitives.WriteInt32BigEndian(m_signature.AsSpan(m_currSig), (int)(data | 0xC0000000u)); m_currSig += 4; return; } throw new ArgumentException(SR.Argument_LargeInteger); } private void AddElementType(CorElementType cvt) { if (m_currSig + 1 > m_signature.Length) { m_signature = ExpandArray(m_signature); } m_signature[m_currSig++] = (byte)cvt; } private void AddToken(int token) { int num = token & 0xFFFFFF; MetadataTokenType metadataTokenType = (MetadataTokenType)(token & -16777216); if (num > 67108863) { throw new ArgumentException(SR.Argument_LargeInteger); } num <<= 2; switch (metadataTokenType) { case MetadataTokenType.TypeRef: num |= 1; break; case MetadataTokenType.TypeSpec: num |= 2; break; } AddData(num); } private void InternalAddTypeToken(int clsToken, CorElementType CorType) { AddElementType(CorType); AddToken(clsToken); } private unsafe void InternalAddRuntimeType(Type type) { AddElementType(CorElementType.ELEMENT_TYPE_INTERNAL); IntPtr value = type.GetTypeHandleInternal().Value; if (m_currSig + sizeof(void*) > m_signature.Length) { m_signature = ExpandArray(m_signature); } byte* ptr = (byte*)(&value); for (int i = 0; i < sizeof(void*); i++) { m_signature[m_currSig++] = ptr[i]; } } private static byte[] ExpandArray(byte[] inArray) { return ExpandArray(inArray, inArray.Length * 2); } private static byte[] ExpandArray(byte[] inArray, int requiredLength) { if (requiredLength < inArray.Length) { requiredLength = inArray.Length * 2; } byte[] array = new byte[requiredLength]; Buffer.BlockCopy(inArray, 0, array, 0, inArray.Length); return array; } private void IncrementArgCounts() { if (m_sizeLoc != -1) { m_argCount++; } } private void SetNumberOfSignatureElements(bool forceCopy) { int currSig = m_currSig; if (m_sizeLoc != -1) { if (m_argCount < 128 && !forceCopy) { m_signature[m_sizeLoc] = (byte)m_argCount; return; } int num = ((m_argCount < 128) ? 1 : ((m_argCount >= 16384) ? 4 : 2)); byte[] array = new byte[m_currSig + num - 1]; array[0] = m_signature[0]; Buffer.BlockCopy(m_signature, m_sizeLoc + 1, array, m_sizeLoc + num, currSig - (m_sizeLoc + 1)); m_signature = array; m_currSig = m_sizeLoc; AddData(m_argCount); m_currSig = currSig + (num - 1); } } internal static bool IsSimpleType(CorElementType type) { if ((int)type <= 14) { return true; } if (type == CorElementType.ELEMENT_TYPE_TYPEDBYREF || type == CorElementType.ELEMENT_TYPE_I || type == CorElementType.ELEMENT_TYPE_U || type == CorElementType.ELEMENT_TYPE_OBJECT) { return true; } return false; } internal byte[] InternalGetSignature(out int length) { if (!m_sigDone) { m_sigDone = true; SetNumberOfSignatureElements(forceCopy: false); } length = m_currSig; return m_signature; } internal byte[] InternalGetSignatureArray() { int argCount = m_argCount; int currSig = m_currSig; int num = currSig; num = ((argCount < 127) ? (num + 1) : ((argCount >= 16383) ? (num + 4) : (num + 2))); byte[] array = new byte[num]; int dstOffset = 0; array[dstOffset++] = m_signature[0]; if (argCount <= 127) { array[dstOffset++] = (byte)((uint)argCount & 0xFFu); } else if (argCount <= 16383) { array[dstOffset++] = (byte)((uint)(argCount >> 8) | 0x80u); array[dstOffset++] = (byte)((uint)argCount & 0xFFu); } else { if (argCount > 536870911) { throw new ArgumentException(SR.Argument_LargeInteger); } array[dstOffset++] = (byte)((uint)(argCount >> 24) | 0xC0u); array[dstOffset++] = (byte)((uint)(argCount >> 16) & 0xFFu); array[dstOffset++] = (byte)((uint)(argCount >> 8) & 0xFFu); array[dstOffset++] = (byte)((uint)argCount & 0xFFu); } Buffer.BlockCopy(m_signature, 2, array, dstOffset, currSig - 2); array[num - 1] = 0; return array; } public void AddArgument(Type clsArgument) { AddArgument(clsArgument, null, null); } public void AddArgument(Type argument, bool pinned) { if (argument == null) { throw new ArgumentNullException("argument"); } IncrementArgCounts(); AddOneArgTypeHelper(argument, pinned); } public void AddArguments(Type[]? arguments, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers) { if (requiredCustomModifiers != null && (arguments == null || requiredCustomModifiers.Length != arguments.Length)) { throw new ArgumentException(SR.Format(SR.Argument_MismatchedArrays, "requiredCustomModifiers", "arguments")); } if (optionalCustomModifiers != null && (arguments == null || optionalCustomModifiers.Length != arguments.Length)) { throw new ArgumentException(SR.Format(SR.Argument_MismatchedArrays, "optionalCustomModifiers", "arguments")); } if (arguments != null) { for (int i = 0; i < arguments.Length; i++) { AddArgument(arguments[i], (requiredCustomModifiers != null) ? requiredCustomModifiers[i] : null, (optionalCustomModifiers != null) ? optionalCustomModifiers[i] : null); } } } public void AddArgument(Type argument, Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers) { if (m_sigDone) { throw new ArgumentException(SR.Argument_SigIsFinalized); } if (argument == null) { throw new ArgumentNullException("argument"); } IncrementArgCounts(); AddOneArgTypeHelper(argument, requiredCustomModifiers, optionalCustomModifiers); } public void AddSentinel() { AddElementType(CorElementType.ELEMENT_TYPE_SENTINEL); } public override bool Equals(object? obj) { if (!(obj is SignatureHelper)) { return false; } SignatureHelper signatureHelper = (SignatureHelper)obj; if (!signatureHelper.m_module.Equals(m_module) || signatureHelper.m_currSig != m_currSig || signatureHelper.m_sizeLoc != m_sizeLoc || signatureHelper.m_sigDone != m_sigDone) { return false; } for (int i = 0; i < m_currSig; i++) { if (m_signature[i] != signatureHelper.m_signature[i]) { return false; } } return true; } public override int GetHashCode() { int num = m_module.GetHashCode() + m_currSig + m_sizeLoc; if (m_sigDone) { num++; } for (int i = 0; i < m_currSig; i++) { num += m_signature[i].GetHashCode(); } return num; } public byte[] GetSignature() { return GetSignature(appendEndOfSig: false); } internal byte[] GetSignature(bool appendEndOfSig) { if (!m_sigDone) { if (appendEndOfSig) { AddElementType(CorElementType.ELEMENT_TYPE_END); } SetNumberOfSignatureElements(forceCopy: true); m_sigDone = true; } if (m_signature.Length > m_currSig) { byte[] array = new byte[m_currSig]; Array.Copy(m_signature, array, m_currSig); m_signature = array; } return m_signature; } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("Length: ").Append(m_currSig).AppendLine(); if (m_sizeLoc != -1) { stringBuilder.Append("Arguments: ").Append(m_signature[m_sizeLoc]).AppendLine(); } else { stringBuilder.AppendLine("Field Signature"); } stringBuilder.AppendLine("Signature: "); for (int i = 0; i <= m_currSig; i++) { stringBuilder.Append(m_signature[i]).Append(" "); } stringBuilder.AppendLine(); return stringBuilder.ToString(); } } internal sealed class SymbolMethod : MethodInfo { private ModuleBuilder m_module; private Type m_containingType; private string m_name; private CallingConventions m_callingConvention; private Type m_returnType; private int m_token; private Type[] m_parameterTypes; public override int MetadataToken => m_token; public override Module Module => m_module; public override Type ReflectedType => m_containingType; public override string Name => m_name; public override Type DeclaringType => m_containingType; public override MethodAttributes Attributes { get { throw new NotSupportedException(SR.NotSupported_SymbolMethod); } } public override CallingConventions CallingConvention => m_callingConvention; public override RuntimeMethodHandle MethodHandle { get { throw new NotSupportedException(SR.NotSupported_SymbolMethod); } } public override Type ReturnType => m_returnType; public override ICustomAttributeProvider ReturnTypeCustomAttributes => new EmptyCAHolder(); internal SymbolMethod(ModuleBuilder mod, int token, Type arrayClass, string methodName, CallingConventions callingConvention, Type returnType, Type[] parameterTypes) { m_token = token; m_returnType = returnType ?? typeof(void); if (parameterTypes != null) { m_parameterTypes = new Type[parameterTypes.Length]; Array.Copy(parameterTypes, m_parameterTypes, parameterTypes.Length); } else { m_parameterTypes = Type.EmptyTypes; } m_module = mod; m_containingType = arrayClass; m_name = methodName; m_callingConvention = callingConvention; SignatureHelper.GetMethodSigHelper(mod, callingConvention, returnType, null, null, parameterTypes, null, null); } internal override Type[] GetParameterTypes() { return m_parameterTypes; } internal int GetToken(ModuleBuilder mod) { return mod.GetArrayMethodToken(m_containingType, m_name, m_callingConvention, m_returnType, m_parameterTypes); } public override ParameterInfo[] GetParameters() { throw new NotSupportedException(SR.NotSupported_SymbolMethod); } public override MethodImplAttributes GetMethodImplementationFlags() { throw new NotSupportedException(SR.NotSupported_SymbolMethod); } public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { throw new NotSupportedException(SR.NotSupported_SymbolMethod); } public override MethodInfo GetBaseDefinition() { return this; } public override object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(SR.NotSupported_SymbolMethod); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_SymbolMethod); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_SymbolMethod); } public Module GetModule() { return m_module; } } internal enum TypeKind { IsArray = 1, IsPointer, IsByRef } internal sealed class SymbolType : TypeInfo { internal TypeKind m_typeKind; internal Type m_baseType; internal int m_cRank; internal int[] m_iaLowerBound; internal int[] m_iaUpperBound; private string m_format; private bool m_isSzArray = true; public override bool IsTypeDefinition => false; public override bool IsSZArray { get { if (m_cRank <= 1) { return m_isSzArray; } return false; } } public override Guid GUID { get { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } } public override Module Module { get { Type baseType = m_baseType; while (baseType is SymbolType) { baseType = ((SymbolType)baseType).m_baseType; } return baseType.Module; } } public override Assembly Assembly { get { Type baseType = m_baseType; while (baseType is SymbolType) { baseType = ((SymbolType)baseType).m_baseType; } return baseType.Assembly; } } public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } } public override string Name { get { string text = m_format; Type baseType = m_baseType; while (baseType is SymbolType) { text = ((SymbolType)baseType).m_format + text; baseType = ((SymbolType)baseType).m_baseType; } return baseType.Name + text; } } public override string FullName => TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName); public override string AssemblyQualifiedName => TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); public override string Namespace => m_baseType.Namespace; public override Type BaseType => typeof(Array); public override bool IsConstructedGenericType => false; public override Type UnderlyingSystemType => this; public override bool IsAssignableFrom([NotNullWhen(true)] TypeInfo typeInfo) { if (typeInfo == null) { return false; } return IsAssignableFrom(typeInfo.AsType()); } internal static Type FormCompoundType(string format, Type baseType, int curIndex) { if (format == null || curIndex == format.Length) { return baseType; } if (format[curIndex] == '&') { SymbolType symbolType = new SymbolType(TypeKind.IsByRef); symbolType.SetFormat(format, curIndex, 1); curIndex++; if (curIndex != format.Length) { throw new ArgumentException(SR.Argument_BadSigFormat); } symbolType.SetElementType(baseType); return symbolType; } if (format[curIndex] == '[') { SymbolType symbolType = new SymbolType(TypeKind.IsArray); int num = curIndex; curIndex++; int num2 = 0; int num3 = -1; while (format[curIndex] != ']') { if (format[curIndex] == '*') { symbolType.m_isSzArray = false; curIndex++; } if ((format[curIndex] >= '0' && format[curIndex] <= '9') || format[curIndex] == '-') { bool flag = false; if (format[curIndex] == '-') { flag = true; curIndex++; } while (format[curIndex] >= '0' && format[curIndex] <= '9') { num2 *= 10; num2 += format[curIndex] - 48; curIndex++; } if (flag) { num2 = -num2; } num3 = num2 - 1; } if (format[curIndex] == '.') { curIndex++; if (format[curIndex] != '.') { throw new ArgumentException(SR.Argument_BadSigFormat); } curIndex++; if ((format[curIndex] >= '0' && format[curIndex] <= '9') || format[curIndex] == '-') { bool flag2 = false; num3 = 0; if (format[curIndex] == '-') { flag2 = true; curIndex++; } while (format[curIndex] >= '0' && format[curIndex] <= '9') { num3 *= 10; num3 += format[curIndex] - 48; curIndex++; } if (flag2) { num3 = -num3; } if (num3 < num2) { throw new ArgumentException(SR.Argument_BadSigFormat); } } } if (format[curIndex] == ',') { curIndex++; symbolType.SetBounds(num2, num3); num2 = 0; num3 = -1; } else if (format[curIndex] != ']') { throw new ArgumentException(SR.Argument_BadSigFormat); } } symbolType.SetBounds(num2, num3); curIndex++; symbolType.SetFormat(format, num, curIndex - num); symbolType.SetElementType(baseType); return FormCompoundType(format, symbolType, curIndex); } if (format[curIndex] == '*') { SymbolType symbolType = new SymbolType(TypeKind.IsPointer); symbolType.SetFormat(format, curIndex, 1); curIndex++; symbolType.SetElementType(baseType); return FormCompoundType(format, symbolType, curIndex); } return null; } internal SymbolType(TypeKind typeKind) { m_typeKind = typeKind; m_iaLowerBound = new int[4]; m_iaUpperBound = new int[4]; } internal void SetElementType(Type baseType) { if ((object)baseType == null) { throw new ArgumentNullException("baseType"); } m_baseType = baseType; } private void SetBounds(int lower, int upper) { if (lower != 0 || upper != -1) { m_isSzArray = false; } if (m_iaLowerBound.Length <= m_cRank) { int[] array = new int[m_cRank * 2]; Array.Copy(m_iaLowerBound, array, m_cRank); m_iaLowerBound = array; Array.Copy(m_iaUpperBound, array, m_cRank); m_iaUpperBound = array; } m_iaLowerBound[m_cRank] = lower; m_iaUpperBound[m_cRank] = upper; m_cRank++; } internal void SetFormat(string format, int curIndex, int length) { m_format = format.Substring(curIndex, length); } public override Type MakePointerType() { return FormCompoundType(m_format + "*", m_baseType, 0); } public override Type MakeByRefType() { return FormCompoundType(m_format + "&", m_baseType, 0); } public override Type MakeArrayType() { return FormCompoundType(m_format + "[]", m_baseType, 0); } public override Type MakeArrayType(int rank) { string rankString = TypeInfo.GetRankString(rank); return FormCompoundType(m_format + rankString, m_baseType, 0) as SymbolType; } public override int GetArrayRank() { if (!base.IsArray) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); } return m_cRank; } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } public override string ToString() { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo GetField(string name, BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2063:UnrecognizedReflectionPattern", Justification = "Linker doesn't recognize always throwing method. https://github.com/mono/linker/issues/2025")] [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type GetInterface(string name, bool ignoreCase) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type[] GetInterfaces() { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo GetEvent(string name, BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] public override EventInfo[] GetEvents() { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type GetNestedType(string name, BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type interfaceType) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } protected override TypeAttributes GetAttributeFlagsImpl() { Type baseType = m_baseType; while (baseType is SymbolType) { baseType = ((SymbolType)baseType).m_baseType; } return baseType.Attributes; } protected override bool IsArrayImpl() { return m_typeKind == TypeKind.IsArray; } protected override bool IsPointerImpl() { return m_typeKind == TypeKind.IsPointer; } protected override bool IsByRefImpl() { return m_typeKind == TypeKind.IsByRef; } protected override bool IsPrimitiveImpl() { return false; } protected override bool IsValueTypeImpl() { return false; } protected override bool IsCOMObjectImpl() { return false; } public override Type GetElementType() { return m_baseType; } protected override bool HasElementTypeImpl() { return m_baseType != null; } public override object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(SR.NotSupported_NonReflectedType); } } public sealed class TypeBuilder : TypeInfo { private sealed class CustAttr { private readonly ConstructorInfo m_con; private readonly byte[] m_binaryAttribute; private readonly CustomAttributeBuilder m_customBuilder; public CustAttr(ConstructorInfo con, byte[] binaryAttribute) { if ((object)con == null) { throw new ArgumentNullException("con"); } if (binaryAttribute == null) { throw new ArgumentNullException("binaryAttribute"); } m_con = con; m_binaryAttribute = binaryAttribute; } public CustAttr(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { throw new ArgumentNullException("customBuilder"); } m_customBuilder = customBuilder; } public void Bake(ModuleBuilder module, int token) { if (m_customBuilder == null) { DefineCustomAttribute(module, token, module.GetConstructorToken(m_con), m_binaryAttribute); } else { m_customBuilder.CreateCustomAttribute(module, token); } } } public const int UnspecifiedTypeSize = 0; private List m_ca; private int m_tdType; private readonly ModuleBuilder m_module; private readonly string m_strName; private readonly string m_strNameSpace; private string m_strFullQualName; [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] private Type m_typeParent; private List m_typeInterfaces; private readonly TypeAttributes m_iAttr; private GenericParameterAttributes m_genParamAttributes; internal List m_listMethods; internal int m_lastTokenizedMethod; private int m_constructorCount; private readonly int m_iTypeSize; private readonly PackingSize m_iPackingSize; private readonly TypeBuilder m_DeclaringType; private Type m_enumUnderlyingType; internal bool m_isHiddenGlobalType; private bool m_hasBeenCreated; [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] private RuntimeType m_bakedRuntimeType; private readonly int m_genParamPos; private GenericTypeParameterBuilder[] m_inst; private readonly bool m_bIsGenParam; private readonly MethodBuilder m_declMeth; private readonly TypeBuilder m_genTypeDef; internal object SyncRoot => m_module.SyncRoot; internal RuntimeType BakedRuntimeType => m_bakedRuntimeType; public override Type? DeclaringType => m_DeclaringType; public override Type? ReflectedType => m_DeclaringType; public override string Name => m_strName; public override Module Module => GetModuleBuilder(); public override bool IsByRefLike => false; public override int MetadataToken => m_tdType; public override Guid GUID { get { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GUID; } } public override Assembly Assembly => m_module.Assembly; public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(SR.NotSupported_DynamicModule); } } public override string? FullName => m_strFullQualName ?? (m_strFullQualName = TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName)); public override string? Namespace => m_strNameSpace; public override string? AssemblyQualifiedName => TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); public override Type? BaseType => m_typeParent; public override bool IsTypeDefinition => true; public override bool IsSZArray => false; public override bool IsSecurityCritical => true; public override bool IsSecuritySafeCritical => false; public override bool IsSecurityTransparent => false; public override Type UnderlyingSystemType { get { if (m_bakedRuntimeType != null) { return m_bakedRuntimeType; } if (IsEnum) { if (m_enumUnderlyingType == null) { throw new InvalidOperationException(SR.InvalidOperation_NoUnderlyingTypeOnEnum); } return m_enumUnderlyingType; } return this; } } public override GenericParameterAttributes GenericParameterAttributes => m_genParamAttributes; public override bool IsGenericTypeDefinition => IsGenericType; public override bool IsGenericType => m_inst != null; public override bool IsGenericParameter => m_bIsGenParam; public override bool IsConstructedGenericType => false; public override int GenericParameterPosition => m_genParamPos; public override MethodBase? DeclaringMethod => m_declMeth; public int Size => m_iTypeSize; public PackingSize PackingSize => m_iPackingSize; internal int TypeToken { get { if (IsGenericParameter) { ThrowIfCreated(); } return m_tdType; } } public override bool IsAssignableFrom([NotNullWhen(true)] TypeInfo? typeInfo) { if (typeInfo == null) { return false; } return IsAssignableFrom(typeInfo.AsType()); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2055:UnrecognizedReflectionPattern", Justification = "MakeGenericType is only called on a TypeBuilder which is not subject to trimming")] public static MethodInfo GetMethod(Type type, MethodInfo method) { if (!(type is TypeBuilder) && !(type is TypeBuilderInstantiation)) { throw new ArgumentException(SR.Argument_MustBeTypeBuilder); } if (method.IsGenericMethod && !method.IsGenericMethodDefinition) { throw new ArgumentException(SR.Argument_NeedGenericMethodDefinition, "method"); } if (method.DeclaringType == null || !method.DeclaringType.IsGenericTypeDefinition) { throw new ArgumentException(SR.Argument_MethodNeedGenericDeclaringType, "method"); } if (type.GetGenericTypeDefinition() != method.DeclaringType) { throw new ArgumentException(SR.Argument_InvalidMethodDeclaringType, "type"); } if (type.IsGenericTypeDefinition) { type = type.MakeGenericType(type.GetGenericArguments()); } if (!(type is TypeBuilderInstantiation)) { throw new ArgumentException(SR.Argument_NeedNonGenericType, "type"); } return MethodOnTypeBuilderInstantiation.GetMethod(method, type as TypeBuilderInstantiation); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2055:UnrecognizedReflectionPattern", Justification = "MakeGenericType is only called on a TypeBuilder which is not subject to trimming")] public static ConstructorInfo GetConstructor(Type type, ConstructorInfo constructor) { if (!(type is TypeBuilder) && !(type is TypeBuilderInstantiation)) { throw new ArgumentException(SR.Argument_MustBeTypeBuilder); } if (!constructor.DeclaringType.IsGenericTypeDefinition) { throw new ArgumentException(SR.Argument_ConstructorNeedGenericDeclaringType, "constructor"); } if (!(type is TypeBuilderInstantiation)) { throw new ArgumentException(SR.Argument_NeedNonGenericType, "type"); } if (type is TypeBuilder && type.IsGenericTypeDefinition) { type = type.MakeGenericType(type.GetGenericArguments()); } if (type.GetGenericTypeDefinition() != constructor.DeclaringType) { throw new ArgumentException(SR.Argument_InvalidConstructorDeclaringType, "type"); } return ConstructorOnTypeBuilderInstantiation.GetConstructor(constructor, type as TypeBuilderInstantiation); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2055:UnrecognizedReflectionPattern", Justification = "MakeGenericType is only called on a TypeBuilder which is not subject to trimming")] public static FieldInfo GetField(Type type, FieldInfo field) { if (!(type is TypeBuilder) && !(type is TypeBuilderInstantiation)) { throw new ArgumentException(SR.Argument_MustBeTypeBuilder); } if (!field.DeclaringType.IsGenericTypeDefinition) { throw new ArgumentException(SR.Argument_FieldNeedGenericDeclaringType, "field"); } if (!(type is TypeBuilderInstantiation)) { throw new ArgumentException(SR.Argument_NeedNonGenericType, "type"); } if (type is TypeBuilder && type.IsGenericTypeDefinition) { type = type.MakeGenericType(type.GetGenericArguments()); } if (type.GetGenericTypeDefinition() != field.DeclaringType) { throw new ArgumentException(SR.Argument_InvalidFieldDeclaringType, "type"); } return FieldOnTypeBuilderInstantiation.GetField(field, type as TypeBuilderInstantiation); } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void SetParentType(QCallModule module, int tdTypeDef, int tkParent); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void AddInterfaceImpl(QCallModule module, int tdTypeDef, int tkInterface); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern int DefineMethod(QCallModule module, int tkParent, string name, byte[] signature, int sigLength, MethodAttributes attributes); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern int DefineMethodSpec(QCallModule module, int tkParent, byte[] signature, int sigLength); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern int DefineField(QCallModule module, int tkParent, string name, byte[] signature, int sigLength, FieldAttributes attributes); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void SetMethodIL(QCallModule module, int tk, bool isInitLocals, byte[] body, int bodyLength, byte[] LocalSig, int sigLength, int maxStackSize, ExceptionHandler[] exceptions, int numExceptions, int[] tokenFixups, int numTokenFixups); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void DefineCustomAttribute(QCallModule module, int tkAssociate, int tkConstructor, byte[] attr, int attrLength); internal static void DefineCustomAttribute(ModuleBuilder module, int tkAssociate, int tkConstructor, byte[] attr) { byte[] array = null; if (attr != null) { array = new byte[attr.Length]; Buffer.BlockCopy(attr, 0, array, 0, attr.Length); } DefineCustomAttribute(new QCallModule(ref module), tkAssociate, tkConstructor, array, (array != null) ? array.Length : 0); } [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern int DefineProperty(QCallModule module, int tkParent, string name, PropertyAttributes attributes, byte[] signature, int sigLength); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern int DefineEvent(QCallModule module, int tkParent, string name, EventAttributes attributes, int tkEventType); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern void DefineMethodSemantics(QCallModule module, int tkAssociation, MethodSemanticsAttributes semantics, int tkMethod); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern void DefineMethodImpl(QCallModule module, int tkType, int tkBody, int tkDecl); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern void SetMethodImpl(QCallModule module, int tkMethod, MethodImplAttributes MethodImplAttributes); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern int SetParamInfo(QCallModule module, int tkMethod, int iSequence, ParameterAttributes iParamAttributes, string strParamName); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern int GetTokenFromSig(QCallModule module, byte[] signature, int sigLength); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern void SetFieldLayoutOffset(QCallModule module, int fdToken, int iOffset); [DllImport("QCall", CharSet = CharSet.Unicode)] internal static extern void SetClassLayout(QCallModule module, int tk, PackingSize iPackingSize, int iTypeSize); [DllImport("QCall", CharSet = CharSet.Unicode)] private unsafe static extern void SetConstantValue(QCallModule module, int tk, int corType, void* pValue); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void SetPInvokeData(QCallModule module, string DllName, string name, int token, int linkFlags); internal static bool IsTypeEqual(Type t1, Type t2) { if (t1 == t2) { return true; } TypeBuilder typeBuilder = null; TypeBuilder typeBuilder2 = null; Type type; if (t1 is TypeBuilder) { typeBuilder = (TypeBuilder)t1; type = typeBuilder.m_bakedRuntimeType; } else { type = t1; } Type type2; if (t2 is TypeBuilder) { typeBuilder2 = (TypeBuilder)t2; type2 = typeBuilder2.m_bakedRuntimeType; } else { type2 = t2; } if (typeBuilder != null && typeBuilder2 != null && (object)typeBuilder == typeBuilder2) { return true; } if (type != null && type2 != null && type == type2) { return true; } return false; } internal unsafe static void SetConstantValue(ModuleBuilder module, int tk, Type destType, object value) { if (value != null) { Type type = value.GetType(); if (destType.IsByRef) { destType = destType.GetElementType(); } destType = Nullable.GetUnderlyingType(destType) ?? destType; if (destType.IsEnum) { Type type2; if (destType is EnumBuilder enumBuilder) { type2 = enumBuilder.GetEnumUnderlyingType(); if (type != enumBuilder.m_typeBuilder.m_bakedRuntimeType && type != type2) { throw new ArgumentException(SR.Argument_ConstantDoesntMatch); } } else if (destType is TypeBuilder typeBuilder) { type2 = typeBuilder.m_enumUnderlyingType; if (type2 == null || (type != typeBuilder.UnderlyingSystemType && type != type2)) { throw new ArgumentException(SR.Argument_ConstantDoesntMatch); } } else { type2 = Enum.GetUnderlyingType(destType); if (type != destType && type != type2) { throw new ArgumentException(SR.Argument_ConstantDoesntMatch); } } type = type2; } else if (!destType.IsAssignableFrom(type)) { throw new ArgumentException(SR.Argument_ConstantDoesntMatch); } CorElementType corElementType = RuntimeTypeHandle.GetCorElementType((RuntimeType)type); if (corElementType - 2 <= CorElementType.ELEMENT_TYPE_U8) { fixed (byte* pValue = &value.GetRawData()) { SetConstantValue(new QCallModule(ref module), tk, (int)corElementType, pValue); } return; } if (type == typeof(string)) { fixed (char* pValue2 = (string)value) { SetConstantValue(new QCallModule(ref module), tk, 14, pValue2); } return; } if (!(type == typeof(DateTime))) { throw new ArgumentException(SR.Format(SR.Argument_ConstantNotSupported, type)); } long ticks = ((DateTime)value).Ticks; SetConstantValue(new QCallModule(ref module), tk, 10, &ticks); } else { SetConstantValue(new QCallModule(ref module), tk, 18, null); } } internal TypeBuilder(ModuleBuilder module) { m_tdType = 33554432; m_isHiddenGlobalType = true; m_module = module; m_listMethods = new List(); m_lastTokenizedMethod = -1; } internal TypeBuilder(string szName, int genParamPos, MethodBuilder declMeth) { m_strName = szName; m_genParamPos = genParamPos; m_bIsGenParam = true; m_typeInterfaces = new List(); m_declMeth = declMeth; m_DeclaringType = m_declMeth.GetTypeBuilder(); m_module = declMeth.GetModuleBuilder(); } private TypeBuilder(string szName, int genParamPos, TypeBuilder declType) { m_strName = szName; m_genParamPos = genParamPos; m_bIsGenParam = true; m_typeInterfaces = new List(); m_DeclaringType = declType; m_module = declType.GetModuleBuilder(); } internal TypeBuilder(string fullname, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type parent, Type[] interfaces, ModuleBuilder module, PackingSize iPackingSize, int iTypeSize, TypeBuilder enclosingType) { if (fullname == null) { throw new ArgumentNullException("fullname"); } if (fullname.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "fullname"); } if (fullname[0] == '\0') { throw new ArgumentException(SR.Argument_IllegalName, "fullname"); } if (fullname.Length > 1023) { throw new ArgumentException(SR.Argument_TypeNameTooLong, "fullname"); } m_module = module; m_DeclaringType = enclosingType; AssemblyBuilder containingAssemblyBuilder = m_module.ContainingAssemblyBuilder; containingAssemblyBuilder._assemblyData.CheckTypeNameConflict(fullname, enclosingType); if (enclosingType != null && ((attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public || (attr & TypeAttributes.VisibilityMask) == 0)) { throw new ArgumentException(SR.Argument_BadNestedTypeFlags, "attr"); } int[] array = null; if (interfaces != null) { for (int i = 0; i < interfaces.Length; i++) { if (interfaces[i] == null) { throw new ArgumentNullException("interfaces"); } } array = new int[interfaces.Length + 1]; for (int i = 0; i < interfaces.Length; i++) { array[i] = m_module.GetTypeTokenInternal(interfaces[i]); } } int num = fullname.LastIndexOf('.'); if (num == -1 || num == 0) { m_strNameSpace = string.Empty; m_strName = fullname; } else { m_strNameSpace = fullname.Substring(0, num); m_strName = fullname.Substring(num + 1); } VerifyTypeAttributes(attr); m_iAttr = attr; SetParent(parent); m_listMethods = new List(); m_lastTokenizedMethod = -1; SetInterfaces(interfaces); int tkParent = 0; if (m_typeParent != null) { tkParent = m_module.GetTypeTokenInternal(m_typeParent); } int tkEnclosingType = 0; if (enclosingType != null) { tkEnclosingType = enclosingType.m_tdType; } m_tdType = DefineType(new QCallModule(ref module), fullname, tkParent, m_iAttr, tkEnclosingType, array); m_iPackingSize = iPackingSize; m_iTypeSize = iTypeSize; if (m_iPackingSize != 0 || m_iTypeSize != 0) { SetClassLayout(new QCallModule(ref module), m_tdType, m_iPackingSize, m_iTypeSize); } m_module.AddType(FullName, this); } private FieldBuilder DefineDataHelper(string name, byte[] data, int size, FieldAttributes attributes) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "name"); } if (size <= 0 || size >= 4128768) { throw new ArgumentException(SR.Argument_BadSizeForData); } ThrowIfCreated(); string text = "$ArrayType$" + size; Type type = m_module.FindTypeBuilderWithName(text, ignoreCase: false); TypeBuilder typeBuilder = type as TypeBuilder; if (typeBuilder == null) { TypeAttributes attr = TypeAttributes.Public | TypeAttributes.ExplicitLayout | TypeAttributes.Sealed; typeBuilder = m_module.DefineType(text, attr, typeof(ValueType), PackingSize.Size1, size); typeBuilder.CreateType(); } FieldBuilder fieldBuilder = DefineField(name, typeBuilder, attributes | FieldAttributes.Static); fieldBuilder.SetData(data, size); return fieldBuilder; } private void VerifyTypeAttributes(TypeAttributes attr) { if (DeclaringType == null) { if ((attr & TypeAttributes.VisibilityMask) != 0 && (attr & TypeAttributes.VisibilityMask) != TypeAttributes.Public) { throw new ArgumentException(SR.Argument_BadTypeAttrNestedVisibilityOnNonNestedType); } } else if ((attr & TypeAttributes.VisibilityMask) == 0 || (attr & TypeAttributes.VisibilityMask) == TypeAttributes.Public) { throw new ArgumentException(SR.Argument_BadTypeAttrNonNestedVisibilityNestedType); } if ((attr & TypeAttributes.LayoutMask) != 0 && (attr & TypeAttributes.LayoutMask) != TypeAttributes.SequentialLayout && (attr & TypeAttributes.LayoutMask) != TypeAttributes.ExplicitLayout) { throw new ArgumentException(SR.Argument_BadTypeAttrInvalidLayout); } if ((attr & TypeAttributes.ReservedMask) != 0) { throw new ArgumentException(SR.Argument_BadTypeAttrReservedBitsSet); } } public bool IsCreated() { return m_hasBeenCreated; } [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern int DefineType(QCallModule module, string fullname, int tkParent, TypeAttributes attributes, int tkEnclosingType, int[] interfaceTokens); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern int DefineGenericParam(QCallModule module, string name, int tkParent, GenericParameterAttributes attributes, int position, int[] constraints); [DllImport("QCall", CharSet = CharSet.Unicode)] private static extern void TermCreateClass(QCallModule module, int tk, ObjectHandleOnStack type); internal void ThrowIfCreated() { if (IsCreated()) { throw new InvalidOperationException(SR.InvalidOperation_TypeHasBeenCreated); } } internal ModuleBuilder GetModuleBuilder() { return m_module; } internal void SetGenParamAttributes(GenericParameterAttributes genericParameterAttributes) { m_genParamAttributes = genericParameterAttributes; } internal void SetGenParamCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { CustAttr genParamCustomAttributeNoLock = new CustAttr(con, binaryAttribute); lock (SyncRoot) { SetGenParamCustomAttributeNoLock(genParamCustomAttributeNoLock); } } internal void SetGenParamCustomAttribute(CustomAttributeBuilder customBuilder) { CustAttr genParamCustomAttributeNoLock = new CustAttr(customBuilder); lock (SyncRoot) { SetGenParamCustomAttributeNoLock(genParamCustomAttributeNoLock); } } private void SetGenParamCustomAttributeNoLock(CustAttr ca) { if (m_ca == null) { m_ca = new List(); } m_ca.Add(ca); } public override string ToString() { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public override object? InvokeMember(string name, BindingFlags invokeAttr, Binder? binder, object? target, object?[]? args, ParameterModifier[]? modifiers, CultureInfo? culture, string[]? namedParameters) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] protected override ConstructorInfo? GetConstructorImpl(BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[] types, ParameterModifier[]? modifiers) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetConstructor(bindingAttr, binder, callConvention, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetConstructors(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] protected override MethodInfo? GetMethodImpl(string name, BindingFlags bindingAttr, Binder? binder, CallingConventions callConvention, Type[]? types, ParameterModifier[]? modifiers) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } if (types == null) { return m_bakedRuntimeType.GetMethod(name, bindingAttr); } return m_bakedRuntimeType.GetMethod(name, bindingAttr, binder, callConvention, types, modifiers); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetMethods(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo? GetField(string name, BindingFlags bindingAttr) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetField(name, bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo[] GetFields(BindingFlags bindingAttr) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetFields(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type? GetInterface(string name, bool ignoreCase) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetInterface(name, ignoreCase); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type[] GetInterfaces() { if (m_bakedRuntimeType != null) { return m_bakedRuntimeType.GetInterfaces(); } if (m_typeInterfaces == null) { return Type.EmptyTypes; } return m_typeInterfaces.ToArray(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo? GetEvent(string name, BindingFlags bindingAttr) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetEvent(name, bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] public override EventInfo[] GetEvents() { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetEvents(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder? binder, Type? returnType, Type[]? types, ParameterModifier[]? modifiers) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetProperties(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type[] GetNestedTypes(BindingFlags bindingAttr) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetNestedTypes(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type? GetNestedType(string name, BindingFlags bindingAttr) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetNestedType(name, bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetMember(name, type, bindingAttr); } public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type interfaceType) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetInterfaceMap(interfaceType); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo[] GetEvents(BindingFlags bindingAttr) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetEvents(bindingAttr); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return m_bakedRuntimeType.GetMembers(bindingAttr); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "The GetInterfaces technically requires all interfaces to be preservedBut in this case it acts only on TypeBuilder which is never trimmed (as it's runtime created).")] public override bool IsAssignableFrom([NotNullWhen(true)] Type? c) { if (IsTypeEqual(c, this)) { return true; } TypeBuilder typeBuilder = c as TypeBuilder; Type type = ((!(typeBuilder != null)) ? c : typeBuilder.m_bakedRuntimeType); if (type != null && type is RuntimeType) { if (m_bakedRuntimeType == null) { return false; } return m_bakedRuntimeType.IsAssignableFrom(type); } if (typeBuilder == null) { return false; } if (typeBuilder.IsSubclassOf(this)) { return true; } if (!base.IsInterface) { return false; } Type[] interfaces = typeBuilder.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { if (IsTypeEqual(interfaces[i], this)) { return true; } if (interfaces[i].IsSubclassOf(this)) { return true; } } return false; } protected override TypeAttributes GetAttributeFlagsImpl() { return m_iAttr; } protected override bool IsArrayImpl() { return false; } protected override bool IsByRefImpl() { return false; } protected override bool IsPointerImpl() { return false; } protected override bool IsPrimitiveImpl() { return false; } protected override bool IsCOMObjectImpl() { if ((GetAttributeFlagsImpl() & TypeAttributes.Import) == 0) { return false; } return true; } public override Type GetElementType() { throw new NotSupportedException(SR.NotSupported_DynamicModule); } protected override bool HasElementTypeImpl() { return false; } public override bool IsSubclassOf(Type c) { Type type = this; if (IsTypeEqual(type, c)) { return false; } type = type.BaseType; while (type != null) { if (IsTypeEqual(type, c)) { return true; } type = type.BaseType; } return false; } public override Type MakePointerType() { return SymbolType.FormCompoundType("*", this, 0); } public override Type MakeByRefType() { return SymbolType.FormCompoundType("&", this, 0); } public override Type MakeArrayType() { return SymbolType.FormCompoundType("[]", this, 0); } public override Type MakeArrayType(int rank) { string rankString = TypeInfo.GetRankString(rank); return SymbolType.FormCompoundType(rankString, this, 0); } public override object[] GetCustomAttributes(bool inherit) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, typeof(object) as RuntimeType, inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.GetCustomAttributes(m_bakedRuntimeType, runtimeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { if (!IsCreated()) { throw new NotSupportedException(SR.NotSupported_TypeNotYetCreated); } if (attributeType == null) { throw new ArgumentNullException("attributeType"); } RuntimeType runtimeType = attributeType.UnderlyingSystemType as RuntimeType; if (runtimeType == null) { throw new ArgumentException(SR.Arg_MustBeType, "attributeType"); } return CustomAttribute.IsDefined(m_bakedRuntimeType, runtimeType, inherit); } internal void SetInterfaces(params Type[] interfaces) { ThrowIfCreated(); m_typeInterfaces = new List(); if (interfaces != null) { m_typeInterfaces.AddRange(interfaces); } } public GenericTypeParameterBuilder[] DefineGenericParameters(params string[] names) { if (names == null) { throw new ArgumentNullException("names"); } if (names.Length == 0) { throw new ArgumentException(SR.Arg_EmptyArray, "names"); } for (int i = 0; i < names.Length; i++) { if (names[i] == null) { throw new ArgumentNullException("names"); } } if (m_inst != null) { throw new InvalidOperationException(); } m_inst = new GenericTypeParameterBuilder[names.Length]; for (int j = 0; j < names.Length; j++) { m_inst[j] = new GenericTypeParameterBuilder(new TypeBuilder(names[j], j, this)); } return m_inst; } [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public override Type MakeGenericType(params Type[] typeArguments) { AssemblyBuilder.CheckContext(typeArguments); return TypeBuilderInstantiation.MakeGenericType(this, typeArguments); } public override Type[] GetGenericArguments() { Type[] inst = m_inst; return inst ?? Type.EmptyTypes; } public override Type GetGenericTypeDefinition() { if (IsGenericTypeDefinition) { return this; } if (m_genTypeDef == null) { throw new InvalidOperationException(); } return m_genTypeDef; } public void DefineMethodOverride(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) { lock (SyncRoot) { DefineMethodOverrideNoLock(methodInfoBody, methodInfoDeclaration); } } private void DefineMethodOverrideNoLock(MethodInfo methodInfoBody, MethodInfo methodInfoDeclaration) { if (methodInfoBody == null) { throw new ArgumentNullException("methodInfoBody"); } if (methodInfoDeclaration == null) { throw new ArgumentNullException("methodInfoDeclaration"); } ThrowIfCreated(); if ((object)methodInfoBody.DeclaringType != this) { throw new ArgumentException(SR.ArgumentException_BadMethodImplBody); } int methodToken = m_module.GetMethodToken(methodInfoBody); int methodToken2 = m_module.GetMethodToken(methodInfoDeclaration); ModuleBuilder module = m_module; DefineMethodImpl(new QCallModule(ref module), m_tdType, methodToken, methodToken2); } public MethodBuilder DefineMethod(string name, MethodAttributes attributes, Type? returnType, Type[]? parameterTypes) { return DefineMethod(name, attributes, CallingConventions.Standard, returnType, parameterTypes); } public MethodBuilder DefineMethod(string name, MethodAttributes attributes) { return DefineMethod(name, attributes, CallingConventions.Standard, null, null); } public MethodBuilder DefineMethod(string name, MethodAttributes attributes, CallingConventions callingConvention) { return DefineMethod(name, attributes, callingConvention, null, null); } public MethodBuilder DefineMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes) { return DefineMethod(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null); } public MethodBuilder DefineMethod(string name, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers) { lock (SyncRoot) { return DefineMethodNoLock(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2082:UnrecognizedReflectionPattern", Justification = "Reflection.Emit is not subject to trimming")] private MethodBuilder DefineMethodNoLock(string name, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "name"); } AssemblyBuilder.CheckContext(returnType); AssemblyBuilder.CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes); AssemblyBuilder.CheckContext(parameterTypeRequiredCustomModifiers); AssemblyBuilder.CheckContext(parameterTypeOptionalCustomModifiers); if (parameterTypes != null) { if (parameterTypeOptionalCustomModifiers != null && parameterTypeOptionalCustomModifiers.Length != parameterTypes.Length) { throw new ArgumentException(SR.Format(SR.Argument_MismatchedArrays, "parameterTypeOptionalCustomModifiers", "parameterTypes")); } if (parameterTypeRequiredCustomModifiers != null && parameterTypeRequiredCustomModifiers.Length != parameterTypes.Length) { throw new ArgumentException(SR.Format(SR.Argument_MismatchedArrays, "parameterTypeRequiredCustomModifiers", "parameterTypes")); } } ThrowIfCreated(); MethodBuilder methodBuilder = new MethodBuilder(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, m_module, this); if (!m_isHiddenGlobalType && (methodBuilder.Attributes & MethodAttributes.SpecialName) != 0 && methodBuilder.Name.Equals(ConstructorInfo.ConstructorName)) { m_constructorCount++; } m_listMethods.Add(methodBuilder); return methodBuilder; } [RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")] public MethodBuilder DefinePInvokeMethod(string name, string dllName, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { return DefinePInvokeMethodHelper(name, dllName, name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, nativeCallConv, nativeCharSet); } [RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")] public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? parameterTypes, CallingConvention nativeCallConv, CharSet nativeCharSet) { return DefinePInvokeMethodHelper(name, dllName, entryName, attributes, callingConvention, returnType, null, null, parameterTypes, null, null, nativeCallConv, nativeCharSet); } [RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")] public MethodBuilder DefinePInvokeMethod(string name, string dllName, string entryName, MethodAttributes attributes, CallingConventions callingConvention, Type? returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers, CallingConvention nativeCallConv, CharSet nativeCharSet) { return DefinePInvokeMethodHelper(name, dllName, entryName, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, nativeCallConv, nativeCharSet); } [RequiresUnreferencedCode("P/Invoke marshalling may dynamically access members that could be trimmed.")] private MethodBuilder DefinePInvokeMethodHelper(string name, string dllName, string importName, MethodAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers, CallingConvention nativeCallConv, CharSet nativeCharSet) { AssemblyBuilder.CheckContext(returnType); AssemblyBuilder.CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes); AssemblyBuilder.CheckContext(parameterTypeRequiredCustomModifiers); AssemblyBuilder.CheckContext(parameterTypeOptionalCustomModifiers); lock (SyncRoot) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "name"); } if (dllName == null) { throw new ArgumentNullException("dllName"); } if (dllName.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "dllName"); } if (importName == null) { throw new ArgumentNullException("importName"); } if (importName.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "importName"); } if ((attributes & MethodAttributes.Abstract) != 0) { throw new ArgumentException(SR.Argument_BadPInvokeMethod); } if ((m_iAttr & TypeAttributes.ClassSemanticsMask) == TypeAttributes.ClassSemanticsMask) { throw new ArgumentException(SR.Argument_BadPInvokeOnInterface); } ThrowIfCreated(); attributes |= MethodAttributes.PinvokeImpl; MethodBuilder methodBuilder = new MethodBuilder(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers, m_module, this); methodBuilder.GetMethodSignature().InternalGetSignature(out var _); if (m_listMethods.Contains(methodBuilder)) { throw new ArgumentException(SR.Argument_MethodRedefined); } m_listMethods.Add(methodBuilder); int metadataToken = methodBuilder.MetadataToken; int num = 0; switch (nativeCallConv) { case CallingConvention.Winapi: num = 256; break; case CallingConvention.Cdecl: num = 512; break; case CallingConvention.StdCall: num = 768; break; case CallingConvention.ThisCall: num = 1024; break; case CallingConvention.FastCall: num = 1280; break; } switch (nativeCharSet) { case CharSet.None: num |= 0; break; case CharSet.Ansi: num |= 2; break; case CharSet.Unicode: num |= 4; break; case CharSet.Auto: num |= 6; break; } ModuleBuilder module = m_module; SetPInvokeData(new QCallModule(ref module), dllName, importName, metadataToken, num); methodBuilder.SetToken(metadataToken); return methodBuilder; } } public ConstructorBuilder DefineTypeInitializer() { lock (SyncRoot) { return DefineTypeInitializerNoLock(); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2082:UnrecognizedReflectionPattern", Justification = "Reflection.Emit is not subject to trimming")] private ConstructorBuilder DefineTypeInitializerNoLock() { ThrowIfCreated(); return new ConstructorBuilder(ConstructorInfo.TypeConstructorName, MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.SpecialName, CallingConventions.Standard, null, m_module, this); } public ConstructorBuilder DefineDefaultConstructor(MethodAttributes attributes) { if ((m_iAttr & TypeAttributes.ClassSemanticsMask) == TypeAttributes.ClassSemanticsMask) { throw new InvalidOperationException(SR.InvalidOperation_ConstructorNotAllowedOnInterface); } lock (SyncRoot) { return DefineDefaultConstructorNoLock(attributes); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2055:UnrecognizedReflectionPattern", Justification = "MakeGenericType is only called on a TypeBuilderInstantiation which is not subject to trimming")] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2075:UnrecognizedReflectionPattern", Justification = "GetConstructor is only called on a TypeBuilderInstantiation which is not subject to trimming")] private ConstructorBuilder DefineDefaultConstructorNoLock(MethodAttributes attributes) { ConstructorInfo constructorInfo = null; if (m_typeParent is TypeBuilderInstantiation) { Type type = m_typeParent.GetGenericTypeDefinition(); if (type is TypeBuilder) { type = ((TypeBuilder)type).m_bakedRuntimeType; } if (type == null) { throw new NotSupportedException(SR.NotSupported_DynamicModule); } Type type2 = type.MakeGenericType(m_typeParent.GetGenericArguments()); constructorInfo = ((!(type2 is TypeBuilderInstantiation)) ? type2.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null) : GetConstructor(type2, type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null))); } if (constructorInfo == null) { constructorInfo = m_typeParent.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null); } if (constructorInfo == null) { throw new NotSupportedException(SR.NotSupported_NoParentDefaultConstructor); } ConstructorBuilder constructorBuilder = DefineConstructor(attributes, CallingConventions.Standard, null); m_constructorCount++; ILGenerator iLGenerator = constructorBuilder.GetILGenerator(); iLGenerator.Emit(OpCodes.Ldarg_0); iLGenerator.Emit(OpCodes.Call, constructorInfo); iLGenerator.Emit(OpCodes.Ret); constructorBuilder.m_isDefaultConstructor = true; return constructorBuilder; } public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention, Type[]? parameterTypes) { return DefineConstructor(attributes, callingConvention, parameterTypes, null, null); } public ConstructorBuilder DefineConstructor(MethodAttributes attributes, CallingConventions callingConvention, Type[]? parameterTypes, Type[][]? requiredCustomModifiers, Type[][]? optionalCustomModifiers) { if ((m_iAttr & TypeAttributes.ClassSemanticsMask) == TypeAttributes.ClassSemanticsMask && (attributes & MethodAttributes.Static) != MethodAttributes.Static) { throw new InvalidOperationException(SR.InvalidOperation_ConstructorNotAllowedOnInterface); } lock (SyncRoot) { return DefineConstructorNoLock(attributes, callingConvention, parameterTypes, requiredCustomModifiers, optionalCustomModifiers); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2082:UnrecognizedReflectionPattern", Justification = "Reflection.Emit is not subject to trimming")] private ConstructorBuilder DefineConstructorNoLock(MethodAttributes attributes, CallingConventions callingConvention, Type[] parameterTypes, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers) { AssemblyBuilder.CheckContext(parameterTypes); AssemblyBuilder.CheckContext(requiredCustomModifiers); AssemblyBuilder.CheckContext(optionalCustomModifiers); ThrowIfCreated(); string name = (((attributes & MethodAttributes.Static) != 0) ? ConstructorInfo.TypeConstructorName : ConstructorInfo.ConstructorName); attributes |= MethodAttributes.SpecialName; ConstructorBuilder result = new ConstructorBuilder(name, attributes, callingConvention, parameterTypes, requiredCustomModifiers, optionalCustomModifiers, m_module, this); m_constructorCount++; return result; } public TypeBuilder DefineNestedType(string name) { lock (SyncRoot) { return DefineNestedTypeNoLock(name, TypeAttributes.NestedPrivate, null, null, PackingSize.Unspecified, 0); } } public TypeBuilder DefineNestedType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, Type[]? interfaces) { lock (SyncRoot) { AssemblyBuilder.CheckContext(parent); AssemblyBuilder.CheckContext(interfaces); return DefineNestedTypeNoLock(name, attr, parent, interfaces, PackingSize.Unspecified, 0); } } public TypeBuilder DefineNestedType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent) { lock (SyncRoot) { return DefineNestedTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, 0); } } public TypeBuilder DefineNestedType(string name, TypeAttributes attr) { lock (SyncRoot) { return DefineNestedTypeNoLock(name, attr, null, null, PackingSize.Unspecified, 0); } } public TypeBuilder DefineNestedType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, int typeSize) { lock (SyncRoot) { return DefineNestedTypeNoLock(name, attr, parent, null, PackingSize.Unspecified, typeSize); } } public TypeBuilder DefineNestedType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, PackingSize packSize) { lock (SyncRoot) { return DefineNestedTypeNoLock(name, attr, parent, null, packSize, 0); } } public TypeBuilder DefineNestedType(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent, PackingSize packSize, int typeSize) { lock (SyncRoot) { return DefineNestedTypeNoLock(name, attr, parent, null, packSize, typeSize); } } private TypeBuilder DefineNestedTypeNoLock(string name, TypeAttributes attr, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type parent, Type[] interfaces, PackingSize packSize, int typeSize) { return new TypeBuilder(name, attr, parent, interfaces, m_module, packSize, typeSize, this); } public FieldBuilder DefineField(string fieldName, Type type, FieldAttributes attributes) { return DefineField(fieldName, type, null, null, attributes); } public FieldBuilder DefineField(string fieldName, Type type, Type[]? requiredCustomModifiers, Type[]? optionalCustomModifiers, FieldAttributes attributes) { lock (SyncRoot) { return DefineFieldNoLock(fieldName, type, requiredCustomModifiers, optionalCustomModifiers, attributes); } } private FieldBuilder DefineFieldNoLock(string fieldName, Type type, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers, FieldAttributes attributes) { ThrowIfCreated(); AssemblyBuilder.CheckContext(type); AssemblyBuilder.CheckContext(requiredCustomModifiers); if (m_enumUnderlyingType == null && IsEnum && (attributes & FieldAttributes.Static) == 0) { m_enumUnderlyingType = type; } return new FieldBuilder(this, fieldName, type, requiredCustomModifiers, optionalCustomModifiers, attributes); } public FieldBuilder DefineInitializedData(string name, byte[] data, FieldAttributes attributes) { lock (SyncRoot) { return DefineInitializedDataNoLock(name, data, attributes); } } private FieldBuilder DefineInitializedDataNoLock(string name, byte[] data, FieldAttributes attributes) { if (data == null) { throw new ArgumentNullException("data"); } return DefineDataHelper(name, data, data.Length, attributes); } public FieldBuilder DefineUninitializedData(string name, int size, FieldAttributes attributes) { lock (SyncRoot) { return DefineUninitializedDataNoLock(name, size, attributes); } } private FieldBuilder DefineUninitializedDataNoLock(string name, int size, FieldAttributes attributes) { return DefineDataHelper(name, null, size, attributes); } public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, Type returnType, Type[]? parameterTypes) { return DefineProperty(name, attributes, returnType, null, null, parameterTypes, null, null); } public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[]? parameterTypes) { return DefineProperty(name, attributes, callingConvention, returnType, null, null, parameterTypes, null, null); } public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, Type returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers) { return DefineProperty(name, attributes, (CallingConventions)0, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); } public PropertyBuilder DefineProperty(string name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[]? returnTypeRequiredCustomModifiers, Type[]? returnTypeOptionalCustomModifiers, Type[]? parameterTypes, Type[][]? parameterTypeRequiredCustomModifiers, Type[][]? parameterTypeOptionalCustomModifiers) { lock (SyncRoot) { return DefinePropertyNoLock(name, attributes, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); } } private PropertyBuilder DefinePropertyNoLock(string name, PropertyAttributes attributes, CallingConventions callingConvention, Type returnType, Type[] returnTypeRequiredCustomModifiers, Type[] returnTypeOptionalCustomModifiers, Type[] parameterTypes, Type[][] parameterTypeRequiredCustomModifiers, Type[][] parameterTypeOptionalCustomModifiers) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "name"); } AssemblyBuilder.CheckContext(returnType); AssemblyBuilder.CheckContext(returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes); AssemblyBuilder.CheckContext(parameterTypeRequiredCustomModifiers); AssemblyBuilder.CheckContext(parameterTypeOptionalCustomModifiers); ThrowIfCreated(); SignatureHelper propertySigHelper = SignatureHelper.GetPropertySigHelper(m_module, callingConvention, returnType, returnTypeRequiredCustomModifiers, returnTypeOptionalCustomModifiers, parameterTypes, parameterTypeRequiredCustomModifiers, parameterTypeOptionalCustomModifiers); int length; byte[] signature = propertySigHelper.InternalGetSignature(out length); ModuleBuilder module = m_module; int prToken = DefineProperty(new QCallModule(ref module), m_tdType, name, attributes, signature, length); return new PropertyBuilder(m_module, name, propertySigHelper, attributes, returnType, prToken, this); } public EventBuilder DefineEvent(string name, EventAttributes attributes, Type eventtype) { lock (SyncRoot) { return DefineEventNoLock(name, attributes, eventtype); } } private EventBuilder DefineEventNoLock(string name, EventAttributes attributes, Type eventtype) { if (name == null) { throw new ArgumentNullException("name"); } if (name.Length == 0) { throw new ArgumentException(SR.Argument_EmptyName, "name"); } if (name[0] == '\0') { throw new ArgumentException(SR.Argument_IllegalName, "name"); } AssemblyBuilder.CheckContext(eventtype); ThrowIfCreated(); int typeTokenInternal = m_module.GetTypeTokenInternal(eventtype); ModuleBuilder module = m_module; int evToken = DefineEvent(new QCallModule(ref module), m_tdType, name, attributes, typeTokenInternal); return new EventBuilder(m_module, name, attributes, this, evToken); } [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public TypeInfo? CreateTypeInfo() { lock (SyncRoot) { return CreateTypeNoLock(); } } [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public Type? CreateType() { lock (SyncRoot) { return CreateTypeNoLock(); } } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2083:UnrecognizedReflectionPattern", Justification = "Reflection.Emit is not subject to trimming")] [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] private TypeInfo CreateTypeNoLock() { if (IsCreated()) { return m_bakedRuntimeType; } if (m_typeInterfaces == null) { m_typeInterfaces = new List(); } int[] array = new int[m_typeInterfaces.Count]; for (int i = 0; i < m_typeInterfaces.Count; i++) { array[i] = m_module.GetTypeTokenInternal(m_typeInterfaces[i]); } int num = 0; if (m_typeParent != null) { num = m_module.GetTypeTokenInternal(m_typeParent); } ModuleBuilder module = m_module; if (IsGenericParameter) { int[] array2; if (m_typeParent != null) { array2 = new int[m_typeInterfaces.Count + 2]; array2[^2] = num; } else { array2 = new int[m_typeInterfaces.Count + 1]; } for (int j = 0; j < m_typeInterfaces.Count; j++) { array2[j] = m_module.GetTypeTokenInternal(m_typeInterfaces[j]); } int tkParent = ((m_declMeth == null) ? m_DeclaringType.m_tdType : m_declMeth.MetadataToken); m_tdType = DefineGenericParam(new QCallModule(ref module), m_strName, tkParent, m_genParamAttributes, m_genParamPos, array2); if (m_ca != null) { foreach (CustAttr item in m_ca) { item.Bake(m_module, MetadataToken); } } m_hasBeenCreated = true; return this; } if (((uint)m_tdType & 0xFFFFFFu) != 0 && ((uint)num & 0xFFFFFFu) != 0) { SetParentType(new QCallModule(ref module), m_tdType, num); } if (m_inst != null) { GenericTypeParameterBuilder[] inst = m_inst; foreach (GenericTypeParameterBuilder genericTypeParameterBuilder in inst) { genericTypeParameterBuilder.m_type.CreateType(); } } if (!m_isHiddenGlobalType && m_constructorCount == 0 && (m_iAttr & TypeAttributes.ClassSemanticsMask) == 0 && !base.IsValueType && (m_iAttr & (TypeAttributes.Abstract | TypeAttributes.Sealed)) != (TypeAttributes.Abstract | TypeAttributes.Sealed)) { DefineDefaultConstructor(MethodAttributes.Public); } int count = m_listMethods.Count; for (int l = 0; l < count; l++) { MethodBuilder methodBuilder = m_listMethods[l]; if (methodBuilder.IsGenericMethodDefinition) { int metadataToken = methodBuilder.MetadataToken; } MethodAttributes attributes = methodBuilder.Attributes; if ((methodBuilder.GetMethodImplementationFlags() & (MethodImplAttributes)135) != 0 || (attributes & MethodAttributes.PinvokeImpl) != 0) { continue; } int signatureLength; byte[] localSignature = methodBuilder.GetLocalSignature(out signatureLength); if ((attributes & MethodAttributes.Abstract) != 0 && (m_iAttr & TypeAttributes.Abstract) == 0) { throw new InvalidOperationException(SR.InvalidOperation_BadTypeAttributesNotAbstract); } byte[] body = methodBuilder.GetBody(); if ((attributes & MethodAttributes.Abstract) != 0) { if (body != null) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_BadMethodBody, methodBuilder.Name)); } } else if (body == null || body.Length == 0) { if (methodBuilder.m_ilGenerator != null) { methodBuilder.CreateMethodBodyHelper(methodBuilder.GetILGenerator()); } body = methodBuilder.GetBody(); if ((body == null || body.Length == 0) && !methodBuilder.m_canBeRuntimeImpl) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_BadEmptyMethodBody, methodBuilder.Name)); } } int maxStack = methodBuilder.GetMaxStack(); ExceptionHandler[] exceptionHandlers = methodBuilder.GetExceptionHandlers(); int[] tokenFixups = methodBuilder.GetTokenFixups(); SetMethodIL(new QCallModule(ref module), methodBuilder.MetadataToken, methodBuilder.InitLocals, body, (body != null) ? body.Length : 0, localSignature, signatureLength, maxStack, exceptionHandlers, (exceptionHandlers != null) ? exceptionHandlers.Length : 0, tokenFixups, (tokenFixups != null) ? tokenFixups.Length : 0); if (m_module.ContainingAssemblyBuilder._assemblyData._access == AssemblyBuilderAccess.Run) { methodBuilder.ReleaseBakedStructures(); } } m_hasBeenCreated = true; RuntimeType o = null; TermCreateClass(new QCallModule(ref module), m_tdType, ObjectHandleOnStack.Create(ref o)); if (!m_isHiddenGlobalType) { m_bakedRuntimeType = o; if (m_DeclaringType != null && m_DeclaringType.m_bakedRuntimeType != null) { m_DeclaringType.m_bakedRuntimeType.InvalidateCachedNestedType(); } return o; } return null; } public void SetParent([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type? parent) { ThrowIfCreated(); if (parent != null) { AssemblyBuilder.CheckContext(parent); if (parent.IsInterface) { throw new ArgumentException(SR.Argument_CannotSetParentToInterface); } m_typeParent = parent; } else if ((m_iAttr & TypeAttributes.ClassSemanticsMask) != TypeAttributes.ClassSemanticsMask) { m_typeParent = typeof(object); } else { if ((m_iAttr & TypeAttributes.Abstract) == 0) { throw new InvalidOperationException(SR.InvalidOperation_BadInterfaceNotAbstract); } m_typeParent = null; } } public void AddInterfaceImplementation([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type interfaceType) { if (interfaceType == null) { throw new ArgumentNullException("interfaceType"); } AssemblyBuilder.CheckContext(interfaceType); ThrowIfCreated(); int typeTokenInternal = m_module.GetTypeTokenInternal(interfaceType); ModuleBuilder module = m_module; AddInterfaceImpl(new QCallModule(ref module), m_tdType, typeTokenInternal); m_typeInterfaces.Add(interfaceType); } public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { if (con == null) { throw new ArgumentNullException("con"); } if (binaryAttribute == null) { throw new ArgumentNullException("binaryAttribute"); } DefineCustomAttribute(m_module, m_tdType, m_module.GetConstructorToken(con), binaryAttribute); } public void SetCustomAttribute(CustomAttributeBuilder customBuilder) { if (customBuilder == null) { throw new ArgumentNullException("customBuilder"); } customBuilder.CreateCustomAttribute(m_module, m_tdType); } } internal sealed class TypeBuilderInstantiation : TypeInfo { private Type m_type; private Type[] m_inst; private string m_strFullQualName; internal Hashtable m_hashtable; public override Type DeclaringType => m_type.DeclaringType; public override Type ReflectedType => m_type.ReflectedType; public override string Name => m_type.Name; public override Module Module => m_type.Module; public override Guid GUID { get { throw new NotSupportedException(); } } public override Assembly Assembly => m_type.Assembly; public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } } public override string FullName => m_strFullQualName ?? (m_strFullQualName = TypeNameBuilder.ToString(this, TypeNameBuilder.Format.FullName)); public override string Namespace => m_type.Namespace; public override string AssemblyQualifiedName => TypeNameBuilder.ToString(this, TypeNameBuilder.Format.AssemblyQualifiedName); public override Type BaseType { get { Type baseType = m_type.BaseType; if (baseType == null) { return null; } TypeBuilderInstantiation typeBuilderInstantiation = baseType as TypeBuilderInstantiation; if (typeBuilderInstantiation == null) { return baseType; } return typeBuilderInstantiation.Substitute(GetGenericArguments()); } } public override bool IsTypeDefinition => false; public override bool IsSZArray => false; public override Type UnderlyingSystemType => this; public override bool IsGenericTypeDefinition => false; public override bool IsGenericType => true; public override bool IsConstructedGenericType => true; public override bool IsGenericParameter => false; public override int GenericParameterPosition { get { throw new InvalidOperationException(); } } public override bool ContainsGenericParameters { get { for (int i = 0; i < m_inst.Length; i++) { if (m_inst[i].ContainsGenericParameters) { return true; } } return false; } } public override MethodBase DeclaringMethod => null; public override bool IsAssignableFrom([NotNullWhen(true)] TypeInfo typeInfo) { if (typeInfo == null) { return false; } return IsAssignableFrom(typeInfo.AsType()); } internal static Type MakeGenericType(Type type, Type[] typeArguments) { if (!type.IsGenericTypeDefinition) { throw new InvalidOperationException(); } if (typeArguments == null) { throw new ArgumentNullException("typeArguments"); } foreach (Type type2 in typeArguments) { if (type2 == null) { throw new ArgumentNullException("typeArguments"); } } return new TypeBuilderInstantiation(type, typeArguments); } private TypeBuilderInstantiation(Type type, Type[] inst) { m_type = type; m_inst = inst; m_hashtable = new Hashtable(); } public override string ToString() { return TypeNameBuilder.ToString(this, TypeNameBuilder.Format.ToString); } public override Type MakePointerType() { return SymbolType.FormCompoundType("*", this, 0); } public override Type MakeByRefType() { return SymbolType.FormCompoundType("&", this, 0); } public override Type MakeArrayType() { return SymbolType.FormCompoundType("[]", this, 0); } public override Type MakeArrayType(int rank) { if (rank <= 0) { throw new IndexOutOfRangeException(); } string format = ((rank == 1) ? "[]" : ("[" + new string(',', rank - 1) + "]")); return SymbolType.FormCompoundType(format, this, 0); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { throw new NotSupportedException(); } [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2055:UnrecognizedReflectionPattern", Justification = "The entire TypeBuilderInstantiation is serving the MakeGenericType implementation. Currently this is not supported by linker. Once it is supported the outercall (Type.MakeGenericType)will validate that the types fullfill the necessary requirements of annotations on type parameters.As such the actual internals of the implementation are not interesting.")] private Type Substitute(Type[] substitutes) { Type[] genericArguments = GetGenericArguments(); Type[] array = new Type[genericArguments.Length]; for (int i = 0; i < array.Length; i++) { Type type = genericArguments[i]; if (type is TypeBuilderInstantiation typeBuilderInstantiation) { array[i] = typeBuilderInstantiation.Substitute(substitutes); } else if (type is GenericTypeParameterBuilder) { array[i] = substitutes[type.GenericParameterPosition]; } else { array[i] = type; } } return GetGenericTypeDefinition().MakeGenericType(array); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo GetField(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] [UnconditionalSuppressMessage("ReflectionAnalysis", "IL2063:UnrecognizedReflectionPattern", Justification = "Linker doesn't recognize always throwing method. https://github.com/mono/linker/issues/2025")] [return: DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type GetInterface(string name, bool ignoreCase) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] public override Type[] GetInterfaces() { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo GetEvent(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents)] public override EventInfo[] GetEvents() { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties)] public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes)] public override Type GetNestedType(string name, BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); } public override InterfaceMapping GetInterfaceMap([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type interfaceType) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); } [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods | DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicNestedTypes | DynamicallyAccessedMemberTypes.NonPublicNestedTypes | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.NonPublicProperties | DynamicallyAccessedMemberTypes.PublicEvents | DynamicallyAccessedMemberTypes.NonPublicEvents)] public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); } protected override TypeAttributes GetAttributeFlagsImpl() { return m_type.Attributes; } protected override bool IsArrayImpl() { return false; } protected override bool IsByRefImpl() { return false; } protected override bool IsPointerImpl() { return false; } protected override bool IsPrimitiveImpl() { return false; } protected override bool IsCOMObjectImpl() { return false; } public override Type GetElementType() { throw new NotSupportedException(); } protected override bool HasElementTypeImpl() { return false; } public override Type[] GetGenericArguments() { return m_inst; } protected override bool IsValueTypeImpl() { return m_type.IsValueType; } public override Type GetGenericTypeDefinition() { return m_type; } [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public override Type MakeGenericType(params Type[] inst) { throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericTypeDefinition, this)); } public override bool IsAssignableFrom([NotNullWhen(true)] Type c) { throw new NotSupportedException(); } public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); } public override object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); } } internal sealed class MethodOnTypeBuilderInstantiation : MethodInfo { internal MethodInfo m_method; private TypeBuilderInstantiation m_type; public override MemberTypes MemberType => m_method.MemberType; public override string Name => m_method.Name; public override Type DeclaringType => m_type; public override Type ReflectedType => m_type; public override Module Module => m_method.Module; public override RuntimeMethodHandle MethodHandle => m_method.MethodHandle; public override MethodAttributes Attributes => m_method.Attributes; public override CallingConventions CallingConvention => m_method.CallingConvention; public override bool IsGenericMethodDefinition => m_method.IsGenericMethodDefinition; public override bool ContainsGenericParameters => m_method.ContainsGenericParameters; public override bool IsGenericMethod => m_method.IsGenericMethod; public override Type ReturnType => m_method.ReturnType; public override ParameterInfo ReturnParameter { get { throw new NotSupportedException(); } } public override ICustomAttributeProvider ReturnTypeCustomAttributes { get { throw new NotSupportedException(); } } internal static MethodInfo GetMethod(MethodInfo method, TypeBuilderInstantiation type) { return new MethodOnTypeBuilderInstantiation(method, type); } internal MethodOnTypeBuilderInstantiation(MethodInfo method, TypeBuilderInstantiation type) { m_method = method; m_type = type; } internal override Type[] GetParameterTypes() { return m_method.GetParameterTypes(); } public override object[] GetCustomAttributes(bool inherit) { return m_method.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_method.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_method.IsDefined(attributeType, inherit); } public override ParameterInfo[] GetParameters() { return m_method.GetParameters(); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_method.GetMethodImplementationFlags(); } public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { throw new NotSupportedException(); } public override Type[] GetGenericArguments() { return m_method.GetGenericArguments(); } public override MethodInfo GetGenericMethodDefinition() { return m_method; } [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] public override MethodInfo MakeGenericMethod(params Type[] typeArgs) { if (!IsGenericMethodDefinition) { throw new InvalidOperationException(SR.Format(SR.Arg_NotGenericMethodDefinition, this)); } return MethodBuilderInstantiation.MakeGenericMethod(this, typeArgs); } public override MethodInfo GetBaseDefinition() { throw new NotSupportedException(); } } internal sealed class ConstructorOnTypeBuilderInstantiation : ConstructorInfo { internal ConstructorInfo m_ctor; private TypeBuilderInstantiation m_type; public override MemberTypes MemberType => m_ctor.MemberType; public override string Name => m_ctor.Name; public override Type DeclaringType => m_type; public override Type ReflectedType => m_type; public override int MetadataToken { get { ConstructorBuilder constructorBuilder = m_ctor as ConstructorBuilder; if (constructorBuilder != null) { return constructorBuilder.MetadataToken; } return m_ctor.MetadataToken; } } public override Module Module => m_ctor.Module; public override RuntimeMethodHandle MethodHandle => m_ctor.MethodHandle; public override MethodAttributes Attributes => m_ctor.Attributes; public override CallingConventions CallingConvention => m_ctor.CallingConvention; public override bool IsGenericMethodDefinition => false; public override bool ContainsGenericParameters => false; public override bool IsGenericMethod => false; internal static ConstructorInfo GetConstructor(ConstructorInfo Constructor, TypeBuilderInstantiation type) { return new ConstructorOnTypeBuilderInstantiation(Constructor, type); } internal ConstructorOnTypeBuilderInstantiation(ConstructorInfo constructor, TypeBuilderInstantiation type) { m_ctor = constructor; m_type = type; } internal override Type[] GetParameterTypes() { return m_ctor.GetParameterTypes(); } internal override Type GetReturnType() { return m_type; } public override object[] GetCustomAttributes(bool inherit) { return m_ctor.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_ctor.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_ctor.IsDefined(attributeType, inherit); } public override ParameterInfo[] GetParameters() { return m_ctor.GetParameters(); } public override MethodImplAttributes GetMethodImplementationFlags() { return m_ctor.GetMethodImplementationFlags(); } public override object Invoke(object obj, BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { throw new NotSupportedException(); } public override Type[] GetGenericArguments() { return m_ctor.GetGenericArguments(); } public override object Invoke(BindingFlags invokeAttr, Binder binder, object[] parameters, CultureInfo culture) { throw new InvalidOperationException(); } } internal sealed class FieldOnTypeBuilderInstantiation : FieldInfo { private FieldInfo m_field; private TypeBuilderInstantiation m_type; internal FieldInfo FieldInfo => m_field; public override MemberTypes MemberType => MemberTypes.Field; public override string Name => m_field.Name; public override Type DeclaringType => m_type; public override Type ReflectedType => m_type; public override int MetadataToken { get { FieldBuilder fieldBuilder = m_field as FieldBuilder; if (fieldBuilder != null) { return fieldBuilder.MetadataToken; } return m_field.MetadataToken; } } public override Module Module => m_field.Module; public override RuntimeFieldHandle FieldHandle { get { throw new NotImplementedException(); } } public override Type FieldType { get { throw new NotImplementedException(); } } public override FieldAttributes Attributes => m_field.Attributes; internal static FieldInfo GetField(FieldInfo Field, TypeBuilderInstantiation type) { FieldInfo fieldInfo; if (type.m_hashtable.Contains(Field)) { fieldInfo = type.m_hashtable[Field] as FieldInfo; } else { fieldInfo = new FieldOnTypeBuilderInstantiation(Field, type); type.m_hashtable[Field] = fieldInfo; } return fieldInfo; } internal FieldOnTypeBuilderInstantiation(FieldInfo field, TypeBuilderInstantiation type) { m_field = field; m_type = type; } public override object[] GetCustomAttributes(bool inherit) { return m_field.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return m_field.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return m_field.IsDefined(attributeType, inherit); } public override Type[] GetRequiredCustomModifiers() { return m_field.GetRequiredCustomModifiers(); } public override Type[] GetOptionalCustomModifiers() { return m_field.GetOptionalCustomModifiers(); } public override void SetValueDirect(TypedReference obj, object value) { throw new NotImplementedException(); } public override object GetValueDirect(TypedReference obj) { throw new NotImplementedException(); } public override object GetValue(object obj) { throw new InvalidOperationException(); } public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { throw new InvalidOperationException(); } } [Flags] public enum AssemblyBuilderAccess { Run = 1, RunAndCollect = 9 } internal sealed class EmptyCAHolder : ICustomAttributeProvider { internal EmptyCAHolder() { } object[] ICustomAttributeProvider.GetCustomAttributes(Type attributeType, bool inherit) { return Array.Empty(); } object[] ICustomAttributeProvider.GetCustomAttributes(bool inherit) { return Array.Empty(); } bool ICustomAttributeProvider.IsDefined(Type attributeType, bool inherit) { return false; } } public enum FlowControl { Branch, Break, Call, Cond_Branch, Meta, Next, [Obsolete("FlowControl.Phi has been deprecated and is not supported.")] Phi, Return, Throw } public readonly struct Label : IEquatable