summaryrefslogtreecommitdiff
path: root/src/mscorlib/shared
diff options
context:
space:
mode:
authorJiyoung Yun <jy910.yun@samsung.com>2017-04-13 14:17:19 +0900
committerJiyoung Yun <jy910.yun@samsung.com>2017-04-13 14:17:19 +0900
commita56e30c8d33048216567753d9d3fefc2152af8ac (patch)
tree7e5d979695fc4a431740982eb1cfecc2898b23a5 /src/mscorlib/shared
parent4b11dc566a5bbfa1378d6266525c281b028abcc8 (diff)
downloadcoreclr-a56e30c8d33048216567753d9d3fefc2152af8ac.tar.gz
coreclr-a56e30c8d33048216567753d9d3fefc2152af8ac.tar.bz2
coreclr-a56e30c8d33048216567753d9d3fefc2152af8ac.zip
Imported Upstream version 2.0.0.11353upstream/2.0.0.11353
Diffstat (limited to 'src/mscorlib/shared')
-rw-r--r--src/mscorlib/shared/Interop/Unix/Interop.Errors.cs207
-rw-r--r--src/mscorlib/shared/Interop/Unix/Interop.IOErrors.cs170
-rw-r--r--src/mscorlib/shared/Interop/Unix/Interop.Libraries.cs12
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs33
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Casing.cs23
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Idna.cs21
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs40
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs19
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs18
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs31
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Utils.cs52
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.Close.cs15
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.FLock.cs31
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.FSync.cs15
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.FTruncate.cs15
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.GetCwd.cs74
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.GetRandomBytes.cs21
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.LSeek.cs22
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.LockFileRegion.cs21
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.MksTemps.cs17
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.Open.cs15
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.OpenFlags.cs27
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.PathConf.cs73
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.Permissions.cs32
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.PosixFAdvise.cs36
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.Read.cs25
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.Stat.cs59
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.SysLog.cs58
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.Unlink.cs15
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.Write.cs27
-rw-r--r--src/mscorlib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs44
-rw-r--r--src/mscorlib/shared/Interop/Windows/Crypt32/Interop.CryptProtectMemory.cs22
-rw-r--r--src/mscorlib/shared/Interop/Windows/Interop.BOOL.cs21
-rw-r--r--src/mscorlib/shared/Interop/Windows/Interop.Errors.cs44
-rw-r--r--src/mscorlib/shared/Interop/Windows/Interop.Libraries.cs15
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CancelIoEx.cs16
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs16
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CreateFile.cs40
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs31
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FILE_INFO_BY_HANDLE_CLASS.cs39
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FileTypes.cs16
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FlushFileBuffers.cs17
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FormatMessage.cs112
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetFileInformationByHandleEx.cs25
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs15
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs18
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs18
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs16
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetTempPathW.cs16
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.LockFile.cs20
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.OutputDebugString.cs14
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_IntPtr.cs21
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_NativeOverlapped.cs22
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SECURITY_ATTRIBUTES.cs21
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SecurityOptions.cs18
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetEndOfFile.cs15
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetErrorMode.cs16
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetFilePointerEx.cs15
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.WideCharToMultiByte.cs22
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs23
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_NativeOverlapped.cs22
-rw-r--r--src/mscorlib/shared/Interop/Windows/NtDll/Interop.ZeroMemory.cs16
-rw-r--r--src/mscorlib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs19
-rw-r--r--src/mscorlib/shared/Interop/Windows/OleAut32/Interop.SysFreeString.cs15
-rw-r--r--src/mscorlib/shared/Interop/Windows/OleAut32/Interop.SysStringLen.cs19
-rw-r--r--src/mscorlib/shared/Microsoft/Win32/SafeHandles/CriticalHandleMinusOneIsInvalid.cs20
-rw-r--r--src/mscorlib/shared/Microsoft/Win32/SafeHandles/CriticalHandleZeroOrMinusOneIsInvalid.cs20
-rw-r--r--src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs119
-rw-r--r--src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs50
-rw-r--r--src/mscorlib/shared/README.md19
-rw-r--r--src/mscorlib/shared/System.Private.CoreLib.Shared.projitems534
-rw-r--r--src/mscorlib/shared/System.Private.CoreLib.Shared.shproj19
-rw-r--r--src/mscorlib/shared/System/Action.cs35
-rw-r--r--src/mscorlib/shared/System/ApplicationException.cs56
-rw-r--r--src/mscorlib/shared/System/ArgumentException.cs97
-rw-r--r--src/mscorlib/shared/System/ArgumentNullException.cs53
-rw-r--r--src/mscorlib/shared/System/ArithmeticException.cs51
-rw-r--r--src/mscorlib/shared/System/ArrayTypeMismatchException.cs51
-rw-r--r--src/mscorlib/shared/System/AssemblyLoadEventArgs.cs18
-rw-r--r--src/mscorlib/shared/System/AssemblyLoadEventHandler.cs8
-rw-r--r--src/mscorlib/shared/System/AsyncCallback.cs17
-rw-r--r--src/mscorlib/shared/System/AttributeTargets.cs36
-rw-r--r--src/mscorlib/shared/System/AttributeUsageAttribute.cs58
-rw-r--r--src/mscorlib/shared/System/Buffers/ArrayPool.cs100
-rw-r--r--src/mscorlib/shared/System/Buffers/ConfigurableArrayPool.cs265
-rw-r--r--src/mscorlib/shared/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs292
-rw-r--r--src/mscorlib/shared/System/Buffers/Utilities.cs35
-rw-r--r--src/mscorlib/shared/System/CLSCompliantAttribute.cs34
-rw-r--r--src/mscorlib/shared/System/Char.cs1122
-rw-r--r--src/mscorlib/shared/System/CharEnumerator.cs80
-rw-r--r--src/mscorlib/shared/System/Collections/DictionaryEntry.cs58
-rw-r--r--src/mscorlib/shared/System/Collections/Generic/ICollection.cs35
-rw-r--r--src/mscorlib/shared/System/Collections/Generic/IComparer.cs20
-rw-r--r--src/mscorlib/shared/System/Collections/Generic/IDictionary.cs51
-rw-r--r--src/mscorlib/shared/System/Collections/Generic/IEnumerable.cs21
-rw-r--r--src/mscorlib/shared/System/Collections/Generic/IEnumerator.cs26
-rw-r--r--src/mscorlib/shared/System/Collections/Generic/IEqualityComparer.cs18
-rw-r--r--src/mscorlib/shared/System/Collections/Generic/IList.cs37
-rw-r--r--src/mscorlib/shared/System/Collections/Generic/IReadOnlyCollection.cs16
-rw-r--r--src/mscorlib/shared/System/Collections/Generic/IReadOnlyDictionary.cs20
-rw-r--r--src/mscorlib/shared/System/Collections/Generic/IReadOnlyList.cs16
-rw-r--r--src/mscorlib/shared/System/Collections/Generic/KeyNotFoundException.cs33
-rw-r--r--src/mscorlib/shared/System/Collections/Generic/KeyValuePair.cs82
-rw-r--r--src/mscorlib/shared/System/Collections/ICollection.cs70
-rw-r--r--src/mscorlib/shared/System/Collections/IComparer.cs22
-rw-r--r--src/mscorlib/shared/System/Collections/IDictionary.cs61
-rw-r--r--src/mscorlib/shared/System/Collections/IDictionaryEnumerator.cs68
-rw-r--r--src/mscorlib/shared/System/Collections/IEnumerable.cs18
-rw-r--r--src/mscorlib/shared/System/Collections/IEnumerator.cs41
-rw-r--r--src/mscorlib/shared/System/Collections/IEqualityComparer.cs16
-rw-r--r--src/mscorlib/shared/System/Collections/IList.cs60
-rw-r--r--src/mscorlib/shared/System/Collections/IStructuralComparable.cs13
-rw-r--r--src/mscorlib/shared/System/Collections/IStructuralEquatable.cs12
-rw-r--r--src/mscorlib/shared/System/ComponentModel/DefaultValueAttribute.cs228
-rw-r--r--src/mscorlib/shared/System/ComponentModel/EditorBrowsableAttribute.cs48
-rw-r--r--src/mscorlib/shared/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs16
-rw-r--r--src/mscorlib/shared/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs13
-rw-r--r--src/mscorlib/shared/System/Convert.cs3031
-rw-r--r--src/mscorlib/shared/System/CurrentSystemTimeZone.cs199
-rw-r--r--src/mscorlib/shared/System/DBNull.cs119
-rw-r--r--src/mscorlib/shared/System/DataMisalignedException.cs39
-rw-r--r--src/mscorlib/shared/System/DateTime.cs1516
-rw-r--r--src/mscorlib/shared/System/DateTimeKind.cs17
-rw-r--r--src/mscorlib/shared/System/DateTimeOffset.cs921
-rw-r--r--src/mscorlib/shared/System/DayOfWeek.cs27
-rw-r--r--src/mscorlib/shared/System/DefaultBinder.cs1201
-rw-r--r--src/mscorlib/shared/System/Diagnostics/CodeAnalysis/SuppressMessageAttribute.cs39
-rw-r--r--src/mscorlib/shared/System/Diagnostics/ConditionalAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Debug.cs323
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/ActivityTracker.cs665
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/EventActivityOptions.cs39
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/EventCounter.cs436
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/EventDescriptor.cs209
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs1207
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs6942
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/EventSourceException.cs53
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/StubEnvironment.cs381
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/ArrayTypeInfo.cs63
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/ConcurrentSet.cs127
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/ConcurrentSetItem.cs25
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/DataCollector.cs318
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EmptyStruct.cs17
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EnumHelper.cs30
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EnumerableTypeInfo.cs64
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventDataAttribute.cs146
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventFieldAttribute.cs76
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventFieldFormat.cs130
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventIgnoreAttribute.cs25
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventPayload.cs155
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs321
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceOptions.cs130
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/FieldMetadata.cs231
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/InvokeTypeInfo.cs96
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/NameInfo.cs79
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyAnalysis.cs39
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/PropertyValue.cs252
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleEventTypes.cs39
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/SimpleTypeInfos.cs297
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/Statics.cs727
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataCollector.cs104
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataType.cs349
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs890
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTraits.cs28
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventTypes.cs262
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingMetadataCollector.cs370
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingTypeInfo.cs209
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TypeAnalysis.cs103
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/Winmeta.cs196
-rw-r--r--src/mscorlib/shared/System/DivideByZeroException.cs41
-rw-r--r--src/mscorlib/shared/System/DuplicateWaitObjectException.cs65
-rw-r--r--src/mscorlib/shared/System/EntryPointNotFoundException.cs42
-rw-r--r--src/mscorlib/shared/System/EventArgs.cs19
-rw-r--r--src/mscorlib/shared/System/EventHandler.cs14
-rw-r--r--src/mscorlib/shared/System/ExecutionEngineException.cs47
-rw-r--r--src/mscorlib/shared/System/FieldAccessException.cs39
-rw-r--r--src/mscorlib/shared/System/FlagsAttribute.cs22
-rw-r--r--src/mscorlib/shared/System/FormatException.cs41
-rw-r--r--src/mscorlib/shared/System/FormattableString.cs81
-rw-r--r--src/mscorlib/shared/System/Globalization/CalendarAlgorithmType.cs18
-rw-r--r--src/mscorlib/shared/System/Globalization/CalendarWeekRule.cs16
-rw-r--r--src/mscorlib/shared/System/Globalization/CalendricalCalculationsHelper.cs412
-rw-r--r--src/mscorlib/shared/System/Globalization/ChineseLunisolarCalendar.cs390
-rw-r--r--src/mscorlib/shared/System/Globalization/CultureNotFoundException.cs120
-rw-r--r--src/mscorlib/shared/System/Globalization/CultureTypes.cs27
-rw-r--r--src/mscorlib/shared/System/Globalization/DateTimeFormat.cs1206
-rw-r--r--src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs3028
-rw-r--r--src/mscorlib/shared/System/Globalization/DateTimeFormatInfoScanner.cs739
-rw-r--r--src/mscorlib/shared/System/Globalization/DateTimeParse.cs5672
-rw-r--r--src/mscorlib/shared/System/Globalization/DateTimeStyles.cs49
-rw-r--r--src/mscorlib/shared/System/Globalization/DaylightTime.cs50
-rw-r--r--src/mscorlib/shared/System/Globalization/DigitShapes.cs13
-rw-r--r--src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs710
-rw-r--r--src/mscorlib/shared/System/Globalization/GregorianCalendarTypes.cs19
-rw-r--r--src/mscorlib/shared/System/Globalization/HebrewCalendar.cs1129
-rw-r--r--src/mscorlib/shared/System/Globalization/HebrewNumber.cs457
-rw-r--r--src/mscorlib/shared/System/Globalization/HijriCalendar.cs677
-rw-r--r--src/mscorlib/shared/System/Globalization/InternalGlobalizationHelper.cs48
-rw-r--r--src/mscorlib/shared/System/Globalization/JapaneseCalendar.cs409
-rw-r--r--src/mscorlib/shared/System/Globalization/JapaneseLunisolarCalendar.cs305
-rw-r--r--src/mscorlib/shared/System/Globalization/JulianCalendar.cs443
-rw-r--r--src/mscorlib/shared/System/Globalization/KoreanCalendar.cs266
-rw-r--r--src/mscorlib/shared/System/Globalization/KoreanLunisolarCalendar.cs1323
-rw-r--r--src/mscorlib/shared/System/Globalization/LocaleData.Unix.cs4572
-rw-r--r--src/mscorlib/shared/System/Globalization/NumberStyles.cs65
-rw-r--r--src/mscorlib/shared/System/Globalization/PersianCalendar.cs606
-rw-r--r--src/mscorlib/shared/System/Globalization/SortVersion.cs98
-rw-r--r--src/mscorlib/shared/System/Globalization/TaiwanCalendar.cs285
-rw-r--r--src/mscorlib/shared/System/Globalization/TaiwanLunisolarCalendar.cs325
-rw-r--r--src/mscorlib/shared/System/Globalization/ThaiBuddhistCalendar.cs236
-rw-r--r--src/mscorlib/shared/System/Globalization/TimeSpanStyles.cs13
-rw-r--r--src/mscorlib/shared/System/Globalization/UmAlQuraCalendar.cs865
-rw-r--r--src/mscorlib/shared/System/Globalization/UnicodeCategory.cs40
-rw-r--r--src/mscorlib/shared/System/IAsyncResult.cs30
-rw-r--r--src/mscorlib/shared/System/ICloneable.cs11
-rw-r--r--src/mscorlib/shared/System/IComparable.cs37
-rw-r--r--src/mscorlib/shared/System/IConvertible.cs63
-rw-r--r--src/mscorlib/shared/System/ICustomFormatter.cs24
-rw-r--r--src/mscorlib/shared/System/IDisposable.cs60
-rw-r--r--src/mscorlib/shared/System/IEquatable.cs14
-rw-r--r--src/mscorlib/shared/System/IFormatProvider.cs23
-rw-r--r--src/mscorlib/shared/System/IFormattable.cs15
-rw-r--r--src/mscorlib/shared/System/IO/DirectoryNotFoundException.cs41
-rw-r--r--src/mscorlib/shared/System/IO/EndOfStreamException.cs35
-rw-r--r--src/mscorlib/shared/System/IO/Error.cs49
-rw-r--r--src/mscorlib/shared/System/IO/FileAccess.cs29
-rw-r--r--src/mscorlib/shared/System/IO/FileLoadException.cs102
-rw-r--r--src/mscorlib/shared/System/IO/FileMode.cs38
-rw-r--r--src/mscorlib/shared/System/IO/FileNotFoundException.cs114
-rw-r--r--src/mscorlib/shared/System/IO/FileOptions.cs33
-rw-r--r--src/mscorlib/shared/System/IO/FileShare.cs45
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.Linux.cs30
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.OSX.cs19
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.Unix.cs933
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.Win32.cs77
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.WinRT.cs78
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.Windows.cs1717
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.cs684
-rw-r--r--src/mscorlib/shared/System/IO/FileStreamCompletionSource.Win32.cs222
-rw-r--r--src/mscorlib/shared/System/IO/Path.Unix.cs215
-rw-r--r--src/mscorlib/shared/System/IO/Path.Windows.cs155
-rw-r--r--src/mscorlib/shared/System/IO/Path.cs574
-rw-r--r--src/mscorlib/shared/System/IO/PathHelper.Windows.cs398
-rw-r--r--src/mscorlib/shared/System/IO/PathInternal.Unix.cs104
-rw-r--r--src/mscorlib/shared/System/IO/PathInternal.Windows.StringBuffer.cs93
-rw-r--r--src/mscorlib/shared/System/IO/PathInternal.Windows.cs442
-rw-r--r--src/mscorlib/shared/System/IO/PathInternal.cs171
-rw-r--r--src/mscorlib/shared/System/IO/PathTooLongException.cs37
-rw-r--r--src/mscorlib/shared/System/IO/SeekOrigin.cs16
-rw-r--r--src/mscorlib/shared/System/IO/StreamHelpers.CopyValidation.cs46
-rw-r--r--src/mscorlib/shared/System/IO/Win32Marshal.cs109
-rw-r--r--src/mscorlib/shared/System/IObservable.cs11
-rw-r--r--src/mscorlib/shared/System/IObserver.cs13
-rw-r--r--src/mscorlib/shared/System/IProgress.cs15
-rw-r--r--src/mscorlib/shared/System/IndexOutOfRangeException.cs41
-rw-r--r--src/mscorlib/shared/System/InsufficientExecutionStackException.cs32
-rw-r--r--src/mscorlib/shared/System/InvalidCastException.cs44
-rw-r--r--src/mscorlib/shared/System/InvalidOperationException.cs42
-rw-r--r--src/mscorlib/shared/System/InvalidProgramException.cs41
-rw-r--r--src/mscorlib/shared/System/InvalidTimeZoneException.cs28
-rw-r--r--src/mscorlib/shared/System/Lazy.cs561
-rw-r--r--src/mscorlib/shared/System/MarshalByRefObject.cs30
-rw-r--r--src/mscorlib/shared/System/MemberAccessException.cs48
-rw-r--r--src/mscorlib/shared/System/MethodAccessException.cs39
-rw-r--r--src/mscorlib/shared/System/MidpointRounding.cs12
-rw-r--r--src/mscorlib/shared/System/MissingMethodException.cs60
-rw-r--r--src/mscorlib/shared/System/MulticastNotSupportedException.cs37
-rw-r--r--src/mscorlib/shared/System/NotFiniteNumberException.cs71
-rw-r--r--src/mscorlib/shared/System/NotImplementedException.cs40
-rw-r--r--src/mscorlib/shared/System/NotSupportedException.cs41
-rw-r--r--src/mscorlib/shared/System/NullReferenceException.cs41
-rw-r--r--src/mscorlib/shared/System/ObjectDisposedException.cs82
-rw-r--r--src/mscorlib/shared/System/ObsoleteAttribute.cs61
-rw-r--r--src/mscorlib/shared/System/OverflowException.cs41
-rw-r--r--src/mscorlib/shared/System/ParamArrayAttribute.cs21
-rw-r--r--src/mscorlib/shared/System/ParamsArray.cs82
-rw-r--r--src/mscorlib/shared/System/PlatformNotSupportedException.cs41
-rw-r--r--src/mscorlib/shared/System/Progress.cs105
-rw-r--r--src/mscorlib/shared/System/Random.cs274
-rw-r--r--src/mscorlib/shared/System/RankException.cs42
-rw-r--r--src/mscorlib/shared/System/Reflection/AmbiguousMatchException.cs35
-rw-r--r--src/mscorlib/shared/System/Reflection/Assembly.cs200
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyAlgorithmIdAttribute.cs27
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyCompanyAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyConfigurationAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyContentType.cs13
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyCopyrightAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyCultureAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyDefaultAliasAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyDelaySignAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyDescriptionAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyFileVersionAttribute.cs20
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyFlagsAttribute.cs43
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyInformationalVersionAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyKeyFileAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyKeyNameAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyMetadataAttribute.cs21
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyNameFlags.cs21
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyProductAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblySignatureKeyAttribute.cs21
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyTitleAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyTrademarkAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/AssemblyVersionAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/Binder.cs19
-rw-r--r--src/mscorlib/shared/System/Reflection/BindingFlags.cs50
-rw-r--r--src/mscorlib/shared/System/Reflection/CallingConventions.cs20
-rw-r--r--src/mscorlib/shared/System/Reflection/ConstructorInfo.cs40
-rw-r--r--src/mscorlib/shared/System/Reflection/CustomAttributeFormatException.cs33
-rw-r--r--src/mscorlib/shared/System/Reflection/DefaultMemberAttribute.cs22
-rw-r--r--src/mscorlib/shared/System/Reflection/EventAttributes.cs22
-rw-r--r--src/mscorlib/shared/System/Reflection/EventInfo.cs115
-rw-r--r--src/mscorlib/shared/System/Reflection/ExceptionHandlingClauseOptions.cs16
-rw-r--r--src/mscorlib/shared/System/Reflection/FieldAttributes.cs40
-rw-r--r--src/mscorlib/shared/System/Reflection/FieldInfo.cs72
-rw-r--r--src/mscorlib/shared/System/Reflection/GenericParameterAttributes.cs20
-rw-r--r--src/mscorlib/shared/System/Reflection/ICustomAttributeProvider.cs13
-rw-r--r--src/mscorlib/shared/System/Reflection/IReflect.cs76
-rw-r--r--src/mscorlib/shared/System/Reflection/IReflectableType.cs12
-rw-r--r--src/mscorlib/shared/System/Reflection/ImageFileMachine.cs15
-rw-r--r--src/mscorlib/shared/System/Reflection/InterfaceMapping.cs14
-rw-r--r--src/mscorlib/shared/System/Reflection/IntrospectionExtensions.cs20
-rw-r--r--src/mscorlib/shared/System/Reflection/InvalidFilterCriteriaException.cs33
-rw-r--r--src/mscorlib/shared/System/Reflection/ManifestResourceInfo.cs23
-rw-r--r--src/mscorlib/shared/System/Reflection/MemberFilter.cs8
-rw-r--r--src/mscorlib/shared/System/Reflection/MemberInfo.cs75
-rw-r--r--src/mscorlib/shared/System/Reflection/MemberInfoSerializationHolder.cs315
-rw-r--r--src/mscorlib/shared/System/Reflection/MemberTypes.cs20
-rw-r--r--src/mscorlib/shared/System/Reflection/MethodAttributes.cs50
-rw-r--r--src/mscorlib/shared/System/Reflection/MethodBase.cs86
-rw-r--r--src/mscorlib/shared/System/Reflection/MethodImplAttributes.cs37
-rw-r--r--src/mscorlib/shared/System/Reflection/MethodInfo.cs43
-rw-r--r--src/mscorlib/shared/System/Reflection/Missing.cs24
-rw-r--r--src/mscorlib/shared/System/Reflection/Module.cs182
-rw-r--r--src/mscorlib/shared/System/Reflection/ModuleResolveEventHandler.cs9
-rw-r--r--src/mscorlib/shared/System/Reflection/ObfuscateAssemblyAttribute.cs19
-rw-r--r--src/mscorlib/shared/System/Reflection/ObfuscationAttribute.cs21
-rw-r--r--src/mscorlib/shared/System/Reflection/ParameterAttributes.cs29
-rw-r--r--src/mscorlib/shared/System/Reflection/ParameterInfo.cs110
-rw-r--r--src/mscorlib/shared/System/Reflection/ParameterModifier.cs36
-rw-r--r--src/mscorlib/shared/System/Reflection/Pointer.cs61
-rw-r--r--src/mscorlib/shared/System/Reflection/PortableExecutableKinds.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/ProcessorArchitecture.cs16
-rw-r--r--src/mscorlib/shared/System/Reflection/PropertyAttributes.cs25
-rw-r--r--src/mscorlib/shared/System/Reflection/PropertyInfo.cs74
-rw-r--r--src/mscorlib/shared/System/Reflection/ReflectionContext.cs24
-rw-r--r--src/mscorlib/shared/System/Reflection/ReflectionTypeLoadException.cs46
-rw-r--r--src/mscorlib/shared/System/Reflection/ResourceAttributes.cs14
-rw-r--r--src/mscorlib/shared/System/Reflection/ResourceLocation.cs15
-rw-r--r--src/mscorlib/shared/System/Reflection/StrongNameKeyPair.cs74
-rw-r--r--src/mscorlib/shared/System/Reflection/TargetException.cs33
-rw-r--r--src/mscorlib/shared/System/Reflection/TargetInvocationException.cs29
-rw-r--r--src/mscorlib/shared/System/Reflection/TargetParameterCountException.cs35
-rw-r--r--src/mscorlib/shared/System/Reflection/TypeAttributes.cs63
-rw-r--r--src/mscorlib/shared/System/Reflection/TypeDelegator.cs124
-rw-r--r--src/mscorlib/shared/System/Reflection/TypeFilter.cs8
-rw-r--r--src/mscorlib/shared/System/Reflection/TypeInfo.cs84
-rw-r--r--src/mscorlib/shared/System/ResolveEventArgs.cs25
-rw-r--r--src/mscorlib/shared/System/ResolveEventHandler.cs10
-rw-r--r--src/mscorlib/shared/System/Resources/IResourceReader.cs30
-rw-r--r--src/mscorlib/shared/System/Resources/MissingManifestResourceException.cs36
-rw-r--r--src/mscorlib/shared/System/Resources/MissingSatelliteAssemblyException.cs63
-rw-r--r--src/mscorlib/shared/System/Resources/NeutralResourcesLanguageAttribute.cs33
-rw-r--r--src/mscorlib/shared/System/Resources/ResourceTypeCode.cs58
-rw-r--r--src/mscorlib/shared/System/Resources/SatelliteContractVersionAttribute.cs31
-rw-r--r--src/mscorlib/shared/System/Resources/UltimateResourceFallbackLocation.cs25
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/AccessedThroughPropertyAttribute.cs17
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/AsyncStateMachineAttribute.cs16
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/CallerFilePathAttribute.cs14
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/CallerLineNumberAttribute.cs14
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/CallerMemberNameAttribute.cs14
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/CompilationRelaxations.cs16
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/CompilationRelaxationsAttribute.cs23
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/CompilerGeneratedAttribute.cs13
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/CompilerGlobalScopeAttribute.cs16
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/DefaultDependencyAttribute.cs18
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/DependencyAttribute.cs20
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/DisablePrivateReflectionAttribute.cs13
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/DiscardableAttribute.cs13
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/ExtensionAttribute.cs14
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/FixedAddressValueTypeAttribute.cs13
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/FixedBufferAttribute.cs32
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/FormattableStringFactory.cs58
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/IAsyncStateMachine.cs27
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/INotifyCompletion.cs39
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/ITuple.cs22
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/IndexerNameAttribute.cs15
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/InternalsVisibleToAttribute.cs21
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/IsConst.cs10
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/IsVolatile.cs12
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/IteratorStateMachineAttribute.cs16
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/LoadHint.cs14
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/MethodCodeType.cs17
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/MethodImplOptions.cs21
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/ReadOnlyAttribute.cs21
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/ReferenceAssemblyAttribute.cs33
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/RuntimeCompatibilityAttribute.cs31
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/RuntimeFeature.cs19
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/SpecialNameAttribute.cs12
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/StateMachineAttribute.cs20
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/StringFreezingAttribute.cs15
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/StrongBox.cs59
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/SuppressIldasmAttribute.cs13
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/TupleElementNamesAttribute.cs57
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/TypeForwardedFromAttribute.cs17
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/TypeForwardedToAttribute.cs17
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/UnsafeValueTypeAttribute.cs12
-rw-r--r--src/mscorlib/shared/System/Runtime/ConstrainedExecution/Cer.cs14
-rw-r--r--src/mscorlib/shared/System/Runtime/ConstrainedExecution/Consistency.cs15
-rw-r--r--src/mscorlib/shared/System/Runtime/ConstrainedExecution/ReliabilityContractAttribute.cs33
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/CallingConvention.cs16
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/CharSet.cs21
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/ComVisibleAttribute.cs17
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/ExternalException.cs89
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/LayoutKind.cs14
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/StringBuffer.cs301
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/UnmanagedFunctionPointerAttribute.cs27
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/UnmanagedType.cs48
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/VarEnum.cs54
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/IDeserializationCallback.cs11
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/IFormatterConverter.cs28
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/IObjectReference.cs11
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/ISafeSerializationData.cs207
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/ISerializable.cs11
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/OnDeserializedAttribute.cs11
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/OnDeserializingAttribute.cs11
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/OnSerializedAttribute.cs11
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/OnSerializingAttribute.cs11
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/OptionalFieldAttribute.cs25
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/SafeSerializationEventArgs.cs31
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/SerializationException.cs39
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/SerializationInfoEnumerator.cs127
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/StreamingContext.cs53
-rw-r--r--src/mscorlib/shared/System/Runtime/Versioning/NonVersionableAttribute.cs36
-rw-r--r--src/mscorlib/shared/System/Runtime/Versioning/TargetFrameworkAttribute.cs48
-rw-r--r--src/mscorlib/shared/System/Security/AllowPartiallyTrustedCallersAttribute.cs19
-rw-r--r--src/mscorlib/shared/System/Security/CryptographicException.cs44
-rw-r--r--src/mscorlib/shared/System/Security/PartialTrustVisibilityLevel.cs13
-rw-r--r--src/mscorlib/shared/System/Security/SafeBSTRHandle.cs81
-rw-r--r--src/mscorlib/shared/System/Security/SecureString.Unix.cs295
-rw-r--r--src/mscorlib/shared/System/Security/SecureString.Windows.cs311
-rw-r--r--src/mscorlib/shared/System/Security/SecureString.cs189
-rw-r--r--src/mscorlib/shared/System/Security/SecurityCriticalAttribute.cs36
-rw-r--r--src/mscorlib/shared/System/Security/SecurityCriticalScope.cs14
-rw-r--r--src/mscorlib/shared/System/Security/SecurityException.cs66
-rw-r--r--src/mscorlib/shared/System/Security/SecurityRuleSet.cs14
-rw-r--r--src/mscorlib/shared/System/Security/SecurityRulesAttribute.cs28
-rw-r--r--src/mscorlib/shared/System/Security/SecuritySafeCriticalAttribute.cs30
-rw-r--r--src/mscorlib/shared/System/Security/SecurityTransparentAttribute.cs19
-rw-r--r--src/mscorlib/shared/System/Security/SecurityTreatAsSafeAttribute.cs32
-rw-r--r--src/mscorlib/shared/System/Security/SuppressUnmanagedCodeSecurityAttribute.cs16
-rw-r--r--src/mscorlib/shared/System/Security/UnverifiableCodeAttribute.cs15
-rw-r--r--src/mscorlib/shared/System/Security/VerificationException.cs35
-rw-r--r--src/mscorlib/shared/System/StackOverflowException.cs41
-rw-r--r--src/mscorlib/shared/System/StringComparer.cs274
-rw-r--r--src/mscorlib/shared/System/StringComparison.cs17
-rw-r--r--src/mscorlib/shared/System/StringSplitOptions.cs13
-rw-r--r--src/mscorlib/shared/System/SystemException.cs32
-rw-r--r--src/mscorlib/shared/System/Text/ASCIIEncoding.cs973
-rw-r--r--src/mscorlib/shared/System/Text/Decoder.cs339
-rw-r--r--src/mscorlib/shared/System/Text/Encoder.cs333
-rw-r--r--src/mscorlib/shared/System/Text/EncodingInfo.cs72
-rw-r--r--src/mscorlib/shared/System/Text/EncodingNLS.cs322
-rw-r--r--src/mscorlib/shared/System/Text/EncodingProvider.cs136
-rw-r--r--src/mscorlib/shared/System/Text/Normalization.cs29
-rw-r--r--src/mscorlib/shared/System/Text/StringBuilder.cs2409
-rw-r--r--src/mscorlib/shared/System/Text/UTF32Encoding.cs1234
-rw-r--r--src/mscorlib/shared/System/Text/UTF8Encoding.cs2668
-rw-r--r--src/mscorlib/shared/System/Text/UnicodeEncoding.cs2058
-rw-r--r--src/mscorlib/shared/System/ThreadAttributes.cs28
-rw-r--r--src/mscorlib/shared/System/ThreadStaticAttribute.cs28
-rw-r--r--src/mscorlib/shared/System/Threading/AbandonedMutexException.cs77
-rw-r--r--src/mscorlib/shared/System/Threading/ApartmentState.cs16
-rw-r--r--src/mscorlib/shared/System/Threading/AsyncLocal.cs484
-rw-r--r--src/mscorlib/shared/System/Threading/AutoResetEvent.cs12
-rw-r--r--src/mscorlib/shared/System/Threading/DeferredDisposableLifetime.cs116
-rw-r--r--src/mscorlib/shared/System/Threading/EventResetMode.cs22
-rw-r--r--src/mscorlib/shared/System/Threading/ExecutionContext.cs370
-rw-r--r--src/mscorlib/shared/System/Threading/LazyThreadSafetyMode.cs44
-rw-r--r--src/mscorlib/shared/System/Threading/LockRecursionException.cs29
-rw-r--r--src/mscorlib/shared/System/Threading/ManualResetEvent.cs12
-rw-r--r--src/mscorlib/shared/System/Threading/ParameterizedThreadStart.cs18
-rw-r--r--src/mscorlib/shared/System/Threading/SemaphoreFullException.cs29
-rw-r--r--src/mscorlib/shared/System/Threading/SendOrPostCallback.cs8
-rw-r--r--src/mscorlib/shared/System/Threading/SynchronizationLockException.cs44
-rw-r--r--src/mscorlib/shared/System/Threading/Tasks/TaskCanceledException.cs89
-rw-r--r--src/mscorlib/shared/System/Threading/Tasks/TaskExtensions.cs48
-rw-r--r--src/mscorlib/shared/System/Threading/Tasks/TaskSchedulerException.cs77
-rw-r--r--src/mscorlib/shared/System/Threading/ThreadAbortException.cs36
-rw-r--r--src/mscorlib/shared/System/Threading/ThreadPriority.cs18
-rw-r--r--src/mscorlib/shared/System/Threading/ThreadStart.cs18
-rw-r--r--src/mscorlib/shared/System/Threading/ThreadStartException.cs29
-rw-r--r--src/mscorlib/shared/System/Threading/ThreadState.cs24
-rw-r--r--src/mscorlib/shared/System/Threading/ThreadStateException.cs45
-rw-r--r--src/mscorlib/shared/System/Threading/Timeout.cs20
-rw-r--r--src/mscorlib/shared/System/Threading/TimeoutHelper.cs54
-rw-r--r--src/mscorlib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs31
-rw-r--r--src/mscorlib/shared/System/TimeZone.cs281
-rw-r--r--src/mscorlib/shared/System/TimeZoneNotFoundException.cs28
-rw-r--r--src/mscorlib/shared/System/TimeoutException.cs41
-rw-r--r--src/mscorlib/shared/System/TupleExtensions.cs930
-rw-r--r--src/mscorlib/shared/System/Type.Enum.cs186
-rw-r--r--src/mscorlib/shared/System/Type.Helpers.cs527
-rw-r--r--src/mscorlib/shared/System/Type.cs358
-rw-r--r--src/mscorlib/shared/System/TypeAccessException.cs34
-rw-r--r--src/mscorlib/shared/System/TypeCode.cs48
-rw-r--r--src/mscorlib/shared/System/TypeInitializationException.cs79
-rw-r--r--src/mscorlib/shared/System/TypeUnloadedException.cs39
-rw-r--r--src/mscorlib/shared/System/UnauthorizedAccessException.cs45
-rw-r--r--src/mscorlib/shared/System/UnhandledExceptionEventArgs.cs29
-rw-r--r--src/mscorlib/shared/System/UnhandledExceptionEventHandler.cs9
-rw-r--r--src/mscorlib/shared/System/UnitySerializationHolder.cs329
-rw-r--r--src/mscorlib/shared/System/ValueTuple.cs2324
-rw-r--r--src/mscorlib/shared/System/Version.cs495
-rw-r--r--src/mscorlib/shared/System/Void.cs17
513 files changed, 89034 insertions, 0 deletions
diff --git a/src/mscorlib/shared/Interop/Unix/Interop.Errors.cs b/src/mscorlib/shared/Interop/Unix/Interop.Errors.cs
new file mode 100644
index 0000000000..4248434db3
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/Interop.Errors.cs
@@ -0,0 +1,207 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ /// <summary>Common Unix errno error codes.</summary>
+ internal enum Error
+ {
+ // These values were defined in src/Native/System.Native/fxerrno.h
+ //
+ // They compare against values obtained via Interop.Sys.GetLastError() not Marshal.GetLastWin32Error()
+ // which obtains the raw errno that varies between unixes. The strong typing as an enum is meant to
+ // prevent confusing the two. Casting to or from int is suspect. Use GetLastErrorInfo() if you need to
+ // correlate these to the underlying platform values or obtain the corresponding error message.
+ //
+
+ SUCCESS = 0,
+
+ E2BIG = 0x10001, // Argument list too long.
+ EACCES = 0x10002, // Permission denied.
+ EADDRINUSE = 0x10003, // Address in use.
+ EADDRNOTAVAIL = 0x10004, // Address not available.
+ EAFNOSUPPORT = 0x10005, // Address family not supported.
+ EAGAIN = 0x10006, // Resource unavailable, try again (same value as EWOULDBLOCK),
+ EALREADY = 0x10007, // Connection already in progress.
+ EBADF = 0x10008, // Bad file descriptor.
+ EBADMSG = 0x10009, // Bad message.
+ EBUSY = 0x1000A, // Device or resource busy.
+ ECANCELED = 0x1000B, // Operation canceled.
+ ECHILD = 0x1000C, // No child processes.
+ ECONNABORTED = 0x1000D, // Connection aborted.
+ ECONNREFUSED = 0x1000E, // Connection refused.
+ ECONNRESET = 0x1000F, // Connection reset.
+ EDEADLK = 0x10010, // Resource deadlock would occur.
+ EDESTADDRREQ = 0x10011, // Destination address required.
+ EDOM = 0x10012, // Mathematics argument out of domain of function.
+ EDQUOT = 0x10013, // Reserved.
+ EEXIST = 0x10014, // File exists.
+ EFAULT = 0x10015, // Bad address.
+ EFBIG = 0x10016, // File too large.
+ EHOSTUNREACH = 0x10017, // Host is unreachable.
+ EIDRM = 0x10018, // Identifier removed.
+ EILSEQ = 0x10019, // Illegal byte sequence.
+ EINPROGRESS = 0x1001A, // Operation in progress.
+ EINTR = 0x1001B, // Interrupted function.
+ EINVAL = 0x1001C, // Invalid argument.
+ EIO = 0x1001D, // I/O error.
+ EISCONN = 0x1001E, // Socket is connected.
+ EISDIR = 0x1001F, // Is a directory.
+ ELOOP = 0x10020, // Too many levels of symbolic links.
+ EMFILE = 0x10021, // File descriptor value too large.
+ EMLINK = 0x10022, // Too many links.
+ EMSGSIZE = 0x10023, // Message too large.
+ EMULTIHOP = 0x10024, // Reserved.
+ ENAMETOOLONG = 0x10025, // Filename too long.
+ ENETDOWN = 0x10026, // Network is down.
+ ENETRESET = 0x10027, // Connection aborted by network.
+ ENETUNREACH = 0x10028, // Network unreachable.
+ ENFILE = 0x10029, // Too many files open in system.
+ ENOBUFS = 0x1002A, // No buffer space available.
+ ENODEV = 0x1002C, // No such device.
+ ENOENT = 0x1002D, // No such file or directory.
+ ENOEXEC = 0x1002E, // Executable file format error.
+ ENOLCK = 0x1002F, // No locks available.
+ ENOLINK = 0x10030, // Reserved.
+ ENOMEM = 0x10031, // Not enough space.
+ ENOMSG = 0x10032, // No message of the desired type.
+ ENOPROTOOPT = 0x10033, // Protocol not available.
+ ENOSPC = 0x10034, // No space left on device.
+ ENOSYS = 0x10037, // Function not supported.
+ ENOTCONN = 0x10038, // The socket is not connected.
+ ENOTDIR = 0x10039, // Not a directory or a symbolic link to a directory.
+ ENOTEMPTY = 0x1003A, // Directory not empty.
+ ENOTSOCK = 0x1003C, // Not a socket.
+ ENOTSUP = 0x1003D, // Not supported (same value as EOPNOTSUP).
+ ENOTTY = 0x1003E, // Inappropriate I/O control operation.
+ ENXIO = 0x1003F, // No such device or address.
+ EOVERFLOW = 0x10040, // Value too large to be stored in data type.
+ EPERM = 0x10042, // Operation not permitted.
+ EPIPE = 0x10043, // Broken pipe.
+ EPROTO = 0x10044, // Protocol error.
+ EPROTONOSUPPORT = 0x10045, // Protocol not supported.
+ EPROTOTYPE = 0x10046, // Protocol wrong type for socket.
+ ERANGE = 0x10047, // Result too large.
+ EROFS = 0x10048, // Read-only file system.
+ ESPIPE = 0x10049, // Invalid seek.
+ ESRCH = 0x1004A, // No such process.
+ ESTALE = 0x1004B, // Reserved.
+ ETIMEDOUT = 0x1004D, // Connection timed out.
+ ETXTBSY = 0x1004E, // Text file busy.
+ EXDEV = 0x1004F, // Cross-device link.
+ ESOCKTNOSUPPORT = 0x1005E, // Socket type not supported.
+ EPFNOSUPPORT = 0x10060, // Protocol family not supported.
+ ESHUTDOWN = 0x1006C, // Socket shutdown.
+ EHOSTDOWN = 0x10070, // Host is down.
+ ENODATA = 0x10071, // No data available.
+
+ // POSIX permits these to have the same value and we make them always equal so
+ // that CoreFX cannot introduce a dependency on distinguishing between them that
+ // would not work on all platforms.
+ EOPNOTSUPP = ENOTSUP, // Operation not supported on socket.
+ EWOULDBLOCK = EAGAIN, // Operation would block.
+ }
+
+
+ // Represents a platform-agnostic Error and underlying platform-specific errno
+ internal struct ErrorInfo
+ {
+ private Error _error;
+ private int _rawErrno;
+
+ internal ErrorInfo(int errno)
+ {
+ _error = Interop.Sys.ConvertErrorPlatformToPal(errno);
+ _rawErrno = errno;
+ }
+
+ internal ErrorInfo(Error error)
+ {
+ _error = error;
+ _rawErrno = -1;
+ }
+
+ internal Error Error
+ {
+ get { return _error; }
+ }
+
+ internal int RawErrno
+ {
+ get { return _rawErrno == -1 ? (_rawErrno = Interop.Sys.ConvertErrorPalToPlatform(_error)) : _rawErrno; }
+ }
+
+ internal string GetErrorMessage()
+ {
+ return Interop.Sys.StrError(RawErrno);
+ }
+
+ public override string ToString()
+ {
+ return string.Format(
+ "RawErrno: {0} Error: {1} GetErrorMessage: {2}", // No localization required; text is member names used for debugging purposes
+ RawErrno, Error, GetErrorMessage());
+ }
+ }
+
+ internal partial class Sys
+ {
+ internal static Error GetLastError()
+ {
+ return ConvertErrorPlatformToPal(Marshal.GetLastWin32Error());
+ }
+
+ internal static ErrorInfo GetLastErrorInfo()
+ {
+ return new ErrorInfo(Marshal.GetLastWin32Error());
+ }
+
+ internal static unsafe string StrError(int platformErrno)
+ {
+ int maxBufferLength = 1024; // should be long enough for most any UNIX error
+ byte* buffer = stackalloc byte[maxBufferLength];
+ byte* message = StrErrorR(platformErrno, buffer, maxBufferLength);
+
+ if (message == null)
+ {
+ // This means the buffer was not large enough, but still contains
+ // as much of the error message as possible and is guaranteed to
+ // be null-terminated. We're not currently resizing/retrying because
+ // maxBufferLength is large enough in practice, but we could do
+ // so here in the future if necessary.
+ message = buffer;
+ }
+
+ return Marshal.PtrToStringAnsi((IntPtr)message);
+ }
+
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConvertErrorPlatformToPal")]
+ internal static extern Error ConvertErrorPlatformToPal(int platformErrno);
+
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_ConvertErrorPalToPlatform")]
+ internal static extern int ConvertErrorPalToPlatform(Error error);
+
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_StrErrorR")]
+ private static unsafe extern byte* StrErrorR(int platformErrno, byte* buffer, int bufferSize);
+ }
+}
+
+// NOTE: extension method can't be nested inside Interop class.
+internal static class InteropErrorExtensions
+{
+ // Intended usage is e.g. Interop.Error.EFAIL.Info() for brevity
+ // vs. new Interop.ErrorInfo(Interop.Error.EFAIL) for synthesizing
+ // errors. Errors originated from the system should be obtained
+ // via GetLastErrorInfo(), not GetLastError().Info() as that will
+ // convert twice, which is not only inefficient but also lossy if
+ // we ever encounter a raw errno that no equivalent in the Error
+ // enum.
+ public static Interop.ErrorInfo Info(this Interop.Error error)
+ {
+ return new Interop.ErrorInfo(error);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/Interop.IOErrors.cs b/src/mscorlib/shared/Interop/Unix/Interop.IOErrors.cs
new file mode 100644
index 0000000000..e9d6ce61d6
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/Interop.IOErrors.cs
@@ -0,0 +1,170 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+
+internal static partial class Interop
+{
+ private static void ThrowExceptionForIoErrno(ErrorInfo errorInfo, string path, bool isDirectory, Func<ErrorInfo, ErrorInfo> errorRewriter)
+ {
+ Debug.Assert(errorInfo.Error != Error.SUCCESS);
+ Debug.Assert(errorInfo.Error != Error.EINTR, "EINTR errors should be handled by the native shim and never bubble up to managed code");
+
+ if (errorRewriter != null)
+ {
+ errorInfo = errorRewriter(errorInfo);
+ }
+
+ throw Interop.GetExceptionForIoErrno(errorInfo, path, isDirectory);
+ }
+
+ internal static void CheckIo(Error error, string path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo> errorRewriter = null)
+ {
+ if (error != Interop.Error.SUCCESS)
+ {
+ ThrowExceptionForIoErrno(error.Info(), path, isDirectory, errorRewriter);
+ }
+ }
+
+ /// <summary>
+ /// Validates the result of system call that returns greater than or equal to 0 on success
+ /// and less than 0 on failure, with errno set to the error code.
+ /// If the system call failed for any reason, an exception is thrown. Otherwise, the system call succeeded.
+ /// </summary>
+ /// <param name="result">The result of the system call.</param>
+ /// <param name="path">The path with which this error is associated. This may be null.</param>
+ /// <param name="isDirectory">true if the <paramref name="path"/> is known to be a directory; otherwise, false.</param>
+ /// <param name="errorRewriter">Optional function to change an error code prior to processing it.</param>
+ /// <returns>
+ /// On success, returns the non-negative result long that was validated.
+ /// </returns>
+ internal static long CheckIo(long result, string path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo> errorRewriter = null)
+ {
+ if (result < 0)
+ {
+ ThrowExceptionForIoErrno(Sys.GetLastErrorInfo(), path, isDirectory, errorRewriter);
+ }
+
+ return result;
+ }
+
+ /// <summary>
+ /// Validates the result of system call that returns greater than or equal to 0 on success
+ /// and less than 0 on failure, with errno set to the error code.
+ /// If the system call failed for any reason, an exception is thrown. Otherwise, the system call succeeded.
+ /// </summary>
+ /// <returns>
+ /// On success, returns the non-negative result int that was validated.
+ /// </returns>
+ internal static int CheckIo(int result, string path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo> errorRewriter = null)
+ {
+ CheckIo((long)result, path, isDirectory, errorRewriter);
+
+ return result;
+ }
+
+ /// <summary>
+ /// Validates the result of system call that returns greater than or equal to 0 on success
+ /// and less than 0 on failure, with errno set to the error code.
+ /// If the system call failed for any reason, an exception is thrown. Otherwise, the system call succeeded.
+ /// </summary>
+ /// <returns>
+ /// On success, returns the non-negative result IntPtr that was validated.
+ /// </returns>
+ internal static IntPtr CheckIo(IntPtr result, string path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo> errorRewriter = null)
+ {
+ CheckIo((long)result, path, isDirectory, errorRewriter);
+
+ return result;
+ }
+
+ /// <summary>
+ /// Validates the result of system call that returns greater than or equal to 0 on success
+ /// and less than 0 on failure, with errno set to the error code.
+ /// If the system call failed for any reason, an exception is thrown. Otherwise, the system call succeeded.
+ /// </summary>
+ /// <returns>
+ /// On success, returns the valid SafeFileHandle that was validated.
+ /// </returns>
+ internal static TSafeHandle CheckIo<TSafeHandle>(TSafeHandle handle, string path = null, bool isDirectory = false, Func<ErrorInfo, ErrorInfo> errorRewriter = null)
+ where TSafeHandle : SafeHandle
+ {
+ if (handle.IsInvalid)
+ {
+ ThrowExceptionForIoErrno(Sys.GetLastErrorInfo(), path, isDirectory, errorRewriter);
+ }
+
+ return handle;
+ }
+
+ /// <summary>
+ /// Gets an Exception to represent the supplied error info.
+ /// </summary>
+ /// <param name="error">The error info</param>
+ /// <param name="path">The path with which this error is associated. This may be null.</param>
+ /// <param name="isDirectory">true if the <paramref name="path"/> is known to be a directory; otherwise, false.</param>
+ /// <returns></returns>
+ internal static Exception GetExceptionForIoErrno(ErrorInfo errorInfo, string path = null, bool isDirectory = false)
+ {
+ // Translate the errno into a known set of exception types. For cases where multiple errnos map
+ // to the same exception type, include an inner exception with the details.
+ switch (errorInfo.Error)
+ {
+ case Error.ENOENT:
+ if (isDirectory)
+ {
+ return !string.IsNullOrEmpty(path) ?
+ new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, path)) :
+ new DirectoryNotFoundException(SR.IO_PathNotFound_NoPathName);
+ }
+ else
+ {
+ return !string.IsNullOrEmpty(path) ?
+ new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, path), path) :
+ new FileNotFoundException(SR.IO_FileNotFound);
+ }
+
+ case Error.EACCES:
+ case Error.EBADF:
+ case Error.EPERM:
+ Exception inner = GetIOException(errorInfo);
+ return !string.IsNullOrEmpty(path) ?
+ new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, path), inner) :
+ new UnauthorizedAccessException(SR.UnauthorizedAccess_IODenied_NoPathName, inner);
+
+ case Error.ENAMETOOLONG:
+ return new PathTooLongException(SR.IO_PathTooLong);
+
+ case Error.EWOULDBLOCK:
+ return !string.IsNullOrEmpty(path) ?
+ new IOException(SR.Format(SR.IO_SharingViolation_File, path), errorInfo.RawErrno) :
+ new IOException(SR.IO_SharingViolation_NoFileName, errorInfo.RawErrno);
+
+ case Error.ECANCELED:
+ return new OperationCanceledException();
+
+ case Error.EFBIG:
+ return new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_FileLengthTooBig);
+
+ case Error.EEXIST:
+ if (!string.IsNullOrEmpty(path))
+ {
+ return new IOException(SR.Format(SR.IO_FileExists_Name, path), errorInfo.RawErrno);
+ }
+ goto default;
+
+ default:
+ return GetIOException(errorInfo);
+ }
+ }
+
+ internal static Exception GetIOException(Interop.ErrorInfo errorInfo)
+ {
+ return new IOException(errorInfo.GetErrorMessage(), errorInfo.RawErrno);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/Interop.Libraries.cs b/src/mscorlib/shared/Interop/Unix/Interop.Libraries.cs
new file mode 100644
index 0000000000..7b3dea453d
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/Interop.Libraries.cs
@@ -0,0 +1,12 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+internal static partial class Interop
+{
+ internal static partial class Libraries
+ {
+ internal const string GlobalizationInterop = "System.Globalization.Native";
+ internal const string SystemNative = "System.Native";
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs
new file mode 100644
index 0000000000..7b3caeabdd
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Calendar.cs
@@ -0,0 +1,33 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Globalization;
+using System.Runtime.InteropServices;
+using System.Text;
+
+internal static partial class Interop
+{
+ internal static partial class GlobalizationInterop
+ {
+ internal delegate void EnumCalendarInfoCallback(
+ [MarshalAs(UnmanagedType.LPWStr)] string calendarString,
+ IntPtr context);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetCalendars")]
+ internal static extern int GetCalendars(string localeName, CalendarId[] calendars, int calendarsCapacity);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetCalendarInfo")]
+ internal static extern ResultCode GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType calendarDataType, [Out] StringBuilder result, int resultCapacity);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_EnumCalendarInfo")]
+ internal static extern bool EnumCalendarInfo(EnumCalendarInfoCallback callback, string localeName, CalendarId calendarId, CalendarDataType calendarDataType, IntPtr context);
+
+ [DllImport(Libraries.GlobalizationInterop, EntryPoint = "GlobalizationNative_GetLatestJapaneseEra")]
+ internal static extern int GetLatestJapaneseEra();
+
+ [DllImport(Libraries.GlobalizationInterop, EntryPoint = "GlobalizationNative_GetJapaneseEraStartDate")]
+ internal static extern bool GetJapaneseEraStartDate(int era, out int startYear, out int startMonth, out int startDay);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Casing.cs b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Casing.cs
new file mode 100644
index 0000000000..769506b8f6
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Casing.cs
@@ -0,0 +1,23 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+using System.Security;
+using System.Text;
+
+internal static partial class Interop
+{
+ internal static partial class GlobalizationInterop
+ {
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ChangeCase")]
+ internal unsafe static extern void ChangeCase(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ChangeCaseInvariant")]
+ internal unsafe static extern void ChangeCaseInvariant(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ChangeCaseTurkish")]
+ internal unsafe static extern void ChangeCaseTurkish(char* src, int srcLen, char* dstBuffer, int dstBufferCapacity, bool bToUpper);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Idna.cs b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Idna.cs
new file mode 100644
index 0000000000..43c72281ae
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Idna.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal static partial class GlobalizationInterop
+ {
+ internal const int AllowUnassigned = 0x1;
+ internal const int UseStd3AsciiRules = 0x2;
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ToAscii")]
+ internal static unsafe extern int ToAscii(uint flags, char* src, int srcLen, char* dstBuffer, int dstBufferCapacity);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_ToUnicode")]
+ internal static unsafe extern int ToUnicode(uint flags, char* src, int srcLen, char* dstBuffer, int dstBufferCapacity);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs
new file mode 100644
index 0000000000..fcea708ee8
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Locale.cs
@@ -0,0 +1,40 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+using System.Text;
+
+internal static partial class Interop
+{
+ internal static partial class GlobalizationInterop
+ {
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleName")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal unsafe static extern bool GetLocaleName(string localeName, [Out] StringBuilder value, int valueLength);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleInfoString")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal unsafe static extern bool GetLocaleInfoString(string localeName, uint localeStringData, [Out] StringBuilder value, int valueLength);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetDefaultLocaleName")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal unsafe static extern bool GetDefaultLocaleName([Out] StringBuilder value, int valueLength);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleTimeFormat")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal unsafe static extern bool GetLocaleTimeFormat(string localeName, bool shortFormat, [Out] StringBuilder value, int valueLength);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleInfoInt")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal unsafe static extern bool GetLocaleInfoInt(string localeName, uint localeNumberData, ref int value);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocaleInfoGroupingSizes")]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal unsafe static extern bool GetLocaleInfoGroupingSizes(string localeName, uint localeGroupingData, ref int primaryGroupSize, ref int secondaryGroupSize);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetLocales")]
+ internal unsafe static extern int GetLocales([Out] Char[] value, int valueLength);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs
new file mode 100644
index 0000000000..c4cb9fb851
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Normalization.cs
@@ -0,0 +1,19 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+using System.Text;
+
+internal static partial class Interop
+{
+ internal static partial class GlobalizationInterop
+ {
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_IsNormalized")]
+ internal static extern int IsNormalized(NormalizationForm normalizationForm, string src, int srcLen);
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_NormalizeString")]
+ internal static extern int NormalizeString(NormalizationForm normalizationForm, string src, int srcLen, [Out] char[] dstBuffer, int dstBufferCapacity);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs
new file mode 100644
index 0000000000..cca6ae4dcb
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.ResultCode.cs
@@ -0,0 +1,18 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+internal static partial class Interop
+{
+ internal static partial class GlobalizationInterop
+ {
+ // needs to be kept in sync with ResultCode in System.Globalization.Native
+ internal enum ResultCode
+ {
+ Success = 0,
+ UnknownError = 1,
+ InsufficentBuffer = 2,
+ OutOfMemory = 3
+ }
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs
new file mode 100644
index 0000000000..26a9fe0579
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.TimeZoneInfo.cs
@@ -0,0 +1,31 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.InteropServices;
+using System.Text;
+
+internal static partial class Interop
+{
+ internal static partial class GlobalizationInterop
+ {
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Ansi, EntryPoint = "GlobalizationNative_ReadLink")] // readlink requires char*
+ internal static extern bool ReadLink(string filePath, [Out] StringBuilder result, uint resultCapacity);
+
+ // needs to be kept in sync with TimeZoneDisplayNameType in System.Globalization.Native
+ internal enum TimeZoneDisplayNameType
+ {
+ Generic = 0,
+ Standard = 1,
+ DaylightSavings = 2,
+ }
+
+ [DllImport(Libraries.GlobalizationInterop, CharSet = CharSet.Unicode, EntryPoint = "GlobalizationNative_GetTimeZoneDisplayName")]
+ internal static extern ResultCode GetTimeZoneDisplayName(
+ string localeName,
+ string timeZoneId,
+ TimeZoneDisplayNameType type,
+ [Out] StringBuilder result,
+ int resultLength);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Utils.cs b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Utils.cs
new file mode 100644
index 0000000000..33b10c0d74
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Utils.cs
@@ -0,0 +1,52 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Text;
+
+internal static partial class Interop
+{
+ /// <summary>
+ /// Helper for making interop calls that return a string, but we don't know
+ /// the correct size of buffer to make. So invoke the interop call with an
+ /// increasing buffer until the size is big enough.
+ /// </summary>
+ internal static bool CallStringMethod<TArg1, TArg2, TArg3>(
+ Func<TArg1, TArg2, TArg3, StringBuilder, GlobalizationInterop.ResultCode> interopCall,
+ TArg1 arg1,
+ TArg2 arg2,
+ TArg3 arg3,
+ out string result)
+ {
+ const int initialStringSize = 80;
+ const int maxDoubleAttempts = 5;
+
+ StringBuilder stringBuilder = StringBuilderCache.Acquire(initialStringSize);
+
+ for (int i = 0; i < maxDoubleAttempts; i++)
+ {
+ GlobalizationInterop.ResultCode resultCode = interopCall(arg1, arg2, arg3, stringBuilder);
+
+ if (resultCode == GlobalizationInterop.ResultCode.Success)
+ {
+ result = StringBuilderCache.GetStringAndRelease(stringBuilder);
+ return true;
+ }
+ else if (resultCode == GlobalizationInterop.ResultCode.InsufficentBuffer)
+ {
+ // increase the string size and loop
+ stringBuilder.EnsureCapacity(stringBuilder.Capacity * 2);
+ }
+ else
+ {
+ // if there is an unknown error, don't proceed
+ break;
+ }
+ }
+
+ StringBuilderCache.Release(stringBuilder);
+ result = null;
+ return false;
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Close.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Close.cs
new file mode 100644
index 0000000000..8d192398a0
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Close.cs
@@ -0,0 +1,15 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Close", SetLastError = true)]
+ internal static extern int Close(IntPtr fd);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.FLock.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.FLock.cs
new file mode 100644
index 0000000000..22934a3e77
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.FLock.cs
@@ -0,0 +1,31 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ internal enum LockOperations : int
+ {
+ LOCK_SH = 1, /* shared lock */
+ LOCK_EX = 2, /* exclusive lock */
+ LOCK_NB = 4, /* don't block when locking*/
+ LOCK_UN = 8, /* unlock */
+ }
+
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FLock", SetLastError = true)]
+ internal static extern int FLock(SafeFileHandle fd, LockOperations operation);
+
+ /// <summary>
+ /// Exposing this for SafeFileHandle.ReleaseHandle() to call.
+ /// Normal callers should use FLock(SafeFileHandle fd).
+ /// </summary>
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FLock", SetLastError = true)]
+ internal static extern int FLock(IntPtr fd, LockOperations operation);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.FSync.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.FSync.cs
new file mode 100644
index 0000000000..e3ab970931
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.FSync.cs
@@ -0,0 +1,15 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FSync", SetLastError = true)]
+ internal static extern int FSync(SafeFileHandle fd);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.FTruncate.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.FTruncate.cs
new file mode 100644
index 0000000000..5dad650362
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.FTruncate.cs
@@ -0,0 +1,15 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FTruncate", SetLastError = true)]
+ internal static extern int FTruncate(SafeFileHandle fd, long length);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.GetCwd.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.GetCwd.cs
new file mode 100644
index 0000000000..a27a35c9f5
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.GetCwd.cs
@@ -0,0 +1,74 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetCwd", SetLastError = true)]
+ private static unsafe extern byte* GetCwd(byte* buffer, int bufferLength);
+
+ internal static unsafe string GetCwd()
+ {
+ const int StackLimit = 256;
+
+ // First try to get the path into a buffer on the stack
+ byte* stackBuf = stackalloc byte[StackLimit];
+ string result = GetCwdHelper(stackBuf, StackLimit);
+ if (result != null)
+ {
+ return result;
+ }
+
+ // If that was too small, try increasing large buffer sizes
+ // until we get one that works or until we hit MaxPath.
+ int maxPath = Interop.Sys.MaxPath;
+ if (StackLimit < maxPath)
+ {
+ int bufferSize = StackLimit;
+ do
+ {
+ checked { bufferSize *= 2; }
+ var buf = new byte[Math.Min(bufferSize, maxPath)];
+ fixed (byte* ptr = &buf[0])
+ {
+ result = GetCwdHelper(ptr, buf.Length);
+ if (result != null)
+ {
+ return result;
+ }
+ }
+ }
+ while (bufferSize < maxPath);
+ }
+
+ // If we couldn't get the cwd with a MaxPath-sized buffer, something's wrong.
+ throw Interop.GetExceptionForIoErrno(new ErrorInfo(Interop.Error.ENAMETOOLONG));
+ }
+
+ private static unsafe string GetCwdHelper(byte* ptr, int bufferSize)
+ {
+ // Call the real getcwd
+ byte* result = GetCwd(ptr, bufferSize);
+
+ // If it returned non-null, the null-terminated path is in the buffer
+ if (result != null)
+ {
+ return Marshal.PtrToStringAnsi((IntPtr)ptr);
+ }
+
+ // Otherwise, if it failed due to the buffer being too small, return null;
+ // for anything else, throw.
+ ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo();
+ if (errorInfo.Error == Interop.Error.ERANGE)
+ {
+ return null;
+ }
+ throw Interop.GetExceptionForIoErrno(errorInfo);
+ }
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.GetRandomBytes.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.GetRandomBytes.cs
new file mode 100644
index 0000000000..62156e8d8e
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.GetRandomBytes.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal unsafe partial class Sys
+ {
+ [DllImport(Interop.Libraries.SystemNative, EntryPoint = "SystemNative_GetNonCryptographicallySecureRandomBytes")]
+ internal static unsafe extern void GetNonCryptographicallySecureRandomBytes(byte* buffer, int length);
+ }
+
+ internal static unsafe void GetRandomBytes(byte* buffer, int length)
+ {
+ Sys.GetNonCryptographicallySecureRandomBytes(buffer, length);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.LSeek.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.LSeek.cs
new file mode 100644
index 0000000000..7f8df7c6bf
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.LSeek.cs
@@ -0,0 +1,22 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ internal enum SeekWhence
+ {
+ SEEK_SET = 0,
+ SEEK_CUR = 1,
+ SEEK_END = 2
+ }
+
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LSeek", SetLastError = true)]
+ internal static extern long LSeek(SafeFileHandle fd, long offset, SeekWhence whence);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.LockFileRegion.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.LockFileRegion.cs
new file mode 100644
index 0000000000..23b48a4f5d
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.LockFileRegion.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ internal enum LockType : short
+ {
+ F_WRLCK = 1, // exclusive or write lock
+ F_UNLCK = 2 // unlock
+ }
+
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LockFileRegion", SetLastError=true)]
+ internal static extern int LockFileRegion(SafeHandle fd, long offset, long length, LockType lockType);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.MksTemps.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.MksTemps.cs
new file mode 100644
index 0000000000..b8694d9007
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.MksTemps.cs
@@ -0,0 +1,17 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_MksTemps", SetLastError = true)]
+ internal static extern IntPtr MksTemps(
+ byte[] template,
+ int suffixlen);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Open.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Open.cs
new file mode 100644
index 0000000000..a9a994c78c
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Open.cs
@@ -0,0 +1,15 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Open", SetLastError = true)]
+ internal static extern SafeFileHandle Open(string filename, OpenFlags flags, int mode);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.OpenFlags.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.OpenFlags.cs
new file mode 100644
index 0000000000..f9e54c3cbc
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.OpenFlags.cs
@@ -0,0 +1,27 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ [Flags]
+ internal enum OpenFlags
+ {
+ // Access modes (mutually exclusive)
+ O_RDONLY = 0x0000,
+ O_WRONLY = 0x0001,
+ O_RDWR = 0x0002,
+
+ // Flags (combinable)
+ O_CLOEXEC = 0x0010,
+ O_CREAT = 0x0020,
+ O_EXCL = 0x0040,
+ O_TRUNC = 0x0080,
+ O_SYNC = 0x0100,
+ }
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.PathConf.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.PathConf.cs
new file mode 100644
index 0000000000..4a1fcf67d0
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.PathConf.cs
@@ -0,0 +1,73 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ internal static int DEFAULT_PC_NAME_MAX = 255;
+
+ internal enum PathConfName : int
+ {
+ PC_LINK_MAX = 1,
+ PC_MAX_CANON = 2,
+ PC_MAX_INPUT = 3,
+ PC_NAME_MAX = 4,
+ PC_PATH_MAX = 5,
+ PC_PIPE_BUF = 6,
+ PC_CHOWN_RESTRICTED = 7,
+ PC_NO_TRUNC = 8,
+ PC_VDISABLE = 9,
+ }
+
+ /// <summary>The maximum path length for the system. -1 if it hasn't yet been initialized.</summary>
+ private static int s_maxPath = -1;
+
+ /// <summary>The maximum name length for the system. -1 if it hasn't yet been initialized.</summary>
+ private static int s_maxName = -1;
+
+ internal static int MaxPath
+ {
+ get
+ {
+ // Benign race condition on cached value
+ if (s_maxPath < 0)
+ {
+ // GetMaximumPath returns a long from PathConf
+ // but our callers expect an int so we need to convert.
+ long temp = GetMaximumPath();
+ if (temp > int.MaxValue)
+ s_maxPath = int.MaxValue;
+ else
+ s_maxPath = Convert.ToInt32(temp);
+ }
+ return s_maxPath;
+ }
+ }
+
+ internal static int MaxName
+ {
+ get
+ {
+ // Benign race condition on cached value
+ if (s_maxName < 0)
+ {
+ int result = PathConf("/", PathConfName.PC_NAME_MAX);
+ s_maxName = result >= 0 ? result : DEFAULT_PC_NAME_MAX;
+ }
+
+ return s_maxName;
+ }
+ }
+
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_PathConf", SetLastError = true)]
+ private static extern int PathConf(string path, PathConfName name);
+
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_GetMaximumPath")]
+ private static extern long GetMaximumPath();
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Permissions.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Permissions.cs
new file mode 100644
index 0000000000..f1d13787d2
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Permissions.cs
@@ -0,0 +1,32 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ [Flags]
+ internal enum Permissions
+ {
+ Mask = S_IRWXU | S_IRWXG | S_IRWXO,
+
+ S_IRWXU = S_IRUSR | S_IWUSR | S_IXUSR,
+ S_IRUSR = 0x100,
+ S_IWUSR = 0x80,
+ S_IXUSR = 0x40,
+
+ S_IRWXG = S_IRGRP | S_IWGRP | S_IXGRP,
+ S_IRGRP = 0x20,
+ S_IWGRP = 0x10,
+ S_IXGRP = 0x8,
+
+ S_IRWXO = S_IROTH | S_IWOTH | S_IXOTH,
+ S_IROTH = 0x4,
+ S_IWOTH = 0x2,
+ S_IXOTH = 0x1,
+ }
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.PosixFAdvise.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.PosixFAdvise.cs
new file mode 100644
index 0000000000..69e39b30d2
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.PosixFAdvise.cs
@@ -0,0 +1,36 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ internal enum FileAdvice : int
+ {
+ POSIX_FADV_NORMAL = 0, /* no special advice, the default value */
+ POSIX_FADV_RANDOM = 1, /* random I/O access */
+ POSIX_FADV_SEQUENTIAL = 2, /* sequential I/O access */
+ POSIX_FADV_WILLNEED = 3, /* will need specified pages */
+ POSIX_FADV_DONTNEED = 4, /* don't need the specified pages */
+ POSIX_FADV_NOREUSE = 5, /* data will only be acessed once */
+ }
+
+ /// <summary>
+ /// Notifies the OS kernel that the specified file will be accessed in a particular way soon; this allows the kernel to
+ /// potentially optimize the access pattern of the file.
+ /// </summary>
+ /// <param name="fd">The file descriptor of the file</param>
+ /// <param name="offset">The start of the region to advise about</param>
+ /// <param name="length">The number of bytes of the region (until the end of the file if 0)</param>
+ /// <param name="advice">The type of advice to give the kernel about the specified region</param>
+ /// <returns>
+ /// Returns 0 on success; otherwise, the error code is returned
+ /// </returns>
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_PosixFAdvise", SetLastError = false /* this is explicitly called out in the man page */)]
+ internal static extern int PosixFAdvise(SafeFileHandle fd, long offset, long length, FileAdvice advice);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Read.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Read.cs
new file mode 100644
index 0000000000..812ae348dc
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Read.cs
@@ -0,0 +1,25 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ /// <summary>
+ /// Reads a number of bytes from an open file descriptor into a specified buffer.
+ /// </summary>
+ /// <param name="fd">The open file descriptor to try to read from</param>
+ /// <param name="buffer">The buffer to read info into</param>
+ /// <param name="count">The size of the buffer</param>
+ /// <returns>
+ /// Returns the number of bytes read on success; otherwise, -1 is returned
+ /// Note - on fail. the position of the stream may change depending on the platform; consult man 2 read for more info
+ /// </returns>
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Read", SetLastError = true)]
+ internal static unsafe extern int Read(SafeFileHandle fd, byte* buffer, int count);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Stat.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Stat.cs
new file mode 100644
index 0000000000..a8bc2ec7d1
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Stat.cs
@@ -0,0 +1,59 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ // Even though csc will by default use a sequential layout, a CS0649 warning as error
+ // is produced for un-assigned fields when no StructLayout is specified.
+ //
+ // Explicitly saying Sequential disables that warning/error for consumers which only
+ // use Stat in debug builds.
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct FileStatus
+ {
+ internal FileStatusFlags Flags;
+ internal int Mode;
+ internal uint Uid;
+ internal uint Gid;
+ internal long Size;
+ internal long ATime;
+ internal long MTime;
+ internal long CTime;
+ internal long BirthTime;
+ }
+
+ internal static class FileTypes
+ {
+ internal const int S_IFMT = 0xF000;
+ internal const int S_IFIFO = 0x1000;
+ internal const int S_IFCHR = 0x2000;
+ internal const int S_IFDIR = 0x4000;
+ internal const int S_IFREG = 0x8000;
+ internal const int S_IFLNK = 0xA000;
+ internal const int S_IFSOCK = 0xC000;
+ }
+
+ [Flags]
+ internal enum FileStatusFlags
+ {
+ None = 0,
+ HasBirthTime = 1,
+ }
+
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_FStat", SetLastError = true)]
+ internal static extern int FStat(SafeFileHandle fd, out FileStatus output);
+
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Stat", SetLastError = true)]
+ internal static extern int Stat(string path, out FileStatus output);
+
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_LStat", SetLastError = true)]
+ internal static extern int LStat(string path, out FileStatus output);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.SysLog.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.SysLog.cs
new file mode 100644
index 0000000000..6b6a74b743
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.SysLog.cs
@@ -0,0 +1,58 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ internal enum SysLogPriority : int
+ {
+ // Priorities
+ LOG_EMERG = 0, /* system is unusable */
+ LOG_ALERT = 1, /* action must be taken immediately */
+ LOG_CRIT = 2, /* critical conditions */
+ LOG_ERR = 3, /* error conditions */
+ LOG_WARNING = 4, /* warning conditions */
+ LOG_NOTICE = 5, /* normal but significant condition */
+ LOG_INFO = 6, /* informational */
+ LOG_DEBUG = 7, /* debug-level messages */
+ // Facilities
+ LOG_KERN = (0<<3), /* kernel messages */
+ LOG_USER = (1<<3), /* random user-level messages */
+ LOG_MAIL = (2<<3), /* mail system */
+ LOG_DAEMON = (3<<3), /* system daemons */
+ LOG_AUTH = (4<<3), /* authorization messages */
+ LOG_SYSLOG = (5<<3), /* messages generated internally by syslogd */
+ LOG_LPR = (6<<3), /* line printer subsystem */
+ LOG_NEWS = (7<<3), /* network news subsystem */
+ LOG_UUCP = (8<<3), /* UUCP subsystem */
+ LOG_CRON = (9<<3), /* clock daemon */
+ LOG_AUTHPRIV = (10<<3), /* authorization messages (private) */
+ LOG_FTP = (11<<3), /* ftp daemon */
+ // Between FTP and Local is reserved for system use
+ LOG_LOCAL0 = (16<<3), /* reserved for local use */
+ LOG_LOCAL1 = (17<<3), /* reserved for local use */
+ LOG_LOCAL2 = (18<<3), /* reserved for local use */
+ LOG_LOCAL3 = (19<<3), /* reserved for local use */
+ LOG_LOCAL4 = (20<<3), /* reserved for local use */
+ LOG_LOCAL5 = (21<<3), /* reserved for local use */
+ LOG_LOCAL6 = (22<<3), /* reserved for local use */
+ LOG_LOCAL7 = (23<<3), /* reserved for local use */
+ }
+
+ /// <summary>
+ /// Write a message to the system logger, which in turn writes the message to the system console, log files, etc.
+ /// See man 3 syslog for more info
+ /// </summary>
+ /// <param name="priority">
+ /// The OR of a priority and facility in the SysLogPriority enum to declare the priority and facility of the log entry
+ /// </param>
+ /// <param name="message">The message to put in the log entry</param>
+ /// <param name="arg1">Like printf, the argument is passed to the variadic part of the C++ function to wildcards in the message</param>
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_SysLog")]
+ internal static extern void SysLog(SysLogPriority priority, string message, string arg1);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Unlink.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Unlink.cs
new file mode 100644
index 0000000000..829210fa7e
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Unlink.cs
@@ -0,0 +1,15 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Unlink", SetLastError = true)]
+ internal static extern int Unlink(string pathname);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Write.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Write.cs
new file mode 100644
index 0000000000..c14fc26263
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.Write.cs
@@ -0,0 +1,27 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.InteropServices;
+using Microsoft.Win32.SafeHandles;
+
+internal static partial class Interop
+{
+ internal static partial class Sys
+ {
+ /// <summary>
+ /// Writes the specified buffer to the provided open file descriptor
+ /// </summary>
+ /// <param name="fd">The file descriptor to try and write to</param>
+ /// <param name="buffer">The data to attempt to write</param>
+ /// <param name="bufferSize">The amount of data to write, in bytes</param>
+ /// <returns>
+ /// Returns the number of bytes written on success; otherwise, returns -1 and sets errno
+ /// </returns>
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Write", SetLastError = true)]
+ internal static unsafe extern int Write(SafeFileHandle fd, byte* buffer, int bufferSize);
+
+ [DllImport(Libraries.SystemNative, EntryPoint = "SystemNative_Write", SetLastError = true)]
+ internal static unsafe extern int Write(int fd, byte* buffer, int bufferSize);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs b/src/mscorlib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs
new file mode 100644
index 0000000000..bc357125b5
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/BCrypt/Interop.BCryptGenRandom.cs
@@ -0,0 +1,44 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class BCrypt
+ {
+ internal static unsafe int BCryptGenRandom(byte* pbBuffer, int count)
+ {
+ Debug.Assert(pbBuffer != null);
+ Debug.Assert(count >= 0);
+
+ return BCryptGenRandom(IntPtr.Zero, pbBuffer, count, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
+ }
+
+ private const int BCRYPT_USE_SYSTEM_PREFERRED_RNG = 0x00000002;
+ internal const int STATUS_SUCCESS = 0x0;
+ internal const int STATUS_NO_MEMORY = unchecked((int)0xC0000017);
+
+ [DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)]
+ private static unsafe extern int BCryptGenRandom(IntPtr hAlgorithm, byte* pbBuffer, int cbBuffer, int dwFlags);
+ }
+
+ internal static unsafe void GetRandomBytes(byte* buffer, int length)
+ {
+ int status = BCrypt.BCryptGenRandom(buffer, length);
+ if (status != BCrypt.STATUS_SUCCESS)
+ {
+ if (status == BCrypt.STATUS_NO_MEMORY)
+ {
+ throw new OutOfMemoryException();
+ }
+ else
+ {
+ throw new InvalidOperationException();
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Crypt32/Interop.CryptProtectMemory.cs b/src/mscorlib/shared/Interop/Windows/Crypt32/Interop.CryptProtectMemory.cs
new file mode 100644
index 0000000000..b10cb6a041
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Crypt32/Interop.CryptProtectMemory.cs
@@ -0,0 +1,22 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+using System.Security;
+
+internal partial class Interop
+{
+ internal partial class Crypt32
+ {
+ internal const uint CRYPTPROTECTMEMORY_BLOCK_SIZE = 16;
+ internal const uint CRYPTPROTECTMEMORY_SAME_PROCESS = 0;
+
+ [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
+ internal static extern bool CryptProtectMemory(SafeBSTRHandle pData, uint cbData, uint dwFlags);
+
+ [DllImport(Libraries.Crypt32, CharSet = CharSet.Unicode, SetLastError = true)]
+ internal static extern bool CryptUnprotectMemory(SafeBSTRHandle pData, uint cbData, uint dwFlags);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Interop.BOOL.cs b/src/mscorlib/shared/Interop/Windows/Interop.BOOL.cs
new file mode 100644
index 0000000000..9f4dab8935
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Interop.BOOL.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+internal partial class Interop
+{
+ /// <summary>
+ /// Blittable version of Windows BOOL type. It is convenient in situations where
+ /// manual marshalling is required, or to avoid overhead of regular bool marshalling.
+ /// </summary>
+ /// <remarks>
+ /// Some Windows APIs return arbitrary integer values although the return type is defined
+ /// as BOOL. It is best to never compare BOOL to TRUE. Always use bResult != BOOL.FALSE
+ /// or bResult == BOOL.FALSE .
+ /// </remarks>
+ internal enum BOOL : int
+ {
+ FALSE = 0,
+ TRUE = 1,
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Interop.Errors.cs b/src/mscorlib/shared/Interop/Windows/Interop.Errors.cs
new file mode 100644
index 0000000000..ff2653765c
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Interop.Errors.cs
@@ -0,0 +1,44 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+internal partial class Interop
+{
+ // As defined in winerror.h and https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx
+ internal partial class Errors
+ {
+ internal const int ERROR_SUCCESS = 0x0;
+ internal const int ERROR_FILE_NOT_FOUND = 0x2;
+ internal const int ERROR_PATH_NOT_FOUND = 0x3;
+ internal const int ERROR_ACCESS_DENIED = 0x5;
+ internal const int ERROR_INVALID_HANDLE = 0x6;
+ internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
+ internal const int ERROR_INVALID_DRIVE = 0xF;
+ internal const int ERROR_NO_MORE_FILES = 0x12;
+ internal const int ERROR_NOT_READY = 0x15;
+ internal const int ERROR_SHARING_VIOLATION = 0x20;
+ internal const int ERROR_HANDLE_EOF = 0x26;
+ internal const int ERROR_FILE_EXISTS = 0x50;
+ internal const int ERROR_INVALID_PARAMETER = 0x57;
+ internal const int ERROR_BROKEN_PIPE = 0x6D;
+ internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A;
+ internal const int ERROR_INVALID_NAME = 0x7B;
+ internal const int ERROR_BAD_PATHNAME = 0xA1;
+ internal const int ERROR_ALREADY_EXISTS = 0xB7;
+ internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB;
+ internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE;
+ internal const int ERROR_NO_DATA = 0xE8;
+ internal const int ERROR_MORE_DATA = 0xEA;
+ internal const int ERROR_NO_MORE_ITEMS = 0x103;
+ internal const int ERROR_NOT_OWNER = 0x120;
+ internal const int ERROR_TOO_MANY_POSTS = 0x12A;
+ internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216;
+ internal const int ERROR_MUTANT_LIMIT_EXCEEDED = 0x24B;
+ internal const int ERROR_OPERATION_ABORTED = 0x3E3;
+ internal const int ERROR_IO_PENDING = 0x3E5;
+ internal const int ERROR_NO_UNICODE_TRANSLATION = 0x459;
+ internal const int ERROR_NOT_FOUND = 0x490;
+ internal const int ERROR_BAD_IMPERSONATION_LEVEL = 0x542;
+ internal const int E_FILENOTFOUND = unchecked((int)0x80070002);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Interop.Libraries.cs b/src/mscorlib/shared/Interop/Windows/Interop.Libraries.cs
new file mode 100644
index 0000000000..58bb12d637
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Interop.Libraries.cs
@@ -0,0 +1,15 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+internal static partial class Interop
+{
+ internal static partial class Libraries
+ {
+ internal const string BCrypt = "BCrypt.dll";
+ internal const string Crypt32 = "crypt32.dll";
+ internal const string Kernel32 = "kernel32.dll";
+ internal const string NtDll = "ntdll.dll";
+ internal const string OleAut32 = "oleaut32.dll";
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CancelIoEx.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CancelIoEx.cs
new file mode 100644
index 0000000000..fc99e3052f
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CancelIoEx.cs
@@ -0,0 +1,16 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System.Runtime.InteropServices;
+using System.Threading;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ internal static extern unsafe bool CancelIoEx(SafeHandle handle, NativeOverlapped* lpOverlapped);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs
new file mode 100644
index 0000000000..96ed922a84
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CloseHandle.cs
@@ -0,0 +1,16 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal static extern bool CloseHandle(IntPtr handle);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CreateFile.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CreateFile.cs
new file mode 100644
index 0000000000..9ee1e16fa6
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CreateFile.cs
@@ -0,0 +1,40 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ /// <summary>
+ /// WARNING: This method does not implicitly handle long paths. Use CreateFile.
+ /// </summary>
+ [DllImport(Libraries.Kernel32, EntryPoint = "CreateFileW", SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)]
+ private static extern SafeFileHandle CreateFilePrivate(
+ string lpFileName,
+ int dwDesiredAccess,
+ System.IO.FileShare dwShareMode,
+ ref SECURITY_ATTRIBUTES securityAttrs,
+ System.IO.FileMode dwCreationDisposition,
+ int dwFlagsAndAttributes,
+ IntPtr hTemplateFile);
+
+ internal static SafeFileHandle CreateFile(
+ string lpFileName,
+ int dwDesiredAccess,
+ System.IO.FileShare dwShareMode,
+ ref SECURITY_ATTRIBUTES securityAttrs,
+ System.IO.FileMode dwCreationDisposition,
+ int dwFlagsAndAttributes,
+ IntPtr hTemplateFile)
+ {
+ lpFileName = PathInternal.EnsureExtendedPrefixOverMaxPath(lpFileName);
+ return CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, ref securityAttrs, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
+ }
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs
new file mode 100644
index 0000000000..0909d3a6c8
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs
@@ -0,0 +1,31 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, EntryPoint = "CreateFile2", SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)]
+ internal static extern unsafe SafeFileHandle CreateFile2(
+ string lpFileName,
+ int dwDesiredAccess,
+ System.IO.FileShare dwShareMode,
+ System.IO.FileMode dwCreationDisposition,
+ CREATEFILE2_EXTENDED_PARAMETERS* pCreateExParams);
+
+ internal unsafe struct CREATEFILE2_EXTENDED_PARAMETERS
+ {
+ internal uint dwSize;
+ internal uint dwFileAttributes;
+ internal uint dwFileFlags;
+ internal uint dwSecurityQosFlags;
+ internal SECURITY_ATTRIBUTES* lpSecurityAttributes;
+ internal IntPtr hTemplateFile;
+ }
+ }
+} \ No newline at end of file
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FILE_INFO_BY_HANDLE_CLASS.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FILE_INFO_BY_HANDLE_CLASS.cs
new file mode 100644
index 0000000000..e31a453ba9
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FILE_INFO_BY_HANDLE_CLASS.cs
@@ -0,0 +1,39 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ internal enum FILE_INFO_BY_HANDLE_CLASS : uint
+ {
+ FileBasicInfo = 0x0u,
+ FileStandardInfo = 0x1u,
+ FileNameInfo = 0x2u,
+ FileRenameInfo = 0x3u,
+ FileDispositionInfo = 0x4u,
+ FileAllocationInfo = 0x5u,
+ FileEndOfFileInfo = 0x6u,
+ FileStreamInfo = 0x7u,
+ FileCompressionInfo = 0x8u,
+ FileAttributeTagInfo = 0x9u,
+ FileIdBothDirectoryInfo = 0xAu,
+ FileIdBothDirectoryRestartInfo = 0xBu,
+ FileIoPriorityHintInfo = 0xCu,
+ FileRemoteProtocolInfo = 0xDu,
+ FileFullDirectoryInfo = 0xEu,
+ FileFullDirectoryRestartInfo = 0xFu,
+ FileStorageInfo = 0x10u,
+ FileAlignmentInfo = 0x11u,
+ FileIdInfo = 0x12u,
+ FileIdExtdDirectoryInfo = 0x13u,
+ FileIdExtdDirectoryRestartInfo = 0x14u,
+ MaximumFileInfoByHandleClass = 0x15u,
+ }
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FileTypes.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FileTypes.cs
new file mode 100644
index 0000000000..1d306665b1
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FileTypes.cs
@@ -0,0 +1,16 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ internal partial class FileTypes
+ {
+ internal const int FILE_TYPE_DISK = 0x0001;
+ internal const int FILE_TYPE_CHAR = 0x0002;
+ internal const int FILE_TYPE_PIPE = 0x0003;
+ }
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FlushFileBuffers.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FlushFileBuffers.cs
new file mode 100644
index 0000000000..e10a2279cf
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FlushFileBuffers.cs
@@ -0,0 +1,17 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ [return: MarshalAs(UnmanagedType.Bool)]
+ internal static extern bool FlushFileBuffers(SafeHandle hHandle);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FormatMessage.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FormatMessage.cs
new file mode 100644
index 0000000000..94722b6c8b
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FormatMessage.cs
@@ -0,0 +1,112 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Text;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
+ private const int FORMAT_MESSAGE_FROM_HMODULE = 0x00000800;
+ private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000;
+ private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000;
+
+
+ private const int ERROR_INSUFFICIENT_BUFFER = 0x7A;
+
+ [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, EntryPoint = "FormatMessageW", SetLastError = true, BestFitMapping = true)]
+ private static extern int FormatMessage(
+ int dwFlags,
+ IntPtr lpSource,
+ uint dwMessageId,
+ int dwLanguageId,
+ [Out] StringBuilder lpBuffer,
+ int nSize,
+ IntPtr[] arguments);
+
+ /// <summary>
+ /// Returns a string message for the specified Win32 error code.
+ /// </summary>
+ internal static string GetMessage(int errorCode)
+ {
+ return GetMessage(IntPtr.Zero, errorCode);
+ }
+
+ internal static string GetMessage(IntPtr moduleHandle, int errorCode)
+ {
+ var sb = new StringBuilder(InitialBufferSize);
+ do
+ {
+ string errorMsg;
+ if (TryGetErrorMessage(moduleHandle, errorCode, sb, out errorMsg))
+ {
+ return errorMsg;
+ }
+ else
+ {
+ // increase the capacity of the StringBuilder.
+ sb.Capacity *= BufferSizeIncreaseFactor;
+ }
+ }
+ while (sb.Capacity < MaxAllowedBufferSize);
+
+ // If you come here then a size as large as 65K is also not sufficient and so we give the generic errorMsg.
+ return string.Format("Unknown error (0x{0:x})", errorCode);
+ }
+
+ private static bool TryGetErrorMessage(IntPtr moduleHandle, int errorCode, StringBuilder sb, out string errorMsg)
+ {
+ errorMsg = "";
+
+ int flags = FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY;
+ if (moduleHandle != IntPtr.Zero)
+ {
+ flags |= FORMAT_MESSAGE_FROM_HMODULE;
+ }
+
+ int result = FormatMessage(flags, moduleHandle, (uint)errorCode, 0, sb, sb.Capacity, null);
+ if (result != 0)
+ {
+ int i = sb.Length;
+ while (i > 0)
+ {
+ char ch = sb[i - 1];
+ if (ch > 32 && ch != '.') break;
+ i--;
+ }
+ errorMsg = sb.ToString(0, i);
+ }
+ else if (Marshal.GetLastWin32Error() == ERROR_INSUFFICIENT_BUFFER)
+ {
+ return false;
+ }
+ else
+ {
+ errorMsg = string.Format("Unknown error (0x{0:x})", errorCode);
+ }
+
+ return true;
+ }
+
+ // Windows API FormatMessage lets you format a message string given an errorcode.
+ // Unlike other APIs this API does not support a way to query it for the total message size.
+ //
+ // So the API can only be used in one of these two ways.
+ // a. You pass a buffer of appropriate size and get the resource.
+ // b. Windows creates a buffer and passes the address back and the onus of releasing the buffer lies on the caller.
+ //
+ // Since the error code is coming from the user, it is not possible to know the size in advance.
+ // Unfortunately we can't use option b. since the buffer can only be freed using LocalFree and it is a private API on onecore.
+ // Also, using option b is ugly for the managed code and could cause memory leak in situations where freeing is unsuccessful.
+ //
+ // As a result we use the following approach.
+ // We initially call the API with a buffer size of 256 and then gradually increase the size in case of failure until we reach the maximum allowed limit of 65K.
+ private const int InitialBufferSize = 256;
+ private const int BufferSizeIncreaseFactor = 4;
+ private const int MaxAllowedBufferSize = 65 * 1024;
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetFileInformationByHandleEx.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetFileInformationByHandleEx.cs
new file mode 100644
index 0000000000..1106cff1c5
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetFileInformationByHandleEx.cs
@@ -0,0 +1,25 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ internal static extern bool GetFileInformationByHandleEx(SafeFileHandle hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, out FILE_STANDARD_INFO lpFileInformation, uint dwBufferSize);
+
+ internal struct FILE_STANDARD_INFO
+ {
+ internal long AllocationSize;
+ internal long EndOfFile;
+ internal uint NumberOfLinks;
+ internal BOOL DeletePending;
+ internal BOOL Directory;
+ }
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs
new file mode 100644
index 0000000000..c07a1683a5
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetFileType_SafeHandle.cs
@@ -0,0 +1,15 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ internal extern static int GetFileType(SafeHandle hFile);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs
new file mode 100644
index 0000000000..15dd581113
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetFullPathNameW.cs
@@ -0,0 +1,18 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ /// <summary>
+ /// WARNING: This method does not implicitly handle long paths. Use GetFullPathName or PathHelper.
+ /// </summary>
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false, ExactSpelling = true)]
+ unsafe internal static extern uint GetFullPathNameW(char* path, uint numBufferChars, char[] buffer, IntPtr mustBeZero);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs
new file mode 100644
index 0000000000..ce04078af5
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetLongPathNameW.cs
@@ -0,0 +1,18 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ /// <summary>
+ /// WARNING: This method does not implicitly handle long paths. Use GetFullPath/PathHelper.
+ /// </summary>
+ [DllImport(Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false, ExactSpelling = true)]
+ internal static extern uint GetLongPathNameW(char[] lpszShortPath, char[] lpszLongPath, uint cchBuffer);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs
new file mode 100644
index 0000000000..36673895b4
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetTempFileNameW.cs
@@ -0,0 +1,16 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Text;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)]
+ internal static extern uint GetTempFileNameW(string tmpPath, string prefix, uint uniqueIdOrZero, [Out]StringBuilder tmpFileName);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetTempPathW.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetTempPathW.cs
new file mode 100644
index 0000000000..ff2783be26
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.GetTempPathW.cs
@@ -0,0 +1,16 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.IO;
+using System.Text;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, BestFitMapping = false)]
+ internal static extern uint GetTempPathW(int bufferLen, [Out]StringBuilder buffer);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.LockFile.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.LockFile.cs
new file mode 100644
index 0000000000..a21d00f4f6
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.LockFile.cs
@@ -0,0 +1,20 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System;
+using System.IO;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ internal static extern bool LockFile(SafeFileHandle handle, int offsetLow, int offsetHigh, int countLow, int countHigh);
+
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ internal static extern bool UnlockFile(SafeFileHandle handle, int offsetLow, int offsetHigh, int countLow, int countHigh);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.OutputDebugString.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.OutputDebugString.cs
new file mode 100644
index 0000000000..8da50ff8ab
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.OutputDebugString.cs
@@ -0,0 +1,14 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Unicode, EntryPoint = "OutputDebugStringW", ExactSpelling = true)]
+ internal static extern void OutputDebugString(string message);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_IntPtr.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_IntPtr.cs
new file mode 100644
index 0000000000..076f7f136f
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_IntPtr.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ internal static extern unsafe int ReadFile(
+ SafeHandle handle,
+ byte* bytes,
+ int numBytesToRead,
+ out int numBytesRead,
+ IntPtr mustBeZero);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_NativeOverlapped.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_NativeOverlapped.cs
new file mode 100644
index 0000000000..3ae65a8806
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.ReadFile_SafeHandle_NativeOverlapped.cs
@@ -0,0 +1,22 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System;
+using System.Runtime.InteropServices;
+using System.Threading;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ internal static extern unsafe int ReadFile(
+ SafeHandle handle,
+ byte* bytes,
+ int numBytesToRead,
+ IntPtr numBytesRead_mustBeZero,
+ NativeOverlapped* overlapped);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SECURITY_ATTRIBUTES.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SECURITY_ATTRIBUTES.cs
new file mode 100644
index 0000000000..8d31f8622f
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SECURITY_ATTRIBUTES.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [StructLayout(LayoutKind.Sequential)]
+ internal struct SECURITY_ATTRIBUTES
+ {
+ internal uint nLength;
+ internal IntPtr lpSecurityDescriptor;
+ internal BOOL bInheritHandle;
+ }
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SecurityOptions.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SecurityOptions.cs
new file mode 100644
index 0000000000..4a4402484f
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SecurityOptions.cs
@@ -0,0 +1,18 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ internal partial class SecurityOptions
+ {
+ internal const int SECURITY_SQOS_PRESENT = 0x00100000;
+ internal const int SECURITY_ANONYMOUS = 0 << 16;
+ internal const int SECURITY_IDENTIFICATION = 1 << 16;
+ internal const int SECURITY_IMPERSONATION = 2 << 16;
+ internal const int SECURITY_DELEGATION = 3 << 16;
+ }
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetEndOfFile.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetEndOfFile.cs
new file mode 100644
index 0000000000..e5d60041a8
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetEndOfFile.cs
@@ -0,0 +1,15 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ internal static extern bool SetEndOfFile(SafeFileHandle hFile);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetErrorMode.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetErrorMode.cs
new file mode 100644
index 0000000000..276f49c519
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetErrorMode.cs
@@ -0,0 +1,16 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, SetLastError = false, EntryPoint = "SetErrorMode", ExactSpelling = true)]
+ internal static extern uint SetErrorMode(uint newMode);
+
+ internal const uint SEM_FAILCRITICALERRORS = 1;
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetFilePointerEx.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetFilePointerEx.cs
new file mode 100644
index 0000000000..c0e5247a52
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.SetFilePointerEx.cs
@@ -0,0 +1,15 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ internal static extern bool SetFilePointerEx(SafeFileHandle hFile, long liDistanceToMove, out long lpNewFilePointer, uint dwMoveMethod);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.WideCharToMultiByte.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.WideCharToMultiByte.cs
new file mode 100644
index 0000000000..a06c9153f4
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.WideCharToMultiByte.cs
@@ -0,0 +1,22 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ [DllImport(Libraries.Kernel32)]
+ internal static extern unsafe int WideCharToMultiByte(
+ uint CodePage, uint dwFlags,
+ char* lpWideCharStr, int cchWideChar,
+ byte* lpMultiByteStr, int cbMultiByte,
+ IntPtr lpDefaultChar, IntPtr lpUsedDefaultChar);
+
+ internal const uint CP_ACP = 0;
+ internal const uint WC_NO_BEST_FIT_CHARS = 0x00000400;
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs
new file mode 100644
index 0000000000..69651ca1ca
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_IntPtr.cs
@@ -0,0 +1,23 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ // Note there are two different WriteFile prototypes - this is to use
+ // the type system to force you to not trip across a "feature" in
+ // Win32's async IO support. You can't do the following three things
+ // simultaneously: overlapped IO, free the memory for the overlapped
+ // struct in a callback (or an EndWrite method called by that callback),
+ // and pass in an address for the numBytesRead parameter.
+
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ internal static extern unsafe int WriteFile(SafeHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_NativeOverlapped.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_NativeOverlapped.cs
new file mode 100644
index 0000000000..dc1e97555b
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.WriteFile_SafeHandle_NativeOverlapped.cs
@@ -0,0 +1,22 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32.SafeHandles;
+using System;
+using System.Runtime.InteropServices;
+using System.Threading;
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ // Note there are two different WriteFile prototypes - this is to use
+ // the type system to force you to not trip across a "feature" in
+ // Win32's async IO support. You can't do the following three things
+ // simultaneously: overlapped IO, free the memory for the overlapped
+ // struct in a callback (or an EndWrite method called by that callback),
+ // and pass in an address for the numBytesRead parameter.
+ [DllImport(Libraries.Kernel32, SetLastError = true)]
+ internal static extern unsafe int WriteFile(SafeHandle handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWritten_mustBeZero, NativeOverlapped* lpOverlapped);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/NtDll/Interop.ZeroMemory.cs b/src/mscorlib/shared/Interop/Windows/NtDll/Interop.ZeroMemory.cs
new file mode 100644
index 0000000000..9bf7321f2a
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/NtDll/Interop.ZeroMemory.cs
@@ -0,0 +1,16 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+using System.Security;
+
+internal partial class Interop
+{
+ internal partial class NtDll
+ {
+ [DllImport(Libraries.NtDll, CharSet = CharSet.Unicode, EntryPoint = "RtlZeroMemory")]
+ internal static extern void ZeroMemory(IntPtr address, UIntPtr length);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs b/src/mscorlib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs
new file mode 100644
index 0000000000..1af2b3fce9
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/OleAut32/Interop.SysAllocStringLen.cs
@@ -0,0 +1,19 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+using System.Security;
+
+internal partial class Interop
+{
+ internal partial class OleAut32
+ {
+ [DllImport(Libraries.OleAut32, CharSet = CharSet.Unicode)]
+ internal static extern SafeBSTRHandle SysAllocStringLen(IntPtr src, uint len);
+
+ [DllImport(Libraries.OleAut32, CharSet = CharSet.Unicode)]
+ internal static extern IntPtr SysAllocStringLen(String src, int len);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/OleAut32/Interop.SysFreeString.cs b/src/mscorlib/shared/Interop/Windows/OleAut32/Interop.SysFreeString.cs
new file mode 100644
index 0000000000..8673cc6724
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/OleAut32/Interop.SysFreeString.cs
@@ -0,0 +1,15 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class OleAut32
+ {
+ [DllImport(Libraries.OleAut32)]
+ internal static extern void SysFreeString(IntPtr bstr);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/OleAut32/Interop.SysStringLen.cs b/src/mscorlib/shared/Interop/Windows/OleAut32/Interop.SysStringLen.cs
new file mode 100644
index 0000000000..cf65d6b086
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/OleAut32/Interop.SysStringLen.cs
@@ -0,0 +1,19 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+using System.Security;
+
+internal partial class Interop
+{
+ internal partial class OleAut32
+ {
+ [DllImport(Libraries.OleAut32)]
+ internal static extern uint SysStringLen(SafeBSTRHandle bstr);
+
+ [DllImport(Libraries.OleAut32)]
+ internal static extern uint SysStringLen(IntPtr bstr);
+ }
+}
diff --git a/src/mscorlib/shared/Microsoft/Win32/SafeHandles/CriticalHandleMinusOneIsInvalid.cs b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/CriticalHandleMinusOneIsInvalid.cs
new file mode 100644
index 0000000000..a76c51d966
--- /dev/null
+++ b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/CriticalHandleMinusOneIsInvalid.cs
@@ -0,0 +1,20 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+namespace Microsoft.Win32.SafeHandles
+{
+ // Class of critical handle which uses only -1 as an invalid handle.
+ public abstract class CriticalHandleMinusOneIsInvalid : CriticalHandle
+ {
+ protected CriticalHandleMinusOneIsInvalid()
+ : base(new IntPtr(-1))
+ {
+ }
+
+ public override bool IsInvalid => handle == new IntPtr(-1);
+ }
+}
diff --git a/src/mscorlib/shared/Microsoft/Win32/SafeHandles/CriticalHandleZeroOrMinusOneIsInvalid.cs b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/CriticalHandleZeroOrMinusOneIsInvalid.cs
new file mode 100644
index 0000000000..195e48df76
--- /dev/null
+++ b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/CriticalHandleZeroOrMinusOneIsInvalid.cs
@@ -0,0 +1,20 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+namespace Microsoft.Win32.SafeHandles
+{
+ // Class of critical handle which uses 0 or -1 as an invalid handle.
+ public abstract class CriticalHandleZeroOrMinusOneIsInvalid : CriticalHandle
+ {
+ protected CriticalHandleZeroOrMinusOneIsInvalid()
+ : base(IntPtr.Zero)
+ {
+ }
+
+ public override bool IsInvalid => handle.IsNull() || handle == new IntPtr(-1);
+ }
+}
diff --git a/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs
new file mode 100644
index 0000000000..d13b536204
--- /dev/null
+++ b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Unix.cs
@@ -0,0 +1,119 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
+
+namespace Microsoft.Win32.SafeHandles
+{
+ public sealed class SafeFileHandle : SafeHandleZeroOrMinusOneIsInvalid
+ {
+ /// <summary>A handle value of -1.</summary>
+ private static readonly IntPtr s_invalidHandle = new IntPtr(-1);
+
+ private SafeFileHandle() : this(ownsHandle: true)
+ {
+ }
+
+ private SafeFileHandle(bool ownsHandle)
+ : base(ownsHandle)
+ {
+ SetHandle(s_invalidHandle);
+ }
+
+ public SafeFileHandle(IntPtr preexistingHandle, bool ownsHandle) : this(ownsHandle)
+ {
+ SetHandle(preexistingHandle);
+ }
+
+ internal bool? IsAsync { get; set; }
+
+ /// <summary>Opens the specified file with the requested flags and mode.</summary>
+ /// <param name="path">The path to the file.</param>
+ /// <param name="flags">The flags with which to open the file.</param>
+ /// <param name="mode">The mode for opening the file.</param>
+ /// <returns>A SafeFileHandle for the opened file.</returns>
+ internal static SafeFileHandle Open(string path, Interop.Sys.OpenFlags flags, int mode)
+ {
+ Debug.Assert(path != null);
+
+ // If we fail to open the file due to a path not existing, we need to know whether to blame
+ // the file itself or its directory. If we're creating the file, then we blame the directory,
+ // otherwise we blame the file.
+ bool enoentDueToDirectory = (flags & Interop.Sys.OpenFlags.O_CREAT) != 0;
+
+ // Open the file.
+ SafeFileHandle handle = Interop.CheckIo(
+ Interop.Sys.Open(path, flags, mode),
+ path,
+ isDirectory: enoentDueToDirectory,
+ errorRewriter: e => (e.Error == Interop.Error.EISDIR) ? Interop.Error.EACCES.Info() : e);
+
+ // Make sure it's not a directory; we do this after opening it once we have a file descriptor
+ // to avoid race conditions.
+ Interop.Sys.FileStatus status;
+ if (Interop.Sys.FStat(handle, out status) != 0)
+ {
+ handle.Dispose();
+ throw Interop.GetExceptionForIoErrno(Interop.Sys.GetLastErrorInfo(), path);
+ }
+ if ((status.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR)
+ {
+ handle.Dispose();
+ throw Interop.GetExceptionForIoErrno(Interop.Error.EACCES.Info(), path, isDirectory: true);
+ }
+
+ return handle;
+ }
+
+ /// <summary>Opens a SafeFileHandle for a file descriptor created by a provided delegate.</summary>
+ /// <param name="fdFunc">
+ /// The function that creates the file descriptor. Returns the file descriptor on success, or an invalid
+ /// file descriptor on error with Marshal.GetLastWin32Error() set to the error code.
+ /// </param>
+ /// <returns>The created SafeFileHandle.</returns>
+ internal static SafeFileHandle Open(Func<SafeFileHandle> fdFunc)
+ {
+ SafeFileHandle handle = Interop.CheckIo(fdFunc());
+
+ Debug.Assert(!handle.IsInvalid, "File descriptor is invalid");
+ return handle;
+ }
+
+ protected override bool ReleaseHandle()
+ {
+ // When the SafeFileHandle was opened, we likely issued an flock on the created descriptor in order to add
+ // an advisory lock. This lock should be removed via closing the file descriptor, but close can be
+ // interrupted, and we don't retry closes. As such, we could end up leaving the file locked,
+ // which could prevent subsequent usage of the file until this process dies. To avoid that, we proactively
+ // try to release the lock before we close the handle. (If it's not locked, there's no behavioral
+ // problem trying to unlock it.)
+ Interop.Sys.FLock(handle, Interop.Sys.LockOperations.LOCK_UN); // ignore any errors
+
+ // Close the descriptor. Although close is documented to potentially fail with EINTR, we never want
+ // to retry, as the descriptor could actually have been closed, been subsequently reassigned, and
+ // be in use elsewhere in the process. Instead, we simply check whether the call was successful.
+ int result = Interop.Sys.Close(handle);
+#if DEBUG
+ if (result != 0)
+ {
+ Debug.Fail(string.Format(
+ "Close failed with result {0} and error {1}",
+ result, Interop.Sys.GetLastErrorInfo()));
+ }
+#endif
+ return result == 0;
+ }
+
+ public override bool IsInvalid
+ {
+ get
+ {
+ long h = (long)handle;
+ return h < 0 || h > int.MaxValue;
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs
new file mode 100644
index 0000000000..4eabe8f08c
--- /dev/null
+++ b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeFileHandle.Windows.cs
@@ -0,0 +1,50 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Security;
+using System.Runtime.InteropServices;
+using System.Threading;
+using Microsoft.Win32;
+
+namespace Microsoft.Win32.SafeHandles
+{
+ public sealed class SafeFileHandle : SafeHandleZeroOrMinusOneIsInvalid
+ {
+ private bool? _isAsync;
+
+ private SafeFileHandle() : base(true)
+ {
+ _isAsync = null;
+ }
+
+ public SafeFileHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle)
+ {
+ SetHandle(preexistingHandle);
+
+ _isAsync = null;
+ }
+
+ internal bool? IsAsync
+ {
+ get
+ {
+ return _isAsync;
+ }
+
+ set
+ {
+ _isAsync = value;
+ }
+ }
+
+ internal ThreadPoolBoundHandle ThreadPoolBinding { get; set; }
+
+ override protected bool ReleaseHandle()
+ {
+ return Interop.Kernel32.CloseHandle(handle);
+ }
+ }
+}
+
diff --git a/src/mscorlib/shared/README.md b/src/mscorlib/shared/README.md
new file mode 100644
index 0000000000..d55f32576d
--- /dev/null
+++ b/src/mscorlib/shared/README.md
@@ -0,0 +1,19 @@
+# System.Private.CoreLib Shared Sources
+
+This directory contains the shared sources for System.Private.CoreLib. These are shared between [dotnet/corert](https://github.com/dotnet/corert/tree/master/src/System.Private.CoreLib/shared) and [dotnet/coreclr](https://github.com/dotnet/coreclr/tree/master/src/mscorlib/shared).
+
+The sources are synchronized with a mirroring tool that watches for new commits on either side and creates new pull requests (as @dotnet-bot) in the other repository.
+
+## Conventions
+
+Code in the shared directory should have no code specific to CoreCLR or CoreRT. Parts of classes that need to have different implementations on different runtimes should use partial classes and &#42;.CoreRT.cs/&#42;.CoreCLR.cs files in the non shared portion. Code that is different based on platform (Windows/Unix) is fine to leave in the shared portion. Remember to follow the [style guidelines](https://github.com/dotnet/corefx/blob/master/Documentation/coding-guidelines/coding-style.md).
+
+## Getting clean CI and merging the mirror PRs
+
+Once the mirror PR is created there is a chance that the new code will require changes to get a clean CI. Any changes can be added to the PR by checking out the PR branch and adding new commits. Please follow the following guidelines for modifying these PRs.
+
+ - **DO NOT** modify the commits made by @dotnet-bot in any way.
+ - **TRY** to only make changes outside of shared.
+ - Changes made in the shared folder in additional commits will get mirrored properly if the mirror PR is merged with a **REBASE**
+ - **ALWAYS** Merge the mirror PR with the **REBASE** option.
+ - Using one of the other options will cause the mirror to miss commits
diff --git a/src/mscorlib/shared/System.Private.CoreLib.Shared.projitems b/src/mscorlib/shared/System.Private.CoreLib.Shared.projitems
new file mode 100644
index 0000000000..6ef7fc1681
--- /dev/null
+++ b/src/mscorlib/shared/System.Private.CoreLib.Shared.projitems
@@ -0,0 +1,534 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup>
+ <MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
+ <HasSharedItems>true</HasSharedItems>
+ <SharedGUID>c5ed3c1d-b572-46f1-8f96-522a85ce1179</SharedGUID>
+ </PropertyGroup>
+ <PropertyGroup Label="Configuration">
+ <Import_RootNamespace/>
+ </PropertyGroup>
+ <PropertyGroup>
+ <TargetsWindows Condition="'$(TargetsWindows)' != 'true'">false</TargetsWindows>
+ <TargetsUnix Condition="'$(TargetsUnix)' != 'true'">false</TargetsUnix>
+ <TargetsOSX Condition="'$(TargetsOSX)' != 'true'">false</TargetsOSX>
+ </PropertyGroup>
+ <ItemGroup>
+ <Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\CriticalHandleMinusOneIsInvalid.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\CriticalHandleZeroOrMinusOneIsInvalid.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Action.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ApplicationException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ArgumentException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ArgumentNullException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ArithmeticException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ArrayTypeMismatchException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\AssemblyLoadEventArgs.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\AssemblyLoadEventHandler.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\AsyncCallback.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\AttributeTargets.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\AttributeUsageAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Buffers\ArrayPool.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Buffers\ConfigurableArrayPool.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Buffers\TlsOverPerCoreLockedStacksArrayPool.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Buffers\Utilities.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Char.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\CharEnumerator.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\CLSCompliantAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\DictionaryEntry.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\ICollection.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\IComparer.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\IDictionary.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\IEnumerable.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\IEnumerator.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\IEqualityComparer.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\IList.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\IReadOnlyCollection.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\IReadOnlyDictionary.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\IReadOnlyList.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\KeyNotFoundException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\Generic\KeyValuePair.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\ICollection.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\IComparer.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\IDictionary.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\IDictionaryEnumerator.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\IEnumerable.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\IEnumerator.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\IEqualityComparer.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\IList.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\IStructuralComparable.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\IStructuralEquatable.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ComponentModel\DefaultValueAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ComponentModel\EditorBrowsableAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Configuration\Assemblies\AssemblyHashAlgorithm.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Configuration\Assemblies\AssemblyVersionCompatibility.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Convert.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\CurrentSystemTimeZone.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\DataMisalignedException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\DateTime.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\DateTimeKind.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\DateTimeOffset.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\DayOfWeek.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\DBNull.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\DefaultBinder.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\CodeAnalysis\SuppressMessageAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\ConditionalAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Debug.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\DivideByZeroException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\DuplicateWaitObjectException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\EntryPointNotFoundException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\EventArgs.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\EventHandler.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ExecutionEngineException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\FieldAccessException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\FlagsAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\FormatException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\FormattableString.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\CalendarAlgorithmType.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\CalendarWeekRule.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\CalendricalCalculationsHelper.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\ChineseLunisolarCalendar.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\CultureNotFoundException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\CultureTypes.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\DateTimeFormat.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\DateTimeFormatInfo.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\DateTimeFormatInfoScanner.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\DateTimeParse.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\DateTimeStyles.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\DaylightTime.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\DigitShapes.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\EastAsianLunisolarCalendar.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\GregorianCalendarTypes.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\HebrewCalendar.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\HebrewNumber.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\HijriCalendar.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\InternalGlobalizationHelper.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\JapaneseCalendar.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\JapaneseLunisolarCalendar.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\JulianCalendar.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\KoreanCalendar.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\KoreanLunisolarCalendar.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\NumberStyles.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\PersianCalendar.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\SortVersion.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\TaiwanCalendar.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\TaiwanLunisolarCalendar.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\ThaiBuddhistCalendar.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\TimeSpanStyles.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\UmAlQuraCalendar.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\UnicodeCategory.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IAsyncResult.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ICloneable.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IComparable.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IConvertible.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ICustomFormatter.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IDisposable.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IEquatable.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IFormatProvider.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IFormattable.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IndexOutOfRangeException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\InsufficientExecutionStackException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\InvalidCastException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\InvalidOperationException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\InvalidProgramException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\InvalidTimeZoneException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\DirectoryNotFoundException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\EndOfStreamException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\Error.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileAccess.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileLoadException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileMode.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileNotFoundException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileOptions.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileShare.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\Path.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\PathInternal.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\PathTooLongException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\SeekOrigin.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\StreamHelpers.CopyValidation.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IObservable.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IObserver.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IProgress.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Lazy.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\MarshalByRefObject.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\MemberAccessException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\MethodAccessException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\MidpointRounding.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\MissingMethodException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\MulticastNotSupportedException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\NotFiniteNumberException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\NotImplementedException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\NotSupportedException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\NullReferenceException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ObjectDisposedException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ObsoleteAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\OverflowException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ParamArrayAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ParamsArray.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\PlatformNotSupportedException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Progress.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Random.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\RankException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AmbiguousMatchException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\Assembly.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyAlgorithmIdAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyCompanyAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyConfigurationAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyContentType.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyCopyrightAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyCultureAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyDefaultAliasAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyDelaySignAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyDescriptionAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyFileVersionAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyFlagsAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyInformationalVersionAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyKeyFileAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyKeyNameAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyMetadataAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyNameFlags.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyProductAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblySignatureKeyAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyTitleAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyTrademarkAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyVersionAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\Binder.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\BindingFlags.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\CallingConventions.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ConstructorInfo.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\CustomAttributeFormatException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\DefaultMemberAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\EventAttributes.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\EventInfo.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ExceptionHandlingClauseOptions.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\FieldAttributes.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\FieldInfo.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\GenericParameterAttributes.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ICustomAttributeProvider.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ImageFileMachine.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\InterfaceMapping.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\IntrospectionExtensions.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\InvalidFilterCriteriaException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\IReflect.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\IReflectableType.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ManifestResourceInfo.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\MemberFilter.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\MemberInfo.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\MemberInfoSerializationHolder.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\MemberTypes.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\MethodAttributes.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\MethodBase.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\MethodImplAttributes.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\MethodInfo.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\Missing.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\Module.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ModuleResolveEventHandler.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ObfuscateAssemblyAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ObfuscationAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ParameterAttributes.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ParameterInfo.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ParameterModifier.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\Pointer.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\PortableExecutableKinds.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ProcessorArchitecture.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\PropertyAttributes.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\PropertyInfo.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ReflectionContext.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ReflectionTypeLoadException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ResourceAttributes.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ResourceLocation.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\StrongNameKeyPair.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\TargetException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\TargetInvocationException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\TargetParameterCountException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\TypeAttributes.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\TypeDelegator.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\TypeFilter.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\TypeInfo.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\ResolveEventArgs.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\ResolveEventHandler.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Resources\IResourceReader.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Resources\MissingManifestResourceException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Resources\MissingSatelliteAssemblyException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Resources\NeutralResourcesLanguageAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Resources\ResourceTypeCode.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Resources\SatelliteContractVersionAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Resources\UltimateResourceFallbackLocation.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\AccessedThroughPropertyAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\AsyncStateMachineAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\CallerFilePathAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\CallerLineNumberAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\CallerMemberNameAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\CompilationRelaxations.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\CompilationRelaxationsAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\CompilerGeneratedAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\CompilerGlobalScopeAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\DefaultDependencyAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\DependencyAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\DisablePrivateReflectionAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\DiscardableAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\ExtensionAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\FixedAddressValueTypeAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\FixedBufferAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\FormattableStringFactory.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IAsyncStateMachine.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IndexerNameAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\InternalsVisibleToAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\INotifyCompletion.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IsConst.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IsVolatile.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IteratorStateMachineAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\ITuple.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\LoadHint.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\MethodCodeType.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\MethodImplOptions.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\ReadOnlyAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\ReferenceAssemblyAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\RuntimeCompatibilityAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\RuntimeFeature.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\SpecialNameAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\StateMachineAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\StringFreezingAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\StrongBox.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\SuppressIldasmAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\TupleElementNamesAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\TypeForwardedFromAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\TypeForwardedToAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\UnsafeValueTypeAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\ConstrainedExecution\Cer.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\ConstrainedExecution\Consistency.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\ConstrainedExecution\ReliabilityContractAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\CallingConvention.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\CharSet.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\ComVisibleAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\ExternalException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\LayoutKind.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\StringBuffer.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\UnmanagedFunctionPointerAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\UnmanagedType.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\VarEnum.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Serialization\IDeserializationCallback.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Serialization\IFormatterConverter.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Serialization\IObjectReference.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Serialization\ISafeSerializationData.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Serialization\ISerializable.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Serialization\OnDeserializedAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Serialization\OnDeserializingAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Serialization\OnSerializedAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Serialization\OnSerializingAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Serialization\OptionalFieldAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Serialization\SafeSerializationEventArgs.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Serialization\SerializationException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Serialization\SerializationInfoEnumerator.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Serialization\StreamingContext.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Versioning\NonVersionableAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\Versioning\TargetFrameworkAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\AllowPartiallyTrustedCallersAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\CryptographicException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\PartialTrustVisibilityLevel.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\SecureString.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\SecurityCriticalAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\SecurityCriticalScope.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\SecurityException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\SecurityRulesAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\SecurityRuleSet.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\SecuritySafeCriticalAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\SecurityTransparentAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\SecurityTreatAsSafeAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\SuppressUnmanagedCodeSecurityAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\UnverifiableCodeAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\VerificationException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\StackOverflowException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\StringComparer.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\StringComparison.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\StringSplitOptions.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\SystemException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Text\ASCIIEncoding.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Text\Decoder.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Text\Encoder.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Text\EncodingInfo.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Text\EncodingNLS.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Text\EncodingProvider.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Text\Normalization.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Text\StringBuilder.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Text\UTF32Encoding.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Text\UTF8Encoding.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Text\UnicodeEncoding.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ThreadAttributes.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\AbandonedMutexException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\ApartmentState.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\AsyncLocal.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\AutoResetEvent.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\DeferredDisposableLifetime.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\EventResetMode.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\ExecutionContext.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\LazyThreadSafetyMode.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\LockRecursionException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\ManualResetEvent.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\ParameterizedThreadStart.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\SemaphoreFullException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\SendOrPostCallback.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\SynchronizationLockException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\Tasks\TaskCanceledException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\Tasks\TaskExtensions.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\Tasks\TaskSchedulerException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\ThreadAbortException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\ThreadPriority.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\ThreadStart.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\ThreadStartException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\ThreadState.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\ThreadStateException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\Timeout.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\TimeoutHelper.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Threading\WaitHandleCannotBeOpenedException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ThreadStaticAttribute.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\TimeoutException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\TimeZone.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\TimeZoneNotFoundException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\TupleExtensions.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Type.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Type.Enum.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Type.Helpers.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\TypeAccessException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\TypeCode.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\TypeInitializationException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\TypeUnloadedException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\UnauthorizedAccessException.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\UnhandledExceptionEventArgs.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\UnhandledExceptionEventHandler.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\UnitySerializationHolder.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\ValueTuple.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Version.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Void.cs"/>
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\ActivityTracker.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\EventActivityOptions.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\EventCounter.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\EventDescriptor.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\EventProvider.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\EventSource.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\EventSourceException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\StubEnvironment.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\Winmeta.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\ArrayTypeInfo.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\ConcurrentSet.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\ConcurrentSetItem.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\DataCollector.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\EmptyStruct.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\EnumerableTypeInfo.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\EnumHelper.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\EventDataAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\EventFieldAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\EventFieldFormat.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\EventIgnoreAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\EventPayload.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\EventSourceActivity.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\EventSourceOptions.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\FieldMetadata.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\InvokeTypeInfo.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\NameInfo.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\PropertyAnalysis.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\PropertyValue.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\SimpleEventTypes.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\SimpleTypeInfos.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\Statics.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\TraceLoggingDataCollector.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\TraceLoggingDataType.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\TraceLoggingEventSource.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\TraceLoggingEventTraits.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\TraceLoggingEventTypes.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\TraceLoggingMetadataCollector.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\TraceLoggingTypeInfo.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Tracing\TraceLogging\TypeAnalysis.cs" />
+ </ItemGroup>
+ <ItemGroup Condition="$(TargetsWindows)">
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\BCrypt\Interop.BCryptGenRandom.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Crypt32\Interop.CryptProtectMemory.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Interop.BOOL.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Interop.Errors.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Interop.Libraries.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.CancelIoEx.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.CloseHandle.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.CreateFile.cs" Condition="'$(IsProjectNLibrary)' != 'true'" />
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.CreateFile2.cs" Condition="'$(IsProjectNLibrary)' == 'true'" />
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.FILE_INFO_BY_HANDLE_CLASS.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.FileTypes.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.FlushFileBuffers.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.FormatMessage.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.GetFileInformationByHandleEx.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.GetFileType_SafeHandle.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.GetFullPathNameW.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.GetLongPathNameW.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.GetTempFileNameW.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.GetTempPathW.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.LockFile.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.OutputDebugString.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.ReadFile_SafeHandle_IntPtr.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.ReadFile_SafeHandle_NativeOverlapped.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.SECURITY_ATTRIBUTES.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.SecurityOptions.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.SetEndOfFile.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.SetErrorMode.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.SetFilePointerEx.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.WideCharToMultiByte.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.WriteFile_SafeHandle_IntPtr.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.WriteFile_SafeHandle_NativeOverlapped.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\NtDll\Interop.ZeroMemory.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\OleAut32\Interop.SysAllocStringLen.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\OleAut32\Interop.SysFreeString.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\OleAut32\Interop.SysStringLen.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\SafeFileHandle.Windows.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.Win32.cs" Condition="'$(IsProjectNLibrary)' != 'true'" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.Windows.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.WinRT.cs" Condition="'$(IsProjectNLibrary)' == 'true'" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStreamCompletionSource.Win32.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\Path.Windows.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\PathHelper.Windows.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\PathInternal.Windows.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\PathInternal.Windows.StringBuffer.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\Win32Marshal.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\SafeBSTRHandle.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\SecureString.Windows.cs"/>
+ </ItemGroup>
+ <ItemGroup Condition="$(TargetsUnix)">
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\Interop.Errors.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\Interop.IOErrors.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\Interop.Libraries.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Globalization.Native\Interop.Calendar.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Globalization.Native\Interop.Casing.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Globalization.Native\Interop.Idna.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Globalization.Native\Interop.Locale.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Globalization.Native\Interop.Normalization.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Globalization.Native\Interop.ResultCode.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Globalization.Native\Interop.TimeZoneInfo.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Globalization.Native\Interop.Utils.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.Close.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.FLock.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.FSync.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.FTruncate.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.GetCwd.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.GetRandomBytes.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.LockFileRegion.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.LSeek.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.MksTemps.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.Open.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.OpenFlags.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.PathConf.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.Permissions.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.PosixFAdvise.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.Read.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.Stat.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.SysLog.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.Unlink.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\System.Native\Interop.Write.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\SafeFileHandle.Unix.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\LocaleData.Unix.cs" Condition="'$(EnableDummyGlobalizationImplementation)' != 'true'"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.OSX.cs" Condition="'$(TargetsOSX)' == 'true'"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.Linux.cs" Condition="'$(TargetsOSX)' != 'true'"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.Unix.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\Path.Unix.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\PathInternal.Unix.cs"/>
+ <Compile Include="$(MSBuildThisFileDirectory)System\Security\SecureString.Unix.cs"/>
+ </ItemGroup>
+</Project>
diff --git a/src/mscorlib/shared/System.Private.CoreLib.Shared.shproj b/src/mscorlib/shared/System.Private.CoreLib.Shared.shproj
new file mode 100644
index 0000000000..af61b3b59e
--- /dev/null
+++ b/src/mscorlib/shared/System.Private.CoreLib.Shared.shproj
@@ -0,0 +1,19 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+ <PropertyGroup Label="Globals">
+ <ProjectGuid>c5ed3c1d-b572-46f1-8f96-522a85ce1179</ProjectGuid>
+ <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
+ </PropertyGroup>
+ <!-- Set the properties to prevent any items from being excluded from the IDE view -->
+ <PropertyGroup>
+ <TargetsWindows>true</TargetsWindows>
+ <TargetsUnix>true</TargetsUnix>
+ <TargetsOSX>true</TargetsOSX>
+ </PropertyGroup>
+ <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
+ <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
+ <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
+ <PropertyGroup />
+ <Import Project="System.Private.CoreLib.Shared.projitems" Label="Shared" />
+ <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
+</Project>
diff --git a/src/mscorlib/shared/System/Action.cs b/src/mscorlib/shared/System/Action.cs
new file mode 100644
index 0000000000..b82c14d9dc
--- /dev/null
+++ b/src/mscorlib/shared/System/Action.cs
@@ -0,0 +1,35 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System
+{
+ public delegate void Action<in T>(T obj);
+
+ public delegate void Action();
+ public delegate void Action<in T1, in T2>(T1 arg1, T2 arg2);
+ public delegate void Action<in T1, in T2, in T3>(T1 arg1, T2 arg2, T3 arg3);
+ public delegate void Action<in T1, in T2, in T3, in T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
+
+ public delegate TResult Func<out TResult>();
+ public delegate TResult Func<in T, out TResult>(T arg);
+ public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
+ public delegate TResult Func<in T1, in T2, in T3, out TResult>(T1 arg1, T2 arg2, T3 arg3);
+ public delegate TResult Func<in T1, in T2, in T3, in T4, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
+
+ public delegate void Action<in T1, in T2, in T3, in T4, in T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
+ public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
+ public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
+ public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
+
+ public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
+ public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6);
+ public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7);
+ public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8);
+
+ public delegate int Comparison<in T>(T x, T y);
+
+ public delegate TOutput Converter<in TInput, out TOutput>(TInput input);
+
+ public delegate bool Predicate<in T>(T obj);
+}
diff --git a/src/mscorlib/shared/System/ApplicationException.cs b/src/mscorlib/shared/System/ApplicationException.cs
new file mode 100644
index 0000000000..900feb57f9
--- /dev/null
+++ b/src/mscorlib/shared/System/ApplicationException.cs
@@ -0,0 +1,56 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*=============================================================================
+**
+**
+**
+** Purpose: The base class for all "less serious" exceptions that must be
+** declared or caught.
+**
+**
+=============================================================================*/
+
+using System.Runtime.Serialization;
+
+namespace System
+{
+ // The ApplicationException is the base class for nonfatal,
+ // application errors that occur. These exceptions are generated
+ // (i.e., thrown) by an application, not the Runtime. Applications that need
+ // to create their own exceptions do so by extending this class.
+ // ApplicationException extends but adds no new functionality to
+ // RecoverableException.
+ //
+ [Serializable]
+ public class ApplicationException : Exception
+ {
+ // Creates a new ApplicationException with its message string set to
+ // the empty string, its HRESULT set to COR_E_APPLICATION,
+ // and its ExceptionInfo reference set to null.
+ public ApplicationException()
+ : base(SR.Arg_ApplicationException)
+ {
+ HResult = __HResults.COR_E_APPLICATION;
+ }
+
+ // Creates a new ApplicationException with its message string set to
+ // message, its HRESULT set to COR_E_APPLICATION,
+ // and its ExceptionInfo reference set to null.
+ //
+ public ApplicationException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_APPLICATION;
+ }
+
+ public ApplicationException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_APPLICATION;
+ }
+
+ protected ApplicationException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ }
+}
diff --git a/src/mscorlib/shared/System/ArgumentException.cs b/src/mscorlib/shared/System/ArgumentException.cs
new file mode 100644
index 0000000000..96afbe10d9
--- /dev/null
+++ b/src/mscorlib/shared/System/ArgumentException.cs
@@ -0,0 +1,97 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*=============================================================================
+**
+**
+**
+** Purpose: Exception class for invalid arguments to a method.
+**
+**
+=============================================================================*/
+
+using System.Globalization;
+using System.Runtime.Serialization;
+
+namespace System
+{
+ // The ArgumentException is thrown when an argument does not meet
+ // the contract of the method. Ideally it should give a meaningful error
+ // message describing what was wrong and which parameter is incorrect.
+ //
+ [Serializable]
+ public class ArgumentException : SystemException
+ {
+ private String _paramName;
+
+ // Creates a new ArgumentException with its message
+ // string set to the empty string.
+ public ArgumentException()
+ : base(SR.Arg_ArgumentException)
+ {
+ HResult = __HResults.COR_E_ARGUMENT;
+ }
+
+ // Creates a new ArgumentException with its message
+ // string set to message.
+ //
+ public ArgumentException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_ARGUMENT;
+ }
+
+ public ArgumentException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_ARGUMENT;
+ }
+
+ public ArgumentException(String message, String paramName, Exception innerException)
+ : base(message, innerException)
+ {
+ _paramName = paramName;
+ HResult = __HResults.COR_E_ARGUMENT;
+ }
+
+ public ArgumentException(String message, String paramName)
+ : base(message)
+ {
+ _paramName = paramName;
+ HResult = __HResults.COR_E_ARGUMENT;
+ }
+
+ 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));
+ }
+
+ public override String Message
+ {
+ get
+ {
+ String s = base.Message;
+ if (!String.IsNullOrEmpty(_paramName))
+ {
+ String resourceString = SR.Format(SR.Arg_ParamName_Name, _paramName);
+ return s + Environment.NewLine + resourceString;
+ }
+ else
+ return s;
+ }
+ }
+
+ public virtual String ParamName
+ {
+ get { return _paramName; }
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/ArgumentNullException.cs b/src/mscorlib/shared/System/ArgumentNullException.cs
new file mode 100644
index 0000000000..3a86223ccf
--- /dev/null
+++ b/src/mscorlib/shared/System/ArgumentNullException.cs
@@ -0,0 +1,53 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*=============================================================================
+**
+**
+**
+** Purpose: Exception class for null arguments to a method.
+**
+**
+=============================================================================*/
+
+using System.Runtime.Serialization;
+
+namespace System
+{
+ // The ArgumentException is thrown when an argument
+ // is null when it shouldn't be.
+ //
+ [Serializable]
+ public class ArgumentNullException : ArgumentException
+ {
+ // Creates a new ArgumentNullException with its message
+ // string set to a default message explaining an argument was null.
+ public ArgumentNullException()
+ : base(SR.ArgumentNull_Generic)
+ {
+ // Use E_POINTER - COM used that for null pointers. Description is "invalid pointer"
+ HResult = __HResults.E_POINTER;
+ }
+
+ public ArgumentNullException(String paramName)
+ : base(SR.ArgumentNull_Generic, paramName)
+ {
+ HResult = __HResults.E_POINTER;
+ }
+
+ public ArgumentNullException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.E_POINTER;
+ }
+
+ public ArgumentNullException(String paramName, String message)
+ : base(message, paramName)
+ {
+ HResult = __HResults.E_POINTER;
+ }
+
+ protected ArgumentNullException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ }
+}
diff --git a/src/mscorlib/shared/System/ArithmeticException.cs b/src/mscorlib/shared/System/ArithmeticException.cs
new file mode 100644
index 0000000000..081ba454f5
--- /dev/null
+++ b/src/mscorlib/shared/System/ArithmeticException.cs
@@ -0,0 +1,51 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*=============================================================================
+**
+**
+**
+** Purpose: Exception class for bad arithmetic conditions!
+**
+**
+=============================================================================*/
+
+using System.Runtime.Serialization;
+
+namespace System
+{
+ // The ArithmeticException is thrown when overflow or underflow
+ // occurs.
+ //
+ [Serializable]
+ public class ArithmeticException : SystemException
+ {
+ // Creates a new ArithmeticException with its message string set to
+ // the empty string, its HRESULT set to COR_E_ARITHMETIC,
+ // and its ExceptionInfo reference set to null.
+ public ArithmeticException()
+ : base(SR.Arg_ArithmeticException)
+ {
+ HResult = __HResults.COR_E_ARITHMETIC;
+ }
+
+ // Creates a new ArithmeticException with its message string set to
+ // message, its HRESULT set to COR_E_ARITHMETIC,
+ // and its ExceptionInfo reference set to null.
+ //
+ public ArithmeticException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_ARITHMETIC;
+ }
+
+ public ArithmeticException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_ARITHMETIC;
+ }
+
+ protected ArithmeticException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ }
+}
diff --git a/src/mscorlib/shared/System/ArrayTypeMismatchException.cs b/src/mscorlib/shared/System/ArrayTypeMismatchException.cs
new file mode 100644
index 0000000000..3e941fdf8e
--- /dev/null
+++ b/src/mscorlib/shared/System/ArrayTypeMismatchException.cs
@@ -0,0 +1,51 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*=============================================================================
+**
+**
+**
+** Purpose: The arrays are of different primitive types.
+**
+**
+=============================================================================*/
+
+using System.Runtime.Serialization;
+
+namespace System
+{
+ // The ArrayMismatchException is thrown when an attempt to store
+ // an object of the wrong type within an array occurs.
+ //
+ [Serializable]
+ public class ArrayTypeMismatchException : SystemException
+ {
+ // Creates a new ArrayMismatchException with its message string set to
+ // the empty string, its HRESULT set to COR_E_ARRAYTYPEMISMATCH,
+ // and its ExceptionInfo reference set to null.
+ public ArrayTypeMismatchException()
+ : base(SR.Arg_ArrayTypeMismatchException)
+ {
+ HResult = __HResults.COR_E_ARRAYTYPEMISMATCH;
+ }
+
+ // Creates a new ArrayMismatchException with its message string set to
+ // message, its HRESULT set to COR_E_ARRAYTYPEMISMATCH,
+ // and its ExceptionInfo reference set to null.
+ //
+ public ArrayTypeMismatchException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_ARRAYTYPEMISMATCH;
+ }
+
+ public ArrayTypeMismatchException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_ARRAYTYPEMISMATCH;
+ }
+
+ protected ArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ }
+}
diff --git a/src/mscorlib/shared/System/AssemblyLoadEventArgs.cs b/src/mscorlib/shared/System/AssemblyLoadEventArgs.cs
new file mode 100644
index 0000000000..d7e5249693
--- /dev/null
+++ b/src/mscorlib/shared/System/AssemblyLoadEventArgs.cs
@@ -0,0 +1,18 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Reflection;
+
+namespace System
+{
+ public class AssemblyLoadEventArgs : EventArgs
+ {
+ public AssemblyLoadEventArgs(Assembly loadedAssembly)
+ {
+ LoadedAssembly = loadedAssembly;
+ }
+
+ public Assembly LoadedAssembly { get; }
+ }
+}
diff --git a/src/mscorlib/shared/System/AssemblyLoadEventHandler.cs b/src/mscorlib/shared/System/AssemblyLoadEventHandler.cs
new file mode 100644
index 0000000000..752379fdc7
--- /dev/null
+++ b/src/mscorlib/shared/System/AssemblyLoadEventHandler.cs
@@ -0,0 +1,8 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System
+{
+ public delegate void AssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args);
+}
diff --git a/src/mscorlib/shared/System/AsyncCallback.cs b/src/mscorlib/shared/System/AsyncCallback.cs
new file mode 100644
index 0000000000..5c49535cff
--- /dev/null
+++ b/src/mscorlib/shared/System/AsyncCallback.cs
@@ -0,0 +1,17 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*============================================================
+**
+** Interface: AsyncCallbackDelegate
+**
+** Purpose: Type of callback for async operations
+**
+===========================================================*/
+
+namespace System
+{
+ [Serializable]
+ public delegate void AsyncCallback(IAsyncResult ar);
+}
diff --git a/src/mscorlib/shared/System/AttributeTargets.cs b/src/mscorlib/shared/System/AttributeTargets.cs
new file mode 100644
index 0000000000..fdfa4ab730
--- /dev/null
+++ b/src/mscorlib/shared/System/AttributeTargets.cs
@@ -0,0 +1,36 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+////////////////////////////////////////////////////////////////////////////////
+////////////////////////////////////////////////////////////////////////////////
+
+namespace System
+{
+ // Enum used to indicate all the elements of the
+ // VOS it is valid to attach this element to.
+ [Flags]
+ [Serializable]
+ public enum AttributeTargets
+ {
+ Assembly = 0x0001,
+ Module = 0x0002,
+ Class = 0x0004,
+ Struct = 0x0008,
+ Enum = 0x0010,
+ Constructor = 0x0020,
+ Method = 0x0040,
+ Property = 0x0080,
+ Field = 0x0100,
+ Event = 0x0200,
+ Interface = 0x0400,
+ Parameter = 0x0800,
+ Delegate = 0x1000,
+ ReturnValue = 0x2000,
+ GenericParameter = 0x4000,
+
+ All = Assembly | Module | Class | Struct | Enum | Constructor |
+ Method | Property | Field | Event | Interface | Parameter |
+ Delegate | ReturnValue | GenericParameter
+ }
+}
diff --git a/src/mscorlib/shared/System/AttributeUsageAttribute.cs b/src/mscorlib/shared/System/AttributeUsageAttribute.cs
new file mode 100644
index 0000000000..6f9aeb20f3
--- /dev/null
+++ b/src/mscorlib/shared/System/AttributeUsageAttribute.cs
@@ -0,0 +1,58 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*============================================================
+**
+**
+**
+** Purpose: The class denotes how to specify the usage of an attribute
+**
+**
+===========================================================*/
+
+using System.Reflection;
+
+namespace System
+{
+ /* By default, attributes are inherited and multiple attributes are not allowed */
+ [Serializable]
+ [AttributeUsage(AttributeTargets.Class, Inherited = true)]
+ public sealed class AttributeUsageAttribute : Attribute
+ {
+ private AttributeTargets _attributeTarget = AttributeTargets.All; // Defaults to all
+ private bool _allowMultiple = false; // Defaults to false
+ private bool _inherited = true; // Defaults to true
+
+ internal static AttributeUsageAttribute Default = new AttributeUsageAttribute(AttributeTargets.All);
+
+ //Constructors
+ public AttributeUsageAttribute(AttributeTargets validOn)
+ {
+ _attributeTarget = validOn;
+ }
+ internal AttributeUsageAttribute(AttributeTargets validOn, bool allowMultiple, bool inherited)
+ {
+ _attributeTarget = validOn;
+ _allowMultiple = allowMultiple;
+ _inherited = inherited;
+ }
+
+ public AttributeTargets ValidOn
+ {
+ get { return _attributeTarget; }
+ }
+
+ public bool AllowMultiple
+ {
+ get { return _allowMultiple; }
+ set { _allowMultiple = value; }
+ }
+
+ public bool Inherited
+ {
+ get { return _inherited; }
+ set { _inherited = value; }
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Buffers/ArrayPool.cs b/src/mscorlib/shared/System/Buffers/ArrayPool.cs
new file mode 100644
index 0000000000..77a07f7fa5
--- /dev/null
+++ b/src/mscorlib/shared/System/Buffers/ArrayPool.cs
@@ -0,0 +1,100 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.Buffers
+{
+ /// <summary>
+ /// Provides a resource pool that enables reusing instances of type <see cref="T:T[]"/>.
+ /// </summary>
+ /// <remarks>
+ /// <para>
+ /// Renting and returning buffers with an <see cref="ArrayPool{T}"/> can increase performance
+ /// in situations where arrays are created and destroyed frequently, resulting in significant
+ /// memory pressure on the garbage collector.
+ /// </para>
+ /// <para>
+ /// This class is thread-safe. All members may be used by multiple threads concurrently.
+ /// </para>
+ /// </remarks>
+ public abstract class ArrayPool<T>
+ {
+ /// <summary>
+ /// Retrieves a shared <see cref="ArrayPool{T}"/> instance.
+ /// </summary>
+ /// <remarks>
+ /// The shared pool provides a default implementation of <see cref="ArrayPool{T}"/>
+ /// that's intended for general applicability. It maintains arrays of multiple sizes, and
+ /// may hand back a larger array than was actually requested, but will never hand back a smaller
+ /// array than was requested. Renting a buffer from it with <see cref="Rent"/> will result in an
+ /// existing buffer being taken from the pool if an appropriate buffer is available or in a new
+ /// buffer being allocated if one is not available.
+ /// byte[] and char[] are the most commonly pooled array types. For these we use a special pool type
+ /// optimized for very fast access speeds, at the expense of more memory consumption.
+ /// The shared pool instance is created lazily on first access.
+ /// </remarks>
+ public static ArrayPool<T> Shared { get; } =
+ typeof(T) == typeof(byte) || typeof(T) == typeof(char) ? new TlsOverPerCoreLockedStacksArrayPool<T>() :
+ Create();
+
+ /// <summary>
+ /// Creates a new <see cref="ArrayPool{T}"/> instance using default configuration options.
+ /// </summary>
+ /// <returns>A new <see cref="ArrayPool{T}"/> instance.</returns>
+ public static ArrayPool<T> Create() => new ConfigurableArrayPool<T>();
+
+ /// <summary>
+ /// Creates a new <see cref="ArrayPool{T}"/> instance using custom configuration options.
+ /// </summary>
+ /// <param name="maxArrayLength">The maximum length of array instances that may be stored in the pool.</param>
+ /// <param name="maxArraysPerBucket">
+ /// The maximum number of array instances that may be stored in each bucket in the pool. The pool
+ /// groups arrays of similar lengths into buckets for faster access.
+ /// </param>
+ /// <returns>A new <see cref="ArrayPool{T}"/> instance with the specified configuration options.</returns>
+ /// <remarks>
+ /// The created pool will group arrays into buckets, with no more than <paramref name="maxArraysPerBucket"/>
+ /// in each bucket and with those arrays not exceeding <paramref name="maxArrayLength"/> in length.
+ /// </remarks>
+ public static ArrayPool<T> Create(int maxArrayLength, int maxArraysPerBucket) =>
+ new ConfigurableArrayPool<T>(maxArrayLength, maxArraysPerBucket);
+
+ /// <summary>
+ /// Retrieves a buffer that is at least the requested length.
+ /// </summary>
+ /// <param name="minimumLength">The minimum length of the array needed.</param>
+ /// <returns>
+ /// An <see cref="T:T[]"/> that is at least <paramref name="minimumLength"/> in length.
+ /// </returns>
+ /// <remarks>
+ /// This buffer is loaned to the caller and should be returned to the same pool via
+ /// <see cref="Return"/> so that it may be reused in subsequent usage of <see cref="Rent"/>.
+ /// It is not a fatal error to not return a rented buffer, but failure to do so may lead to
+ /// decreased application performance, as the pool may need to create a new buffer to replace
+ /// the one lost.
+ /// </remarks>
+ public abstract T[] Rent(int minimumLength);
+
+ /// <summary>
+ /// Returns to the pool an array that was previously obtained via <see cref="Rent"/> on the same
+ /// <see cref="ArrayPool{T}"/> instance.
+ /// </summary>
+ /// <param name="array">
+ /// The buffer previously obtained from <see cref="Rent"/> to return to the pool.
+ /// </param>
+ /// <param name="clearArray">
+ /// If <c>true</c> and if the pool will store the buffer to enable subsequent reuse, <see cref="Return"/>
+ /// will clear <paramref name="array"/> of its contents so that a subsequent consumer via <see cref="Rent"/>
+ /// will not see the previous consumer's content. If <c>false</c> or if the pool will release the buffer,
+ /// the array's contents are left unchanged.
+ /// </param>
+ /// <remarks>
+ /// Once a buffer has been returned to the pool, the caller gives up all ownership of the buffer
+ /// and must not use it. The reference returned from a given call to <see cref="Rent"/> must only be
+ /// returned via <see cref="Return"/> once. The default <see cref="ArrayPool{T}"/>
+ /// may hold onto the returned buffer in order to rent it again, or it may release the returned buffer
+ /// if it's determined that the pool already has enough buffers stored.
+ /// </remarks>
+ public abstract void Return(T[] array, bool clearArray = false);
+ }
+}
diff --git a/src/mscorlib/shared/System/Buffers/ConfigurableArrayPool.cs b/src/mscorlib/shared/System/Buffers/ConfigurableArrayPool.cs
new file mode 100644
index 0000000000..f7b6034d20
--- /dev/null
+++ b/src/mscorlib/shared/System/Buffers/ConfigurableArrayPool.cs
@@ -0,0 +1,265 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+using System.Threading;
+
+namespace System.Buffers
+{
+ internal sealed partial class ConfigurableArrayPool<T> : ArrayPool<T>
+ {
+ /// <summary>The default maximum length of each array in the pool (2^20).</summary>
+ private const int DefaultMaxArrayLength = 1024 * 1024;
+ /// <summary>The default maximum number of arrays per bucket that are available for rent.</summary>
+ private const int DefaultMaxNumberOfArraysPerBucket = 50;
+
+ private readonly Bucket[] _buckets;
+
+ internal ConfigurableArrayPool() : this(DefaultMaxArrayLength, DefaultMaxNumberOfArraysPerBucket)
+ {
+ }
+
+ internal ConfigurableArrayPool(int maxArrayLength, int maxArraysPerBucket)
+ {
+ if (maxArrayLength <= 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(maxArrayLength));
+ }
+ if (maxArraysPerBucket <= 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(maxArraysPerBucket));
+ }
+
+ // Our bucketing algorithm has a min length of 2^4 and a max length of 2^30.
+ // Constrain the actual max used to those values.
+ const int MinimumArrayLength = 0x10, MaximumArrayLength = 0x40000000;
+ if (maxArrayLength > MaximumArrayLength)
+ {
+ maxArrayLength = MaximumArrayLength;
+ }
+ else if (maxArrayLength < MinimumArrayLength)
+ {
+ maxArrayLength = MinimumArrayLength;
+ }
+
+ // Create the buckets.
+ int poolId = Id;
+ int maxBuckets = Utilities.SelectBucketIndex(maxArrayLength);
+ var buckets = new Bucket[maxBuckets + 1];
+ for (int i = 0; i < buckets.Length; i++)
+ {
+ buckets[i] = new Bucket(Utilities.GetMaxSizeForBucket(i), maxArraysPerBucket, poolId);
+ }
+ _buckets = buckets;
+ }
+
+ /// <summary>Gets an ID for the pool to use with events.</summary>
+ private int Id => GetHashCode();
+
+ public override T[] Rent(int minimumLength)
+ {
+ // Arrays can't be smaller than zero. We allow requesting zero-length arrays (even though
+ // pooling such an array isn't valuable) as it's a valid length array, and we want the pool
+ // to be usable in general instead of using `new`, even for computed lengths.
+ if (minimumLength < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(minimumLength));
+ }
+ else if (minimumLength == 0)
+ {
+ // No need for events with the empty array. Our pool is effectively infinite
+ // and we'll never allocate for rents and never store for returns.
+ return Array.Empty<T>();
+ }
+
+ var log = ArrayPoolEventSource.Log;
+ T[] buffer = null;
+
+ int index = Utilities.SelectBucketIndex(minimumLength);
+ if (index < _buckets.Length)
+ {
+ // Search for an array starting at the 'index' bucket. If the bucket is empty, bump up to the
+ // next higher bucket and try that one, but only try at most a few buckets.
+ const int MaxBucketsToTry = 2;
+ int i = index;
+ do
+ {
+ // Attempt to rent from the bucket. If we get a buffer from it, return it.
+ buffer = _buckets[i].Rent();
+ if (buffer != null)
+ {
+ if (log.IsEnabled())
+ {
+ log.BufferRented(buffer.GetHashCode(), buffer.Length, Id, _buckets[i].Id);
+ }
+ return buffer;
+ }
+ }
+ while (++i < _buckets.Length && i != index + MaxBucketsToTry);
+
+ // The pool was exhausted for this buffer size. Allocate a new buffer with a size corresponding
+ // to the appropriate bucket.
+ buffer = new T[_buckets[index]._bufferLength];
+ }
+ else
+ {
+ // The request was for a size too large for the pool. Allocate an array of exactly the requested length.
+ // When it's returned to the pool, we'll simply throw it away.
+ buffer = new T[minimumLength];
+ }
+
+ if (log.IsEnabled())
+ {
+ int bufferId = buffer.GetHashCode(), bucketId = -1; // no bucket for an on-demand allocated buffer
+ log.BufferRented(bufferId, buffer.Length, Id, bucketId);
+ log.BufferAllocated(bufferId, buffer.Length, Id, bucketId, index >= _buckets.Length ?
+ ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize : ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted);
+ }
+
+ return buffer;
+ }
+
+ public override void Return(T[] array, bool clearArray = false)
+ {
+ if (array == null)
+ {
+ throw new ArgumentNullException(nameof(array));
+ }
+ else if (array.Length == 0)
+ {
+ // Ignore empty arrays. When a zero-length array is rented, we return a singleton
+ // rather than actually taking a buffer out of the lowest bucket.
+ return;
+ }
+
+ // Determine with what bucket this array length is associated
+ int bucket = Utilities.SelectBucketIndex(array.Length);
+
+ // If we can tell that the buffer was allocated, drop it. Otherwise, check if we have space in the pool
+ if (bucket < _buckets.Length)
+ {
+ // Clear the array if the user requests
+ if (clearArray)
+ {
+ Array.Clear(array, 0, array.Length);
+ }
+
+ // Return the buffer to its bucket. In the future, we might consider having Return return false
+ // instead of dropping a bucket, in which case we could try to return to a lower-sized bucket,
+ // just as how in Rent we allow renting from a higher-sized bucket.
+ _buckets[bucket].Return(array);
+ }
+
+ // Log that the buffer was returned
+ var log = ArrayPoolEventSource.Log;
+ if (log.IsEnabled())
+ {
+ log.BufferReturned(array.GetHashCode(), array.Length, Id);
+ }
+ }
+
+ /// <summary>Provides a thread-safe bucket containing buffers that can be Rent'd and Return'd.</summary>
+ private sealed class Bucket
+ {
+ internal readonly int _bufferLength;
+ private readonly T[][] _buffers;
+ private readonly int _poolId;
+
+ private SpinLock _lock; // do not make this readonly; it's a mutable struct
+ private int _index;
+
+ /// <summary>
+ /// Creates the pool with numberOfBuffers arrays where each buffer is of bufferLength length.
+ /// </summary>
+ internal Bucket(int bufferLength, int numberOfBuffers, int poolId)
+ {
+ _lock = new SpinLock(Debugger.IsAttached); // only enable thread tracking if debugger is attached; it adds non-trivial overheads to Enter/Exit
+ _buffers = new T[numberOfBuffers][];
+ _bufferLength = bufferLength;
+ _poolId = poolId;
+ }
+
+ /// <summary>Gets an ID for the bucket to use with events.</summary>
+ internal int Id => GetHashCode();
+
+ /// <summary>Takes an array from the bucket. If the bucket is empty, returns null.</summary>
+ internal T[] Rent()
+ {
+ T[][] buffers = _buffers;
+ T[] buffer = null;
+
+ // While holding the lock, grab whatever is at the next available index and
+ // update the index. We do as little work as possible while holding the spin
+ // lock to minimize contention with other threads. The try/finally is
+ // necessary to properly handle thread aborts on platforms which have them.
+ bool lockTaken = false, allocateBuffer = false;
+ try
+ {
+ _lock.Enter(ref lockTaken);
+
+ if (_index < buffers.Length)
+ {
+ buffer = buffers[_index];
+ buffers[_index++] = null;
+ allocateBuffer = buffer == null;
+ }
+ }
+ finally
+ {
+ if (lockTaken) _lock.Exit(false);
+ }
+
+ // While we were holding the lock, we grabbed whatever was at the next available index, if
+ // there was one. If we tried and if we got back null, that means we hadn't yet allocated
+ // for that slot, in which case we should do so now.
+ if (allocateBuffer)
+ {
+ buffer = new T[_bufferLength];
+
+ var log = ArrayPoolEventSource.Log;
+ if (log.IsEnabled())
+ {
+ log.BufferAllocated(buffer.GetHashCode(), _bufferLength, _poolId, Id,
+ ArrayPoolEventSource.BufferAllocatedReason.Pooled);
+ }
+ }
+
+ return buffer;
+ }
+
+ /// <summary>
+ /// Attempts to return the buffer to the bucket. If successful, the buffer will be stored
+ /// in the bucket and true will be returned; otherwise, the buffer won't be stored, and false
+ /// will be returned.
+ /// </summary>
+ internal void Return(T[] array)
+ {
+ // Check to see if the buffer is the correct size for this bucket
+ if (array.Length != _bufferLength)
+ {
+ throw new ArgumentException(SR.ArgumentException_BufferNotFromPool, nameof(array));
+ }
+
+ // While holding the spin lock, if there's room available in the bucket,
+ // put the buffer into the next available slot. Otherwise, we just drop it.
+ // The try/finally is necessary to properly handle thread aborts on platforms
+ // which have them.
+ bool lockTaken = false;
+ try
+ {
+ _lock.Enter(ref lockTaken);
+
+ if (_index != 0)
+ {
+ _buffers[--_index] = array;
+ }
+ }
+ finally
+ {
+ if (lockTaken) _lock.Exit(false);
+ }
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs b/src/mscorlib/shared/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs
new file mode 100644
index 0000000000..64c5cebe85
--- /dev/null
+++ b/src/mscorlib/shared/System/Buffers/TlsOverPerCoreLockedStacksArrayPool.cs
@@ -0,0 +1,292 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using Microsoft.Win32;
+using System.Runtime.CompilerServices;
+using System.Threading;
+
+namespace System.Buffers
+{
+ /// <summary>
+ /// Provides an ArrayPool implementation meant to be used as the singleton returned from ArrayPool.Shared.
+ /// </summary>
+ /// <remarks>
+ /// The implementation uses a tiered caching scheme, with a small per-thread cache for each array size, followed
+ /// by a cache per array size shared by all threads, split into per-core stacks meant to be used by threads
+ /// running on that core. Locks are used to protect each per-core stack, because a thread can migrate after
+ /// checking its processor number, because multiple threads could interleave on the same core, and because
+ /// a thread is allowed to check other core's buckets if its core's bucket is empty/full.
+ /// </remarks>
+ internal sealed partial class TlsOverPerCoreLockedStacksArrayPool<T> : ArrayPool<T>
+ {
+ // TODO: #7747: "Investigate optimizing ArrayPool heuristics"
+ // - Explore caching in TLS more than one array per size per thread, and moving stale buffers to the global queue.
+ // - Explore dumping stale buffers from the global queue, similar to PinnableBufferCache (maybe merging them).
+ // - Explore changing the size of each per-core bucket, potentially dynamically or based on other factors like array size.
+ // - Explore changing number of buckets and what sizes of arrays are cached.
+ // - Investigate whether false sharing is causing any issues, in particular on LockedStack's count and the contents of its array.
+ // ...
+
+ /// <summary>The number of buckets (array sizes) in the pool, one for each array length, starting from length 16.</summary>
+ private const int NumBuckets = 17; // Utilities.SelectBucketIndex(2*1024*1024)
+ /// <summary>Maximum number of per-core stacks to use per array size.</summary>
+ private const int MaxPerCorePerArraySizeStacks = 64; // selected to avoid needing to worry about processor groups
+ /// <summary>The maximum number of buffers to store in a bucket's global queue.</summary>
+ private const int MaxBuffersPerArraySizePerCore = 8;
+
+ /// <summary>The length of arrays stored in the corresponding indices in <see cref="_buckets"/> and <see cref="t_tlsBuckets"/>.</summary>
+ private readonly int[] _bucketArraySizes;
+ /// <summary>
+ /// An array of per-core array stacks. The slots are lazily initialized to avoid creating
+ /// lots of overhead for unused array sizes.
+ /// </summary>
+ private readonly PerCoreLockedStacks[] _buckets = new PerCoreLockedStacks[NumBuckets];
+ /// <summary>A per-thread array of arrays, to cache one array per array size per thread.</summary>
+ [ThreadStatic]
+ private static T[][] t_tlsBuckets;
+
+ /// <summary>Initialize the pool.</summary>
+ public TlsOverPerCoreLockedStacksArrayPool()
+ {
+ var sizes = new int[NumBuckets];
+ for (int i = 0; i < sizes.Length; i++)
+ {
+ sizes[i] = Utilities.GetMaxSizeForBucket(i);
+ }
+ _bucketArraySizes = sizes;
+ }
+
+ /// <summary>Allocate a new PerCoreLockedStacks and try to store it into the <see cref="_buckets"/> array.</summary>
+ private PerCoreLockedStacks CreatePerCoreLockedStacks(int bucketIndex)
+ {
+ var inst = new PerCoreLockedStacks();
+ return Interlocked.CompareExchange(ref _buckets[bucketIndex], inst, null) ?? inst;
+ }
+
+ /// <summary>Gets an ID for the pool to use with events.</summary>
+ private int Id => GetHashCode();
+
+ public override T[] Rent(int minimumLength)
+ {
+ // Arrays can't be smaller than zero. We allow requesting zero-length arrays (even though
+ // pooling such an array isn't valuable) as it's a valid length array, and we want the pool
+ // to be usable in general instead of using `new`, even for computed lengths.
+ if (minimumLength < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(minimumLength));
+ }
+ else if (minimumLength == 0)
+ {
+ // No need to log the empty array. Our pool is effectively infinite
+ // and we'll never allocate for rents and never store for returns.
+ return Array.Empty<T>();
+ }
+
+ ArrayPoolEventSource log = ArrayPoolEventSource.Log;
+ T[] buffer;
+
+ // Get the bucket number for the array length
+ int bucketIndex = Utilities.SelectBucketIndex(minimumLength);
+
+ // If the array could come from a bucket...
+ if (bucketIndex < _buckets.Length)
+ {
+ // First try to get it from TLS if possible.
+ T[][] tlsBuckets = t_tlsBuckets;
+ if (tlsBuckets != null)
+ {
+ buffer = tlsBuckets[bucketIndex];
+ if (buffer != null)
+ {
+ tlsBuckets[bucketIndex] = null;
+ if (log.IsEnabled())
+ {
+ log.BufferRented(buffer.GetHashCode(), buffer.Length, Id, bucketIndex);
+ }
+ return buffer;
+ }
+ }
+
+ // We couldn't get a buffer from TLS, so try the global stack.
+ PerCoreLockedStacks b = _buckets[bucketIndex];
+ if (b != null)
+ {
+ buffer = b.TryPop();
+ if (buffer != null)
+ {
+ if (log.IsEnabled())
+ {
+ log.BufferRented(buffer.GetHashCode(), buffer.Length, Id, bucketIndex);
+ }
+ return buffer;
+ }
+ }
+
+ // No buffer available. Allocate a new buffer with a size corresponding to the appropriate bucket.
+ buffer = new T[_bucketArraySizes[bucketIndex]];
+ }
+ else
+ {
+ // The request was for a size too large for the pool. Allocate an array of exactly the requested length.
+ // When it's returned to the pool, we'll simply throw it away.
+ buffer = new T[minimumLength];
+ }
+
+ if (log.IsEnabled())
+ {
+ int bufferId = buffer.GetHashCode(), bucketId = -1; // no bucket for an on-demand allocated buffer
+ log.BufferRented(bufferId, buffer.Length, Id, bucketId);
+ log.BufferAllocated(bufferId, buffer.Length, Id, bucketId, bucketIndex >= _buckets.Length ?
+ ArrayPoolEventSource.BufferAllocatedReason.OverMaximumSize :
+ ArrayPoolEventSource.BufferAllocatedReason.PoolExhausted);
+ }
+
+ return buffer;
+ }
+
+ public override void Return(T[] array, bool clearArray = false)
+ {
+ if (array == null)
+ {
+ throw new ArgumentNullException(nameof(array));
+ }
+
+ // Determine with what bucket this array length is associated
+ int bucketIndex = Utilities.SelectBucketIndex(array.Length);
+
+ // If we can tell that the buffer was allocated (or empty), drop it. Otherwise, check if we have space in the pool.
+ if (bucketIndex < _buckets.Length)
+ {
+ // Clear the array if the user requests.
+ if (clearArray)
+ {
+ Array.Clear(array, 0, array.Length);
+ }
+
+ // Check to see if the buffer is the correct size for this bucket
+ if (array.Length != _bucketArraySizes[bucketIndex])
+ {
+ throw new ArgumentException(SR.ArgumentException_BufferNotFromPool, nameof(array));
+ }
+
+ // Write through the TLS bucket. If there weren't any buckets, create them
+ // and store this array into it. If there were, store this into it, and
+ // if there was a previous one there, push that to the global stack. This
+ // helps to keep LIFO access such that the most recently pushed stack will
+ // be in TLS and the first to be popped next.
+ T[][] tlsBuckets = t_tlsBuckets;
+ if (tlsBuckets == null)
+ {
+ t_tlsBuckets = tlsBuckets = new T[NumBuckets][];
+ tlsBuckets[bucketIndex] = array;
+ }
+ else
+ {
+ T[] prev = tlsBuckets[bucketIndex];
+ tlsBuckets[bucketIndex] = array;
+ if (prev != null)
+ {
+ PerCoreLockedStacks bucket = _buckets[bucketIndex] ?? CreatePerCoreLockedStacks(bucketIndex);
+ bucket.TryPush(prev);
+ }
+ }
+ }
+
+ // Log that the buffer was returned
+ ArrayPoolEventSource log = ArrayPoolEventSource.Log;
+ if (log.IsEnabled())
+ {
+ log.BufferReturned(array.GetHashCode(), array.Length, Id);
+ }
+ }
+
+ /// <summary>
+ /// Stores a set of stacks of arrays, with one stack per core.
+ /// </summary>
+ private sealed class PerCoreLockedStacks
+ {
+ /// <summary>The stacks.</summary>
+ private readonly LockedStack[] _perCoreStacks;
+
+ /// <summary>Initializes the stacks.</summary>
+ public PerCoreLockedStacks()
+ {
+ // Create the stacks. We create as many as there are processors, limited by our max.
+ var stacks = new LockedStack[Math.Min(Environment.ProcessorCount, MaxPerCorePerArraySizeStacks)];
+ for (int i = 0; i < stacks.Length; i++)
+ {
+ stacks[i] = new LockedStack();
+ }
+ _perCoreStacks = stacks;
+ }
+
+ /// <summary>Try to push the array into the stacks. If each is full when it's tested, the array will be dropped.</summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public void TryPush(T[] array)
+ {
+ // Try to push on to the associated stack first. If that fails,
+ // round-robin through the other stacks.
+ LockedStack[] stacks = _perCoreStacks;
+ int index = Environment.CurrentExecutionId % stacks.Length;
+ for (int i = 0; i < stacks.Length; i++)
+ {
+ if (stacks[index].TryPush(array)) return;
+ if (++index == stacks.Length) index = 0;
+ }
+ }
+
+ /// <summary>Try to get an array from the stacks. If each is empty when it's tested, null will be returned.</summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public T[] TryPop()
+ {
+ // Try to pop from the associated stack first. If that fails,
+ // round-robin through the other stacks.
+ T[] arr;
+ LockedStack[] stacks = _perCoreStacks;
+ int index = Environment.CurrentExecutionId % stacks.Length;
+ for (int i = 0; i < stacks.Length; i++)
+ {
+ if ((arr = stacks[index].TryPop()) != null) return arr;
+ if (++index == stacks.Length) index = 0;
+ }
+ return null;
+ }
+ }
+
+ /// <summary>Provides a simple stack of arrays, protected by a lock.</summary>
+ private sealed class LockedStack
+ {
+ private readonly T[][] _arrays = new T[MaxBuffersPerArraySizePerCore][];
+ private int _count;
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public bool TryPush(T[] array)
+ {
+ bool enqueued = false;
+ Monitor.Enter(this);
+ if (_count < MaxBuffersPerArraySizePerCore)
+ {
+ _arrays[_count++] = array;
+ enqueued = true;
+ }
+ Monitor.Exit(this);
+ return enqueued;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public T[] TryPop()
+ {
+ T[] arr = null;
+ Monitor.Enter(this);
+ if (_count > 0)
+ {
+ arr = _arrays[--_count];
+ _arrays[_count] = null;
+ }
+ Monitor.Exit(this);
+ return arr;
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Buffers/Utilities.cs b/src/mscorlib/shared/System/Buffers/Utilities.cs
new file mode 100644
index 0000000000..4f115fe9dd
--- /dev/null
+++ b/src/mscorlib/shared/System/Buffers/Utilities.cs
@@ -0,0 +1,35 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+
+namespace System.Buffers
+{
+ internal static class Utilities
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal static int SelectBucketIndex(int bufferSize)
+ {
+ uint bitsRemaining = ((uint)bufferSize - 1) >> 4;
+
+ int poolIndex = 0;
+ if (bitsRemaining > 0xFFFF) { bitsRemaining >>= 16; poolIndex = 16; }
+ if (bitsRemaining > 0xFF) { bitsRemaining >>= 8; poolIndex += 8; }
+ if (bitsRemaining > 0xF) { bitsRemaining >>= 4; poolIndex += 4; }
+ if (bitsRemaining > 0x3) { bitsRemaining >>= 2; poolIndex += 2; }
+ if (bitsRemaining > 0x1) { bitsRemaining >>= 1; poolIndex += 1; }
+
+ return poolIndex + (int)bitsRemaining;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal static int GetMaxSizeForBucket(int binIndex)
+ {
+ int maxSize = 16 << binIndex;
+ Debug.Assert(maxSize >= 0);
+ return maxSize;
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/CLSCompliantAttribute.cs b/src/mscorlib/shared/System/CLSCompliantAttribute.cs
new file mode 100644
index 0000000000..e03600d132
--- /dev/null
+++ b/src/mscorlib/shared/System/CLSCompliantAttribute.cs
@@ -0,0 +1,34 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*=============================================================================
+**
+**
+**
+** Purpose: Container for assemblies.
+**
+**
+=============================================================================*/
+
+namespace System
+{
+ [Serializable]
+ [AttributeUsage(AttributeTargets.All, Inherited = true, AllowMultiple = false)]
+ public sealed class CLSCompliantAttribute : Attribute
+ {
+ private bool _compliant;
+
+ public CLSCompliantAttribute(bool isCompliant)
+ {
+ _compliant = isCompliant;
+ }
+ public bool IsCompliant
+ {
+ get
+ {
+ return _compliant;
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Char.cs b/src/mscorlib/shared/System/Char.cs
new file mode 100644
index 0000000000..2b3133a669
--- /dev/null
+++ b/src/mscorlib/shared/System/Char.cs
@@ -0,0 +1,1122 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*============================================================
+**
+**
+**
+** Purpose: This is the value class representing a Unicode character
+** Char methods until we create this functionality.
+**
+**
+===========================================================*/
+
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Globalization;
+using System.Runtime.InteropServices;
+
+namespace System
+{
+ [Serializable]
+ [StructLayout(LayoutKind.Sequential)]
+ public struct Char : IComparable, IComparable<Char>, IEquatable<Char>, IConvertible
+ {
+ //
+ // Member Variables
+ //
+ internal char m_value;
+
+ //
+ // Public Constants
+ //
+ // The maximum character value.
+ public const char MaxValue = (char)0xFFFF;
+ // The minimum character value.
+ public const char MinValue = (char)0x00;
+
+ // Unicode category values from Unicode U+0000 ~ U+00FF. Store them in byte[] array to save space.
+ private static readonly byte[] s_categoryForLatin1 = {
+ (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0000 - 0007
+ (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0008 - 000F
+ (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0010 - 0017
+ (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0018 - 001F
+ (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0020 - 0027
+ (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, // 0028 - 002F
+ (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, // 0030 - 0037
+ (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.DecimalDigitNumber, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherPunctuation, // 0038 - 003F
+ (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0040 - 0047
+ (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0048 - 004F
+ (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 0050 - 0057
+ (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.ConnectorPunctuation, // 0058 - 005F
+ (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0060 - 0067
+ (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0068 - 006F
+ (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 0070 - 0077
+ (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OpenPunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.ClosePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.Control, // 0078 - 007F
+ (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0080 - 0087
+ (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0088 - 008F
+ (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0090 - 0097
+ (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, (byte)UnicodeCategory.Control, // 0098 - 009F
+ (byte)UnicodeCategory.SpaceSeparator, (byte)UnicodeCategory.OtherPunctuation, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.CurrencySymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherSymbol, // 00A0 - 00A7
+ (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.InitialQuotePunctuation, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.DashPunctuation, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.ModifierSymbol, // 00A8 - 00AF
+ (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.MathSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.OtherSymbol, (byte)UnicodeCategory.OtherPunctuation, // 00B0 - 00B7
+ (byte)UnicodeCategory.ModifierSymbol, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.FinalQuotePunctuation, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherNumber, (byte)UnicodeCategory.OtherPunctuation, // 00B8 - 00BF
+ (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C0 - 00C7
+ (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, // 00C8 - 00CF
+ (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00D0 - 00D7
+ (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.UppercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00D8 - 00DF
+ (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E0 - 00E7
+ (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00E8 - 00EF
+ (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.MathSymbol, // 00F0 - 00F7
+ (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, (byte)UnicodeCategory.LowercaseLetter, // 00F8 - 00FF
+ };
+
+ // Return true for all characters below or equal U+00ff, which is ASCII + Latin-1 Supplement.
+ private static bool IsLatin1(char ch)
+ {
+ return (ch <= '\x00ff');
+ }
+
+ // Return true for all characters below or equal U+007f, which is ASCII.
+ private static bool IsAscii(char ch)
+ {
+ return (ch <= '\x007f');
+ }
+
+ // Return the Unicode category for Unicode character <= 0x00ff.
+ private static UnicodeCategory GetLatin1UnicodeCategory(char ch)
+ {
+ Debug.Assert(IsLatin1(ch), "Char.GetLatin1UnicodeCategory(): ch should be <= 007f");
+ return (UnicodeCategory)(s_categoryForLatin1[(int)ch]);
+ }
+
+ //
+ // Private Constants
+ //
+
+ //
+ // Overriden Instance Methods
+ //
+
+ // Calculate a hashcode for a 2 byte Unicode character.
+ public override int GetHashCode()
+ {
+ return (int)m_value | ((int)m_value << 16);
+ }
+
+ // Used for comparing two boxed Char objects.
+ //
+ public override bool Equals(Object obj)
+ {
+ if (!(obj is Char))
+ {
+ return false;
+ }
+ return (m_value == ((Char)obj).m_value);
+ }
+
+ [System.Runtime.Versioning.NonVersionable]
+ public bool Equals(Char obj)
+ {
+ return m_value == obj;
+ }
+
+ // Compares this object to another object, returning an integer that
+ // indicates the relationship.
+ // Returns a value less than zero if this object
+ // null is considered to be less than any instance.
+ // If object is not of type Char, this method throws an ArgumentException.
+ //
+ [Pure]
+ public int CompareTo(Object value)
+ {
+ if (value == null)
+ {
+ return 1;
+ }
+ if (!(value is Char))
+ {
+ throw new ArgumentException(SR.Arg_MustBeChar);
+ }
+
+ return (m_value - ((Char)value).m_value);
+ }
+
+ [Pure]
+ public int CompareTo(Char value)
+ {
+ return (m_value - value);
+ }
+
+ // Overrides System.Object.ToString.
+ [Pure]
+ public override String ToString()
+ {
+ Contract.Ensures(Contract.Result<String>() != null);
+ return Char.ToString(m_value);
+ }
+
+ [Pure]
+ public String ToString(IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<String>() != null);
+ return Char.ToString(m_value);
+ }
+
+ //
+ // Formatting Methods
+ //
+
+ /*===================================ToString===================================
+ **This static methods takes a character and returns the String representation of it.
+ ==============================================================================*/
+ // Provides a string representation of a character.
+ [Pure]
+ public static string ToString(char c) => string.CreateFromChar(c);
+
+ public static char Parse(String s)
+ {
+ if (s == null)
+ {
+ throw new ArgumentNullException(nameof(s));
+ }
+ Contract.EndContractBlock();
+
+ if (s.Length != 1)
+ {
+ throw new FormatException(SR.Format_NeedSingleChar);
+ }
+ return s[0];
+ }
+
+ public static bool TryParse(String s, out Char result)
+ {
+ result = '\0';
+ if (s == null)
+ {
+ return false;
+ }
+ if (s.Length != 1)
+ {
+ return false;
+ }
+ result = s[0];
+ return true;
+ }
+
+ //
+ // Static Methods
+ //
+ /*=================================ISDIGIT======================================
+ **A wrapper for Char. Returns a boolean indicating whether **
+ **character c is considered to be a digit. **
+ ==============================================================================*/
+ // Determines whether a character is a digit.
+ [Pure]
+ public static bool IsDigit(char c)
+ {
+ if (IsLatin1(c))
+ {
+ return (c >= '0' && c <= '9');
+ }
+ return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber);
+ }
+
+
+ /*=================================CheckLetter=====================================
+ ** Check if the specified UnicodeCategory belongs to the letter categories.
+ ==============================================================================*/
+ internal static bool CheckLetter(UnicodeCategory uc)
+ {
+ switch (uc)
+ {
+ case (UnicodeCategory.UppercaseLetter):
+ case (UnicodeCategory.LowercaseLetter):
+ case (UnicodeCategory.TitlecaseLetter):
+ case (UnicodeCategory.ModifierLetter):
+ case (UnicodeCategory.OtherLetter):
+ return (true);
+ }
+ return (false);
+ }
+
+ /*=================================ISLETTER=====================================
+ **A wrapper for Char. Returns a boolean indicating whether **
+ **character c is considered to be a letter. **
+ ==============================================================================*/
+ // Determines whether a character is a letter.
+ [Pure]
+ public static bool IsLetter(char c)
+ {
+ if (IsLatin1(c))
+ {
+ if (IsAscii(c))
+ {
+ c |= (char)0x20;
+ return ((c >= 'a' && c <= 'z'));
+ }
+ return (CheckLetter(GetLatin1UnicodeCategory(c)));
+ }
+ return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(c)));
+ }
+
+ private static bool IsWhiteSpaceLatin1(char c)
+ {
+ // There are characters which belong to UnicodeCategory.Control but are considered as white spaces.
+ // We use code point comparisons for these characters here as a temporary fix.
+
+ // U+0009 = <control> HORIZONTAL TAB
+ // U+000a = <control> LINE FEED
+ // U+000b = <control> VERTICAL TAB
+ // U+000c = <contorl> FORM FEED
+ // U+000d = <control> CARRIAGE RETURN
+ // U+0085 = <control> NEXT LINE
+ // U+00a0 = NO-BREAK SPACE
+ if ((c == ' ') || (c >= '\x0009' && c <= '\x000d') || c == '\x00a0' || c == '\x0085')
+ {
+ return (true);
+ }
+ return (false);
+ }
+
+ /*===============================ISWHITESPACE===================================
+ **A wrapper for Char. Returns a boolean indicating whether **
+ **character c is considered to be a whitespace character. **
+ ==============================================================================*/
+ // Determines whether a character is whitespace.
+ [Pure]
+ public static bool IsWhiteSpace(char c)
+ {
+ if (IsLatin1(c))
+ {
+ return (IsWhiteSpaceLatin1(c));
+ }
+ return CharUnicodeInfo.IsWhiteSpace(c);
+ }
+
+
+ /*===================================IsUpper====================================
+ **Arguments: c -- the characater to be checked.
+ **Returns: True if c is an uppercase character.
+ ==============================================================================*/
+ // Determines whether a character is upper-case.
+ [Pure]
+ public static bool IsUpper(char c)
+ {
+ if (IsLatin1(c))
+ {
+ if (IsAscii(c))
+ {
+ return (c >= 'A' && c <= 'Z');
+ }
+ return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter);
+ }
+ return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter);
+ }
+
+ /*===================================IsLower====================================
+ **Arguments: c -- the characater to be checked.
+ **Returns: True if c is an lowercase character.
+ ==============================================================================*/
+ // Determines whether a character is lower-case.
+ [Pure]
+ public static bool IsLower(char c)
+ {
+ if (IsLatin1(c))
+ {
+ if (IsAscii(c))
+ {
+ return (c >= 'a' && c <= 'z');
+ }
+ return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter);
+ }
+ return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter);
+ }
+
+ internal static bool CheckPunctuation(UnicodeCategory uc)
+ {
+ switch (uc)
+ {
+ case UnicodeCategory.ConnectorPunctuation:
+ case UnicodeCategory.DashPunctuation:
+ case UnicodeCategory.OpenPunctuation:
+ case UnicodeCategory.ClosePunctuation:
+ case UnicodeCategory.InitialQuotePunctuation:
+ case UnicodeCategory.FinalQuotePunctuation:
+ case UnicodeCategory.OtherPunctuation:
+ return (true);
+ }
+ return (false);
+ }
+
+
+ /*================================IsPunctuation=================================
+ **Arguments: c -- the characater to be checked.
+ **Returns: True if c is an punctuation mark
+ ==============================================================================*/
+ // Determines whether a character is a punctuation mark.
+ [Pure]
+ public static bool IsPunctuation(char c)
+ {
+ if (IsLatin1(c))
+ {
+ return (CheckPunctuation(GetLatin1UnicodeCategory(c)));
+ }
+ return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(c)));
+ }
+
+ /*=================================CheckLetterOrDigit=====================================
+ ** Check if the specified UnicodeCategory belongs to the letter or digit categories.
+ ==============================================================================*/
+ internal static bool CheckLetterOrDigit(UnicodeCategory uc)
+ {
+ switch (uc)
+ {
+ case UnicodeCategory.UppercaseLetter:
+ case UnicodeCategory.LowercaseLetter:
+ case UnicodeCategory.TitlecaseLetter:
+ case UnicodeCategory.ModifierLetter:
+ case UnicodeCategory.OtherLetter:
+ case UnicodeCategory.DecimalDigitNumber:
+ return (true);
+ }
+ return (false);
+ }
+
+ // Determines whether a character is a letter or a digit.
+ [Pure]
+ public static bool IsLetterOrDigit(char c)
+ {
+ if (IsLatin1(c))
+ {
+ return (CheckLetterOrDigit(GetLatin1UnicodeCategory(c)));
+ }
+ return (CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(c)));
+ }
+
+ /*===================================ToUpper====================================
+ **
+ ==============================================================================*/
+ // Converts a character to upper-case for the specified culture.
+ // <;<;Not fully implemented>;>;
+ public static char ToUpper(char c, CultureInfo culture)
+ {
+ if (culture == null)
+ throw new ArgumentNullException(nameof(culture));
+ Contract.EndContractBlock();
+ return culture.TextInfo.ToUpper(c);
+ }
+
+ /*=================================TOUPPER======================================
+ **A wrapper for Char.toUpperCase. Converts character c to its **
+ **uppercase equivalent. If c is already an uppercase character or is not an **
+ **alphabetic, nothing happens. **
+ ==============================================================================*/
+ // Converts a character to upper-case for the default culture.
+ //
+ public static char ToUpper(char c)
+ {
+ return ToUpper(c, CultureInfo.CurrentCulture);
+ }
+
+
+ // Converts a character to upper-case for invariant culture.
+ public static char ToUpperInvariant(char c)
+ {
+ return ToUpper(c, CultureInfo.InvariantCulture);
+ }
+
+
+ /*===================================ToLower====================================
+ **
+ ==============================================================================*/
+ // Converts a character to lower-case for the specified culture.
+ // <;<;Not fully implemented>;>;
+ public static char ToLower(char c, CultureInfo culture)
+ {
+ if (culture == null)
+ throw new ArgumentNullException(nameof(culture));
+ Contract.EndContractBlock();
+ return culture.TextInfo.ToLower(c);
+ }
+
+ /*=================================TOLOWER======================================
+ **A wrapper for Char.toLowerCase. Converts character c to its **
+ **lowercase equivalent. If c is already a lowercase character or is not an **
+ **alphabetic, nothing happens. **
+ ==============================================================================*/
+ // Converts a character to lower-case for the default culture.
+ public static char ToLower(char c)
+ {
+ return ToLower(c, CultureInfo.CurrentCulture);
+ }
+
+
+ // Converts a character to lower-case for invariant culture.
+ public static char ToLowerInvariant(char c)
+ {
+ return ToLower(c, CultureInfo.InvariantCulture);
+ }
+
+
+ //
+ // IConvertible implementation
+ //
+ [Pure]
+ 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 m_value;
+ }
+
+ sbyte IConvertible.ToSByte(IFormatProvider provider)
+ {
+ return Convert.ToSByte(m_value);
+ }
+
+ byte IConvertible.ToByte(IFormatProvider provider)
+ {
+ return Convert.ToByte(m_value);
+ }
+
+ short IConvertible.ToInt16(IFormatProvider provider)
+ {
+ return Convert.ToInt16(m_value);
+ }
+
+ ushort IConvertible.ToUInt16(IFormatProvider provider)
+ {
+ return Convert.ToUInt16(m_value);
+ }
+
+ int IConvertible.ToInt32(IFormatProvider provider)
+ {
+ return Convert.ToInt32(m_value);
+ }
+
+ uint IConvertible.ToUInt32(IFormatProvider provider)
+ {
+ return Convert.ToUInt32(m_value);
+ }
+
+ long IConvertible.ToInt64(IFormatProvider provider)
+ {
+ return Convert.ToInt64(m_value);
+ }
+
+ ulong IConvertible.ToUInt64(IFormatProvider provider)
+ {
+ return Convert.ToUInt64(m_value);
+ }
+
+ 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((IConvertible)this, type, provider);
+ }
+ public static bool IsControl(char c)
+ {
+ if (IsLatin1(c))
+ {
+ return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control);
+ }
+ return (CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.Control);
+ }
+
+ public static bool IsControl(String s, int index)
+ {
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ char c = s[index];
+ if (IsLatin1(c))
+ {
+ return (GetLatin1UnicodeCategory(c) == UnicodeCategory.Control);
+ }
+ return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.Control);
+ }
+
+
+ public static bool IsDigit(String s, int index)
+ {
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ char c = s[index];
+ if (IsLatin1(c))
+ {
+ return (c >= '0' && c <= '9');
+ }
+ return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.DecimalDigitNumber);
+ }
+
+ public static bool IsLetter(String s, int index)
+ {
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ char c = s[index];
+ if (IsLatin1(c))
+ {
+ if (IsAscii(c))
+ {
+ c |= (char)0x20;
+ return ((c >= 'a' && c <= 'z'));
+ }
+ return (CheckLetter(GetLatin1UnicodeCategory(c)));
+ }
+ return (CheckLetter(CharUnicodeInfo.GetUnicodeCategory(s, index)));
+ }
+
+ public static bool IsLetterOrDigit(String s, int index)
+ {
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ char c = s[index];
+ if (IsLatin1(c))
+ {
+ return CheckLetterOrDigit(GetLatin1UnicodeCategory(c));
+ }
+ return CheckLetterOrDigit(CharUnicodeInfo.GetUnicodeCategory(s, index));
+ }
+
+ public static bool IsLower(String s, int index)
+ {
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ char c = s[index];
+ if (IsLatin1(c))
+ {
+ if (IsAscii(c))
+ {
+ return (c >= 'a' && c <= 'z');
+ }
+ return (GetLatin1UnicodeCategory(c) == UnicodeCategory.LowercaseLetter);
+ }
+
+ return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.LowercaseLetter);
+ }
+
+ /*=================================CheckNumber=====================================
+ ** Check if the specified UnicodeCategory belongs to the number categories.
+ ==============================================================================*/
+
+ internal static bool CheckNumber(UnicodeCategory uc)
+ {
+ switch (uc)
+ {
+ case (UnicodeCategory.DecimalDigitNumber):
+ case (UnicodeCategory.LetterNumber):
+ case (UnicodeCategory.OtherNumber):
+ return (true);
+ }
+ return (false);
+ }
+
+ public static bool IsNumber(char c)
+ {
+ if (IsLatin1(c))
+ {
+ if (IsAscii(c))
+ {
+ return (c >= '0' && c <= '9');
+ }
+ return (CheckNumber(GetLatin1UnicodeCategory(c)));
+ }
+ return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(c)));
+ }
+
+ public static bool IsNumber(String s, int index)
+ {
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ char c = s[index];
+ if (IsLatin1(c))
+ {
+ if (IsAscii(c))
+ {
+ return (c >= '0' && c <= '9');
+ }
+ return (CheckNumber(GetLatin1UnicodeCategory(c)));
+ }
+ return (CheckNumber(CharUnicodeInfo.GetUnicodeCategory(s, index)));
+ }
+
+ ////////////////////////////////////////////////////////////////////////
+ //
+ // IsPunctuation
+ //
+ // Determines if the given character is a punctuation character.
+ //
+ ////////////////////////////////////////////////////////////////////////
+
+ public static bool IsPunctuation(String s, int index)
+ {
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ char c = s[index];
+ if (IsLatin1(c))
+ {
+ return (CheckPunctuation(GetLatin1UnicodeCategory(c)));
+ }
+ return (CheckPunctuation(CharUnicodeInfo.GetUnicodeCategory(s, index)));
+ }
+
+
+ /*================================= CheckSeparator ============================
+ ** Check if the specified UnicodeCategory belongs to the seprator categories.
+ ==============================================================================*/
+
+ internal static bool CheckSeparator(UnicodeCategory uc)
+ {
+ switch (uc)
+ {
+ case UnicodeCategory.SpaceSeparator:
+ case UnicodeCategory.LineSeparator:
+ case UnicodeCategory.ParagraphSeparator:
+ return (true);
+ }
+ return (false);
+ }
+
+ private static bool IsSeparatorLatin1(char c)
+ {
+ // U+00a0 = NO-BREAK SPACE
+ // There is no LineSeparator or ParagraphSeparator in Latin 1 range.
+ return (c == '\x0020' || c == '\x00a0');
+ }
+
+ 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)
+ throw new ArgumentNullException(nameof(s));
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ char c = s[index];
+ if (IsLatin1(c))
+ {
+ return (IsSeparatorLatin1(c));
+ }
+ return (CheckSeparator(CharUnicodeInfo.GetUnicodeCategory(s, index)));
+ }
+
+ [Pure]
+ public static bool IsSurrogate(char c)
+ {
+ return (c >= HIGH_SURROGATE_START && c <= LOW_SURROGATE_END);
+ }
+
+ [Pure]
+ public static bool IsSurrogate(String s, int index)
+ {
+ if (s == null)
+ {
+ throw new ArgumentNullException(nameof(s));
+ }
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ return (IsSurrogate(s[index]));
+ }
+
+ /*================================= CheckSymbol ============================
+ ** Check if the specified UnicodeCategory belongs to the symbol categories.
+ ==============================================================================*/
+
+ internal static bool CheckSymbol(UnicodeCategory uc)
+ {
+ switch (uc)
+ {
+ case (UnicodeCategory.MathSymbol):
+ case (UnicodeCategory.CurrencySymbol):
+ case (UnicodeCategory.ModifierSymbol):
+ case (UnicodeCategory.OtherSymbol):
+ return (true);
+ }
+ return (false);
+ }
+
+ 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)
+ throw new ArgumentNullException(nameof(s));
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ char c = s[index];
+ if (IsLatin1(c))
+ {
+ return (CheckSymbol(GetLatin1UnicodeCategory(c)));
+ }
+ return (CheckSymbol(CharUnicodeInfo.GetUnicodeCategory(s, index)));
+ }
+
+
+ public static bool IsUpper(String s, int index)
+ {
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ char c = s[index];
+ if (IsLatin1(c))
+ {
+ if (IsAscii(c))
+ {
+ return (c >= 'A' && c <= 'Z');
+ }
+ return (GetLatin1UnicodeCategory(c) == UnicodeCategory.UppercaseLetter);
+ }
+
+ return (CharUnicodeInfo.GetUnicodeCategory(s, index) == UnicodeCategory.UppercaseLetter);
+ }
+
+ public static bool IsWhiteSpace(String s, int index)
+ {
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+
+ if (IsLatin1(s[index]))
+ {
+ return IsWhiteSpaceLatin1(s[index]);
+ }
+
+ return CharUnicodeInfo.IsWhiteSpace(s, index);
+ }
+
+ public static UnicodeCategory GetUnicodeCategory(char c)
+ {
+ if (IsLatin1(c))
+ {
+ return (GetLatin1UnicodeCategory(c));
+ }
+ return CharUnicodeInfo.InternalGetUnicodeCategory(c);
+ }
+
+ public static UnicodeCategory GetUnicodeCategory(String s, int index)
+ {
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ if (IsLatin1(s[index]))
+ {
+ return (GetLatin1UnicodeCategory(s[index]));
+ }
+ return CharUnicodeInfo.InternalGetUnicodeCategory(s, index);
+ }
+
+ public static double GetNumericValue(char c)
+ {
+ return CharUnicodeInfo.GetNumericValue(c);
+ }
+
+ public static double GetNumericValue(String s, int index)
+ {
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
+ if (((uint)index) >= ((uint)s.Length))
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ return CharUnicodeInfo.GetNumericValue(s, index);
+ }
+
+
+ /*================================= IsHighSurrogate ============================
+ ** Check if a char is a high surrogate.
+ ==============================================================================*/
+ [Pure]
+ public static bool IsHighSurrogate(char c)
+ {
+ return ((c >= CharUnicodeInfo.HIGH_SURROGATE_START) && (c <= CharUnicodeInfo.HIGH_SURROGATE_END));
+ }
+
+ [Pure]
+ public static bool IsHighSurrogate(String s, int index)
+ {
+ if (s == null)
+ {
+ throw new ArgumentNullException(nameof(s));
+ }
+ if (index < 0 || index >= s.Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ return (IsHighSurrogate(s[index]));
+ }
+
+ /*================================= IsLowSurrogate ============================
+ ** Check if a char is a low surrogate.
+ ==============================================================================*/
+ [Pure]
+ public static bool IsLowSurrogate(char c)
+ {
+ return ((c >= CharUnicodeInfo.LOW_SURROGATE_START) && (c <= CharUnicodeInfo.LOW_SURROGATE_END));
+ }
+
+ [Pure]
+ public static bool IsLowSurrogate(String s, int index)
+ {
+ if (s == null)
+ {
+ throw new ArgumentNullException(nameof(s));
+ }
+ if (index < 0 || index >= s.Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ return (IsLowSurrogate(s[index]));
+ }
+
+ /*================================= IsSurrogatePair ============================
+ ** Check if the string specified by the index starts with a surrogate pair.
+ ==============================================================================*/
+ [Pure]
+ public static bool IsSurrogatePair(String s, int index)
+ {
+ if (s == null)
+ {
+ throw new ArgumentNullException(nameof(s));
+ }
+ if (index < 0 || index >= s.Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(index));
+ }
+ Contract.EndContractBlock();
+ if (index + 1 < s.Length)
+ {
+ return (IsSurrogatePair(s[index], s[index + 1]));
+ }
+ return (false);
+ }
+
+ [Pure]
+ public static bool IsSurrogatePair(char highSurrogate, char lowSurrogate)
+ {
+ return ((highSurrogate >= CharUnicodeInfo.HIGH_SURROGATE_START && highSurrogate <= CharUnicodeInfo.HIGH_SURROGATE_END) &&
+ (lowSurrogate >= CharUnicodeInfo.LOW_SURROGATE_START && lowSurrogate <= CharUnicodeInfo.LOW_SURROGATE_END));
+ }
+
+ internal const int UNICODE_PLANE00_END = 0x00ffff;
+ // The starting codepoint for Unicode plane 1. Plane 1 contains 0x010000 ~ 0x01ffff.
+ internal const int UNICODE_PLANE01_START = 0x10000;
+ // The end codepoint for Unicode plane 16. This is the maximum code point value allowed for Unicode.
+ // Plane 16 contains 0x100000 ~ 0x10ffff.
+ internal const int UNICODE_PLANE16_END = 0x10ffff;
+
+ internal const int HIGH_SURROGATE_START = 0x00d800;
+ internal const int LOW_SURROGATE_END = 0x00dfff;
+
+
+
+ /*================================= ConvertFromUtf32 ============================
+ ** Convert an UTF32 value into a surrogate pair.
+ ==============================================================================*/
+
+ public static String ConvertFromUtf32(int utf32)
+ {
+ // For UTF32 values from U+00D800 ~ U+00DFFF, we should throw. They
+ // are considered as irregular code unit sequence, but they are not illegal.
+ if ((utf32 < 0 || utf32 > UNICODE_PLANE16_END) || (utf32 >= HIGH_SURROGATE_START && utf32 <= LOW_SURROGATE_END))
+ {
+ throw new ArgumentOutOfRangeException(nameof(utf32), SR.ArgumentOutOfRange_InvalidUTF32);
+ }
+ Contract.EndContractBlock();
+
+ if (utf32 < UNICODE_PLANE01_START)
+ {
+ // This is a BMP character.
+ return (Char.ToString((char)utf32));
+ }
+
+ unsafe
+ {
+ // This is a supplementary character. Convert it to a surrogate pair in UTF-16.
+ utf32 -= UNICODE_PLANE01_START;
+ uint surrogate = 0; // allocate 2 chars worth of stack space
+ char* address = (char*)&surrogate;
+ address[0] = (char)((utf32 / 0x400) + (int)CharUnicodeInfo.HIGH_SURROGATE_START);
+ address[1] = (char)((utf32 % 0x400) + (int)CharUnicodeInfo.LOW_SURROGATE_START);
+ return new string(address, 0, 2);
+ }
+ }
+
+
+ /*=============================ConvertToUtf32===================================
+ ** Convert a surrogate pair to UTF32 value
+ ==============================================================================*/
+
+ public static int ConvertToUtf32(char highSurrogate, char lowSurrogate)
+ {
+ if (!IsHighSurrogate(highSurrogate))
+ {
+ throw new ArgumentOutOfRangeException(nameof(highSurrogate), SR.ArgumentOutOfRange_InvalidHighSurrogate);
+ }
+ if (!IsLowSurrogate(lowSurrogate))
+ {
+ throw new ArgumentOutOfRangeException(nameof(lowSurrogate), SR.ArgumentOutOfRange_InvalidLowSurrogate);
+ }
+ Contract.EndContractBlock();
+ return (((highSurrogate - CharUnicodeInfo.HIGH_SURROGATE_START) * 0x400) + (lowSurrogate - CharUnicodeInfo.LOW_SURROGATE_START) + UNICODE_PLANE01_START);
+ }
+
+ /*=============================ConvertToUtf32===================================
+ ** Convert a character or a surrogate pair starting at index of the specified string
+ ** to UTF32 value.
+ ** The char pointed by index should be a surrogate pair or a BMP character.
+ ** This method throws if a high-surrogate is not followed by a low surrogate.
+ ** This method throws if a low surrogate is seen without preceding a high-surrogate.
+ ==============================================================================*/
+
+ public static int ConvertToUtf32(String s, int index)
+ {
+ if (s == null)
+ {
+ throw new ArgumentNullException(nameof(s));
+ }
+
+ if (index < 0 || index >= s.Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
+ }
+ Contract.EndContractBlock();
+ // Check if the character at index is a high surrogate.
+ int temp1 = (int)s[index] - CharUnicodeInfo.HIGH_SURROGATE_START;
+ if (temp1 >= 0 && temp1 <= 0x7ff)
+ {
+ // Found a surrogate char.
+ if (temp1 <= 0x3ff)
+ {
+ // Found a high surrogate.
+ if (index < s.Length - 1)
+ {
+ int temp2 = (int)s[index + 1] - CharUnicodeInfo.LOW_SURROGATE_START;
+ if (temp2 >= 0 && temp2 <= 0x3ff)
+ {
+ // Found a low surrogate.
+ return ((temp1 * 0x400) + temp2 + UNICODE_PLANE01_START);
+ }
+ else
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidHighSurrogate, index), nameof(s));
+ }
+ }
+ else
+ {
+ // Found a high surrogate at the end of the string.
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidHighSurrogate, index), nameof(s));
+ }
+ }
+ else
+ {
+ // Find a low surrogate at the character pointed by index.
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidLowSurrogate, index), nameof(s));
+ }
+ }
+ // Not a high-surrogate or low-surrogate. Genereate the UTF32 value for the BMP characters.
+ return ((int)s[index]);
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/CharEnumerator.cs b/src/mscorlib/shared/System/CharEnumerator.cs
new file mode 100644
index 0000000000..ea9915a7c4
--- /dev/null
+++ b/src/mscorlib/shared/System/CharEnumerator.cs
@@ -0,0 +1,80 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*============================================================
+**
+**
+**
+** Purpose: Enumerates the characters on a string. skips range
+** checks.
+**
+**
+============================================================*/
+
+using System.Collections;
+using System.Collections.Generic;
+
+namespace System
+{
+ public sealed class CharEnumerator : IEnumerator, IEnumerator<char>, IDisposable, ICloneable
+ {
+ private String _str;
+ private int _index;
+ private char _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;
+ }
+ else
+ _index = _str.Length;
+ return false;
+ }
+
+ public void Dispose()
+ {
+ if (_str != null)
+ _index = _str.Length;
+ _str = null;
+ }
+
+ Object IEnumerator.Current
+ {
+ get { return 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;
+ }
+ }
+
+ public void Reset()
+ {
+ _currentElement = (char)0;
+ _index = -1;
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/DictionaryEntry.cs b/src/mscorlib/shared/System/Collections/DictionaryEntry.cs
new file mode 100644
index 0000000000..290306d006
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/DictionaryEntry.cs
@@ -0,0 +1,58 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.ComponentModel;
+
+namespace System.Collections
+{
+ // A DictionaryEntry holds a key and a value from a dictionary.
+ // It is returned by IDictionaryEnumerator::GetEntry().
+ [Serializable]
+ public struct DictionaryEntry
+ {
+ private Object _key;
+ private Object _value;
+
+ // Constructs a new DictionaryEnumerator by setting the Key
+ // and Value fields appropriately.
+ public DictionaryEntry(Object key, Object value)
+ {
+ _key = key;
+ _value = value;
+ }
+
+ public Object Key
+ {
+ get
+ {
+ return _key;
+ }
+
+ set
+ {
+ _key = value;
+ }
+ }
+
+ public Object Value
+ {
+ get
+ {
+ return _value;
+ }
+
+ set
+ {
+ _value = value;
+ }
+ }
+
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public void Deconstruct(out object key, out object value)
+ {
+ key = Key;
+ value = Value;
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/Generic/ICollection.cs b/src/mscorlib/shared/System/Collections/Generic/ICollection.cs
new file mode 100644
index 0000000000..52852aa1fb
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/Generic/ICollection.cs
@@ -0,0 +1,35 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.CompilerServices;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections.Generic
+{
+ // Base interface for all collections, defining enumerators, size, and
+ // synchronization methods.
+ public interface ICollection<T> : IEnumerable<T>
+ {
+ // Number of items in the collections.
+ int Count { get; }
+
+ bool IsReadOnly { get; }
+
+ void Add(T item);
+
+ void Clear();
+
+ bool Contains(T item);
+
+ // CopyTo copies a collection into an Array, starting at a particular
+ // index into the array.
+ //
+ void CopyTo(T[] array, int arrayIndex);
+
+ //void CopyTo(int sourceIndex, T[] destinationArray, int destinationIndex, int count);
+
+ bool Remove(T item);
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/Generic/IComparer.cs b/src/mscorlib/shared/System/Collections/Generic/IComparer.cs
new file mode 100644
index 0000000000..713d499cc8
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/Generic/IComparer.cs
@@ -0,0 +1,20 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+
+namespace System.Collections.Generic
+{
+ // The generic IComparer interface implements a method that compares
+ // two objects. It is used in conjunction with the Sort and
+ // BinarySearch methods on the Array, List, and SortedList classes.
+ public interface IComparer<in T>
+ {
+ // Compares two objects. An implementation of this method must return a
+ // value less than zero if x is less than y, zero if x is equal to y, or a
+ // value greater than zero if x is greater than y.
+ //
+ int Compare(T x, T y);
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/Generic/IDictionary.cs b/src/mscorlib/shared/System/Collections/Generic/IDictionary.cs
new file mode 100644
index 0000000000..a73a2f55bd
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/Generic/IDictionary.cs
@@ -0,0 +1,51 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections.Generic
+{
+ // An IDictionary is a possibly unordered set of key-value pairs.
+ // Keys can be any non-null object. Values can be any object.
+ // You can look up a value in an IDictionary via the default indexed
+ // property, Items.
+ public interface IDictionary<TKey, TValue> : ICollection<KeyValuePair<TKey, TValue>>
+ {
+ // Interfaces are not serializable
+ // The Item property provides methods to read and edit entries
+ // in the Dictionary.
+ TValue this[TKey key]
+ {
+ get;
+ set;
+ }
+
+ // Returns a collections of the keys in this dictionary.
+ ICollection<TKey> Keys
+ {
+ get;
+ }
+
+ // Returns a collections of the values in this dictionary.
+ ICollection<TValue> Values
+ {
+ get;
+ }
+
+ // Returns whether this dictionary contains a particular key.
+ //
+ bool ContainsKey(TKey key);
+
+ // Adds a key-value pair to the dictionary.
+ //
+ void Add(TKey key, TValue value);
+
+ // Removes a particular key from the dictionary.
+ //
+ bool Remove(TKey key);
+
+ bool TryGetValue(TKey key, out TValue value);
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/Generic/IEnumerable.cs b/src/mscorlib/shared/System/Collections/Generic/IEnumerable.cs
new file mode 100644
index 0000000000..84264d5cf0
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/Generic/IEnumerable.cs
@@ -0,0 +1,21 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Collections;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections.Generic
+{
+ // Implement this interface if you need to support foreach semantics.
+ public interface IEnumerable<out T> : IEnumerable
+ {
+ // Returns an IEnumerator for this enumerable Object. The enumerator provides
+ // a simple way to access all the contents of a collection.
+ /// <include file='doc\IEnumerable.uex' path='docs/doc[@for="IEnumerable.GetEnumerator"]/*' />
+ new IEnumerator<T> GetEnumerator();
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/Generic/IEnumerator.cs b/src/mscorlib/shared/System/Collections/Generic/IEnumerator.cs
new file mode 100644
index 0000000000..6360576974
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/Generic/IEnumerator.cs
@@ -0,0 +1,26 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+namespace System.Collections.Generic
+{
+ // Base interface for all generic enumerators, providing a simple approach
+ // to iterating over a collection.
+ public interface IEnumerator<out T> : IDisposable, IEnumerator
+ {
+ // Returns the current element of the enumeration. The returned value is
+ // undefined before the first call to MoveNext and following a
+ // call to MoveNext that returned false. Multiple calls to
+ // GetCurrent with no intervening calls to MoveNext
+ // will return the same object.
+ //
+ /// <include file='doc\IEnumerator.uex' path='docs/doc[@for="IEnumerator.Current"]/*' />
+ new T Current
+ {
+ get;
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/Generic/IEqualityComparer.cs b/src/mscorlib/shared/System/Collections/Generic/IEqualityComparer.cs
new file mode 100644
index 0000000000..543bdb5fce
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/Generic/IEqualityComparer.cs
@@ -0,0 +1,18 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+
+namespace System.Collections.Generic
+{
+ // The generic IEqualityComparer interface implements methods to if check two objects are equal
+ // and generate Hashcode for an object.
+ // It is use in Dictionary class.
+ public interface IEqualityComparer<in T>
+ {
+ bool Equals(T x, T y);
+ int GetHashCode(T obj);
+ }
+}
+
diff --git a/src/mscorlib/shared/System/Collections/Generic/IList.cs b/src/mscorlib/shared/System/Collections/Generic/IList.cs
new file mode 100644
index 0000000000..43d6659da9
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/Generic/IList.cs
@@ -0,0 +1,37 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Collections;
+using System.Runtime.CompilerServices;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections.Generic
+{
+ // An IList is an ordered collection of objects. The exact ordering
+ // is up to the implementation of the list, ranging from a sorted
+ // order to insertion order.
+ public interface IList<T> : ICollection<T>
+ {
+ // The Item property provides methods to read and edit entries in the List.
+ T this[int index]
+ {
+ get;
+ set;
+ }
+
+ // Returns the index of a particular item, if it is in the list.
+ // Returns -1 if the item isn't in the list.
+ int IndexOf(T item);
+
+ // Inserts value into the list at position index.
+ // index must be non-negative and less than or equal to the
+ // number of elements in the list. If index equals the number
+ // of items in the list, then value is appended to the end.
+ void Insert(int index, T item);
+
+ // Removes the item at position index.
+ void RemoveAt(int index);
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/Generic/IReadOnlyCollection.cs b/src/mscorlib/shared/System/Collections/Generic/IReadOnlyCollection.cs
new file mode 100644
index 0000000000..09ee89f035
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/Generic/IReadOnlyCollection.cs
@@ -0,0 +1,16 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Runtime.CompilerServices;
+
+namespace System.Collections.Generic
+{
+ // Provides a read-only, covariant view of a generic list.
+ public interface IReadOnlyCollection<out T> : IEnumerable<T>
+ {
+ int Count { get; }
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/Generic/IReadOnlyDictionary.cs b/src/mscorlib/shared/System/Collections/Generic/IReadOnlyDictionary.cs
new file mode 100644
index 0000000000..169e2958bb
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/Generic/IReadOnlyDictionary.cs
@@ -0,0 +1,20 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections.Generic
+{
+ // Provides a read-only view of a generic dictionary.
+ public interface IReadOnlyDictionary<TKey, TValue> : IReadOnlyCollection<KeyValuePair<TKey, TValue>>
+ {
+ bool ContainsKey(TKey key);
+ bool TryGetValue(TKey key, out TValue value);
+
+ TValue this[TKey key] { get; }
+ IEnumerable<TKey> Keys { get; }
+ IEnumerable<TValue> Values { get; }
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/Generic/IReadOnlyList.cs b/src/mscorlib/shared/System/Collections/Generic/IReadOnlyList.cs
new file mode 100644
index 0000000000..00b5be65ff
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/Generic/IReadOnlyList.cs
@@ -0,0 +1,16 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Runtime.CompilerServices;
+
+namespace System.Collections.Generic
+{
+ // Provides a read-only, covariant view of a generic list.
+ public interface IReadOnlyList<out T> : IReadOnlyCollection<T>
+ {
+ T this[int index] { get; }
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/Generic/KeyNotFoundException.cs b/src/mscorlib/shared/System/Collections/Generic/KeyNotFoundException.cs
new file mode 100644
index 0000000000..1fca7732ae
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/Generic/KeyNotFoundException.cs
@@ -0,0 +1,33 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.Serialization;
+
+namespace System.Collections.Generic
+{
+ [Serializable]
+ public class KeyNotFoundException : SystemException
+ {
+ public KeyNotFoundException()
+ : base(SR.Arg_KeyNotFound)
+ {
+ HResult = __HResults.COR_E_KEYNOTFOUND;
+ }
+
+ public KeyNotFoundException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_KEYNOTFOUND;
+ }
+
+ public KeyNotFoundException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_KEYNOTFOUND;
+ }
+
+ protected KeyNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/Generic/KeyValuePair.cs b/src/mscorlib/shared/System/Collections/Generic/KeyValuePair.cs
new file mode 100644
index 0000000000..fc51af25f8
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/Generic/KeyValuePair.cs
@@ -0,0 +1,82 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.ComponentModel;
+using System.Text;
+
+namespace System.Collections.Generic
+{
+ // Provides the Create factory method for KeyValuePair<TKey, TValue>.
+ public static class KeyValuePair
+ {
+ // Creates a new KeyValuePair<TKey, TValue> from the given values.
+ public static KeyValuePair<TKey, TValue> Create<TKey, TValue>(TKey key, TValue value)
+ {
+ return new KeyValuePair<TKey, TValue>(key, value);
+ }
+
+ /// <summary>
+ /// Used by KeyValuePair.ToString to reduce generic code
+ /// </summary>
+ internal static string PairToString(object key, object value)
+ {
+ StringBuilder s = StringBuilderCache.Acquire();
+ s.Append('[');
+
+ if (key != null)
+ {
+ s.Append(key);
+ }
+
+ s.Append(", ");
+
+ if (value != null)
+ {
+ s.Append(value);
+ }
+
+ s.Append(']');
+
+ return StringBuilderCache.GetStringAndRelease(s);
+ }
+ }
+
+ // A KeyValuePair holds a key and a value from a dictionary.
+ // It is used by the IEnumerable<T> implementation for both IDictionary<TKey, TValue>
+ // and IReadOnlyDictionary<TKey, TValue>.
+ [Serializable]
+ public struct KeyValuePair<TKey, TValue>
+ {
+ private TKey key; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload.
+ private TValue value; // DO NOT change the field name, it's required for compatibility with desktop .NET as it appears in serialization payload.
+
+ public KeyValuePair(TKey key, TValue value)
+ {
+ this.key = key;
+ this.value = value;
+ }
+
+ public TKey Key
+ {
+ get { return key; }
+ }
+
+ public TValue Value
+ {
+ get { return value; }
+ }
+
+ public override string ToString()
+ {
+ return KeyValuePair.PairToString(Key, Value);
+ }
+
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public void Deconstruct(out TKey key, out TValue value)
+ {
+ key = Key;
+ value = Value;
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/ICollection.cs b/src/mscorlib/shared/System/Collections/ICollection.cs
new file mode 100644
index 0000000000..80ea092363
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/ICollection.cs
@@ -0,0 +1,70 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections
+{
+ // Base interface for all collections, defining enumerators, size, and
+ // synchronization methods.
+ public interface ICollection : IEnumerable
+ {
+ // Interfaces are not serialable
+ // CopyTo copies a collection into an Array, starting at a particular
+ // index into the array.
+ //
+ void CopyTo(Array array, int index);
+
+ // Number of items in the collections.
+ int Count
+ { get; }
+
+
+ // SyncRoot will return an Object to use for synchronization
+ // (thread safety). You can use this object in your code to take a
+ // lock on the collection, even if this collection is a wrapper around
+ // another collection. The intent is to tunnel through to a real
+ // implementation of a collection, and use one of the internal objects
+ // found in that code.
+ //
+ // In the absense of a static Synchronized method on a collection,
+ // the expected usage for SyncRoot would look like this:
+ //
+ // ICollection col = ...
+ // lock (col.SyncRoot) {
+ // // Some operation on the collection, which is now thread safe.
+ // // This may include multiple operations.
+ // }
+ //
+ //
+ // The system-provided collections have a static method called
+ // Synchronized which will create a thread-safe wrapper around the
+ // collection. All access to the collection that you want to be
+ // thread-safe should go through that wrapper collection. However, if
+ // you need to do multiple calls on that collection (such as retrieving
+ // two items, or checking the count then doing something), you should
+ // NOT use our thread-safe wrapper since it only takes a lock for the
+ // duration of a single method call. Instead, use Monitor.Enter/Exit
+ // or your language's equivalent to the C# lock keyword as mentioned
+ // above.
+ //
+ // For collections with no publically available underlying store, the
+ // expected implementation is to simply return the this pointer. Note
+ // that the this pointer may not be sufficient for collections that
+ // wrap other collections; those should return the underlying
+ // collection's SyncRoot property.
+ Object SyncRoot
+ { get; }
+
+ // Is this collection synchronized (i.e., thread-safe)? If you want a
+ // thread-safe collection, you can use SyncRoot as an object to
+ // synchronize your collection with. If you're using one of the
+ // collections in System.Collections, you could call the static
+ // Synchronized method to get a thread-safe wrapper around the
+ // underlying collection.
+ bool IsSynchronized
+ { get; }
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/IComparer.cs b/src/mscorlib/shared/System/Collections/IComparer.cs
new file mode 100644
index 0000000000..cef91c3ffa
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/IComparer.cs
@@ -0,0 +1,22 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+
+namespace System.Collections
+{
+ // The IComparer interface implements a method that compares two objects. It is
+ // used in conjunction with the Sort and BinarySearch methods on
+ // the Array and List classes.
+ //
+ // Interfaces are not serializable
+ public interface IComparer
+ {
+ // Compares two objects. An implementation of this method must return a
+ // value less than zero if x is less than y, zero if x is equal to y, or a
+ // value greater than zero if x is greater than y.
+ //
+ int Compare(Object x, Object y);
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/IDictionary.cs b/src/mscorlib/shared/System/Collections/IDictionary.cs
new file mode 100644
index 0000000000..8bc7fcf125
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/IDictionary.cs
@@ -0,0 +1,61 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections
+{
+ // An IDictionary is a possibly unordered set of key-value pairs.
+ // Keys can be any non-null object. Values can be any object.
+ // You can look up a value in an IDictionary via the default indexed
+ // property, Items.
+ public interface IDictionary : ICollection
+ {
+ // Interfaces are not serializable
+ // The Item property provides methods to read and edit entries
+ // in the Dictionary.
+ Object this[Object key]
+ {
+ get;
+ set;
+ }
+
+ // Returns a collections of the keys in this dictionary.
+ ICollection Keys
+ {
+ get;
+ }
+
+ // Returns a collections of the values in this dictionary.
+ ICollection Values
+ {
+ get;
+ }
+
+ // Returns whether this dictionary contains a particular key.
+ //
+ bool Contains(Object key);
+
+ // Adds a key-value pair to the dictionary.
+ //
+ void Add(Object key, Object value);
+
+ // Removes all pairs from the dictionary.
+ void Clear();
+
+ bool IsReadOnly
+ { get; }
+
+ bool IsFixedSize
+ { get; }
+
+ // Returns an IDictionaryEnumerator for this dictionary.
+ new IDictionaryEnumerator GetEnumerator();
+
+ // Removes a particular key from the dictionary.
+ //
+ void Remove(Object key);
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/IDictionaryEnumerator.cs b/src/mscorlib/shared/System/Collections/IDictionaryEnumerator.cs
new file mode 100644
index 0000000000..451cf68976
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/IDictionaryEnumerator.cs
@@ -0,0 +1,68 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.Collections
+{
+ // This interface represents an enumerator that allows sequential access to the
+ // elements of a dictionary. Upon creation, an enumerator is conceptually
+ // positioned before the first element of the enumeration. The first call to the
+ // MoveNext method brings the first element of the enumeration into view,
+ // and each successive call to MoveNext brings the next element into
+ // view until MoveNext returns false, indicating that there are no more
+ // elements to enumerate. Following each call to MoveNext, the
+ // Key and Value methods are used to obtain the key and
+ // value of the element currently in view. The values returned by calls to
+ // Key and Value are undefined before the first call to
+ // MoveNext and following a call to MoveNext that returned false.
+ // Enumerators are typically used in while loops of the form
+ //
+ // IDictionaryEnumerator e = ...;
+ // while (e.MoveNext()) {
+ // Object key = e.Key;
+ // Object value = e.Value;
+ // ...
+ // }
+ //
+ // The IDictionaryEnumerator interface extends the IEnumerator
+ // inerface and can thus be used as a regular enumerator. The Current
+ // method of an IDictionaryEnumerator returns a DictionaryEntry containing
+ // the current key and value pair. However, the GetEntry method will
+ // return the same DictionaryEntry and avoids boxing the DictionaryEntry (boxing
+ // is somewhat expensive).
+ //
+ public interface IDictionaryEnumerator : IEnumerator
+ {
+ // Returns the key of the current element of the enumeration. The returned
+ // value is undefined before the first call to GetNext and following
+ // a call to GetNext that returned false. Multiple calls to
+ // GetKey with no intervening calls to GetNext will return
+ // the same object.
+ //
+ Object Key
+ {
+ get;
+ }
+
+ // Returns the value of the current element of the enumeration. The
+ // returned value is undefined before the first call to GetNext and
+ // following a call to GetNext that returned false. Multiple calls
+ // to GetValue with no intervening calls to GetNext will
+ // return the same object.
+ //
+ Object Value
+ {
+ get;
+ }
+
+ // GetBlock will copy dictionary values into the given Array. It will either
+ // fill up the array, or if there aren't enough elements, it will
+ // copy as much as possible into the Array. The number of elements
+ // copied is returned.
+ //
+ DictionaryEntry Entry
+ {
+ get;
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/IEnumerable.cs b/src/mscorlib/shared/System/Collections/IEnumerable.cs
new file mode 100644
index 0000000000..91aec62423
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/IEnumerable.cs
@@ -0,0 +1,18 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Runtime.InteropServices;
+
+namespace System.Collections
+{
+ public interface IEnumerable
+ {
+ // Returns an IEnumerator for this enumerable Object. The enumerator provides
+ // a simple way to access all the contents of a collection.
+ [Pure]
+ IEnumerator GetEnumerator();
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/IEnumerator.cs b/src/mscorlib/shared/System/Collections/IEnumerator.cs
new file mode 100644
index 0000000000..2c2c2e4a97
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/IEnumerator.cs
@@ -0,0 +1,41 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Runtime.InteropServices;
+
+namespace System.Collections
+{
+ // Base interface for all enumerators, providing a simple approach
+ // to iterating over a collection.
+ public interface IEnumerator
+ {
+ // Advances the enumerator to the next element of the enumeration and
+ // returns a boolean indicating whether an element is available. Upon
+ // creation, an enumerator is conceptually positioned before the first
+ // element of the enumeration, and the first call to MoveNext
+ // brings the first element of the enumeration into view.
+ //
+ bool MoveNext();
+
+ // Returns the current element of the enumeration. The returned value is
+ // undefined before the first call to MoveNext and following a
+ // call to MoveNext that returned false. Multiple calls to
+ // GetCurrent with no intervening calls to MoveNext
+ // will return the same object.
+ //
+ Object Current
+ {
+ get;
+ }
+
+ // Resets the enumerator to the beginning of the enumeration, starting over.
+ // The preferred behavior for Reset is to return the exact same enumeration.
+ // This means if you modify the underlying collection then call Reset, your
+ // IEnumerator will be invalid, just as it would have been if you had called
+ // MoveNext or Current.
+ //
+ void Reset();
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/IEqualityComparer.cs b/src/mscorlib/shared/System/Collections/IEqualityComparer.cs
new file mode 100644
index 0000000000..35513f577d
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/IEqualityComparer.cs
@@ -0,0 +1,16 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+
+namespace System.Collections
+{
+ // An IEqualityComparer is a mechanism to consume custom performant comparison infrastructure
+ // that can be consumed by some of the common collections.
+ public interface IEqualityComparer
+ {
+ bool Equals(Object x, Object y);
+ int GetHashCode(Object obj);
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/IList.cs b/src/mscorlib/shared/System/Collections/IList.cs
new file mode 100644
index 0000000000..bb2e221cc1
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/IList.cs
@@ -0,0 +1,60 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics.Contracts;
+
+namespace System.Collections
+{
+ // An IList is an ordered collection of objects. The exact ordering
+ // is up to the implementation of the list, ranging from a sorted
+ // order to insertion order.
+ public interface IList : ICollection
+ {
+ // The Item property provides methods to read and edit entries in the List.
+ Object this[int index]
+ {
+ get;
+ set;
+ }
+
+ // Adds an item to the list. The exact position in the list is
+ // implementation-dependent, so while ArrayList may always insert
+ // in the last available location, a SortedList most likely would not.
+ // The return value is the position the new element was inserted in.
+ int Add(Object value);
+
+ // Returns whether the list contains a particular item.
+ bool Contains(Object value);
+
+ // Removes all items from the list.
+ void Clear();
+
+ bool IsReadOnly
+ { get; }
+
+
+ bool IsFixedSize
+ {
+ get;
+ }
+
+
+ // Returns the index of a particular item, if it is in the list.
+ // Returns -1 if the item isn't in the list.
+ int IndexOf(Object value);
+
+ // Inserts value into the list at position index.
+ // index must be non-negative and less than or equal to the
+ // number of elements in the list. If index equals the number
+ // of items in the list, then value is appended to the end.
+ void Insert(int index, Object value);
+
+ // Removes an item from the list.
+ void Remove(Object value);
+
+ // Removes the item at position index.
+ void RemoveAt(int index);
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/IStructuralComparable.cs b/src/mscorlib/shared/System/Collections/IStructuralComparable.cs
new file mode 100644
index 0000000000..a5e4834b9b
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/IStructuralComparable.cs
@@ -0,0 +1,13 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+
+namespace System.Collections
+{
+ public interface IStructuralComparable
+ {
+ Int32 CompareTo(Object other, IComparer comparer);
+ }
+}
diff --git a/src/mscorlib/shared/System/Collections/IStructuralEquatable.cs b/src/mscorlib/shared/System/Collections/IStructuralEquatable.cs
new file mode 100644
index 0000000000..4e61d5e75f
--- /dev/null
+++ b/src/mscorlib/shared/System/Collections/IStructuralEquatable.cs
@@ -0,0 +1,12 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.Collections
+{
+ public interface IStructuralEquatable
+ {
+ Boolean Equals(Object other, IEqualityComparer comparer);
+ int GetHashCode(IEqualityComparer comparer);
+ }
+}
diff --git a/src/mscorlib/shared/System/ComponentModel/DefaultValueAttribute.cs b/src/mscorlib/shared/System/ComponentModel/DefaultValueAttribute.cs
new file mode 100644
index 0000000000..3cdc907297
--- /dev/null
+++ b/src/mscorlib/shared/System/ComponentModel/DefaultValueAttribute.cs
@@ -0,0 +1,228 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.ComponentModel;
+using System.Diagnostics;
+using System.Globalization;
+using System.Runtime.InteropServices;
+
+namespace System.ComponentModel
+{
+ /// <devdoc>
+ /// <para>Specifies the default value for a property.</para>
+ /// </devdoc>
+ [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")]
+ [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes")]
+ [AttributeUsage(AttributeTargets.All)]
+ public class DefaultValueAttribute : Attribute
+ {
+ /// <devdoc>
+ /// This is the default value.
+ /// </devdoc>
+ private object _value;
+
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class, converting the
+ /// specified value to the
+ /// specified type, and using the U.S. English culture as the
+ /// translation
+ /// context.</para>
+ /// </devdoc>
+ public DefaultValueAttribute(Type type, string value)
+ {
+ // The try/catch here is because attributes should never throw exceptions. We would fail to
+ // load an otherwise normal class.
+ try
+ {
+ if (type.IsSubclassOf(typeof(Enum)))
+ {
+ _value = Enum.Parse(type, value, true);
+ }
+ else if (type == typeof(TimeSpan))
+ {
+ _value = TimeSpan.Parse(value);
+ }
+ else
+ {
+ _value = Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
+ }
+ }
+ catch
+ {
+ }
+ }
+
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a Unicode
+ /// character.</para>
+ /// </devdoc>
+ public DefaultValueAttribute(char value)
+ {
+ _value = value;
+ }
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using an 8-bit unsigned
+ /// integer.</para>
+ /// </devdoc>
+ public DefaultValueAttribute(byte value)
+ {
+ _value = value;
+ }
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a 16-bit signed
+ /// integer.</para>
+ /// </devdoc>
+ public DefaultValueAttribute(short value)
+ {
+ _value = value;
+ }
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a 32-bit signed
+ /// integer.</para>
+ /// </devdoc>
+ public DefaultValueAttribute(int value)
+ {
+ _value = value;
+ }
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a 64-bit signed
+ /// integer.</para>
+ /// </devdoc>
+ public DefaultValueAttribute(long value)
+ {
+ _value = value;
+ }
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a
+ /// single-precision floating point
+ /// number.</para>
+ /// </devdoc>
+ public DefaultValueAttribute(float value)
+ {
+ _value = value;
+ }
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a
+ /// double-precision floating point
+ /// number.</para>
+ /// </devdoc>
+ public DefaultValueAttribute(double value)
+ {
+ _value = value;
+ }
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.Boolean'/>
+ /// value.</para>
+ /// </devdoc>
+ public DefaultValueAttribute(bool value)
+ {
+ _value = value;
+ }
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.String'/>.</para>
+ /// </devdoc>
+ public DefaultValueAttribute(string value)
+ {
+ _value = value;
+ }
+
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/>
+ /// class.</para>
+ /// </devdoc>
+ public DefaultValueAttribute(object value)
+ {
+ _value = value;
+ }
+
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.SByte'/>
+ /// value.</para>
+ /// </devdoc>
+ [CLSCompliant(false)]
+ public DefaultValueAttribute(sbyte value)
+ {
+ _value = value;
+ }
+
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.UInt16'/>
+ /// value.</para>
+ /// </devdoc>
+ [CLSCompliant(false)]
+ public DefaultValueAttribute(ushort value)
+ {
+ _value = value;
+ }
+
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.UInt32'/>
+ /// value.</para>
+ /// </devdoc>
+ [CLSCompliant(false)]
+ public DefaultValueAttribute(uint value)
+ {
+ _value = value;
+ }
+
+ /// <devdoc>
+ /// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.UInt64'/>
+ /// value.</para>
+ /// </devdoc>
+ [CLSCompliant(false)]
+ public DefaultValueAttribute(ulong value)
+ {
+ _value = value;
+ }
+
+ /// <devdoc>
+ /// <para>
+ /// Gets the default value of the property this
+ /// attribute is
+ /// bound to.
+ /// </para>
+ /// </devdoc>
+ public virtual object Value
+ {
+ get
+ {
+ return _value;
+ }
+ }
+
+ public override bool Equals(object obj)
+ {
+ if (obj == this)
+ {
+ return true;
+ }
+
+ DefaultValueAttribute other = obj as DefaultValueAttribute;
+
+ if (other != null)
+ {
+ if (Value != null)
+ {
+ return Value.Equals(other.Value);
+ }
+ else
+ {
+ return (other.Value == null);
+ }
+ }
+ return false;
+ }
+
+ public override int GetHashCode()
+ {
+ return base.GetHashCode();
+ }
+
+ protected void SetValue(object value)
+ {
+ _value = value;
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/ComponentModel/EditorBrowsableAttribute.cs b/src/mscorlib/shared/System/ComponentModel/EditorBrowsableAttribute.cs
new file mode 100644
index 0000000000..9b4d6e626e
--- /dev/null
+++ b/src/mscorlib/shared/System/ComponentModel/EditorBrowsableAttribute.cs
@@ -0,0 +1,48 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.ComponentModel
+{
+ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Interface)]
+ public sealed class EditorBrowsableAttribute : Attribute
+ {
+ private EditorBrowsableState browsableState;
+
+ public EditorBrowsableAttribute(EditorBrowsableState state)
+ {
+ browsableState = state;
+ }
+
+ public EditorBrowsableAttribute() : this(EditorBrowsableState.Always) { }
+
+ public EditorBrowsableState State
+ {
+ get { return browsableState; }
+ }
+
+ public override bool Equals(object obj)
+ {
+ if (obj == this)
+ {
+ return true;
+ }
+
+ EditorBrowsableAttribute other = obj as EditorBrowsableAttribute;
+
+ return (other != null) && other.browsableState == browsableState;
+ }
+
+ public override int GetHashCode()
+ {
+ return base.GetHashCode();
+ }
+ }
+
+ public enum EditorBrowsableState
+ {
+ Always,
+ Never,
+ Advanced
+ }
+}
diff --git a/src/mscorlib/shared/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs b/src/mscorlib/shared/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs
new file mode 100644
index 0000000000..aca8da5932
--- /dev/null
+++ b/src/mscorlib/shared/System/Configuration/Assemblies/AssemblyHashAlgorithm.cs
@@ -0,0 +1,16 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.Configuration.Assemblies
+{
+ public enum AssemblyHashAlgorithm
+ {
+ None = 0,
+ MD5 = 0x8003,
+ SHA1 = 0x8004,
+ SHA256 = 0x800c,
+ SHA384 = 0x800d,
+ SHA512 = 0x800e,
+ }
+}
diff --git a/src/mscorlib/shared/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs b/src/mscorlib/shared/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs
new file mode 100644
index 0000000000..ef7b3eb45f
--- /dev/null
+++ b/src/mscorlib/shared/System/Configuration/Assemblies/AssemblyVersionCompatibility.cs
@@ -0,0 +1,13 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+namespace System.Configuration.Assemblies
+{
+ public enum AssemblyVersionCompatibility
+ {
+ SameMachine = 1,
+ SameProcess = 2,
+ SameDomain = 3,
+ }
+}
diff --git a/src/mscorlib/shared/System/Convert.cs b/src/mscorlib/shared/System/Convert.cs
new file mode 100644
index 0000000000..576f78f1f1
--- /dev/null
+++ b/src/mscorlib/shared/System/Convert.cs
@@ -0,0 +1,3031 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Globalization;
+using System.Threading;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using System.Security;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
+ [Flags]
+ public enum Base64FormattingOptions
+ {
+ None = 0,
+ InsertLineBreaks = 1
+ }
+
+ // Returns the type code of this object. An implementation of this method
+ // must not return TypeCode.Empty (which represents a null reference) or
+ // TypeCode.Object (which represents an object that doesn't implement the
+ // IConvertible interface). An implementation of this method should return
+ // TypeCode.DBNull if the value of this object is a database null. For
+ // example, a nullable integer type should return TypeCode.DBNull if the
+ // value of the object is the database null. Otherwise, an implementation
+ // of this method should return the TypeCode that best describes the
+ // internal representation of the object.
+ // The Value class provides conversion and querying methods for values. The
+ // Value class contains static members only, and it is not possible to create
+ // instances of the class.
+ //
+ // The statically typed conversion methods provided by the Value class are all
+ // of the form:
+ //
+ // public static XXX ToXXX(YYY value)
+ //
+ // where XXX is the target type and YYY is the source type. The matrix below
+ // shows the set of supported conversions. The set of conversions is symmetric
+ // such that for every ToXXX(YYY) there is also a ToYYY(XXX).
+ //
+ // From: To: Bol Chr SBy Byt I16 U16 I32 U32 I64 U64 Sgl Dbl Dec Dat Str
+ // ----------------------------------------------------------------------
+ // Boolean x x x x x x x x x x x x x
+ // Char x x x x x x x x x x
+ // SByte x x x x x x x x x x x x x x
+ // Byte x x x x x x x x x x x x x x
+ // Int16 x x x x x x x x x x x x x x
+ // UInt16 x x x x x x x x x x x x x x
+ // Int32 x x x x x x x x x x x x x x
+ // UInt32 x x x x x x x x x x x x x x
+ // Int64 x x x x x x x x x x x x x x
+ // UInt64 x x x x x x x x x x x x x x
+ // Single x x x x x x x x x x x x x
+ // Double x x x x x x x x x x x x x
+ // Decimal x x x x x x x x x x x x x
+ // DateTime x x
+ // String x x x x x x x x x x x x x x x
+ // ----------------------------------------------------------------------
+ //
+ // For dynamic conversions, the Value class provides a set of methods of the
+ // form:
+ //
+ // public static XXX ToXXX(object value)
+ //
+ // where XXX is the target type (Boolean, Char, SByte, Byte, Int16, UInt16,
+ // Int32, UInt32, Int64, UInt64, Single, Double, Decimal, DateTime,
+ // or String). The implementations of these methods all take the form:
+ //
+ // public static XXX toXXX(object value) {
+ // return value == null? XXX.Default: ((IConvertible)value).ToXXX();
+ // }
+ //
+ // The code first checks if the given value is a null reference (which is the
+ // same as Value.Empty), in which case it returns the default value for type
+ // XXX. Otherwise, a cast to IConvertible is performed, and the appropriate ToXXX()
+ // method is invoked on the object. An InvalidCastException is thrown if the
+ // cast to IConvertible fails, and that exception is simply allowed to propagate out
+ // of the conversion method.
+
+ // Constant representing the database null value. This value is used in
+ // database applications to indicate the absense of a known value. Note
+ // that Value.DBNull is NOT the same as a null object reference, which is
+ // represented by Value.Empty.
+ //
+ // The Equals() method of DBNull always returns false, even when the
+ // argument is itself DBNull.
+ //
+ // When passed Value.DBNull, the Value.GetTypeCode() method returns
+ // TypeCode.DBNull.
+ //
+ // When passed Value.DBNull, the Value.ToXXX() methods all throw an
+ // InvalidCastException.
+
+ public static class Convert
+ {
+ //A typeof operation is fairly expensive (does a system call), so we'll cache these here
+ //statically. These are exactly lined up with the TypeCode, eg. ConvertType[TypeCode.Int16]
+ //will give you the type of an Int16.
+ internal static readonly Type[] ConvertTypes = {
+ typeof(System.Empty),
+ typeof(Object),
+ typeof(System.DBNull),
+ typeof(Boolean),
+ typeof(Char),
+ typeof(SByte),
+ typeof(Byte),
+ typeof(Int16),
+ typeof(UInt16),
+ typeof(Int32),
+ typeof(UInt32),
+ typeof(Int64),
+ typeof(UInt64),
+ typeof(Single),
+ typeof(Double),
+ typeof(Decimal),
+ typeof(DateTime),
+ typeof(Object), //TypeCode is discontinuous so we need a placeholder.
+ typeof(String)
+ };
+
+ // Need to special case Enum because typecode will be underlying type, e.g. Int32
+ private static readonly Type EnumType = typeof(Enum);
+
+ internal static readonly char[] base64Table = {'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','+','/','=' };
+
+ private const Int32 base64LineBreakPosition = 76;
+
+#if _DEBUG
+ private static bool TriggerAsserts = DoAsserts();
+ private static bool DoAsserts()
+ {
+ Debug.Assert(ConvertTypes != null, "[Convert.cctor]ConvertTypes!=null");
+ Debug.Assert(ConvertTypes.Length == ((int)TypeCode.String + 1), "[Convert.cctor]ConvertTypes.Length == ((int)TypeCode.String + 1)");
+ Debug.Assert(ConvertTypes[(int)TypeCode.Empty] == typeof(System.Empty),
+ "[Convert.cctor]ConvertTypes[(int)TypeCode.Empty]==typeof(System.Empty)");
+ Debug.Assert(ConvertTypes[(int)TypeCode.String] == typeof(String),
+ "[Convert.cctor]ConvertTypes[(int)TypeCode.String]==typeof(System.String)");
+ Debug.Assert(ConvertTypes[(int)TypeCode.Int32] == typeof(int),
+ "[Convert.cctor]ConvertTypes[(int)TypeCode.Int32]==typeof(int)");
+ return true;
+ }
+#endif
+
+ public static readonly Object DBNull = System.DBNull.Value;
+
+ // Returns the type code for the given object. If the argument is null,
+ // the result is TypeCode.Empty. If the argument is not a value (i.e. if
+ // the object does not implement IConvertible), the result is TypeCode.Object.
+ // Otherwise, the result is the type code of the object, as determined by
+ // the object's implementation of IConvertible.
+ [Pure]
+ public static TypeCode GetTypeCode(object value)
+ {
+ if (value == null) return TypeCode.Empty;
+ IConvertible temp = value as IConvertible;
+ if (temp != null)
+ {
+ return temp.GetTypeCode();
+ }
+ return TypeCode.Object;
+ }
+
+ // Returns true if the given object is a database null. This operation
+ // corresponds to "value.GetTypeCode() == TypeCode.DBNull".
+ [Pure]
+ public static bool IsDBNull(object value)
+ {
+ if (value == System.DBNull.Value) return true;
+ IConvertible convertible = value as IConvertible;
+ return convertible != null ? convertible.GetTypeCode() == TypeCode.DBNull : false;
+ }
+
+ // Converts the given object to the given type. In general, this method is
+ // equivalent to calling the Value.ToXXX(value) method for the given
+ // typeCode and boxing the result.
+ //
+ // The method first checks if the given object implements IConvertible. If not,
+ // the only permitted conversion is from a null to TypeCode.Empty, the
+ // result of which is null.
+ //
+ // If the object does implement IConvertible, a check is made to see if the
+ // object already has the given type code, in which case the object is
+ // simply returned. Otherwise, the appropriate ToXXX() is invoked on the
+ // object's implementation of IConvertible.
+ public static Object ChangeType(Object value, TypeCode typeCode)
+ {
+ return ChangeType(value, typeCode, CultureInfo.CurrentCulture);
+ }
+
+ public static Object ChangeType(Object value, TypeCode typeCode, IFormatProvider provider)
+ {
+ if (value == null && (typeCode == TypeCode.Empty || typeCode == TypeCode.String || typeCode == TypeCode.Object))
+ {
+ return null;
+ }
+
+ IConvertible v = value as IConvertible;
+ if (v == null)
+ {
+ throw new InvalidCastException(SR.InvalidCast_IConvertible);
+ }
+
+ // This line is invalid for things like Enums that return a TypeCode
+ // of Int32, but the object can't actually be cast to an Int32.
+ // if (v.GetTypeCode() == typeCode) return value;
+ switch (typeCode)
+ {
+ case TypeCode.Boolean:
+ return v.ToBoolean(provider);
+ case TypeCode.Char:
+ return v.ToChar(provider);
+ case TypeCode.SByte:
+ return v.ToSByte(provider);
+ case TypeCode.Byte:
+ return v.ToByte(provider);
+ case TypeCode.Int16:
+ return v.ToInt16(provider);
+ case TypeCode.UInt16:
+ return v.ToUInt16(provider);
+ case TypeCode.Int32:
+ return v.ToInt32(provider);
+ case TypeCode.UInt32:
+ return v.ToUInt32(provider);
+ case TypeCode.Int64:
+ return v.ToInt64(provider);
+ case TypeCode.UInt64:
+ return v.ToUInt64(provider);
+ case TypeCode.Single:
+ return v.ToSingle(provider);
+ case TypeCode.Double:
+ return v.ToDouble(provider);
+ case TypeCode.Decimal:
+ return v.ToDecimal(provider);
+ case TypeCode.DateTime:
+ return v.ToDateTime(provider);
+ case TypeCode.String:
+ return v.ToString(provider);
+ case TypeCode.Object:
+ return value;
+ case TypeCode.DBNull:
+ throw new InvalidCastException(SR.InvalidCast_DBNull);
+ case TypeCode.Empty:
+ throw new InvalidCastException(SR.InvalidCast_Empty);
+ default:
+ throw new ArgumentException(SR.Arg_UnknownTypeCode);
+ }
+ }
+
+ internal static Object DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
+ {
+ Debug.Assert(value != null, "[Convert.DefaultToType]value!=null");
+ if (targetType == null)
+ {
+ throw new ArgumentNullException(nameof(targetType));
+ }
+ Contract.EndContractBlock();
+
+ if (ReferenceEquals(value.GetType(), targetType))
+ {
+ return value;
+ }
+
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Boolean]))
+ return value.ToBoolean(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Char]))
+ return value.ToChar(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.SByte]))
+ return value.ToSByte(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Byte]))
+ return value.ToByte(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Int16]))
+ return value.ToInt16(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.UInt16]))
+ return value.ToUInt16(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Int32]))
+ return value.ToInt32(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.UInt32]))
+ return value.ToUInt32(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Int64]))
+ return value.ToInt64(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.UInt64]))
+ return value.ToUInt64(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Single]))
+ return value.ToSingle(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Double]))
+ return value.ToDouble(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Decimal]))
+ return value.ToDecimal(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.DateTime]))
+ return value.ToDateTime(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.String]))
+ return value.ToString(provider);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Object]))
+ return (Object)value;
+ // Need to special case Enum because typecode will be underlying type, e.g. Int32
+ if (ReferenceEquals(targetType, EnumType))
+ return (Enum)value;
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.DBNull]))
+ throw new InvalidCastException(SR.InvalidCast_DBNull);
+ if (ReferenceEquals(targetType, ConvertTypes[(int)TypeCode.Empty]))
+ throw new InvalidCastException(SR.InvalidCast_Empty);
+
+ throw new InvalidCastException(string.Format(SR.InvalidCast_FromTo, value.GetType().FullName, targetType.FullName));
+ }
+
+ public static Object ChangeType(Object value, Type conversionType)
+ {
+ return ChangeType(value, conversionType, CultureInfo.CurrentCulture);
+ }
+
+ public static Object ChangeType(Object value, Type conversionType, IFormatProvider provider)
+ {
+ if (ReferenceEquals(conversionType, null))
+ {
+ throw new ArgumentNullException(nameof(conversionType));
+ }
+ Contract.EndContractBlock();
+
+ if (value == null)
+ {
+ if (conversionType.IsValueType)
+ {
+ throw new InvalidCastException(SR.InvalidCast_CannotCastNullToValueType);
+ }
+ return null;
+ }
+
+ IConvertible ic = value as IConvertible;
+ if (ic == null)
+ {
+ if (value.GetType() == conversionType)
+ {
+ return value;
+ }
+ throw new InvalidCastException(SR.InvalidCast_IConvertible);
+ }
+
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Boolean]))
+ return ic.ToBoolean(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Char]))
+ return ic.ToChar(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.SByte]))
+ return ic.ToSByte(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Byte]))
+ return ic.ToByte(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Int16]))
+ return ic.ToInt16(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.UInt16]))
+ return ic.ToUInt16(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Int32]))
+ return ic.ToInt32(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.UInt32]))
+ return ic.ToUInt32(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Int64]))
+ return ic.ToInt64(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.UInt64]))
+ return ic.ToUInt64(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Single]))
+ return ic.ToSingle(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Double]))
+ return ic.ToDouble(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Decimal]))
+ return ic.ToDecimal(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.DateTime]))
+ return ic.ToDateTime(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.String]))
+ return ic.ToString(provider);
+ if (ReferenceEquals(conversionType, ConvertTypes[(int)TypeCode.Object]))
+ return (Object)value;
+
+ return ic.ToType(conversionType, provider);
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void ThrowCharOverflowException() { throw new OverflowException(SR.Overflow_Char); }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void ThrowByteOverflowException() { throw new OverflowException(SR.Overflow_Byte); }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void ThrowSByteOverflowException() { throw new OverflowException(SR.Overflow_SByte); }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void ThrowInt16OverflowException() { throw new OverflowException(SR.Overflow_Int16); }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void ThrowUInt16OverflowException() { throw new OverflowException(SR.Overflow_UInt16); }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void ThrowInt32OverflowException() { throw new OverflowException(SR.Overflow_Int32); }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void ThrowUInt32OverflowException() { throw new OverflowException(SR.Overflow_UInt32); }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void ThrowInt64OverflowException() { throw new OverflowException(SR.Overflow_Int64); }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void ThrowUInt64OverflowException() { throw new OverflowException(SR.Overflow_UInt64); }
+
+ // Conversions to Boolean
+ public static bool ToBoolean(Object value)
+ {
+ return value == null ? false : ((IConvertible)value).ToBoolean(null);
+ }
+
+ public static bool ToBoolean(Object value, IFormatProvider provider)
+ {
+ return value == null ? false : ((IConvertible)value).ToBoolean(provider);
+ }
+
+
+ public static bool ToBoolean(bool value)
+ {
+ return value;
+ }
+
+ [CLSCompliant(false)]
+ public static bool ToBoolean(sbyte value)
+ {
+ return value != 0;
+ }
+
+ // To be consistent with IConvertible in the base data types else we get different semantics
+ // with widening operations. Without this operator this widen succeeds,with this API the widening throws.
+ public static bool ToBoolean(char value)
+ {
+ return ((IConvertible)value).ToBoolean(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(String value)
+ {
+ if (value == null)
+ return false;
+ return Boolean.Parse(value);
+ }
+
+ public static bool ToBoolean(String value, IFormatProvider provider)
+ {
+ if (value == null)
+ return false;
+ return Boolean.Parse(value);
+ }
+
+ public static bool ToBoolean(float value)
+ {
+ return value != 0;
+ }
+
+ public static bool ToBoolean(double value)
+ {
+ return value != 0;
+ }
+
+ public static bool ToBoolean(decimal value)
+ {
+ return value != 0;
+ }
+
+ public static bool ToBoolean(DateTime value)
+ {
+ return ((IConvertible)value).ToBoolean(null);
+ }
+
+ // Disallowed conversions to Boolean
+ // public static bool ToBoolean(TimeSpan value)
+
+ // Conversions to Char
+
+
+ public static char ToChar(object value)
+ {
+ return value == null ? (char)0 : ((IConvertible)value).ToChar(null);
+ }
+
+ public static char ToChar(object value, IFormatProvider provider)
+ {
+ return value == null ? (char)0 : ((IConvertible)value).ToChar(provider);
+ }
+
+ public static char ToChar(bool value)
+ {
+ return ((IConvertible)value).ToChar(null);
+ }
+
+ public static char ToChar(char value)
+ {
+ return value;
+ }
+
+ [CLSCompliant(false)]
+ public static char ToChar(sbyte value)
+ {
+ if (value < 0) ThrowCharOverflowException();
+ Contract.EndContractBlock();
+ return (char)value;
+ }
+
+ public static char ToChar(byte value)
+ {
+ return (char)value;
+ }
+
+ public static char ToChar(short value)
+ {
+ if (value < 0) ThrowCharOverflowException();
+ Contract.EndContractBlock();
+ return (char)value;
+ }
+
+ [CLSCompliant(false)]
+ public static char ToChar(ushort value)
+ {
+ return (char)value;
+ }
+
+ public static char ToChar(int value)
+ {
+ if (value < 0 || value > Char.MaxValue) ThrowCharOverflowException();
+ Contract.EndContractBlock();
+ return (char)value;
+ }
+
+ [CLSCompliant(false)]
+ public static char ToChar(uint value)
+ {
+ if (value > Char.MaxValue) ThrowCharOverflowException();
+ Contract.EndContractBlock();
+ return (char)value;
+ }
+
+ public static char ToChar(long value)
+ {
+ if (value < 0 || value > Char.MaxValue) ThrowCharOverflowException();
+ Contract.EndContractBlock();
+ return (char)value;
+ }
+
+ [CLSCompliant(false)]
+ public static char ToChar(ulong value)
+ {
+ if (value > Char.MaxValue) ThrowCharOverflowException();
+ Contract.EndContractBlock();
+ return (char)value;
+ }
+
+ //
+ // @VariantSwitch
+ // Remove FormatExceptions;
+ //
+ public static char ToChar(String value)
+ {
+ return ToChar(value, null);
+ }
+
+ public static char ToChar(String value, IFormatProvider provider)
+ {
+ if (value == null)
+ throw new ArgumentNullException(nameof(value));
+ Contract.EndContractBlock();
+
+ if (value.Length != 1)
+ throw new FormatException(SR.Format_NeedSingleChar);
+
+ return value[0];
+ }
+
+ // To be consistent with IConvertible in the base data types else we get different semantics
+ // with widening operations. Without this operator this widen succeeds,with this API the widening throws.
+ public static char ToChar(float value)
+ {
+ return ((IConvertible)value).ToChar(null);
+ }
+
+ // To be consistent with IConvertible in the base data types else we get different semantics
+ // with widening operations. Without this operator this widen succeeds,with this API the widening throws.
+ public static char ToChar(double value)
+ {
+ return ((IConvertible)value).ToChar(null);
+ }
+
+ // To be consistent with IConvertible in the base data types else we get different semantics
+ // with widening operations. Without this operator this widen succeeds,with this API the widening throws.
+ public static char ToChar(decimal value)
+ {
+ return ((IConvertible)value).ToChar(null);
+ }
+
+ public static char ToChar(DateTime value)
+ {
+ return ((IConvertible)value).ToChar(null);
+ }
+
+
+ // Disallowed conversions to Char
+ // public static char ToChar(TimeSpan value)
+
+ // Conversions to SByte
+
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(object value)
+ {
+ return value == null ? (sbyte)0 : ((IConvertible)value).ToSByte(null);
+ }
+
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(object value, IFormatProvider provider)
+ {
+ return value == null ? (sbyte)0 : ((IConvertible)value).ToSByte(provider);
+ }
+
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(bool value)
+ {
+ return value ? (sbyte)Boolean.True : (sbyte)Boolean.False;
+ }
+
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(sbyte value)
+ {
+ return value;
+ }
+
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(char value)
+ {
+ if (value > SByte.MaxValue) ThrowSByteOverflowException();
+ Contract.EndContractBlock();
+ return (sbyte)value;
+ }
+
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(byte value)
+ {
+ if (value > SByte.MaxValue) ThrowSByteOverflowException();
+ Contract.EndContractBlock();
+ return (sbyte)value;
+ }
+
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(short value)
+ {
+ if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException();
+ Contract.EndContractBlock();
+ return (sbyte)value;
+ }
+
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(ushort value)
+ {
+ if (value > SByte.MaxValue) ThrowSByteOverflowException();
+ Contract.EndContractBlock();
+ return (sbyte)value;
+ }
+
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(int value)
+ {
+ if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException();
+ Contract.EndContractBlock();
+ return (sbyte)value;
+ }
+
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(uint value)
+ {
+ if (value > SByte.MaxValue) ThrowSByteOverflowException();
+ Contract.EndContractBlock();
+ return (sbyte)value;
+ }
+
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(long value)
+ {
+ if (value < SByte.MinValue || value > SByte.MaxValue) ThrowSByteOverflowException();
+ Contract.EndContractBlock();
+ return (sbyte)value;
+ }
+
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(ulong value)
+ {
+ if (value > (ulong)SByte.MaxValue) ThrowSByteOverflowException();
+ Contract.EndContractBlock();
+ 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, CultureInfo.CurrentCulture);
+ }
+
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(String value, IFormatProvider provider)
+ {
+ return SByte.Parse(value, NumberStyles.Integer, provider);
+ }
+
+ [CLSCompliant(false)]
+ public static sbyte ToSByte(DateTime value)
+ {
+ return ((IConvertible)value).ToSByte(null);
+ }
+
+ // Disallowed conversions to SByte
+ // public static sbyte ToSByte(TimeSpan value)
+
+ // Conversions to Byte
+
+ public static byte ToByte(object value)
+ {
+ return value == null ? (byte)0 : ((IConvertible)value).ToByte(null);
+ }
+
+ public static byte ToByte(object value, IFormatProvider provider)
+ {
+ return value == null ? (byte)0 : ((IConvertible)value).ToByte(provider);
+ }
+
+ public static byte ToByte(bool value)
+ {
+ return value ? (byte)Boolean.True : (byte)Boolean.False;
+ }
+
+ public static byte ToByte(byte value)
+ {
+ return value;
+ }
+
+ public static byte ToByte(char value)
+ {
+ if (value > Byte.MaxValue) ThrowByteOverflowException();
+ Contract.EndContractBlock();
+ return (byte)value;
+ }
+
+ [CLSCompliant(false)]
+ public static byte ToByte(sbyte value)
+ {
+ if (value < Byte.MinValue) ThrowByteOverflowException();
+ Contract.EndContractBlock();
+ return (byte)value;
+ }
+
+ public static byte ToByte(short value)
+ {
+ if (value < Byte.MinValue || value > Byte.MaxValue) ThrowByteOverflowException();
+ Contract.EndContractBlock();
+ return (byte)value;
+ }
+
+ [CLSCompliant(false)]
+ public static byte ToByte(ushort value)
+ {
+ if (value > Byte.MaxValue) ThrowByteOverflowException();
+ Contract.EndContractBlock();
+ return (byte)value;
+ }
+
+ public static byte ToByte(int value)
+ {
+ if (value < Byte.MinValue || value > Byte.MaxValue) ThrowByteOverflowException();
+ Contract.EndContractBlock();
+ return (byte)value;
+ }
+
+ [CLSCompliant(false)]
+ public static byte ToByte(uint value)
+ {
+ if (value > Byte.MaxValue) ThrowByteOverflowException();
+ Contract.EndContractBlock();
+ return (byte)value;
+ }
+
+ public static byte ToByte(long value)
+ {
+ if (value < Byte.MinValue || value > Byte.MaxValue) ThrowByteOverflowException();
+ Contract.EndContractBlock();
+ return (byte)value;
+ }
+
+ [CLSCompliant(false)]
+ public static byte ToByte(ulong value)
+ {
+ if (value > Byte.MaxValue) ThrowByteOverflowException();
+ Contract.EndContractBlock();
+ 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, CultureInfo.CurrentCulture);
+ }
+
+ public static byte ToByte(String value, IFormatProvider provider)
+ {
+ if (value == null)
+ return 0;
+ return Byte.Parse(value, NumberStyles.Integer, provider);
+ }
+
+ public static byte ToByte(DateTime value)
+ {
+ return ((IConvertible)value).ToByte(null);
+ }
+
+
+ // Disallowed conversions to Byte
+ // public static byte ToByte(TimeSpan value)
+
+ // Conversions to Int16
+
+ public static short ToInt16(object value)
+ {
+ return value == null ? (short)0 : ((IConvertible)value).ToInt16(null);
+ }
+
+ public static short ToInt16(object value, IFormatProvider provider)
+ {
+ return value == null ? (short)0 : ((IConvertible)value).ToInt16(provider);
+ }
+
+ public static short ToInt16(bool value)
+ {
+ return value ? (short)Boolean.True : (short)Boolean.False;
+ }
+
+ public static short ToInt16(char value)
+ {
+ if (value > Int16.MaxValue) ThrowInt16OverflowException();
+ Contract.EndContractBlock();
+ 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 > Int16.MaxValue) ThrowInt16OverflowException();
+ Contract.EndContractBlock();
+ return (short)value;
+ }
+
+ public static short ToInt16(int value)
+ {
+ if (value < Int16.MinValue || value > Int16.MaxValue) ThrowInt16OverflowException();
+ Contract.EndContractBlock();
+ return (short)value;
+ }
+
+ [CLSCompliant(false)]
+ public static short ToInt16(uint value)
+ {
+ if (value > Int16.MaxValue) ThrowInt16OverflowException();
+ Contract.EndContractBlock();
+ return (short)value;
+ }
+
+ public static short ToInt16(short value)
+ {
+ return value;
+ }
+
+ public static short ToInt16(long value)
+ {
+ if (value < Int16.MinValue || value > Int16.MaxValue) ThrowInt16OverflowException();
+ Contract.EndContractBlock();
+ return (short)value;
+ }
+
+ [CLSCompliant(false)]
+ public static short ToInt16(ulong value)
+ {
+ if (value > (ulong)Int16.MaxValue) ThrowInt16OverflowException();
+ Contract.EndContractBlock();
+ 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 Int16.Parse(value, CultureInfo.CurrentCulture);
+ }
+
+ public static short ToInt16(String value, IFormatProvider provider)
+ {
+ if (value == null)
+ return 0;
+ return Int16.Parse(value, NumberStyles.Integer, provider);
+ }
+
+ public static short ToInt16(DateTime value)
+ {
+ return ((IConvertible)value).ToInt16(null);
+ }
+
+
+ // Disallowed conversions to Int16
+ // public static short ToInt16(TimeSpan value)
+
+ // Conversions to UInt16
+
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(object value)
+ {
+ return value == null ? (ushort)0 : ((IConvertible)value).ToUInt16(null);
+ }
+
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(object value, IFormatProvider provider)
+ {
+ return value == null ? (ushort)0 : ((IConvertible)value).ToUInt16(provider);
+ }
+
+
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(bool value)
+ {
+ return value ? (ushort)Boolean.True : (ushort)Boolean.False;
+ }
+
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(char value)
+ {
+ return value;
+ }
+
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(sbyte value)
+ {
+ if (value < 0) ThrowUInt16OverflowException();
+ Contract.EndContractBlock();
+ 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();
+ Contract.EndContractBlock();
+ return (ushort)value;
+ }
+
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(int value)
+ {
+ if (value < 0 || value > UInt16.MaxValue) ThrowUInt16OverflowException();
+ Contract.EndContractBlock();
+ return (ushort)value;
+ }
+
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(ushort value)
+ {
+ return value;
+ }
+
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(uint value)
+ {
+ if (value > UInt16.MaxValue) ThrowUInt16OverflowException();
+ Contract.EndContractBlock();
+ return (ushort)value;
+ }
+
+
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(long value)
+ {
+ if (value < 0 || value > UInt16.MaxValue) ThrowUInt16OverflowException();
+ Contract.EndContractBlock();
+ return (ushort)value;
+ }
+
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(ulong value)
+ {
+ if (value > UInt16.MaxValue) ThrowUInt16OverflowException();
+ Contract.EndContractBlock();
+ 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 UInt16.Parse(value, CultureInfo.CurrentCulture);
+ }
+
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(String value, IFormatProvider provider)
+ {
+ if (value == null)
+ return 0;
+ return UInt16.Parse(value, NumberStyles.Integer, provider);
+ }
+
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(DateTime value)
+ {
+ return ((IConvertible)value).ToUInt16(null);
+ }
+
+ // Disallowed conversions to UInt16
+ // public static ushort ToUInt16(TimeSpan value)
+
+ // Conversions to Int32
+
+ public static int ToInt32(object value)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToInt32(null);
+ }
+
+ public static int ToInt32(object value, IFormatProvider provider)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToInt32(provider);
+ }
+
+
+ public static int ToInt32(bool value)
+ {
+ return value ? Boolean.True : Boolean.False;
+ }
+
+ 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 (value > Int32.MaxValue) ThrowInt32OverflowException();
+ Contract.EndContractBlock();
+ return (int)value;
+ }
+
+ public static int ToInt32(int value)
+ {
+ return value;
+ }
+
+ public static int ToInt32(long value)
+ {
+ if (value < Int32.MinValue || value > Int32.MaxValue) ThrowInt32OverflowException();
+ Contract.EndContractBlock();
+ return (int)value;
+ }
+
+ [CLSCompliant(false)]
+ public static int ToInt32(ulong value)
+ {
+ if (value > Int32.MaxValue) ThrowInt32OverflowException();
+ Contract.EndContractBlock();
+ return (int)value;
+ }
+
+ public static int ToInt32(float value)
+ {
+ return ToInt32((double)value);
+ }
+
+ public static int ToInt32(double value)
+ {
+ if (value >= 0)
+ {
+ if (value < 2147483647.5)
+ {
+ int result = (int)value;
+ double dif = value - result;
+ if (dif > 0.5 || dif == 0.5 && (result & 1) != 0) result++;
+ return result;
+ }
+ }
+ else
+ {
+ if (value >= -2147483648.5)
+ {
+ int result = (int)value;
+ double dif = value - result;
+ if (dif < -0.5 || dif == -0.5 && (result & 1) != 0) result--;
+ return result;
+ }
+ }
+ 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 Int32.Parse(value, CultureInfo.CurrentCulture);
+ }
+
+ public static int ToInt32(String value, IFormatProvider provider)
+ {
+ if (value == null)
+ return 0;
+ return Int32.Parse(value, NumberStyles.Integer, provider);
+ }
+
+ public static int ToInt32(DateTime value)
+ {
+ return ((IConvertible)value).ToInt32(null);
+ }
+
+
+ // Disallowed conversions to Int32
+ // public static int ToInt32(TimeSpan value)
+
+ // Conversions to UInt32
+
+ [CLSCompliant(false)]
+ public static uint ToUInt32(object value)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToUInt32(null);
+ }
+
+ [CLSCompliant(false)]
+ public static uint ToUInt32(object value, IFormatProvider provider)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToUInt32(provider);
+ }
+
+
+ [CLSCompliant(false)]
+ public static uint ToUInt32(bool value)
+ {
+ return value ? (uint)Boolean.True : (uint)Boolean.False;
+ }
+
+ [CLSCompliant(false)]
+ public static uint ToUInt32(char value)
+ {
+ return value;
+ }
+
+ [CLSCompliant(false)]
+ public static uint ToUInt32(sbyte value)
+ {
+ if (value < 0) ThrowUInt32OverflowException();
+ Contract.EndContractBlock();
+ 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();
+ Contract.EndContractBlock();
+ 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();
+ Contract.EndContractBlock();
+ return (uint)value;
+ }
+
+ [CLSCompliant(false)]
+ public static uint ToUInt32(uint value)
+ {
+ return value;
+ }
+
+ [CLSCompliant(false)]
+ public static uint ToUInt32(long value)
+ {
+ if (value < 0 || value > UInt32.MaxValue) ThrowUInt32OverflowException();
+ Contract.EndContractBlock();
+ return (uint)value;
+ }
+
+ [CLSCompliant(false)]
+ public static uint ToUInt32(ulong value)
+ {
+ if (value > UInt32.MaxValue) ThrowUInt32OverflowException();
+ Contract.EndContractBlock();
+ 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 result = (uint)value;
+ double dif = value - result;
+ if (dif > 0.5 || dif == 0.5 && (result & 1) != 0) result++;
+ return result;
+ }
+ 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 0;
+ return UInt32.Parse(value, CultureInfo.CurrentCulture);
+ }
+
+ [CLSCompliant(false)]
+ public static uint ToUInt32(String value, IFormatProvider provider)
+ {
+ if (value == null)
+ return 0;
+ return UInt32.Parse(value, NumberStyles.Integer, provider);
+ }
+
+ [CLSCompliant(false)]
+ public static uint ToUInt32(DateTime value)
+ {
+ return ((IConvertible)value).ToUInt32(null);
+ }
+
+ // Disallowed conversions to UInt32
+ // public static uint ToUInt32(TimeSpan value)
+
+ // Conversions to Int64
+
+ public static long ToInt64(object value)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToInt64(null);
+ }
+
+ public static long ToInt64(object value, IFormatProvider provider)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToInt64(provider);
+ }
+
+
+ public static long ToInt64(bool value)
+ {
+ return value ? Boolean.True : Boolean.False;
+ }
+
+ 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 (value > Int64.MaxValue) ThrowInt64OverflowException();
+ Contract.EndContractBlock();
+ 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 0;
+ return Int64.Parse(value, CultureInfo.CurrentCulture);
+ }
+
+ public static long ToInt64(String value, IFormatProvider provider)
+ {
+ if (value == null)
+ return 0;
+ return Int64.Parse(value, NumberStyles.Integer, provider);
+ }
+
+ public static long ToInt64(DateTime value)
+ {
+ return ((IConvertible)value).ToInt64(null);
+ }
+
+ // Disallowed conversions to Int64
+ // public static long ToInt64(TimeSpan value)
+
+ // Conversions to UInt64
+
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(object value)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToUInt64(null);
+ }
+
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(object value, IFormatProvider provider)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToUInt64(provider);
+ }
+
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(bool value)
+ {
+ return value ? (ulong)Boolean.True : (ulong)Boolean.False;
+ }
+
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(char value)
+ {
+ return value;
+ }
+
+
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(sbyte value)
+ {
+ if (value < 0) ThrowUInt64OverflowException();
+ Contract.EndContractBlock();
+ 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();
+ Contract.EndContractBlock();
+ 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();
+ Contract.EndContractBlock();
+ 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();
+ Contract.EndContractBlock();
+ return (ulong)value;
+ }
+
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(UInt64 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 0;
+ return UInt64.Parse(value, CultureInfo.CurrentCulture);
+ }
+
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(String value, IFormatProvider provider)
+ {
+ if (value == null)
+ return 0;
+ return UInt64.Parse(value, NumberStyles.Integer, provider);
+ }
+
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(DateTime value)
+ {
+ return ((IConvertible)value).ToUInt64(null);
+ }
+
+ // Disallowed conversions to UInt64
+ // public static ulong ToUInt64(TimeSpan value)
+
+ // Conversions to Single
+
+ public static float ToSingle(object value)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToSingle(null);
+ }
+
+ public static float ToSingle(object value, IFormatProvider provider)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToSingle(provider);
+ }
+
+ [CLSCompliant(false)]
+ public static float ToSingle(sbyte value)
+ {
+ return value;
+ }
+
+ public static float ToSingle(byte value)
+ {
+ return value;
+ }
+
+ public static float ToSingle(char value)
+ {
+ return ((IConvertible)value).ToSingle(null);
+ }
+
+ public static float ToSingle(short value)
+ {
+ return value;
+ }
+
+ [CLSCompliant(false)]
+ public static float ToSingle(ushort value)
+ {
+ return 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 0;
+ return Single.Parse(value, CultureInfo.CurrentCulture);
+ }
+
+ public static float ToSingle(String value, IFormatProvider provider)
+ {
+ if (value == null)
+ return 0;
+ return Single.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider);
+ }
+
+
+ public static float ToSingle(bool value)
+ {
+ return value ? Boolean.True : Boolean.False;
+ }
+
+ public static float ToSingle(DateTime value)
+ {
+ return ((IConvertible)value).ToSingle(null);
+ }
+
+ // Disallowed conversions to Single
+ // public static float ToSingle(TimeSpan value)
+
+ // Conversions to Double
+
+ public static double ToDouble(object value)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToDouble(null);
+ }
+
+ public static double ToDouble(object value, IFormatProvider provider)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToDouble(provider);
+ }
+
+
+ [CLSCompliant(false)]
+ public static double ToDouble(sbyte value)
+ {
+ return value;
+ }
+
+ public static double ToDouble(byte value)
+ {
+ return value;
+ }
+
+ public static double ToDouble(short value)
+ {
+ return value;
+ }
+
+ public static double ToDouble(char value)
+ {
+ return ((IConvertible)value).ToDouble(null);
+ }
+
+ [CLSCompliant(false)]
+ public static double ToDouble(ushort value)
+ {
+ return 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;
+ return Double.Parse(value, CultureInfo.CurrentCulture);
+ }
+
+ public static double ToDouble(String value, IFormatProvider provider)
+ {
+ if (value == null)
+ return 0;
+ return Double.Parse(value, NumberStyles.Float | NumberStyles.AllowThousands, provider);
+ }
+
+ public static double ToDouble(bool value)
+ {
+ return value ? Boolean.True : Boolean.False;
+ }
+
+ public static double ToDouble(DateTime value)
+ {
+ return ((IConvertible)value).ToDouble(null);
+ }
+
+ // Disallowed conversions to Double
+ // public static double ToDouble(TimeSpan value)
+
+ // Conversions to Decimal
+
+ public static decimal ToDecimal(object value)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToDecimal(null);
+ }
+
+ public static decimal ToDecimal(object value, IFormatProvider provider)
+ {
+ return value == null ? 0 : ((IConvertible)value).ToDecimal(provider);
+ }
+
+ [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(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, CultureInfo.CurrentCulture);
+ }
+
+ public static Decimal ToDecimal(String value, IFormatProvider provider)
+ {
+ if (value == null)
+ return 0m;
+ return Decimal.Parse(value, NumberStyles.Number, provider);
+ }
+
+ public static decimal ToDecimal(decimal value)
+ {
+ return value;
+ }
+
+ public static decimal ToDecimal(bool value)
+ {
+ return value ? Boolean.True : Boolean.False;
+ }
+
+ public static decimal ToDecimal(DateTime value)
+ {
+ return ((IConvertible)value).ToDecimal(null);
+ }
+
+ // Disallowed conversions to Decimal
+ // public static decimal ToDecimal(TimeSpan value)
+
+ // Conversions to DateTime
+
+ public static DateTime ToDateTime(DateTime value)
+ {
+ return value;
+ }
+
+ public static DateTime ToDateTime(object value)
+ {
+ return value == null ? DateTime.MinValue : ((IConvertible)value).ToDateTime(null);
+ }
+
+ public static DateTime ToDateTime(object value, IFormatProvider provider)
+ {
+ return value == null ? DateTime.MinValue : ((IConvertible)value).ToDateTime(provider);
+ }
+
+ public static DateTime ToDateTime(String value)
+ {
+ if (value == null)
+ return new DateTime(0);
+ return DateTime.Parse(value, CultureInfo.CurrentCulture);
+ }
+
+ public static DateTime ToDateTime(String value, IFormatProvider provider)
+ {
+ if (value == null)
+ return new DateTime(0);
+ return DateTime.Parse(value, provider);
+ }
+
+ [CLSCompliant(false)]
+ public static DateTime ToDateTime(sbyte value)
+ {
+ return ((IConvertible)value).ToDateTime(null);
+ }
+
+ public static DateTime ToDateTime(byte value)
+ {
+ return ((IConvertible)value).ToDateTime(null);
+ }
+
+ public static DateTime ToDateTime(short value)
+ {
+ return ((IConvertible)value).ToDateTime(null);
+ }
+
+ [CLSCompliant(false)]
+ public static DateTime ToDateTime(ushort value)
+ {
+ return ((IConvertible)value).ToDateTime(null);
+ }
+
+ public static DateTime ToDateTime(int value)
+ {
+ return ((IConvertible)value).ToDateTime(null);
+ }
+
+ [CLSCompliant(false)]
+ public static DateTime ToDateTime(uint value)
+ {
+ return ((IConvertible)value).ToDateTime(null);
+ }
+
+ public static DateTime ToDateTime(long value)
+ {
+ return ((IConvertible)value).ToDateTime(null);
+ }
+
+ [CLSCompliant(false)]
+ public static DateTime ToDateTime(ulong value)
+ {
+ return ((IConvertible)value).ToDateTime(null);
+ }
+
+ public static DateTime ToDateTime(bool value)
+ {
+ return ((IConvertible)value).ToDateTime(null);
+ }
+
+ public static DateTime ToDateTime(char value)
+ {
+ return ((IConvertible)value).ToDateTime(null);
+ }
+
+ public static DateTime ToDateTime(float value)
+ {
+ return ((IConvertible)value).ToDateTime(null);
+ }
+
+ public static DateTime ToDateTime(double value)
+ {
+ return ((IConvertible)value).ToDateTime(null);
+ }
+
+ public static DateTime ToDateTime(decimal value)
+ {
+ return ((IConvertible)value).ToDateTime(null);
+ }
+
+ // Disallowed conversions to DateTime
+ // public static DateTime ToDateTime(TimeSpan value)
+
+ // Conversions to String
+
+ public static string ToString(Object value)
+ {
+ return ToString(value, null);
+ }
+
+ public static string ToString(Object value, IFormatProvider provider)
+ {
+ IConvertible ic = value as IConvertible;
+ if (ic != null)
+ return ic.ToString(provider);
+ IFormattable formattable = value as IFormattable;
+ if (formattable != null)
+ return formattable.ToString(null, provider);
+ return value == null ? String.Empty : value.ToString();
+ }
+
+ public static string ToString(bool value)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString();
+ }
+
+ public static string ToString(bool value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString();
+ }
+
+ public static string ToString(char value)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return Char.ToString(value);
+ }
+
+ public static string ToString(char value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString();
+ }
+
+ [CLSCompliant(false)]
+ public static string ToString(sbyte value)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(CultureInfo.CurrentCulture);
+ }
+
+ [CLSCompliant(false)]
+ public static string ToString(sbyte value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(provider);
+ }
+
+ public static string ToString(byte value)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(CultureInfo.CurrentCulture);
+ }
+
+ public static string ToString(byte value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(provider);
+ }
+
+ public static string ToString(short value)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(CultureInfo.CurrentCulture);
+ }
+
+ public static string ToString(short value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(provider);
+ }
+
+ [CLSCompliant(false)]
+ public static string ToString(ushort value)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(CultureInfo.CurrentCulture);
+ }
+
+ [CLSCompliant(false)]
+ public static string ToString(ushort value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(provider);
+ }
+
+ public static string ToString(int value)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(CultureInfo.CurrentCulture);
+ }
+
+ public static string ToString(int value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(provider);
+ }
+
+ [CLSCompliant(false)]
+ public static string ToString(uint value)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(CultureInfo.CurrentCulture);
+ }
+
+ [CLSCompliant(false)]
+ public static string ToString(uint value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(provider);
+ }
+
+ public static string ToString(long value)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(CultureInfo.CurrentCulture);
+ }
+
+ public static string ToString(long value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(provider);
+ }
+
+ [CLSCompliant(false)]
+ public static string ToString(ulong value)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(CultureInfo.CurrentCulture);
+ }
+
+ [CLSCompliant(false)]
+ public static string ToString(ulong value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(provider);
+ }
+
+ public static string ToString(float value)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(CultureInfo.CurrentCulture);
+ }
+
+ public static string ToString(float value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(provider);
+ }
+
+ public static string ToString(double value)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(CultureInfo.CurrentCulture);
+ }
+
+ public static string ToString(double value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(provider);
+ }
+
+ public static string ToString(decimal value)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(CultureInfo.CurrentCulture);
+ }
+
+ public static string ToString(Decimal value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(provider);
+ }
+
+ public static string ToString(DateTime value)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString();
+ }
+
+ public static string ToString(DateTime value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return value.ToString(provider);
+ }
+
+ public static String ToString(String value)
+ {
+ Contract.Ensures(Contract.Result<string>() == value); // We were always skipping the null check here.
+ return value;
+ }
+
+ public static String ToString(String value, IFormatProvider provider)
+ {
+ Contract.Ensures(Contract.Result<string>() == value); // We were always skipping the null check here.
+ return value; // avoid the null check
+ }
+
+
+ //
+ // Conversions which understand Base XXX numbers.
+ //
+ // Parses value in base base. base can only
+ // be 2, 8, 10, or 16. If base is 16, the number may be preceded
+ // by 0x; any other leading or trailing characters cause an error.
+ //
+ public static byte ToByte(String value, int fromBase)
+ {
+ if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16)
+ {
+ throw new ArgumentException(SR.Arg_InvalidBase);
+ }
+ Contract.EndContractBlock();
+ int r = ParseNumbers.StringToInt(value, fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsUnsigned);
+ if (r < Byte.MinValue || r > Byte.MaxValue)
+ ThrowByteOverflowException();
+ return (byte)r;
+ }
+
+ // Parses value in base fromBase. fromBase can only
+ // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
+ // by 0x; any other leading or trailing characters cause an error.
+ //
+ [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);
+ }
+ Contract.EndContractBlock();
+ int r = ParseNumbers.StringToInt(value, fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsI1);
+ if (fromBase != 10 && r <= Byte.MaxValue)
+ return (sbyte)r;
+
+ if (r < SByte.MinValue || r > SByte.MaxValue)
+ ThrowSByteOverflowException();
+ return (sbyte)r;
+ }
+
+ // Parses value in base fromBase. fromBase can only
+ // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
+ // by 0x; any other leading or trailing characters cause an error.
+ //
+ public static short ToInt16(String value, int fromBase)
+ {
+ if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16)
+ {
+ throw new ArgumentException(SR.Arg_InvalidBase);
+ }
+ Contract.EndContractBlock();
+ int r = ParseNumbers.StringToInt(value, fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsI2);
+ if (fromBase != 10 && r <= UInt16.MaxValue)
+ return (short)r;
+
+ if (r < Int16.MinValue || r > Int16.MaxValue)
+ ThrowInt16OverflowException();
+ return (short)r;
+ }
+
+ // Parses value in base fromBase. fromBase can only
+ // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
+ // by 0x; any other leading or trailing characters cause an error.
+ //
+ [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);
+ }
+ Contract.EndContractBlock();
+ int r = ParseNumbers.StringToInt(value, fromBase, ParseNumbers.IsTight | ParseNumbers.TreatAsUnsigned);
+ if (r < UInt16.MinValue || r > UInt16.MaxValue)
+ ThrowUInt16OverflowException();
+ return (ushort)r;
+ }
+
+ // Parses value in base fromBase. fromBase can only
+ // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
+ // by 0x; any other leading or trailing characters cause an error.
+ //
+ public static int ToInt32(String value, int fromBase)
+ {
+ if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16)
+ {
+ throw new ArgumentException(SR.Arg_InvalidBase);
+ }
+ Contract.EndContractBlock();
+ return ParseNumbers.StringToInt(value, fromBase, ParseNumbers.IsTight);
+ }
+
+ // Parses value in base fromBase. fromBase can only
+ // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
+ // by 0x; any other leading or trailing characters cause an error.
+ //
+ [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);
+ }
+ Contract.EndContractBlock();
+ return (uint)ParseNumbers.StringToInt(value, fromBase, ParseNumbers.TreatAsUnsigned | ParseNumbers.IsTight);
+ }
+
+ // Parses value in base fromBase. fromBase can only
+ // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
+ // by 0x; any other leading or trailing characters cause an error.
+ //
+ public static long ToInt64(String value, int fromBase)
+ {
+ if (fromBase != 2 && fromBase != 8 && fromBase != 10 && fromBase != 16)
+ {
+ throw new ArgumentException(SR.Arg_InvalidBase);
+ }
+ Contract.EndContractBlock();
+ return ParseNumbers.StringToLong(value, fromBase, ParseNumbers.IsTight);
+ }
+
+ // Parses value in base fromBase. fromBase can only
+ // be 2, 8, 10, or 16. If fromBase is 16, the number may be preceded
+ // by 0x; any other leading or trailing characters cause an error.
+ //
+ [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);
+ }
+ Contract.EndContractBlock();
+ return (ulong)ParseNumbers.StringToLong(value, fromBase, ParseNumbers.TreatAsUnsigned | ParseNumbers.IsTight);
+ }
+
+ // Convert the byte value to a string in base fromBase
+ public static String ToString(byte value, int toBase)
+ {
+ if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16)
+ {
+ throw new ArgumentException(SR.Arg_InvalidBase);
+ }
+ Contract.EndContractBlock();
+ return ParseNumbers.IntToString((int)value, toBase, -1, ' ', ParseNumbers.PrintAsI1);
+ }
+
+ // Convert the Int16 value to a string in base fromBase
+ public static String ToString(short value, int toBase)
+ {
+ if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16)
+ {
+ throw new ArgumentException(SR.Arg_InvalidBase);
+ }
+ Contract.EndContractBlock();
+ return ParseNumbers.IntToString((int)value, toBase, -1, ' ', ParseNumbers.PrintAsI2);
+ }
+
+ // Convert the Int32 value to a string in base toBase
+ public static String ToString(int value, int toBase)
+ {
+ if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16)
+ {
+ throw new ArgumentException(SR.Arg_InvalidBase);
+ }
+ Contract.EndContractBlock();
+ return ParseNumbers.IntToString(value, toBase, -1, ' ', 0);
+ }
+
+ // Convert the Int64 value to a string in base toBase
+ public static String ToString(long value, int toBase)
+ {
+ if (toBase != 2 && toBase != 8 && toBase != 10 && toBase != 16)
+ {
+ throw new ArgumentException(SR.Arg_InvalidBase);
+ }
+ Contract.EndContractBlock();
+ return ParseNumbers.LongToString(value, toBase, -1, ' ', 0);
+ }
+
+ public static String ToBase64String(byte[] inArray)
+ {
+ if (inArray == null)
+ {
+ throw new ArgumentNullException(nameof(inArray));
+ }
+ Contract.Ensures(Contract.Result<string>() != null);
+ Contract.EndContractBlock();
+ return ToBase64String(inArray, 0, inArray.Length, Base64FormattingOptions.None);
+ }
+
+ public static String ToBase64String(byte[] inArray, Base64FormattingOptions options)
+ {
+ if (inArray == null)
+ {
+ throw new ArgumentNullException(nameof(inArray));
+ }
+ Contract.Ensures(Contract.Result<string>() != null);
+ Contract.EndContractBlock();
+ return ToBase64String(inArray, 0, inArray.Length, options);
+ }
+
+ public static String ToBase64String(byte[] inArray, int offset, int length)
+ {
+ return ToBase64String(inArray, offset, length, Base64FormattingOptions.None);
+ }
+
+ public static unsafe String ToBase64String(byte[] inArray, int offset, int length, Base64FormattingOptions options)
+ {
+ //Do data verfication
+ if (inArray == null)
+ throw new ArgumentNullException(nameof(inArray));
+ if (length < 0)
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
+ if (offset < 0)
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_GenericPositive);
+ if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks)
+ throw new ArgumentException(string.Format(SR.Arg_EnumIllegalVal, (int)options));
+ Contract.Ensures(Contract.Result<string>() != null);
+ Contract.EndContractBlock();
+
+ int inArrayLength;
+ int stringLength;
+
+ inArrayLength = inArray.Length;
+ if (offset > (inArrayLength - length))
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_OffsetLength);
+
+ if (inArrayLength == 0)
+ return String.Empty;
+
+ bool insertLineBreaks = (options == Base64FormattingOptions.InsertLineBreaks);
+ //Create the new string. This is the maximally required length.
+ stringLength = ToBase64_CalculateAndValidateOutputLength(length, insertLineBreaks);
+
+ string returnString = string.FastAllocateString(stringLength);
+ fixed (char* outChars = returnString)
+ {
+ fixed (byte* inData = &inArray[0])
+ {
+ int j = ConvertToBase64Array(outChars, inData, offset, length, insertLineBreaks);
+ Debug.Assert(returnString.Length == j, "returnString.Length == j");
+ return returnString;
+ }
+ }
+ }
+
+ public static int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut)
+ {
+ Contract.Ensures(Contract.Result<int>() >= 0);
+ Contract.Ensures(Contract.Result<int>() <= outArray.Length);
+ Contract.EndContractBlock();
+
+ return ToBase64CharArray(inArray, offsetIn, length, outArray, offsetOut, Base64FormattingOptions.None);
+ }
+
+ public static unsafe int ToBase64CharArray(byte[] inArray, int offsetIn, int length, char[] outArray, int offsetOut, Base64FormattingOptions options)
+ {
+ //Do data verfication
+ if (inArray == null)
+ throw new ArgumentNullException(nameof(inArray));
+ if (outArray == null)
+ throw new ArgumentNullException(nameof(outArray));
+ if (length < 0)
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
+ if (offsetIn < 0)
+ throw new ArgumentOutOfRangeException(nameof(offsetIn), SR.ArgumentOutOfRange_GenericPositive);
+ if (offsetOut < 0)
+ throw new ArgumentOutOfRangeException(nameof(offsetOut), SR.ArgumentOutOfRange_GenericPositive);
+
+ if (options < Base64FormattingOptions.None || options > Base64FormattingOptions.InsertLineBreaks)
+ {
+ throw new ArgumentException(string.Format(SR.Arg_EnumIllegalVal, (int)options));
+ }
+ Contract.Ensures(Contract.Result<int>() >= 0);
+ Contract.Ensures(Contract.Result<int>() <= outArray.Length);
+ Contract.EndContractBlock();
+
+
+ int retVal;
+
+ int inArrayLength;
+ int outArrayLength;
+ int numElementsToCopy;
+
+ inArrayLength = inArray.Length;
+
+ if (offsetIn > (int)(inArrayLength - length))
+ throw new ArgumentOutOfRangeException(nameof(offsetIn), SR.ArgumentOutOfRange_OffsetLength);
+
+ if (inArrayLength == 0)
+ return 0;
+
+ bool insertLineBreaks = (options == Base64FormattingOptions.InsertLineBreaks);
+ //This is the maximally required length that must be available in the char array
+ outArrayLength = outArray.Length;
+
+ // Length of the char buffer required
+ numElementsToCopy = ToBase64_CalculateAndValidateOutputLength(length, insertLineBreaks);
+
+ if (offsetOut > (int)(outArrayLength - numElementsToCopy))
+ throw new ArgumentOutOfRangeException(nameof(offsetOut), SR.ArgumentOutOfRange_OffsetOut);
+
+ fixed (char* outChars = &outArray[offsetOut])
+ {
+ fixed (byte* inData = &inArray[0])
+ {
+ retVal = ConvertToBase64Array(outChars, inData, offsetIn, length, insertLineBreaks);
+ }
+ }
+
+ return retVal;
+ }
+
+ private static unsafe int ConvertToBase64Array(char* outChars, byte* inData, int offset, int length, bool insertLineBreaks)
+ {
+ int lengthmod3 = length % 3;
+ int calcLength = offset + (length - lengthmod3);
+ int j = 0;
+ int charcount = 0;
+ //Convert three bytes at a time to base64 notation. This will consume 4 chars.
+ int i;
+
+ // get a pointer to the base64Table to avoid unnecessary range checking
+ fixed (char* base64 = &base64Table[0])
+ {
+ for (i = offset; i < calcLength; i += 3)
+ {
+ if (insertLineBreaks)
+ {
+ if (charcount == base64LineBreakPosition)
+ {
+ outChars[j++] = '\r';
+ outChars[j++] = '\n';
+ charcount = 0;
+ }
+ charcount += 4;
+ }
+ outChars[j] = base64[(inData[i] & 0xfc) >> 2];
+ outChars[j + 1] = base64[((inData[i] & 0x03) << 4) | ((inData[i + 1] & 0xf0) >> 4)];
+ outChars[j + 2] = base64[((inData[i + 1] & 0x0f) << 2) | ((inData[i + 2] & 0xc0) >> 6)];
+ outChars[j + 3] = base64[(inData[i + 2] & 0x3f)];
+ j += 4;
+ }
+
+ //Where we left off before
+ i = calcLength;
+
+ if (insertLineBreaks && (lengthmod3 != 0) && (charcount == base64LineBreakPosition))
+ {
+ outChars[j++] = '\r';
+ outChars[j++] = '\n';
+ }
+
+ switch (lengthmod3)
+ {
+ case 2: //One character padding needed
+ outChars[j] = base64[(inData[i] & 0xfc) >> 2];
+ outChars[j + 1] = base64[((inData[i] & 0x03) << 4) | ((inData[i + 1] & 0xf0) >> 4)];
+ outChars[j + 2] = base64[(inData[i + 1] & 0x0f) << 2];
+ outChars[j + 3] = base64[64]; //Pad
+ j += 4;
+ break;
+ case 1: // Two character padding needed
+ outChars[j] = base64[(inData[i] & 0xfc) >> 2];
+ outChars[j + 1] = base64[(inData[i] & 0x03) << 4];
+ outChars[j + 2] = base64[64]; //Pad
+ outChars[j + 3] = base64[64]; //Pad
+ j += 4;
+ break;
+ }
+ }
+
+ return j;
+ }
+
+ private static int ToBase64_CalculateAndValidateOutputLength(int inputLength, bool insertLineBreaks)
+ {
+ long outlen = ((long)inputLength) / 3 * 4; // the base length - we want integer division here.
+ outlen += ((inputLength % 3) != 0) ? 4 : 0; // at most 4 more chars for the remainder
+
+ if (outlen == 0)
+ return 0;
+
+ if (insertLineBreaks)
+ {
+ long newLines = outlen / base64LineBreakPosition;
+ if ((outlen % base64LineBreakPosition) == 0)
+ {
+ --newLines;
+ }
+ outlen += newLines * 2; // the number of line break chars we'll add, "\r\n"
+ }
+
+ // If we overflow an int then we cannot allocate enough
+ // memory to output the value so throw
+ if (outlen > int.MaxValue)
+ throw new OutOfMemoryException();
+
+ return (int)outlen;
+ }
+
+
+ /// <summary>
+ /// Converts the specified string, which encodes binary data as Base64 digits, to the equivalent byte array.
+ /// </summary>
+ /// <param name="s">The string to convert</param>
+ /// <returns>The array of bytes represented by the specifed Base64 string.</returns>
+ public static Byte[] FromBase64String(String s)
+ {
+ // "s" is an unfortunate parameter name, but we need to keep it for backward compat.
+
+ if (s == null)
+ throw new ArgumentNullException(nameof(s));
+
+ Contract.EndContractBlock();
+
+ unsafe
+ {
+ fixed (Char* sPtr = s)
+ {
+ return FromBase64CharPtr(sPtr, s.Length);
+ }
+ }
+ }
+
+
+ /// <summary>
+ /// Converts the specified range of a Char array, which encodes binary data as Base64 digits, to the equivalent byte array.
+ /// </summary>
+ /// <param name="inArray">Chars representing Base64 encoding characters</param>
+ /// <param name="offset">A position within the input array.</param>
+ /// <param name="length">Number of element to convert.</param>
+ /// <returns>The array of bytes represented by the specified Base64 encoding characters.</returns>
+ public static Byte[] FromBase64CharArray(Char[] inArray, Int32 offset, Int32 length)
+ {
+ if (inArray == null)
+ throw new ArgumentNullException(nameof(inArray));
+
+ if (length < 0)
+ throw new ArgumentOutOfRangeException(nameof(length), SR.ArgumentOutOfRange_Index);
+
+ if (offset < 0)
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_GenericPositive);
+
+ if (offset > inArray.Length - length)
+ throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_OffsetLength);
+
+ Contract.EndContractBlock();
+
+ if (inArray.Length == 0)
+ {
+ return Array.Empty<byte>();
+ }
+
+ unsafe
+ {
+ fixed (Char* inArrayPtr = &inArray[0])
+ {
+ return FromBase64CharPtr(inArrayPtr + offset, length);
+ }
+ }
+ }
+
+
+
+ /// <summary>
+ /// Convert Base64 encoding characters to bytes:
+ /// - Compute result length exactly by actually walking the input;
+ /// - Allocate new result array based on computation;
+ /// - Decode input into the new array;
+ /// </summary>
+ /// <param name="inputPtr">Pointer to the first input char</param>
+ /// <param name="inputLength">Number of input chars</param>
+ /// <returns></returns>
+ private static unsafe Byte[] FromBase64CharPtr(Char* inputPtr, Int32 inputLength)
+ {
+ // The validity of parameters much be checked by callers, thus we are Critical here.
+
+ Debug.Assert(0 <= inputLength);
+
+ // We need to get rid of any trailing white spaces.
+ // Otherwise we would be rejecting input such as "abc= ":
+ while (inputLength > 0)
+ {
+ Int32 lastChar = inputPtr[inputLength - 1];
+ if (lastChar != (Int32)' ' && lastChar != (Int32)'\n' && lastChar != (Int32)'\r' && lastChar != (Int32)'\t')
+ break;
+ inputLength--;
+ }
+
+ // Compute the output length:
+ Int32 resultLength = FromBase64_ComputeResultLength(inputPtr, inputLength);
+
+ Debug.Assert(0 <= resultLength);
+
+ // resultLength can be zero. We will still enter FromBase64_Decode and process the input.
+ // It may either simply write no bytes (e.g. input = " ") or throw (e.g. input = "ab").
+
+ // Create result byte blob:
+ Byte[] decodedBytes = new Byte[resultLength];
+
+ // Convert Base64 chars into bytes:
+ Int32 actualResultLength;
+ fixed (Byte* decodedBytesPtr = decodedBytes)
+ actualResultLength = FromBase64_Decode(inputPtr, inputLength, decodedBytesPtr, resultLength);
+
+ // Note that actualResultLength can differ from resultLength if the caller is modifying the array
+ // as it is being converted. Silently ignore the failure.
+ // Consider throwing exception in an non in-place release.
+
+ // We are done:
+ return decodedBytes;
+ }
+
+
+ /// <summary>
+ /// Decode characters representing a Base64 encoding into bytes:
+ /// Walk the input. Every time 4 chars are read, convert them to the 3 corresponding output bytes.
+ /// This method is a bit lengthy on purpose. We are trying to avoid jumps to helpers in the loop
+ /// to aid performance.
+ /// </summary>
+ /// <param name="inputPtr">Pointer to first input char</param>
+ /// <param name="inputLength">Number of input chars</param>
+ /// <param name="destPtr">Pointer to location for the first result byte</param>
+ /// <param name="destLength">Max length of the preallocated result buffer</param>
+ /// <returns>If the result buffer was not large enough to write all result bytes, return -1;
+ /// Otherwise return the number of result bytes actually produced.</returns>
+ private static unsafe Int32 FromBase64_Decode(Char* startInputPtr, Int32 inputLength, Byte* startDestPtr, Int32 destLength)
+ {
+ // You may find this method weird to look at. It's written for performance, not aesthetics.
+ // You will find unrolled loops label jumps and bit manipulations.
+
+ const UInt32 intA = (UInt32)'A';
+ const UInt32 inta = (UInt32)'a';
+ const UInt32 int0 = (UInt32)'0';
+ const UInt32 intEq = (UInt32)'=';
+ const UInt32 intPlus = (UInt32)'+';
+ const UInt32 intSlash = (UInt32)'/';
+ const UInt32 intSpace = (UInt32)' ';
+ const UInt32 intTab = (UInt32)'\t';
+ const UInt32 intNLn = (UInt32)'\n';
+ const UInt32 intCRt = (UInt32)'\r';
+ const UInt32 intAtoZ = (UInt32)('Z' - 'A'); // = ('z' - 'a')
+ const UInt32 int0to9 = (UInt32)('9' - '0');
+
+ Char* inputPtr = startInputPtr;
+ Byte* destPtr = startDestPtr;
+
+ // Pointers to the end of input and output:
+ Char* endInputPtr = inputPtr + inputLength;
+ Byte* endDestPtr = destPtr + destLength;
+
+ // Current char code/value:
+ UInt32 currCode;
+
+ // This 4-byte integer will contain the 4 codes of the current 4-char group.
+ // Eeach char codes for 6 bits = 24 bits.
+ // The remaining byte will be FF, we use it as a marker when 4 chars have been processed.
+ UInt32 currBlockCodes = 0x000000FFu;
+
+ unchecked
+ {
+ while (true)
+ {
+ // break when done:
+ if (inputPtr >= endInputPtr)
+ goto _AllInputConsumed;
+
+ // Get current char:
+ currCode = (UInt32)(*inputPtr);
+ inputPtr++;
+
+ // Determine current char code:
+
+ if (currCode - intA <= intAtoZ)
+ currCode -= intA;
+
+ else if (currCode - inta <= intAtoZ)
+ currCode -= (inta - 26u);
+
+ else if (currCode - int0 <= int0to9)
+ currCode -= (int0 - 52u);
+
+ else
+ {
+ // Use the slower switch for less common cases:
+ switch (currCode)
+ {
+ // Significant chars:
+ case intPlus:
+ currCode = 62u;
+ break;
+
+ case intSlash:
+ currCode = 63u;
+ break;
+
+ // Legal no-value chars (we ignore these):
+ case intCRt:
+ case intNLn:
+ case intSpace:
+ case intTab:
+ continue;
+
+ // The equality char is only legal at the end of the input.
+ // Jump after the loop to make it easier for the JIT register predictor to do a good job for the loop itself:
+ case intEq:
+ goto _EqualityCharEncountered;
+
+ // Other chars are illegal:
+ default:
+ throw new FormatException(SR.Format_BadBase64Char);
+ }
+ }
+
+ // Ok, we got the code. Save it:
+ currBlockCodes = (currBlockCodes << 6) | currCode;
+
+ // Last bit in currBlockCodes will be on after in shifted right 4 times:
+ if ((currBlockCodes & 0x80000000u) != 0u)
+ {
+ if ((Int32)(endDestPtr - destPtr) < 3)
+ return -1;
+
+ *(destPtr) = (Byte)(currBlockCodes >> 16);
+ *(destPtr + 1) = (Byte)(currBlockCodes >> 8);
+ *(destPtr + 2) = (Byte)(currBlockCodes);
+ destPtr += 3;
+
+ currBlockCodes = 0x000000FFu;
+ }
+ }
+ } // unchecked while
+
+ // 'd be nice to have an assert that we never get here, but CS0162: Unreachable code detected.
+ // Debug.Assert(false, "We only leave the above loop by jumping; should never get here.");
+
+ // We jump here out of the loop if we hit an '=':
+ _EqualityCharEncountered:
+
+ Debug.Assert(currCode == intEq);
+
+ // Recall that inputPtr is now one position past where '=' was read.
+ // '=' can only be at the last input pos:
+ if (inputPtr == endInputPtr)
+ {
+ // Code is zero for trailing '=':
+ currBlockCodes <<= 6;
+
+ // The '=' did not complete a 4-group. The input must be bad:
+ if ((currBlockCodes & 0x80000000u) == 0u)
+ throw new FormatException(SR.Format_BadBase64CharArrayLength);
+
+ if ((int)(endDestPtr - destPtr) < 2) // Autch! We underestimated the output length!
+ return -1;
+
+ // We are good, store bytes form this past group. We had a single "=", so we take two bytes:
+ *(destPtr++) = (Byte)(currBlockCodes >> 16);
+ *(destPtr++) = (Byte)(currBlockCodes >> 8);
+
+ currBlockCodes = 0x000000FFu;
+ }
+ else
+ { // '=' can also be at the pre-last position iff the last is also a '=' excluding the white spaces:
+ // We need to get rid of any intermediate white spaces.
+ // Otherwise we would be rejecting input such as "abc= =":
+ while (inputPtr < (endInputPtr - 1))
+ {
+ Int32 lastChar = *(inputPtr);
+ if (lastChar != (Int32)' ' && lastChar != (Int32)'\n' && lastChar != (Int32)'\r' && lastChar != (Int32)'\t')
+ break;
+ inputPtr++;
+ }
+
+ if (inputPtr == (endInputPtr - 1) && *(inputPtr) == '=')
+ {
+ // Code is zero for each of the two '=':
+ currBlockCodes <<= 12;
+
+ // The '=' did not complete a 4-group. The input must be bad:
+ if ((currBlockCodes & 0x80000000u) == 0u)
+ throw new FormatException(SR.Format_BadBase64CharArrayLength);
+
+ if ((Int32)(endDestPtr - destPtr) < 1) // Autch! We underestimated the output length!
+ return -1;
+
+ // We are good, store bytes form this past group. We had a "==", so we take only one byte:
+ *(destPtr++) = (Byte)(currBlockCodes >> 16);
+
+ currBlockCodes = 0x000000FFu;
+ }
+ else // '=' is not ok at places other than the end:
+ throw new FormatException(SR.Format_BadBase64Char);
+ }
+
+ // We get here either from above or by jumping out of the loop:
+ _AllInputConsumed:
+
+ // The last block of chars has less than 4 items
+ if (currBlockCodes != 0x000000FFu)
+ throw new FormatException(SR.Format_BadBase64CharArrayLength);
+
+ // Return how many bytes were actually recovered:
+ return (Int32)(destPtr - startDestPtr);
+ } // Int32 FromBase64_Decode(...)
+
+
+ /// <summary>
+ /// Compute the number of bytes encoded in the specified Base 64 char array:
+ /// Walk the entire input counting white spaces and padding chars, then compute result length
+ /// based on 3 bytes per 4 chars.
+ /// </summary>
+ private static unsafe Int32 FromBase64_ComputeResultLength(Char* inputPtr, Int32 inputLength)
+ {
+ const UInt32 intEq = (UInt32)'=';
+ const UInt32 intSpace = (UInt32)' ';
+
+ Debug.Assert(0 <= inputLength);
+
+ Char* inputEndPtr = inputPtr + inputLength;
+ Int32 usefulInputLength = inputLength;
+ Int32 padding = 0;
+
+ while (inputPtr < inputEndPtr)
+ {
+ UInt32 c = (UInt32)(*inputPtr);
+ inputPtr++;
+
+ // We want to be as fast as possible and filter out spaces with as few comparisons as possible.
+ // We end up accepting a number of illegal chars as legal white-space chars.
+ // This is ok: as soon as we hit them during actual decode we will recognise them as illegal and throw.
+ if (c <= intSpace)
+ usefulInputLength--;
+
+ else if (c == intEq)
+ {
+ usefulInputLength--;
+ padding++;
+ }
+ }
+
+ Debug.Assert(0 <= usefulInputLength);
+
+ // For legal input, we can assume that 0 <= padding < 3. But it may be more for illegal input.
+ // We will notice it at decode when we see a '=' at the wrong place.
+ Debug.Assert(0 <= padding);
+
+ // Perf: reuse the variable that stored the number of '=' to store the number of bytes encoded by the
+ // last group that contains the '=':
+ if (padding != 0)
+ {
+ if (padding == 1)
+ padding = 2;
+ else if (padding == 2)
+ padding = 1;
+ else
+ throw new FormatException(SR.Format_BadBase64Char);
+ }
+
+ // Done:
+ return (usefulInputLength / 4) * 3 + padding;
+ }
+ } // class Convert
+} // namespace
+
diff --git a/src/mscorlib/shared/System/CurrentSystemTimeZone.cs b/src/mscorlib/shared/System/CurrentSystemTimeZone.cs
new file mode 100644
index 0000000000..2d848397a9
--- /dev/null
+++ b/src/mscorlib/shared/System/CurrentSystemTimeZone.cs
@@ -0,0 +1,199 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*============================================================
+**
+**
+**
+** Purpose:
+** This class represents the current system timezone. It is
+** the only meaningful implementation of the TimeZone class
+** available in this version.
+**
+** The only TimeZone that we support in version 1 is the
+** CurrentTimeZone as determined by the system timezone.
+**
+**
+============================================================*/
+
+using System;
+using System.Diagnostics.Contracts;
+using System.Text;
+using System.Collections;
+using System.Globalization;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
+
+namespace System
+{
+ [Obsolete("System.CurrentSystemTimeZone has been deprecated. Please investigate the use of System.TimeZoneInfo.Local instead.")]
+ [Serializable]
+ internal partial class CurrentSystemTimeZone : TimeZone
+ {
+ // Standard offset in ticks to the Universal time if
+ // no daylight saving is in used.
+ // E.g. the offset for PST (Pacific Standard time) should be -8 * 60 * 60 * 1000 * 10000.
+ // (1 millisecond = 10000 ticks)
+ private long m_ticksOffset;
+ private String m_standardName;
+ private String m_daylightName;
+
+ internal CurrentSystemTimeZone()
+ {
+ TimeZoneInfo local = TimeZoneInfo.Local;
+
+ m_ticksOffset = local.BaseUtcOffset.Ticks;
+ m_standardName = local.StandardName;
+ m_daylightName = local.DaylightName;
+ }
+
+ public override String StandardName
+ {
+ get
+ {
+ return m_standardName;
+ }
+ }
+
+ public override String DaylightName
+ {
+ get
+ {
+ return m_daylightName;
+ }
+ }
+
+ internal long GetUtcOffsetFromUniversalTime(DateTime time, ref Boolean isAmbiguousLocalDst)
+ {
+ // Get the daylight changes for the year of the specified time.
+ TimeSpan offset = new TimeSpan(m_ticksOffset);
+ DaylightTime daylightTime = GetDaylightChanges(time.Year);
+ isAmbiguousLocalDst = false;
+
+ if (daylightTime == null || daylightTime.Delta.Ticks == 0)
+ {
+ return offset.Ticks;
+ }
+
+ // The start and end times represent the range of universal times that are in DST for that year.
+ // Within that there is an ambiguous hour, usually right at the end, but at the beginning in
+ // the unusual case of a negative daylight savings delta.
+ DateTime startTime = daylightTime.Start - offset;
+ DateTime endTime = daylightTime.End - offset - daylightTime.Delta;
+ DateTime ambiguousStart;
+ DateTime ambiguousEnd;
+
+ if (daylightTime.Delta.Ticks > 0)
+ {
+ ambiguousStart = endTime - daylightTime.Delta;
+ ambiguousEnd = endTime;
+ }
+ else
+ {
+ ambiguousStart = startTime;
+ ambiguousEnd = startTime - daylightTime.Delta;
+ }
+
+ Boolean isDst = false;
+ if (startTime > endTime)
+ {
+ // In southern hemisphere, the daylight saving time starts later in the year, and ends in the beginning of next year.
+ // Note, the summer in the southern hemisphere begins late in the year.
+ isDst = (time < endTime || time >= startTime);
+ }
+ else
+ {
+ // In northern hemisphere, the daylight saving time starts in the middle of the year.
+ isDst = (time >= startTime && time < endTime);
+ }
+
+ if (isDst)
+ {
+ offset += daylightTime.Delta;
+
+ // See if the resulting local time becomes ambiguous. This must be captured here or the
+ // DateTime will not be able to round-trip back to UTC accurately.
+ if (time >= ambiguousStart && time < ambiguousEnd)
+ {
+ isAmbiguousLocalDst = true;
+ }
+ }
+ return offset.Ticks;
+ }
+
+ public override DateTime ToLocalTime(DateTime time)
+ {
+ if (time.Kind == DateTimeKind.Local)
+ {
+ return time;
+ }
+ Boolean isAmbiguousLocalDst = false;
+ Int64 offset = GetUtcOffsetFromUniversalTime(time, ref isAmbiguousLocalDst);
+ long tick = time.Ticks + offset;
+ if (tick > DateTime.MaxTicks)
+ {
+ return new DateTime(DateTime.MaxTicks, DateTimeKind.Local);
+ }
+ if (tick < DateTime.MinTicks)
+ {
+ return new DateTime(DateTime.MinTicks, DateTimeKind.Local);
+ }
+ return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);
+ }
+
+ public override DaylightTime GetDaylightChanges(int year)
+ {
+ if (year < 1 || year > 9999)
+ {
+ throw new ArgumentOutOfRangeException(nameof(year), SR.Format(SR.ArgumentOutOfRange_Range, 1, 9999));
+ }
+
+ return GetCachedDaylightChanges(year);
+ }
+
+ private static DaylightTime CreateDaylightChanges(int year)
+ {
+ DaylightTime currentDaylightChanges = null;
+
+ if (TimeZoneInfo.Local.SupportsDaylightSavingTime)
+ {
+ DateTime start;
+ DateTime end;
+ TimeSpan delta;
+
+ foreach (var rule in TimeZoneInfo.Local.GetAdjustmentRules())
+ {
+ if (rule.DateStart.Year <= year && rule.DateEnd.Year >= year && rule.DaylightDelta != TimeSpan.Zero)
+ {
+ start = TimeZoneInfo.TransitionTimeToDateTime(year, rule.DaylightTransitionStart);
+ end = TimeZoneInfo.TransitionTimeToDateTime(year, rule.DaylightTransitionEnd);
+ delta = rule.DaylightDelta;
+
+ currentDaylightChanges = new DaylightTime(start, end, delta);
+ break;
+ }
+ }
+ }
+
+ if (currentDaylightChanges == null)
+ {
+ currentDaylightChanges = new DaylightTime(DateTime.MinValue, DateTime.MinValue, TimeSpan.Zero);
+ }
+
+ return currentDaylightChanges;
+ }
+
+ public override TimeSpan GetUtcOffset(DateTime time)
+ {
+ if (time.Kind == DateTimeKind.Utc)
+ {
+ return TimeSpan.Zero;
+ }
+ else
+ {
+ return new TimeSpan(TimeZone.CalculateUtcOffset(time, GetDaylightChanges(time.Year)).Ticks + m_ticksOffset);
+ }
+ }
+ } // class CurrentSystemTimeZone
+}
diff --git a/src/mscorlib/shared/System/DBNull.cs b/src/mscorlib/shared/System/DBNull.cs
new file mode 100644
index 0000000000..486eb72f2a
--- /dev/null
+++ b/src/mscorlib/shared/System/DBNull.cs
@@ -0,0 +1,119 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System.Runtime.Serialization;
+
+namespace System
+{
+ [Serializable]
+ public sealed class DBNull : ISerializable, IConvertible
+ {
+ private DBNull()
+ {
+ }
+
+ private DBNull(SerializationInfo info, StreamingContext context)
+ {
+ throw new NotSupportedException(SR.NotSupported_DBNullSerial);
+ }
+
+ public static readonly DBNull Value = new DBNull();
+
+ public void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.NullUnity, null, null);
+ }
+
+ 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((IConvertible)this, type, provider);
+ }
+ }
+}
+
diff --git a/src/mscorlib/shared/System/DataMisalignedException.cs b/src/mscorlib/shared/System/DataMisalignedException.cs
new file mode 100644
index 0000000000..b1991a048e
--- /dev/null
+++ b/src/mscorlib/shared/System/DataMisalignedException.cs
@@ -0,0 +1,39 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+/*=============================================================================
+**
+**
+** Purpose: The exception class for a misaligned access exception
+**
+=============================================================================*/
+
+using System.Runtime.Serialization;
+
+namespace System
+{
+ [Serializable]
+ public sealed class DataMisalignedException : SystemException
+ {
+ public DataMisalignedException()
+ : base(SR.Arg_DataMisalignedException)
+ {
+ HResult = __HResults.COR_E_DATAMISALIGNED;
+ }
+
+ public DataMisalignedException(String message)
+ : base(message)
+ {
+ HResult = __HResults.COR_E_DATAMISALIGNED;
+ }
+
+ public DataMisalignedException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = __HResults.COR_E_DATAMISALIGNED;
+ }
+
+ internal DataMisalignedException(SerializationInfo info, StreamingContext context) : base(info, context) { }
+ }
+}
diff --git a/src/mscorlib/shared/System/DateTime.cs b/src/mscorlib/shared/System/DateTime.cs
new file mode 100644
index 0000000000..ddb72da77d
--- /dev/null
+++ b/src/mscorlib/shared/System/DateTime.cs
@@ -0,0 +1,1516 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+// See the LICENSE file in the project root for more information.
+
+using System;
+using System.Diagnostics;
+using System.Diagnostics.Contracts;
+using System.Threading;
+using System.Globalization;
+using System.Runtime;
+using System.Runtime.InteropServices;
+using System.Runtime.CompilerServices;
+using System.Runtime.Serialization;
+using System.Runtime.Versioning;
+using System.Security;
+using CultureInfo = System.Globalization.CultureInfo;
+using Calendar = System.Globalization.Calendar;
+
+namespace System
+{
+
+ // This value type represents a date and time. Every DateTime
+ // object has a private field (Ticks) of type Int64 that stores the
+ // date and time as the number of 100 nanosecond intervals since
+ // 12:00 AM January 1, year 1 A.D. in the proleptic Gregorian Calendar.
+ //
+ // Starting from V2.0, DateTime also stored some context about its time
+ // zone in the form of a 3-state value representing Unspecified, Utc or
+ // Local. This is stored in the two top bits of the 64-bit numeric value
+ // with the remainder of the bits storing the tick count. This information
+ // is only used during time zone conversions and is not part of the
+ // identity of the DateTime. Thus, operations like Compare and Equals
+ // ignore this state. This is to stay compatible with earlier behavior
+ // and performance characteristics and to avoid forcing people into dealing
+ // with the effects of daylight savings. Note, that this has little effect
+ // on how the DateTime works except in a context where its specific time
+ // zone is needed, such as during conversions and some parsing and formatting
+ // cases.
+ //
+ // There is also 4th state stored that is a special type of Local value that
+ // is used to avoid data loss when round-tripping between local and UTC time.
+ // See below for more information on this 4th state, although it is
+ // effectively hidden from most users, who just see the 3-state DateTimeKind
+ // enumeration.
+ //
+ // For compatibility, DateTime does not serialize the Kind data when used in
+ // binary serialization.
+ //
+ // For a description of various calendar issues, look at
+ //
+ // Calendar Studies web site, at
+ // http://serendipity.nofadz.com/hermetic/cal_stud.htm.
+ //
+ //
+ [StructLayout(LayoutKind.Auto)]
+ [Serializable]
+ public partial struct DateTime : IComparable, IFormattable, IConvertible, IComparable<DateTime>, IEquatable<DateTime>, ISerializable
+ {
+ // Number of 100ns ticks per time unit
+ private const long TicksPerMillisecond = 10000;
+ private const long TicksPerSecond = TicksPerMillisecond * 1000;
+ private const long TicksPerMinute = TicksPerSecond * 60;
+ private const long TicksPerHour = TicksPerMinute * 60;
+ private const long TicksPerDay = TicksPerHour * 24;
+
+ // Number of milliseconds per time unit
+ private const int MillisPerSecond = 1000;
+ private const int MillisPerMinute = MillisPerSecond * 60;
+ private const int MillisPerHour = MillisPerMinute * 60;
+ private const int MillisPerDay = MillisPerHour * 24;
+
+ // Number of days in a non-leap year
+ private const int DaysPerYear = 365;
+ // Number of days in 4 years
+ private const int DaysPer4Years = DaysPerYear * 4 + 1; // 1461
+ // Number of days in 100 years
+ private const int DaysPer100Years = DaysPer4Years * 25 - 1; // 36524
+ // Number of days in 400 years
+ private const int DaysPer400Years = DaysPer100Years * 4 + 1; // 146097
+
+ // Number of days from 1/1/0001 to 12/31/1600
+ private const int DaysTo1601 = DaysPer400Years * 4; // 584388
+ // Number of days from 1/1/0001 to 12/30/1899
+ private const int DaysTo1899 = DaysPer400Years * 4 + DaysPer100Years * 3 - 367;
+ // Number of days from 1/1/0001 to 12/31/1969
+ internal const int DaysTo1970 = DaysPer400Years * 4 + DaysPer100Years * 3 + DaysPer4Years * 17 + DaysPerYear; // 719,162
+ // Number of days from 1/1/0001 to 12/31/9999
+ private const int DaysTo10000 = DaysPer400Years * 25 - 366; // 3652059
+
+ internal const long MinTicks = 0;
+ internal const long MaxTicks = DaysTo10000 * TicksPerDay - 1;
+ private const long MaxMillis = (long)DaysTo10000 * MillisPerDay;
+
+ private const long TicksTo1970 = DaysTo1970 * TicksPerDay;
+ private const long FileTimeOffset = DaysTo1601 * TicksPerDay;
+ private const long DoubleDateOffset = DaysTo1899 * TicksPerDay;
+ // The minimum OA date is 0100/01/01 (Note it's year 100).
+ // The maximum OA date is 9999/12/31
+ private const long OADateMinAsTicks = (DaysPer100Years - DaysPerYear) * TicksPerDay;
+ // All OA dates must be greater than (not >=) OADateMinAsDouble
+ private const double OADateMinAsDouble = -657435.0;
+ // All OA dates must be less than (not <=) OADateMaxAsDouble
+ private const double OADateMaxAsDouble = 2958466.0;
+
+ private const int DatePartYear = 0;
+ private const int DatePartDayOfYear = 1;
+ private const int DatePartMonth = 2;
+ private const int DatePartDay = 3;
+
+ private static readonly int[] s_daysToMonth365 = {
+ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
+ private static readonly int[] s_daysToMonth366 = {
+ 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};
+
+ public static readonly DateTime MinValue = new DateTime(MinTicks, DateTimeKind.Unspecified);
+ public static readonly DateTime MaxValue = new DateTime(MaxTicks, DateTimeKind.Unspecified);
+
+ private const UInt64 TicksMask = 0x3FFFFFFFFFFFFFFF;
+ private const UInt64 FlagsMask = 0xC000000000000000;
+ private const UInt64 LocalMask = 0x8000000000000000;
+ private const Int64 TicksCeiling = 0x4000000000000000;
+ private const UInt64 KindUnspecified = 0x0000000000000000;
+ private const UInt64 KindUtc = 0x4000000000000000;
+ private const UInt64 KindLocal = 0x8000000000000000;
+ private const UInt64 KindLocalAmbiguousDst = 0xC000000000000000;
+ private const Int32 KindShift = 62;
+
+ private const String TicksField = "ticks";
+ private const String DateDataField = "_dateData";
+
+ // The data is stored as an unsigned 64-bit integeter
+ // Bits 01-62: The value of 100-nanosecond ticks where 0 represents 1/1/0001 12:00am, up until the value
+ // 12/31/9999 23:59:59.9999999
+ // Bits 63-64: A four-state value that describes the DateTimeKind value of the date time, with a 2nd
+ // value for the rare case where the date time is local, but is in an overlapped daylight
+ // savings time hour and it is in daylight savings time. This allows distinction of these
+ // otherwise ambiguous local times and prevents data loss when round tripping from Local to
+ // UTC time.
+ private UInt64 _dateData;
+
+ // Constructs a DateTime from a tick count. The ticks
+ // argument specifies the date as the number of 100-nanosecond intervals
+ // that have elapsed since 1/1/0001 12:00am.
+ //
+ public DateTime(long ticks)
+ {
+ if (ticks < MinTicks || ticks > MaxTicks)
+ throw new ArgumentOutOfRangeException(nameof(ticks), SR.ArgumentOutOfRange_DateTimeBadTicks);
+ Contract.EndContractBlock();
+ _dateData = (UInt64)ticks;
+ }
+
+ private DateTime(UInt64 dateData)
+ {
+ this._dateData = dateData;
+ }
+
+ public DateTime(long ticks, DateTimeKind kind)
+ {
+ if (ticks < MinTicks || ticks > MaxTicks)
+ {
+ throw new ArgumentOutOfRangeException(nameof(ticks), SR.ArgumentOutOfRange_DateTimeBadTicks);
+ }
+ if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local)
+ {
+ throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind));
+ }
+ Contract.EndContractBlock();
+ _dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
+ }
+
+ internal DateTime(long ticks, DateTimeKind kind, Boolean isAmbiguousDst)
+ {
+ if (ticks < MinTicks || ticks > MaxTicks)
+ {
+ throw new ArgumentOutOfRangeException(nameof(ticks), SR.ArgumentOutOfRange_DateTimeBadTicks);
+ }
+ Debug.Assert(kind == DateTimeKind.Local, "Internal Constructor is for local times only");
+ Contract.EndContractBlock();
+ _dateData = ((UInt64)ticks | (isAmbiguousDst ? KindLocalAmbiguousDst : KindLocal));
+ }
+
+ // Constructs a DateTime from a given year, month, and day. The
+ // time-of-day of the resulting DateTime is always midnight.
+ //
+ public DateTime(int year, int month, int day)
+ {
+ _dateData = (UInt64)DateToTicks(year, month, day);
+ }
+
+ // Constructs a DateTime from a given year, month, and day for
+ // the specified calendar. The
+ // time-of-day of the resulting DateTime is always midnight.
+ //
+ public DateTime(int year, int month, int day, Calendar calendar)
+ : this(year, month, day, 0, 0, 0, calendar)
+ {
+ }
+
+ // Constructs a DateTime from a given year, month, day, hour,
+ // minute, and second.
+ //
+ public DateTime(int year, int month, int day, int hour, int minute, int second)
+ {
+ _dateData = (UInt64)(DateToTicks(year, month, day) + TimeToTicks(hour, minute, second));
+ }
+
+ public DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind)
+ {
+ if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local)
+ {
+ throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind));
+ }
+ Contract.EndContractBlock();
+ Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
+ _dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
+ }
+
+ // Constructs a DateTime from a given year, month, day, hour,
+ // minute, and second for the specified calendar.
+ //
+ public DateTime(int year, int month, int day, int hour, int minute, int second, Calendar calendar)
+ {
+ if (calendar == null)
+ throw new ArgumentNullException(nameof(calendar));
+ Contract.EndContractBlock();
+ _dateData = (UInt64)calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks;
+ }
+
+ // Constructs a DateTime from a given year, month, day, hour,
+ // minute, and second.
+ //
+ public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond)
+ {
+ if (millisecond < 0 || millisecond >= MillisPerSecond)
+ {
+ throw new ArgumentOutOfRangeException(nameof(millisecond), SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1));
+ }
+ Contract.EndContractBlock();
+ Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
+ ticks += millisecond * TicksPerMillisecond;
+ if (ticks < MinTicks || ticks > MaxTicks)
+ throw new ArgumentException(SR.Arg_DateTimeRange);
+ _dateData = (UInt64)ticks;
+ }
+
+ public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind)
+ {
+ if (millisecond < 0 || millisecond >= MillisPerSecond)
+ {
+ throw new ArgumentOutOfRangeException(nameof(millisecond), SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1));
+ }
+ if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local)
+ {
+ throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind));
+ }
+ Contract.EndContractBlock();
+ Int64 ticks = DateToTicks(year, month, day) + TimeToTicks(hour, minute, second);
+ ticks += millisecond * TicksPerMillisecond;
+ if (ticks < MinTicks || ticks > MaxTicks)
+ throw new ArgumentException(SR.Arg_DateTimeRange);
+ _dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
+ }
+
+ // Constructs a DateTime from a given year, month, day, hour,
+ // minute, and second for the specified calendar.
+ //
+ public DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar)
+ {
+ if (calendar == null)
+ throw new ArgumentNullException(nameof(calendar));
+ if (millisecond < 0 || millisecond >= MillisPerSecond)
+ {
+ throw new ArgumentOutOfRangeException(nameof(millisecond), SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1));
+ }
+ Contract.EndContractBlock();
+ Int64 ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks;
+ ticks += millisecond * TicksPerMillisecond;
+ if (ticks < MinTicks || ticks > MaxTicks)
+ throw new ArgumentException(SR.Arg_DateTimeRange);
+ _dateData = (UInt64)ticks;
+ }
+
+ 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(nameof(calendar));
+ if (millisecond < 0 || millisecond >= MillisPerSecond)
+ {
+ throw new ArgumentOutOfRangeException(nameof(millisecond), SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1));
+ }
+ if (kind < DateTimeKind.Unspecified || kind > DateTimeKind.Local)
+ {
+ throw new ArgumentException(SR.Argument_InvalidDateTimeKind, nameof(kind));
+ }
+ Contract.EndContractBlock();
+ Int64 ticks = calendar.ToDateTime(year, month, day, hour, minute, second, 0).Ticks;
+ ticks += millisecond * TicksPerMillisecond;
+ if (ticks < MinTicks || ticks > MaxTicks)
+ throw new ArgumentException(SR.Arg_DateTimeRange);
+ _dateData = ((UInt64)ticks | ((UInt64)kind << KindShift));
+ }
+
+ private DateTime(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ throw new ArgumentNullException(nameof(info));
+ Contract.EndContractBlock();
+
+ Boolean foundTicks = false;
+ Boolean foundDateData = false;
+ Int64 serializedTicks = 0;
+ UInt64 serializedDateData = 0;
+
+
+ // Get the data
+ SerializationInfoEnumerator enumerator = info.GetEnumerator();
+ while (enumerator.MoveNext())
+ {
+ switch (enumerator.Name)
+ {
+ case TicksField:
+ serializedTicks = Convert.ToInt64(enumerator.Value, CultureInfo.InvariantCulture);
+ foundTicks = true;
+ break;
+ case DateDataField:
+ serializedDateData = Convert.ToUInt64(enumerator.Value, CultureInfo.InvariantCulture);
+ foundDateData = true;
+ break;
+ default:
+ // Ignore other fields for forward compatibility.
+ break;
+ }
+ }
+ if (foundDateData)
+ {
+ _dateData = serializedDateData;
+ }
+ else if (foundTicks)
+ {
+ _dateData = (UInt64)serializedTicks;
+ }
+ else
+ {
+ throw new SerializationException(SR.Serialization_MissingDateTimeData);
+ }
+ Int64 ticks = InternalTicks;
+ if (ticks < MinTicks || ticks > MaxTicks)
+ {
+ throw new SerializationException(SR.Serialization_DateTimeTicksOutOfRange);
+ }
+ }
+
+
+
+ internal Int64 InternalTicks
+ {
+ get
+ {
+ return (Int64)(_dateData & TicksMask);
+ }
+ }
+
+ private UInt64 InternalKind
+ {
+ get
+ {
+ return (_dateData & FlagsMask);
+ }
+ }
+
+ // Returns the DateTime resulting from adding the given
+ // TimeSpan to this DateTime.
+ //
+ public DateTime Add(TimeSpan value)
+ {
+ return AddTicks(value._ticks);
+ }
+
+ // Returns the DateTime resulting from adding a fractional number of
+ // time units to this DateTime.
+ private DateTime Add(double value, int scale)
+ {
+ long millis = (long)(value * scale + (value >= 0 ? 0.5 : -0.5));
+ if (millis <= -MaxMillis || millis >= MaxMillis)
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_AddValue);
+ return AddTicks(millis * TicksPerMillisecond);
+ }
+
+ // Returns the DateTime resulting from adding a fractional number of
+ // days to this DateTime. The result is computed by rounding the
+ // fractional number of days given by value to the nearest
+ // millisecond, and adding that interval to this DateTime. The
+ // value argument is permitted to be negative.
+ //
+ public DateTime AddDays(double value)
+ {
+ return Add(value, MillisPerDay);
+ }
+
+ // Returns the DateTime resulting from adding a fractional number of
+ // hours to this DateTime. The result is computed by rounding the
+ // fractional number of hours given by value to the nearest
+ // millisecond, and adding that interval to this DateTime. The
+ // value argument is permitted to be negative.
+ //
+ public DateTime AddHours(double value)
+ {
+ return Add(value, MillisPerHour);
+ }
+
+ // Returns the DateTime resulting from the given number of
+ // milliseconds to this DateTime. The result is computed by rounding
+ // the number of milliseconds given by value to the nearest integer,
+ // and adding that interval to this DateTime. The value
+ // argument is permitted to be negative.
+ //
+ public DateTime AddMilliseconds(double value)
+ {
+ return Add(value, 1);
+ }
+
+ // Returns the DateTime resulting from adding a fractional number of
+ // minutes to this DateTime. The result is computed by rounding the
+ // fractional number of minutes given by value to the nearest
+ // millisecond, and adding that interval to this DateTime. The
+ // value argument is permitted to be negative.
+ //
+ public DateTime AddMinutes(double value)
+ {
+ return Add(value, MillisPerMinute);
+ }
+
+ // Returns the DateTime resulting from adding the given number of
+ // months to this DateTime. The result is computed by incrementing
+ // (or decrementing) the year and month parts of this DateTime by
+ // months months, and, if required, adjusting the day part of the
+ // resulting date downwards to the last day of the resulting month in the
+ // resulting year. The time-of-day part of the result is the same as the
+ // time-of-day part of this DateTime.
+ //
+ // In more precise terms, considering this DateTime to be of the
+ // form y / m / d + t, where y is the
+ // year, m is the month, d is the day, and t is the
+ // time-of-day, the result is y1 / m1 / d1 + t,
+ // where y1 and m1 are computed by adding months months
+ // to y and m, and d1 is the largest value less than
+ // or equal to d that denotes a valid day in month m1 of year
+ // y1.
+ //
+ public DateTime AddMonths(int months)
+ {
+ if (months < -120000 || months > 120000) throw new ArgumentOutOfRangeException(nameof(months), SR.ArgumentOutOfRange_DateTimeBadMonths);
+ Contract.EndContractBlock();
+ int y = GetDatePart(DatePartYear);
+ int m = GetDatePart(DatePartMonth);
+ int d = GetDatePart(DatePartDay);
+ int i = m - 1 + months;
+ if (i >= 0)
+ {
+ m = i % 12 + 1;
+ y = y + i / 12;
+ }
+ else
+ {
+ m = 12 + (i + 1) % 12;
+ y = y + (i - 11) / 12;
+ }
+ if (y < 1 || y > 9999)
+ {
+ throw new ArgumentOutOfRangeException(nameof(months), SR.ArgumentOutOfRange_DateArithmetic);
+ }
+ int days = DaysInMonth(y, m);
+ if (d > days) d = days;
+ return new DateTime((UInt64)(DateToTicks(y, m, d) + InternalTicks % TicksPerDay) | InternalKind);
+ }
+
+ // Returns the DateTime resulting from adding a fractional number of
+ // seconds to this DateTime. The result is computed by rounding the
+ // fractional number of seconds given by value to the nearest
+ // millisecond, and adding that interval to this DateTime. The
+ // value argument is permitted to be negative.
+ //
+ public DateTime AddSeconds(double value)
+ {
+ return Add(value, MillisPerSecond);
+ }
+
+ // Returns the DateTime resulting from adding the given number of
+ // 100-nanosecond ticks to this DateTime. The value argument
+ // is permitted to be negative.
+ //
+ public DateTime AddTicks(long value)
+ {
+ long ticks = InternalTicks;
+ if (value > MaxTicks - ticks || value < MinTicks - ticks)
+ {
+ throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_DateArithmetic);
+ }
+ return new DateTime((UInt64)(ticks + value) | InternalKind);
+ }
+
+ // Returns the DateTime resulting from adding the given number of
+ // years to this DateTime. The result is computed by incrementing
+ // (or decrementing) the year part of this DateTime by value
+ // years. If the month and day of this DateTime is 2/29, and if the
+ // resulting year is not a leap year, the month and day of the resulting
+ // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day
+ // parts of the result are the same as those of this DateTime.
+ //
+ public DateTime AddYears(int value)
+ {
+ if (value < -10000 || value > 10000)
+ {
+ // DateTimeOffset.AddYears(int years) is implemented on top of DateTime.AddYears(int value). Use the more appropriate
+ // parameter name out of the two for the exception.
+ throw new ArgumentOutOfRangeException("years", SR.ArgumentOutOfRange_DateTimeBadYears);
+ }
+ Contract.EndContractBlock();
+ return AddMonths(value * 12);
+ }
+
+ // Compares two DateTime values, returning an integer that indicates
+ // their relationship.
+ //
+ public static int Compare(DateTime t1, DateTime t2)
+ {
+ Int64 ticks1 = t1.InternalTicks;
+ Int64 ticks2 = t2.InternalTicks;
+ if (ticks1 > ticks2) return 1;
+ if (ticks1 < ticks2) return -1;
+ return 0;
+ }
+
+ // Compares this DateTime to a given object. This method provides an
+ // implementation of the IComparable interface. The object
+ // argument must be another DateTime, or otherwise an exception
+ // occurs. Null is considered less than any instance.
+ //
+ // Returns a value less than zero if this object
+ 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);
+ }
+
+ // Returns the tick count corresponding to the given year, month, and day.
+ // Will check the if the parameters are valid.
+ private static long DateToTicks(int year, int month, int day)
+ {
+ if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
+ {
+ int[] days = IsLeapYear(year) ? s_daysToMonth366 : s_daysToMonth365;
+ if (day >= 1 && day <= days[month] - days[month - 1])
+ {
+ int y = year - 1;
+ int n = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1;
+ return n * TicksPerDay;
+ }
+ }
+ throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay);
+ }
+
+ // Return the tick count corresponding to the given hour, minute, second.
+ // Will check the if the parameters are valid.
+ private static long TimeToTicks(int hour, int minute, int second)
+ {
+ //TimeSpan.TimeToTicks is a family access function which does no error checking, so
+ //we need to put some error checking out here.
+ if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60)
+ {
+ return (TimeSpan.TimeToTicks(hour, minute, second));
+ }
+ throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond);
+ }
+
+ // Returns the number of days in the month given by the year and
+ // month arguments.
+ //
+ public static int DaysInMonth(int year, int month)
+ {
+ if (month < 1 || month > 12) throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month);
+ Contract.EndContractBlock();
+ // IsLeapYear checks the year argument
+ int[] days = IsLeapYear(year) ? s_daysToMonth366 : s_daysToMonth365;
+ return days[month] - days[month - 1];
+ }
+
+ // Converts an OLE Date to a tick count.
+ // This function is duplicated in COMDateTime.cpp
+ internal static long DoubleDateToTicks(double value)
+ {
+ // The check done this way will take care of NaN
+ if (!(value < OADateMaxAsDouble) || !(value > OADateMinAsDouble))
+ throw new ArgumentException(SR.Arg_OleAutDateInvalid);
+
+ // Conversion to long will not cause an overflow here, as at this point the "value" is in between OADateMinAsDouble and OADateMaxAsDouble
+ long millis = (long)(value * MillisPerDay + (value >= 0 ? 0.5 : -0.5));
+ // The interesting thing here is when you have a value like 12.5 it all positive 12 days and 12 hours from 01/01/1899
+ // However if you a value of -12.25 it is minus 12 days but still positive 6 hours, almost as though you meant -11.75 all negative
+ // This line below fixes up the millis in the negative case
+ if (millis < 0)
+ {
+ millis -= (millis % MillisPerDay) * 2;
+ }
+
+ millis += DoubleDateOffset / TicksPerMillisecond;
+
+ if (millis < 0 || millis >= MaxMillis) throw new ArgumentException(SR.Arg_OleAutDateScale);
+ return millis * TicksPerMillisecond;
+ }
+
+ // Checks if this DateTime is equal to a given object. Returns
+ // true if the given object is a boxed DateTime and its value
+ // is equal to the value of this DateTime. Returns false
+ // otherwise.
+ //
+ public override bool Equals(Object value)
+ {
+ if (value is DateTime)
+ {
+ return InternalTicks == ((DateTime)value).InternalTicks;
+ }
+ return false;
+ }
+
+ public bool Equals(DateTime value)
+ {
+ return InternalTicks == value.InternalTicks;
+ }
+
+ // Compares two DateTime values for equality. Returns true if
+ // the two DateTime values are equal, or false if they are
+ // not equal.
+ //
+ public static bool Equals(DateTime t1, DateTime t2)
+ {
+ return t1.InternalTicks == t2.InternalTicks;
+ }
+
+ public static DateTime FromBinary(Int64 dateData)
+ {
+ if ((dateData & (unchecked((Int64)LocalMask))) != 0)
+ {
+ // Local times need to be adjusted as you move from one time zone to another,
+ // just as they are when serializing in text. As such the format for local times
+ // changes to store the ticks of the UTC time, but with flags that look like a
+ // local date.
+ Int64 ticks = dateData & (unchecked((Int64)TicksMask));
+ // Negative ticks are stored in the top part of the range and should be converted back into a negative number
+ if (ticks > TicksCeiling - TicksPerDay)
+ {
+ ticks = ticks - TicksCeiling;
+ }
+ // Convert the ticks back to local. If the UTC ticks are out of range, we need to default to
+ // the UTC offset from MinValue and MaxValue to be consistent with Parse.
+ Boolean isAmbiguousLocalDst = false;
+ Int64 offsetTicks;
+ if (ticks < MinTicks)
+ {
+ offsetTicks = TimeZoneInfo.GetLocalUtcOffset(DateTime.MinValue, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks;
+ }
+ else if (ticks > MaxTicks)
+ {
+ offsetTicks = TimeZoneInfo.GetLocalUtcOffset(DateTime.MaxValue, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks;
+ }
+ else
+ {
+ // Because the ticks conversion between UTC and local is lossy, we need to capture whether the
+ // time is in a repeated hour so that it can be passed to the DateTime constructor.
+ DateTime utcDt = new DateTime(ticks, DateTimeKind.Utc);
+ Boolean isDaylightSavings = false;
+ offsetTicks = TimeZoneInfo.GetUtcOffsetFromUtc(utcDt, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst).Ticks;
+ }
+ ticks += offsetTicks;
+ // Another behaviour of parsing is to cause small times to wrap around, so that they can be used
+ // to compare times of day
+ if (ticks < 0)
+ {
+ ticks += TicksPerDay;
+ }
+ if (ticks < MinTicks || ticks > MaxTicks)
+ {
+ throw new ArgumentException(SR.Argument_DateTimeBadBinaryData, nameof(dateData));
+ }
+ return new DateTime(ticks, DateTimeKind.Local, isAmbiguousLocalDst);
+ }
+ else
+ {
+ return DateTime.FromBinaryRaw(dateData);
+ }
+ }
+
+ // A version of ToBinary that uses the real representation and does not adjust local times. This is needed for
+ // scenarios where the serialized data must maintain compatibility
+ internal static DateTime FromBinaryRaw(Int64 dateData)
+ {
+ Int64 ticks = dateData & (Int64)TicksMask;
+ if (ticks < MinTicks || ticks > MaxTicks)
+ throw new ArgumentException(SR.Argument_DateTimeBadBinaryData, nameof(dateData));
+ return new DateTime((UInt64)dateData);
+ }
+
+ // Creates a DateTime from a Windows filetime. A Windows filetime is
+ // a long representing the date and time as the number of
+ // 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am.
+ //
+ public static DateTime FromFileTime(long fileTime)
+ {
+ return FromFileTimeUtc(fileTime).ToLocalTime();
+ }
+
+ public static DateTime FromFileTimeUtc(long fileTime)
+ {
+ if (fileTime < 0 || fileTime > MaxTicks - FileTimeOffset)
+ {
+ throw new ArgumentOutOfRangeException(nameof(fileTime), SR.ArgumentOutOfRange_FileTimeInvalid);
+ }
+ Contract.EndContractBlock();
+
+ // This is the ticks in Universal time for this fileTime.
+ long universalTicks = fileTime + FileTimeOffset;
+ return new DateTime(universalTicks, DateTimeKind.Utc);
+ }
+
+ // Creates a DateTime from an OLE Automation Date.
+ //
+ public static DateTime FromOADate(double d)
+ {
+ return new DateTime(DoubleDateToTicks(d), DateTimeKind.Unspecified);
+ }
+
+ void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
+ throw new ArgumentNullException(nameof(info));
+ }
+ Contract.EndContractBlock();
+
+ // Serialize both the old and the new format
+ info.AddValue(TicksField, InternalTicks);
+ info.AddValue(DateDataField, _dateData);
+ }
+
+ public Boolean IsDaylightSavingTime()
+ {
+ if (Kind == DateTimeKind.Utc)
+ {
+ return false;
+ }
+ return TimeZoneInfo.Local.IsDaylightSavingTime(this, TimeZoneInfoOptions.NoThrowOnInvalidTime);
+ }
+
+ public static DateTime SpecifyKind(DateTime value, DateTimeKind kind)
+ {
+ return new DateTime(value.InternalTicks, kind);
+ }
+
+ public Int64 ToBinary()
+ {
+ if (Kind == DateTimeKind.Local)
+ {
+ // Local times need to be adjusted as you move from one time zone to another,
+ // just as they are when serializing in text. As such the format for local times
+ // changes to store the ticks of the UTC time, but with flags that look like a
+ // local date.
+
+ // To match serialization in text we need to be able to handle cases where
+ // the UTC value would be out of range. Unused parts of the ticks range are
+ // used for this, so that values just past max value are stored just past the
+ // end of the maximum range, and values just below minimum value are stored
+ // at the end of the ticks area, just below 2^62.
+ TimeSpan offset = TimeZoneInfo.GetLocalUtcOffset(this, TimeZoneInfoOptions.NoThrowOnInvalidTime);
+ Int64 ticks = Ticks;
+ Int64 storedTicks = ticks - offset.Ticks;
+ if (storedTicks < 0)
+ {
+ storedTicks = TicksCeiling + storedTicks;
+ }
+ return storedTicks | (unchecked((Int64)LocalMask));
+ }
+ else
+ {
+ return (Int64)_dateData;
+ }
+ }
+
+ // Returns the date part of this DateTime. The resulting value
+ // corresponds to this DateTime with the time-of-day part set to
+ // zero (midnight).
+ //
+ public DateTime Date
+ {
+ get
+ {
+ Int64 ticks = InternalTicks;
+ return new DateTime((UInt64)(ticks - ticks % TicksPerDay) | InternalKind);
+ }
+ }
+
+ // Returns a given date part of this DateTime. This method is used
+ // to compute the year, day-of-year, month, or day part.
+ private int GetDatePart(int part)
+ {
+ Int64 ticks = InternalTicks;
+ // n = number of days since 1/1/0001
+ int n = (int)(ticks / TicksPerDay);
+ // y400 = number of whole 400-year periods since 1/1/0001
+ int y400 = n / DaysPer400Years;
+ // n = day number within 400-year period
+ n -= y400 * DaysPer400Years;
+ // y100 = number of whole 100-year periods within 400-year period
+ int y100 = n / DaysPer100Years;
+ // Last 100-year period has an extra day, so decrement result if 4
+ if (y100 == 4) y100 = 3;
+ // n = day number within 100-year period
+ n -= y100 * DaysPer100Years;
+ // y4 = number of whole 4-year periods within 100-year period
+ int y4 = n / DaysPer4Years;
+ // n = day number within 4-year period
+ n -= y4 * DaysPer4Years;
+ // y1 = number of whole years within 4-year period
+ int y1 = n / DaysPerYear;
+ // Last year has an extra day, so decrement result if 4
+ if (y1 == 4) y1 = 3;
+ // If year was requested, compute and return it
+ if (part == DatePartYear)
+ {
+ return y400 * 400 + y100 * 100 + y4 * 4 + y1 + 1;
+ }
+ // n = day number within year
+ n -= y1 * DaysPerYear;
+ // If day-of-year was requested, return it
+ if (part == DatePartDayOfYear) return n + 1;
+ // Leap year calculation looks different from IsLeapYear since y1, y4,
+ // and y100 are relative to year 1, not year 0
+ bool leapYear = y1 == 3 && (y4 != 24 || y100 == 3);
+ int[] days = leapYear ? s_daysToMonth366 : s_daysToMonth365;
+ // All months have less than 32 days, so n >> 5 is a good conservative
+ // estimate for the month
+ int m = (n >> 5) + 1;
+ // m = 1-based month number
+ while (n >= days[m]) m++;
+ // If month was requested, return it
+ if (part == DatePartMonth) return m;
+ // Return 1-based day-of-month
+ return n - days[m - 1] + 1;
+ }
+
+ // Returns the day-of-month part of this DateTime. The returned
+ // value is an integer between 1 and 31.
+ //
+ public int Day
+ {
+ get
+ {
+ Contract.Ensures(Contract.Result<int>() >= 1);
+ Contract.Ensures(Contract.Result<int>() <= 31);
+ return GetDatePart(DatePartDay);
+ }
+ }
+
+ // Returns the day-of-week part of this DateTime. The returned value
+ // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
+ // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
+ // Thursday, 5 indicates Friday, and 6 indicates Saturday.
+ //
+ public DayOfWeek DayOfWeek
+ {
+ get
+ {
+ Contract.Ensures(Contract.Result<DayOfWeek>() >= DayOfWeek.Sunday);
+ Contract.Ensures(Contract.Result<DayOfWeek>() <= DayOfWeek.Saturday);
+ return (DayOfWeek)((InternalTicks / TicksPerDay + 1) % 7);
+ }
+ }
+
+ // Returns the day-of-year part of this DateTime. The returned value
+ // is an integer between 1 and 366.
+ //
+ public int DayOfYear
+ {
+ get
+ {
+ Contract.Ensures(Contract.Result<int>() >= 1);
+ Contract.Ensures(Contract.Result<int>() <= 366); // leap year
+ return GetDatePart(DatePartDayOfYear);
+ }
+ }
+
+ // Returns the hash code for this DateTime.
+ //
+ public override int GetHashCode()
+ {
+ Int64 ticks = InternalTicks;
+ return unchecked((int)ticks) ^ (int)(ticks >> 32);
+ }
+
+ // Returns the hour part of this DateTime. The returned value is an
+ // integer between 0 and 23.
+ //
+ public int Hour
+ {
+ get
+ {
+ Contract.Ensures(Contract.Result<int>() >= 0);
+ Contract.Ensures(Contract.Result<int>() < 24);
+ return (int)((InternalTicks / TicksPerHour) % 24);
+ }
+ }
+
+ internal Boolean IsAmbiguousDaylightSavingTime()
+ {
+ return (InternalKind == KindLocalAmbiguousDst);
+ }
+
+ [Pure]
+ public DateTimeKind Kind
+ {
+ get
+ {
+ switch (InternalKind)
+ {
+ case KindUnspecified:
+ return DateTimeKind.Unspecified;
+ case KindUtc:
+ return DateTimeKind.Utc;
+ default:
+ return DateTimeKind.Local;
+ }
+ }
+ }
+
+ // Returns the millisecond part of this DateTime. The returned value
+ // is an integer between 0 and 999.
+ //
+ public int Millisecond
+ {
+ get
+ {
+ Contract.Ensures(Contract.Result<int>() >= 0);
+ Contract.Ensures(Contract.Result<int>() < 1000);
+ return (int)((InternalTicks / TicksPerMillisecond) % 1000);
+ }
+ }
+
+ // Returns the minute part of this DateTime. The returned value is
+ // an integer between 0 and 59.
+ //
+ public int Minute
+ {
+ get
+ {
+ Contract.Ensures(Contract.Result<int>() >= 0);
+ Contract.Ensures(Contract.Result<int>() < 60);
+ return (int)((InternalTicks / TicksPerMinute) % 60);
+ }
+ }
+
+ // Returns the month part of this DateTime. The returned value is an
+ // integer between 1 and 12.
+ //
+ public int Month
+ {
+ get
+ {
+ Contract.Ensures(Contract.Result<int>() >= 1);
+ return GetDatePart(DatePartMonth);
+ }
+ }
+
+ // Returns a DateTime representing the current date and time. The
+ // resolution of the returned value depends on the system timer. For
+ // Windows NT 3.5 and later the timer resolution is approximately 10ms,
+ // for Windows NT 3.1 it is approximately 16ms, and for Windows 95 and 98
+ // it is approximately 55ms.
+ //
+ public static DateTime Now
+ {
+ get
+ {
+ Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Local);
+
+ DateTime utc = UtcNow;
+ Boolean isAmbiguousLocalDst = false;
+ Int64 offset = TimeZoneInfo.GetDateTimeNowUtcOffsetFromUtc(utc, out isAmbiguousLocalDst).Ticks;
+ long tick = utc.Ticks + offset;
+ if (tick > DateTime.MaxTicks)
+ {
+ return new DateTime(DateTime.MaxTicks, DateTimeKind.Local);
+ }
+ if (tick < DateTime.MinTicks)
+ {
+ return new DateTime(DateTime.MinTicks, DateTimeKind.Local);
+ }
+ return new DateTime(tick, DateTimeKind.Local, isAmbiguousLocalDst);
+ }
+ }
+
+ // Returns the second part of this DateTime. The returned value is
+ // an integer between 0 and 59.
+ //
+ public int Second
+ {
+ get
+ {
+ Contract.Ensures(Contract.Result<int>() >= 0);
+ Contract.Ensures(Contract.Result<int>() < 60);
+ return (int)((InternalTicks / TicksPerSecond) % 60);
+ }
+ }
+
+ // Returns the tick count for this DateTime. The returned value is
+ // the number of 100-nanosecond intervals that have elapsed since 1/1/0001
+ // 12:00am.
+ //
+ public long Ticks
+ {
+ get
+ {
+ return InternalTicks;
+ }
+ }
+
+ // Returns the time-of-day part of this DateTime. The returned value
+ // is a TimeSpan that indicates the time elapsed since midnight.
+ //
+ public TimeSpan TimeOfDay
+ {
+ get
+ {
+ return new TimeSpan(InternalTicks % TicksPerDay);
+ }