summaryrefslogtreecommitdiff
path: root/src/mscorlib
diff options
context:
space:
mode:
Diffstat (limited to 'src/mscorlib')
-rw-r--r--src/mscorlib/ILLinkTrim.xml40
-rw-r--r--src/mscorlib/MembersMustExist.AnalyzerData3
-rw-r--r--src/mscorlib/Resources/Strings.resx93
-rw-r--r--src/mscorlib/System.Private.CoreLib.csproj81
-rw-r--r--src/mscorlib/System.Private.CoreLib.sln11
-rw-r--r--src/mscorlib/Tools/Versioning/GenerateVersionInfo.targets38
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs2
-rw-r--r--src/mscorlib/shared/Interop/Unix/System.Native/Interop.PosixFAdvise.cs2
-rw-r--r--src/mscorlib/shared/Interop/Windows/Interop.Libraries.cs1
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs24
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs29
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FreeLibrary.cs15
-rw-r--r--src/mscorlib/shared/Interop/Windows/Kernel32/Interop.LoadLibraryEx.cs18
-rw-r--r--src/mscorlib/shared/Interop/Windows/User32/Interop.LoadString.cs16
-rw-r--r--src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs (renamed from src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs)6
-rw-r--r--src/mscorlib/shared/System.Private.CoreLib.Shared.projitems103
-rw-r--r--src/mscorlib/shared/System.Private.CoreLib.Shared.shproj17
-rw-r--r--src/mscorlib/shared/System/AccessViolationException.cs (renamed from src/mscorlib/src/System/AccessViolationException.cs)6
-rw-r--r--src/mscorlib/shared/System/Action.cs6
-rw-r--r--src/mscorlib/shared/System/AggregateException.cs (renamed from src/mscorlib/src/System/AggregateException.cs)34
-rw-r--r--src/mscorlib/shared/System/ApplicationException.cs6
-rw-r--r--src/mscorlib/shared/System/ArgumentException.cs10
-rw-r--r--src/mscorlib/shared/System/ArgumentNullException.cs8
-rw-r--r--src/mscorlib/shared/System/ArgumentOutOfRangeException.cs10
-rw-r--r--src/mscorlib/shared/System/ArithmeticException.cs6
-rw-r--r--src/mscorlib/shared/System/ArrayTypeMismatchException.cs6
-rw-r--r--src/mscorlib/shared/System/BadImageFormatException.cs12
-rw-r--r--src/mscorlib/shared/System/BitConverter.cs185
-rw-r--r--src/mscorlib/shared/System/Boolean.cs (renamed from src/mscorlib/src/System/Boolean.cs)65
-rw-r--r--src/mscorlib/shared/System/Buffers/ArrayPoolEventSource.cs (renamed from src/mscorlib/src/System/Buffers/ArrayPoolEventSource.cs)0
-rw-r--r--src/mscorlib/shared/System/Buffers/IRetainable.cs15
-rw-r--r--src/mscorlib/shared/System/Buffers/MemoryHandle.cs44
-rw-r--r--src/mscorlib/shared/System/Buffers/OwnedMemory.cs53
-rw-r--r--src/mscorlib/shared/System/Byte.cs (renamed from src/mscorlib/src/System/Byte.cs)60
-rw-r--r--src/mscorlib/shared/System/Collections/Generic/KeyNotFoundException.cs6
-rw-r--r--src/mscorlib/shared/System/Collections/ICollection.cs2
-rw-r--r--src/mscorlib/shared/System/Collections/ListDictionaryInternal.cs (renamed from src/mscorlib/src/System/Collections/ListDictionaryInternal.cs)7
-rw-r--r--src/mscorlib/shared/System/Collections/ObjectModel/Collection.cs (renamed from src/mscorlib/src/System/Collections/ObjectModel/Collection.cs)7
-rw-r--r--src/mscorlib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs (renamed from src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs)7
-rw-r--r--src/mscorlib/shared/System/Convert.cs4
-rw-r--r--src/mscorlib/shared/System/DBNull.cs10
-rw-r--r--src/mscorlib/shared/System/DataMisalignedException.cs6
-rw-r--r--src/mscorlib/shared/System/DateTime.cs8
-rw-r--r--src/mscorlib/shared/System/DateTimeOffset.cs6
-rw-r--r--src/mscorlib/shared/System/DefaultBinder.cs42
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs30
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs26
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/IEventProvider.cs2
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs10
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataType.cs2
-rw-r--r--src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs12
-rw-r--r--src/mscorlib/shared/System/DivideByZeroException.cs6
-rw-r--r--src/mscorlib/shared/System/DllNotFoundException.cs6
-rw-r--r--src/mscorlib/shared/System/Double.cs (renamed from src/mscorlib/src/System/Double.cs)98
-rw-r--r--src/mscorlib/shared/System/DuplicateWaitObjectException.cs8
-rw-r--r--src/mscorlib/shared/System/EntryPointNotFoundException.cs6
-rw-r--r--src/mscorlib/shared/System/ExecutionEngineException.cs6
-rw-r--r--src/mscorlib/shared/System/FieldAccessException.cs6
-rw-r--r--src/mscorlib/shared/System/FormatException.cs6
-rw-r--r--src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs6
-rw-r--r--src/mscorlib/shared/System/Globalization/DateTimeParse.cs321
-rw-r--r--src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs2
-rw-r--r--src/mscorlib/shared/System/Globalization/HijriCalendar.Win32.cs4
-rw-r--r--src/mscorlib/shared/System/Globalization/HijriCalendar.cs4
-rw-r--r--src/mscorlib/shared/System/Globalization/JapaneseCalendar.Win32.cs7
-rw-r--r--src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs31
-rw-r--r--src/mscorlib/shared/System/Globalization/TimeSpanFormat.cs (renamed from src/mscorlib/src/System/Globalization/TimeSpanFormat.cs)305
-rw-r--r--src/mscorlib/shared/System/Globalization/TimeSpanParse.cs1675
-rw-r--r--src/mscorlib/shared/System/Guid.cs (renamed from src/mscorlib/src/System/Guid.cs)768
-rw-r--r--src/mscorlib/shared/System/HResults.cs (renamed from src/mscorlib/src/System/__HResults.cs)69
-rw-r--r--src/mscorlib/shared/System/IO/BinaryWriter.cs36
-rw-r--r--src/mscorlib/shared/System/IO/DirectoryNotFoundException.cs6
-rw-r--r--src/mscorlib/shared/System/IO/DisableMediaInsertionPrompt.cs36
-rw-r--r--src/mscorlib/shared/System/IO/DriveNotFoundException.cs (renamed from src/mscorlib/src/System/IO/DriveNotFoundException.cs)24
-rw-r--r--src/mscorlib/shared/System/IO/EndOfStreamException.cs6
-rw-r--r--src/mscorlib/shared/System/IO/FileLoadException.cs10
-rw-r--r--src/mscorlib/shared/System/IO/FileNotFoundException.cs12
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.Unix.cs445
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.Win32.cs45
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.WinRT.cs32
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.Windows.cs359
-rw-r--r--src/mscorlib/shared/System/IO/FileStream.cs170
-rw-r--r--src/mscorlib/shared/System/IO/FileStreamCompletionSource.Win32.cs59
-rw-r--r--src/mscorlib/shared/System/IO/IOException.cs41
-rw-r--r--src/mscorlib/shared/System/IO/Path.cs24
-rw-r--r--src/mscorlib/shared/System/IO/PathInternal.Windows.cs5
-rw-r--r--src/mscorlib/shared/System/IO/PathTooLongException.cs6
-rw-r--r--src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs4
-rw-r--r--src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs156
-rw-r--r--src/mscorlib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs20
-rw-r--r--src/mscorlib/shared/System/IO/Win32Marshal.cs20
-rw-r--r--src/mscorlib/shared/System/IndexOutOfRangeException.cs6
-rw-r--r--src/mscorlib/shared/System/InsufficientExecutionStackException.cs6
-rw-r--r--src/mscorlib/shared/System/Int16.cs (renamed from src/mscorlib/src/System/Int16.cs)56
-rw-r--r--src/mscorlib/shared/System/Int32.cs (renamed from src/mscorlib/src/System/Int32.cs)67
-rw-r--r--src/mscorlib/shared/System/Int64.cs (renamed from src/mscorlib/src/System/Int64.cs)51
-rw-r--r--src/mscorlib/shared/System/InvalidCastException.cs6
-rw-r--r--src/mscorlib/shared/System/InvalidOperationException.cs6
-rw-r--r--src/mscorlib/shared/System/InvalidProgramException.cs6
-rw-r--r--src/mscorlib/shared/System/Lazy.cs2
-rw-r--r--src/mscorlib/shared/System/MemberAccessException.cs6
-rw-r--r--src/mscorlib/shared/System/Memory.cs284
-rw-r--r--src/mscorlib/shared/System/MethodAccessException.cs6
-rw-r--r--src/mscorlib/shared/System/MissingMethodException.cs6
-rw-r--r--src/mscorlib/shared/System/MulticastNotSupportedException.cs6
-rw-r--r--src/mscorlib/shared/System/NonSerializedAttribute.cs14
-rw-r--r--src/mscorlib/shared/System/NotFiniteNumberException.cs12
-rw-r--r--src/mscorlib/shared/System/NotImplementedException.cs6
-rw-r--r--src/mscorlib/shared/System/NotSupportedException.cs6
-rw-r--r--src/mscorlib/shared/System/NullReferenceException.cs6
-rw-r--r--src/mscorlib/shared/System/ObjectDisposedException.cs4
-rw-r--r--src/mscorlib/shared/System/OperationCanceledException.cs6
-rw-r--r--src/mscorlib/shared/System/OverflowException.cs6
-rw-r--r--src/mscorlib/shared/System/PlatformNotSupportedException.cs6
-rw-r--r--src/mscorlib/shared/System/Random.cs38
-rw-r--r--src/mscorlib/shared/System/RankException.cs6
-rw-r--r--src/mscorlib/shared/System/ReadOnlyMemory.cs270
-rw-r--r--src/mscorlib/shared/System/ReadOnlySpan.cs50
-rw-r--r--src/mscorlib/shared/System/Reflection/AmbiguousMatchException.cs6
-rw-r--r--src/mscorlib/shared/System/Reflection/BindingFlags.cs1
-rw-r--r--src/mscorlib/shared/System/Reflection/CustomAttributeFormatException.cs2
-rw-r--r--src/mscorlib/shared/System/Reflection/IReflect.cs4
-rw-r--r--src/mscorlib/shared/System/Reflection/InvalidFilterCriteriaException.cs2
-rw-r--r--src/mscorlib/shared/System/Reflection/MethodInfo.Internal.cs17
-rw-r--r--src/mscorlib/shared/System/Reflection/MethodInfo.cs2
-rw-r--r--src/mscorlib/shared/System/Reflection/Pointer.cs2
-rw-r--r--src/mscorlib/shared/System/Reflection/ReflectionTypeLoadException.cs4
-rw-r--r--src/mscorlib/shared/System/Reflection/SignatureArrayType.cs46
-rw-r--r--src/mscorlib/shared/System/Reflection/SignatureByRefType.cs27
-rw-r--r--src/mscorlib/shared/System/Reflection/SignatureConstructedGenericType.cs73
-rw-r--r--src/mscorlib/shared/System/Reflection/SignatureGenericMethodParameterType.cs18
-rw-r--r--src/mscorlib/shared/System/Reflection/SignatureGenericParameterType.cs46
-rw-r--r--src/mscorlib/shared/System/Reflection/SignatureHasElementType.cs48
-rw-r--r--src/mscorlib/shared/System/Reflection/SignaturePointerType.cs27
-rw-r--r--src/mscorlib/shared/System/Reflection/SignatureType.cs139
-rw-r--r--src/mscorlib/shared/System/Reflection/SignatureTypeExtensions.cs227
-rw-r--r--src/mscorlib/shared/System/Reflection/TargetException.cs2
-rw-r--r--src/mscorlib/shared/System/Reflection/TargetInvocationException.cs4
-rw-r--r--src/mscorlib/shared/System/Reflection/TargetParameterCountException.cs6
-rw-r--r--src/mscorlib/shared/System/Reflection/TypeDelegator.cs1
-rw-r--r--src/mscorlib/shared/System/Resources/MissingManifestResourceException.cs6
-rw-r--r--src/mscorlib/shared/System/Resources/MissingSatelliteAssemblyException.cs8
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs21
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs111
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs71
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs12
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs19
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs39
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/IntrinsicAttribute.cs13
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/MethodImplAttribute.cs29
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/RuntimeWrappedException.cs33
-rw-r--r--src/mscorlib/shared/System/Runtime/CompilerServices/ValueTaskAwaiter.cs37
-rw-r--r--src/mscorlib/shared/System/Runtime/ExceptionServices/HandleProcessCorruptedStateExceptionsAttribute.cs (renamed from src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs)14
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/BestFitMappingAttribute.cs19
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/DefaultCharSetAttribute.cs17
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/DefaultDllImportSearchPathsAttribute.cs17
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/DllImportAttribute.cs26
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/DllImportSearchPath.cs18
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/ExternalException.cs6
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/FieldOffsetAttribute.cs17
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/InAttribute.cs14
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/MarshalAsAttribute.cs39
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/OptionalAttribute.cs14
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/OutAttribute.cs14
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/PreserveSigAttribute.cs14
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/StructLayoutAttribute.cs26
-rw-r--r--src/mscorlib/shared/System/Runtime/InteropServices/UnmanagedFunctionPointerAttribute.cs10
-rw-r--r--src/mscorlib/shared/System/Runtime/Serialization/SerializationException.cs6
-rw-r--r--src/mscorlib/shared/System/SByte.cs (renamed from src/mscorlib/src/System/SByte.cs)71
-rw-r--r--src/mscorlib/shared/System/Security/SecurityException.cs10
-rw-r--r--src/mscorlib/shared/System/Security/VerificationException.cs6
-rw-r--r--src/mscorlib/shared/System/SerializableAttribute.cs12
-rw-r--r--src/mscorlib/shared/System/Single.cs (renamed from src/mscorlib/src/System/Single.cs)96
-rw-r--r--src/mscorlib/shared/System/Span.NonGeneric.cs2
-rw-r--r--src/mscorlib/shared/System/Span.cs55
-rw-r--r--src/mscorlib/shared/System/StackOverflowException.cs6
-rw-r--r--src/mscorlib/shared/System/StringSpanHelpers.cs93
-rw-r--r--src/mscorlib/shared/System/SystemException.cs6
-rw-r--r--src/mscorlib/shared/System/Text/Decoder.cs26
-rw-r--r--src/mscorlib/shared/System/Text/DecoderExceptionFallback.cs6
-rw-r--r--src/mscorlib/shared/System/Text/Encoder.cs26
-rw-r--r--src/mscorlib/shared/System/Text/EncoderExceptionFallback.cs6
-rw-r--r--src/mscorlib/shared/System/Text/Encoding.cs44
-rw-r--r--src/mscorlib/shared/System/Text/Normalization.cs15
-rw-r--r--src/mscorlib/shared/System/Text/StringBuilder.cs77
-rw-r--r--src/mscorlib/shared/System/Text/UTF32Encoding.cs7
-rw-r--r--src/mscorlib/shared/System/Text/UTF8Encoding.cs10
-rw-r--r--src/mscorlib/shared/System/Text/UnicodeEncoding.cs7
-rw-r--r--src/mscorlib/shared/System/Threading/AbandonedMutexException.cs12
-rw-r--r--src/mscorlib/shared/System/Threading/DeferredDisposableLifetime.cs2
-rw-r--r--src/mscorlib/shared/System/Threading/LazyInitializer.cs2
-rw-r--r--src/mscorlib/shared/System/Threading/ReaderWriterLockSlim.cs240
-rw-r--r--src/mscorlib/shared/System/Threading/SpinWait.cs98
-rw-r--r--src/mscorlib/shared/System/Threading/SynchronizationLockException.cs6
-rw-r--r--src/mscorlib/shared/System/Threading/Tasks/ValueTask.cs169
-rw-r--r--src/mscorlib/shared/System/Threading/ThreadAbortException.cs2
-rw-r--r--src/mscorlib/shared/System/Threading/ThreadStartException.cs4
-rw-r--r--src/mscorlib/shared/System/Threading/ThreadStateException.cs6
-rw-r--r--src/mscorlib/shared/System/Threading/TimeoutHelper.cs4
-rw-r--r--src/mscorlib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs6
-rw-r--r--src/mscorlib/shared/System/TimeSpan.cs80
-rw-r--r--src/mscorlib/shared/System/TimeoutException.cs6
-rw-r--r--src/mscorlib/shared/System/Type.cs32
-rw-r--r--src/mscorlib/shared/System/TypeAccessException.cs6
-rw-r--r--src/mscorlib/shared/System/TypeInitializationException.cs6
-rw-r--r--src/mscorlib/shared/System/TypeUnloadedException.cs6
-rw-r--r--src/mscorlib/shared/System/UInt16.cs (renamed from src/mscorlib/src/System/UInt16.cs)59
-rw-r--r--src/mscorlib/shared/System/UInt32.cs (renamed from src/mscorlib/src/System/UInt32.cs)56
-rw-r--r--src/mscorlib/shared/System/UInt64.cs (renamed from src/mscorlib/src/System/UInt64.cs)55
-rw-r--r--src/mscorlib/shared/System/UnauthorizedAccessException.cs6
-rw-r--r--src/mscorlib/shared/System/UnitySerializationHolder.cs66
-rw-r--r--src/mscorlib/shared/System/Version.cs340
-rw-r--r--src/mscorlib/src/Internal/Padding.cs27
-rw-r--r--src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs29
-rw-r--r--src/mscorlib/src/Interop/Unix/Interop.Libraries.cs14
-rw-r--r--src/mscorlib/src/Microsoft/Win32/RegistryKey.cs58
-rw-r--r--src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs27
-rw-r--r--src/mscorlib/src/Microsoft/Win32/Win32Native.cs260
-rw-r--r--src/mscorlib/src/System/Activator.cs18
-rw-r--r--src/mscorlib/src/System/AppContext/AppContextDefaultValues.cs2
-rw-r--r--src/mscorlib/src/System/AppDomain.cs6
-rw-r--r--src/mscorlib/src/System/AppDomainSetup.cs35
-rw-r--r--src/mscorlib/src/System/AppDomainUnloadedException.cs2
-rw-r--r--src/mscorlib/src/System/Array.cs61
-rw-r--r--src/mscorlib/src/System/Buffer.cs14
-rw-r--r--src/mscorlib/src/System/ByReference.cs2
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs614
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs53
-rw-r--r--src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs94
-rw-r--r--src/mscorlib/src/System/Collections/Generic/Dictionary.cs17
-rw-r--r--src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs5
-rw-r--r--src/mscorlib/src/System/Collections/Hashtable.cs3
-rw-r--r--src/mscorlib/src/System/Decimal.cs37
-rw-r--r--src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs2
-rw-r--r--src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs2
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventPipe.cs6
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventPipeEventProvider.cs25
-rw-r--r--src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs2
-rw-r--r--src/mscorlib/src/System/Diagnostics/Stacktrace.cs3
-rw-r--r--src/mscorlib/src/System/Enum.cs17
-rw-r--r--src/mscorlib/src/System/Environment.cs77
-rw-r--r--src/mscorlib/src/System/Exception.cs4
-rw-r--r--src/mscorlib/src/System/Globalization/CompareInfo.Unix.cs18
-rw-r--r--src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs4
-rw-r--r--src/mscorlib/src/System/Globalization/CultureData.Windows.cs16
-rw-r--r--src/mscorlib/src/System/Globalization/CultureData.cs114
-rw-r--r--src/mscorlib/src/System/Globalization/CultureInfo.cs68
-rw-r--r--src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs64
-rw-r--r--src/mscorlib/src/System/Globalization/TextInfo.Unix.cs1
-rw-r--r--src/mscorlib/src/System/Globalization/TextInfo.Windows.cs4
-rw-r--r--src/mscorlib/src/System/Globalization/TextInfo.cs36
-rw-r--r--src/mscorlib/src/System/Globalization/TimeSpanParse.cs1810
-rw-r--r--src/mscorlib/src/System/Guid.CoreCLR.cs27
-rw-r--r--src/mscorlib/src/System/HResults.cs235
-rw-r--r--src/mscorlib/src/System/IO/BinaryReader.cs41
-rw-r--r--src/mscorlib/src/System/IO/Directory.cs6
-rw-r--r--src/mscorlib/src/System/IO/File.cs2
-rw-r--r--src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs2
-rw-r--r--src/mscorlib/src/System/IO/FileSystemEnumerable.cs2
-rw-r--r--src/mscorlib/src/System/IO/IOException.cs73
-rw-r--r--src/mscorlib/src/System/IO/MemoryStream.cs121
-rw-r--r--src/mscorlib/src/System/IO/Stream.cs123
-rw-r--r--src/mscorlib/src/System/IO/StreamReader.cs14
-rw-r--r--src/mscorlib/src/System/IO/__Error.cs66
-rw-r--r--src/mscorlib/src/System/IO/__HResults.cs31
-rw-r--r--src/mscorlib/src/System/InsufficientMemoryException.cs6
-rw-r--r--src/mscorlib/src/System/MissingFieldException.cs6
-rw-r--r--src/mscorlib/src/System/MissingMemberException.cs6
-rw-r--r--src/mscorlib/src/System/MulticastDelegate.cs71
-rw-r--r--src/mscorlib/src/System/NonSerializedAttribute.cs36
-rw-r--r--src/mscorlib/src/System/Number.cs92
-rw-r--r--src/mscorlib/src/System/OutOfMemoryException.cs6
-rw-r--r--src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs6
-rw-r--r--src/mscorlib/src/System/Reflection/CustomAttribute.cs376
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs11
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs8
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs4
-rw-r--r--src/mscorlib/src/System/Reflection/ExceptionHandlingClause.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/INVOCATION_FLAGS.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/MethodBody.cs2
-rw-r--r--src/mscorlib/src/System/Reflection/RtFieldInfo.cs21
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeAssembly.cs74
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs28
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs35
-rw-r--r--src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs88
-rw-r--r--src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs7
-rw-r--r--src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs36
-rw-r--r--src/mscorlib/src/System/Resources/ResourceManager.cs28
-rw-r--r--src/mscorlib/src/System/Resources/ResourceSet.cs8
-rw-r--r--src/mscorlib/src/System/Resources/__HResults.cs24
-rw-r--r--src/mscorlib/src/System/RtType.cs89
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs29
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs46
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs97
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs47
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs42
-rw-r--r--src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs27
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs430
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/COMException.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs6
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs17
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs46
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs12
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs4
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs8
-rw-r--r--src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs2
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/Vector128.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/Vector256.cs11
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Aes.cs74
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Avx.cs996
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Avx2.cs1362
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Bmi1.cs80
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Bmi2.cs54
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Enums.cs189
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Fma.cs119
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Lzcnt.cs27
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Pclmulqdq.cs27
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Popcnt.cs27
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse.cs218
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse2.cs1057
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse3.cs78
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse41.cs408
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse42.cs233
-rw-r--r--src/mscorlib/src/System/Runtime/Intrinsics/X86/Ssse3.cs92
-rw-r--r--src/mscorlib/src/System/Runtime/MemoryFailPoint.cs50
-rw-r--r--src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs1
-rw-r--r--src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs33
-rw-r--r--src/mscorlib/src/System/RuntimeHandles.cs13
-rw-r--r--src/mscorlib/src/System/SerializableAttribute.cs35
-rw-r--r--src/mscorlib/src/System/String.Comparison.cs36
-rw-r--r--src/mscorlib/src/System/String.Searching.cs91
-rw-r--r--src/mscorlib/src/System/String.cs40
-rw-r--r--src/mscorlib/src/System/Threading/CancellationToken.cs2
-rw-r--r--src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs17
-rw-r--r--src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Windows.cs5
-rw-r--r--src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs2
-rw-r--r--src/mscorlib/src/System/Threading/EventWaitHandle.cs13
-rw-r--r--src/mscorlib/src/System/Threading/ManualResetEventSlim.cs47
-rw-r--r--src/mscorlib/src/System/Threading/Mutex.cs7
-rw-r--r--src/mscorlib/src/System/Threading/PinnableBufferCache.cs6
-rw-r--r--src/mscorlib/src/System/Threading/Semaphore.cs8
-rw-r--r--src/mscorlib/src/System/Threading/SemaphoreSlim.cs83
-rw-r--r--src/mscorlib/src/System/Threading/SpinLock.cs70
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs6
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs2
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs19
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs6
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/Task.cs81
-rw-r--r--src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs4
-rw-r--r--src/mscorlib/src/System/Threading/Thread.cs9
-rw-r--r--src/mscorlib/src/System/Threading/ThreadInterruptedException.cs6
-rw-r--r--src/mscorlib/src/System/Threading/ThreadLocal.cs2
-rw-r--r--src/mscorlib/src/System/Threading/ThreadPool.cs204
-rw-r--r--src/mscorlib/src/System/ThrowHelper.cs37
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs2
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.StringSerializer.cs2
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.Unix.cs28
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.Win32.cs12
-rw-r--r--src/mscorlib/src/System/TimeZoneInfo.cs2
-rw-r--r--src/mscorlib/src/System/Type.CoreCLR.cs35
-rw-r--r--src/mscorlib/src/System/TypeLoadException.cs8
387 files changed, 15043 insertions, 7685 deletions
diff --git a/src/mscorlib/ILLinkTrim.xml b/src/mscorlib/ILLinkTrim.xml
new file mode 100644
index 0000000000..fdd89b823e
--- /dev/null
+++ b/src/mscorlib/ILLinkTrim.xml
@@ -0,0 +1,40 @@
+<linker>
+ <!-- To run illink casually on S.P.CoreLib to find dead code, use a command similar to:
+
+C:\git\corefx\Tools/dotnetcli/dotnet.exe "C:\git\corefx\Tools/ILLink/illink.dll" -r System.Private.CoreLib -d C:\git\coreclr\bin\Product\Windows_NT.x64.Debug\ -t -out C:\out\ -b true -v true -h LdtokenTypeMethods,InstanceConstructors -x illinktrim.xml
+
+Then compare the result with an assembly differ.
+
+Note: it will retain all internal members unless you temporarily remove all InternalsVisibleTo attributes (in mscorlib.Friends.cs). Of course, you're then responsible for determining whether those internals were among those the other assemblies use.
+
+Also take care to not remove code that is Unix only, release only, etc.
+
+-->
+ <assembly fullname="System.Private.CoreLib">
+ <type fullname="System.AccessViolationException">
+ <!-- set by runtime -->
+ <field signature="System.Int32 _accessType"/>
+ <field signature="System.IntPtr _ip"/>
+ <field signature="System.IntPtr _target"/>
+ </type>
+ <type fullname="System.Threading.Tasks.Task">
+ <!-- used by debugger -->
+ <field signature="System.Threading.Task ParentForDebugger"/>
+ <field signature="System.Int32 StateFlagsForDebugger"/>
+ </type>
+ <type fullname="System.Runtime.Loader.AssemblyLoadContext">
+ <!-- invoked by runtime -->
+ <method signature="System.Reflection.Assembly Resolve(System.IntPtr,System.Reflection.AssemblyName)"/>
+ <method signature="System.Reflection.Assembly ResolveUsingResolvingEvent(System.IntPtr,System.Reflection.AssemblyName)"/>
+ <method signature="System.IntPtr ResolveUnmanagedDll(System.String,System.IntPtr)"/>
+ </type>
+ <type fullname="System.BadImageFormatException">
+ <!-- invoked by runtime -->
+ <method signature="System.Void .ctor(System.String,System.String,System.Int32)"/>
+ </type>
+ <type fullname="System.Environment">
+ <!-- invoked by runtime -->
+ <method signature="System.Void SetCommandLineArgs(string[])"/>
+ </type>
+ </assembly>
+</linker> \ No newline at end of file
diff --git a/src/mscorlib/MembersMustExist.AnalyzerData b/src/mscorlib/MembersMustExist.AnalyzerData
new file mode 100644
index 0000000000..b5e7a6d742
--- /dev/null
+++ b/src/mscorlib/MembersMustExist.AnalyzerData
@@ -0,0 +1,3 @@
+# Visual Studio
+private int System.Threading.Thread._managedThreadId
+
diff --git a/src/mscorlib/Resources/Strings.resx b/src/mscorlib/Resources/Strings.resx
index 52bd625c97..bbe3636170 100644
--- a/src/mscorlib/Resources/Strings.resx
+++ b/src/mscorlib/Resources/Strings.resx
@@ -1,5 +1,64 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
+ <!--
+ Microsoft ResX Schema
+
+ Version 2.0
+
+ The primary goals of this format is to allow a simple XML format
+ that is mostly human readable. The generation and parsing of the
+ various data types are done through the TypeConverter classes
+ associated with the data types.
+
+ Example:
+
+ ... ado.net/XML headers & schema ...
+ <resheader name="resmimetype">text/microsoft-resx</resheader>
+ <resheader name="version">2.0</resheader>
+ <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
+ <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
+ <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
+ <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
+ <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
+ <value>[base64 mime encoded serialized .NET Framework object]</value>
+ </data>
+ <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
+ <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
+ <comment>This is a comment</comment>
+ </data>
+
+ There are any number of "resheader" rows that contain simple
+ name/value pairs.
+
+ Each data row contains a name, and value. The row also contains a
+ type or mimetype. Type corresponds to a .NET class that support
+ text/value conversion through the TypeConverter architecture.
+ Classes that don't support this are serialized and stored with the
+ mimetype set.
+
+ The mimetype is used for serialized objects, and tells the
+ ResXResourceReader how to depersist the object. This is currently not
+ extensible. For a given mimetype the value must be set accordingly:
+
+ Note - application/x-microsoft.net.object.binary.base64 is the format
+ that the ResXResourceWriter will generate, however the reader can
+ read any of the formats listed below.
+
+ mimetype: application/x-microsoft.net.object.binary.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.soap.base64
+ value : The object must be serialized with
+ : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
+ : and then encoded with base64 encoding.
+
+ mimetype: application/x-microsoft.net.object.bytearray.base64
+ value : The object must be serialized into a byte array
+ : using a System.ComponentModel.TypeConverter
+ : and then encoded with base64 encoding.
+ -->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
@@ -100,8 +159,9 @@
<data name="AggregateException_DeserializationFailure" xml:space="preserve">
<value>The serialization stream contains no inner exceptions.</value>
</data>
- <data name="AggregateException_ToString" xml:space="preserve">
- <value>{0}{1}---&gt; (Inner Exception #{2}) {3}{4}{5}</value>
+ <data name="AggregateException_InnerException" xml:space="preserve">
+ <value>(Inner Exception #{0}) </value>
+ <comment>This text is prepended to each inner exception description during aggregate exception formatting</comment>
</data>
<data name="AppDomain_AppBaseNotSet" xml:space="preserve">
<value>The ApplicationBase must be set before retrieving this property.</value>
@@ -865,9 +925,6 @@
<data name="Argument_CannotSetParentToInterface" xml:space="preserve">
<value>Cannot set parent to an interface.</value>
</data>
- <data name="Argument_CantCallSecObjFunc" xml:space="preserve">
- <value>Cannot evaluate a security function.</value>
- </data>
<data name="Argument_CodepageNotSupported" xml:space="preserve">
<value>{0} is not a supported code page.</value>
</data>
@@ -1217,7 +1274,7 @@
<value>Cannot use type '{0}'. Only value types without pointers or references are supported.</value>
</data>
<data name="Argument_InvalidUnity" xml:space="preserve">
- <value>Invalid Unity type.</value>
+ <value>Type '{0}' is not deserializable.</value>
</data>
<data name="Argument_InvalidValue" xml:space="preserve">
<value>Value was invalid.</value>
@@ -1494,7 +1551,6 @@
</data>
<data name="Argument_UnclosedExceptionBlock" xml:space="preserve">
<value>The IL Generator cannot be used while there are unclosed exceptions.</value>
-
</data>
<data name="Argument_Unexpected_TypeSource" xml:space="preserve">
<value>Unexpected TypeKind when marshaling Windows.Foundation.TypeName.</value>
@@ -3169,7 +3225,7 @@
</data>
<data name="PlatformNotSupported_Remoting" xml:space="preserve">
<value>Remoting is not supported on this platform.</value>
- </data>
+ </data>
<data name="PlatformNotSupported_SecureBinarySerialization" xml:space="preserve">
<value>Secure binary serialization is not supported on this platform.</value>
</data>
@@ -3596,4 +3652,25 @@
<data name="SynchronizationLockException_MisMatchedWrite" xml:space="preserve">
<value>The write lock is being released without being held.</value>
</data>
+ <data name="ConcurrentStack_PushPopRange_CountOutOfRange" xml:space="preserve">
+ <value>The count argument must be greater than or equal to zero.</value>
+ </data>
+ <data name="ConcurrentStack_PushPopRange_InvalidCount" xml:space="preserve">
+ <value>The sum of the startIndex and count arguments must be less than or equal to the collection's Count.</value>
+ </data>
+ <data name="ConcurrentStack_PushPopRange_StartOutOfRange" xml:space="preserve">
+ <value>The startIndex argument must be greater than or equal to zero.</value>
+ </data>
+ <data name="ConcurrentDictionary_SourceContainsDuplicateKeys" xml:space="preserve">
+ <value>The source argument contains duplicate keys.</value>
+ </data>
+ <data name="NotSupported_SignatureType" xml:space="preserve">
+ <value>This method is not supported on signature types.</value>
+ </data>
+ <data name="Memory_ThrowIfDisposed" xml:space="preserve">
+ <value>Memory&lt;T&gt; has been disposed.</value>
+ </data>
+ <data name="Memory_OutstandingReferences" xml:space="preserve">
+ <value>Release all references before disposing this instance.</value>
+ </data>
</root>
diff --git a/src/mscorlib/System.Private.CoreLib.csproj b/src/mscorlib/System.Private.CoreLib.csproj
index 0889a4b854..f7206f98f5 100644
--- a/src/mscorlib/System.Private.CoreLib.csproj
+++ b/src/mscorlib/System.Private.CoreLib.csproj
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <!-- Include common build properties -->
+ <!-- Include common build properties -->
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<!-- Compilation options -->
@@ -44,6 +44,7 @@
<ItemGroup>
<AssemblyMetadata Include="Serviceable">
<Value>True</Value>
+ <Visible>false</Visible>
</AssemblyMetadata>
</ItemGroup>
<!-- Platform specific properties -->
@@ -96,13 +97,6 @@
<MinorVersion>6</MinorVersion>
<ExcludeAssemblyInfoPartialFile>true</ExcludeAssemblyInfoPartialFile>
</PropertyGroup>
- <ItemGroup>
- <AssemblyInfoLines Include="[assembly: System.Resources.SatelliteContractVersion(&quot;$(AssemblyVersion)&quot;)]" />
- <AssemblyInfoLines Include="[assembly: System.Security.AllowPartiallyTrustedCallers]" />
- <AssemblyInfoLines Include="[assembly: System.Runtime.InteropServices.ComVisible(false)]" />
- <AssemblyInfoLines Include="[assembly: System.Resources.NeutralResourcesLanguage(&quot;en-US&quot;)]" />
- <AssemblyInfoLines Include="[assembly: System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)]" />
- </ItemGroup>
<!--
Helper Paths
-->
@@ -114,8 +108,6 @@
</PropertyGroup>
<!-- Msbuild variables needed to get CoreCLR features to be set properly. -->
<PropertyGroup>
- <ClrProduct>core_clr</ClrProduct>
- <BuildForCoreSystem>true</BuildForCoreSystem>
<!-- These are needed to make sure we have the right set of defines -->
<TargetArch Condition="'$(Platform)'=='x86'">i386</TargetArch>
<TargetArch Condition="'$(Platform)'!='x86'">$(Platform)</TargetArch>
@@ -126,16 +118,11 @@
<!-- Sources -->
<ItemGroup>
<Compile Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\RuntimeHelpers.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\CustomConstantAttribute.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\DateTimeConstantAttribute.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\DecimalConstantAttribute.cs" />
<Compile Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\FriendAccessAllowedAttribute.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\MethodImplAttribute.cs" />
<Compile Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\TypeDependencyAttribute.cs" />
<Compile Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\jithelpers.cs" />
<Compile Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\Unsafe.cs" />
<Compile Condition="'$(FeatureICastable)' == 'true'" Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\ICastable.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\RuntimeWrappedException.cs" />
<Compile Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\ConditionalWeakTable.cs" />
<Compile Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\AsyncMethodBuilder.cs" />
<Compile Include="$(BclSourcesRoot)\System\Runtime\CompilerServices\TaskAwaiter.cs" />
@@ -143,7 +130,6 @@
</ItemGroup>
<ItemGroup>
<Compile Include="$(BclSourcesRoot)\System\Runtime\Reliability\CriticalFinalizerObject.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Runtime\Reliability\PrePrepareMethodAttribute.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(BclSourcesRoot)\System\Runtime\MemoryFailPoint.cs" />
@@ -152,7 +138,6 @@
<ItemGroup>
<Compile Include="$(BclSourcesRoot)\System\Collections\Comparer.cs" />
<Compile Include="$(BclSourcesRoot)\System\Collections\CompatibleComparer.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Collections\ListDictionaryInternal.cs" />
<Compile Include="$(BclSourcesRoot)\System\Collections\EmptyReadOnlyDictionaryInternal.cs" />
<Compile Include="$(BclSourcesRoot)\System\Collections\Hashtable.cs" />
<Compile Include="$(BclSourcesRoot)\System\Collections\IHashCodeProvider.cs" />
@@ -277,7 +262,28 @@
<Compile Include="$(BclSourcesRoot)\System\Runtime\InteropServices\WindowsRuntime\CLRIKeyValuePairImpl.cs" />
</ItemGroup>
<ItemGroup>
- <Compile Include="$(BclSourcesRoot)\System\AggregateException.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\Vector128.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\Vector256.cs" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Aes.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Avx.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Avx2.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Bmi1.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Bmi2.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Enums.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Fma.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Lzcnt.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Pclmulqdq.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Popcnt.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Sse.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Sse2.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Sse3.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Sse41.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Sse42.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Runtime\Intrinsics\X86\Ssse3.cs" />
+ </ItemGroup>
+ <ItemGroup>
<Compile Include="$(BclSourcesRoot)\System\AppContext\AppContext.cs" />
<Compile Include="$(BclSourcesRoot)\System\AppContext\AppContextSwitches.cs" />
<Compile Include="$(BclSourcesRoot)\System\AppContext\AppContextDefaultValues.cs" />
@@ -301,11 +307,8 @@
<Compile Include="$(BclSourcesRoot)\System\OutOfMemoryException.cs" />
<Compile Include="$(BclSourcesRoot)\System\Delegate.cs" />
<Compile Include="$(BclSourcesRoot)\System\MulticastDelegate.cs" />
- <Compile Include="$(BclSourcesRoot)\System\__HResults.cs" />
- <Compile Include="$(BclSourcesRoot)\System\HResults.cs" />
<Compile Include="$(BclSourcesRoot)\System\BCLDebug.cs" />
<Compile Include="$(BclSourcesRoot)\System\Activator.cs" />
- <Compile Include="$(BclSourcesRoot)\System\AccessViolationException.cs" />
<Compile Include="$(BclSourcesRoot)\System\AppDomain.cs" />
<Compile Include="$(BclSourcesRoot)\System\AppDomainSetup.cs" />
<Compile Include="$(BclSourcesRoot)\System\AppDomainManager.cs" />
@@ -313,23 +316,17 @@
<Compile Include="$(BclSourcesRoot)\System\ArgIterator.cs" />
<Compile Include="$(BclSourcesRoot)\System\Attribute.cs" />
<Compile Include="$(BclSourcesRoot)\System\BadImageFormatException.CoreCLR.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Boolean.cs" />
<Compile Include="$(BclSourcesRoot)\System\Buffer.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Byte.cs" />
<Compile Include="$(BclSourcesRoot)\System\CompatibilitySwitches.cs" />
<Compile Include="$(BclSourcesRoot)\System\Currency.cs" />
<Compile Include="$(BclSourcesRoot)\System\Decimal.cs" />
<Compile Include="$(BclSourcesRoot)\System\DefaultBinder.CanConvert.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Double.cs" />
<Compile Include="$(BclSourcesRoot)\System\Empty.cs" />
<Compile Include="$(BclSourcesRoot)\System\Enum.cs" />
<Compile Include="$(BclSourcesRoot)\System\Environment.cs" />
<Compile Include="$(BclSourcesRoot)\System\GC.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Guid.cs" />
+ <Compile Include="$(BclSourcesRoot)\System\Guid.CoreCLR.cs" />
<Compile Include="$(BclSourcesRoot)\System\InsufficientMemoryException.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Int16.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Int32.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Int64.cs" />
<Compile Include="$(BclSourcesRoot)\System\IntPtr.cs" />
<Compile Include="$(BclSourcesRoot)\System\Internal.cs" />
<Compile Include="$(BclSourcesRoot)\System\Math.cs" />
@@ -337,17 +334,13 @@
<Compile Include="$(BclSourcesRoot)\System\mda.cs" />
<Compile Include="$(BclSourcesRoot)\System\MissingFieldException.cs" />
<Compile Include="$(BclSourcesRoot)\System\MissingMemberException.cs" />
- <Compile Include="$(BclSourcesRoot)\System\NonSerializedAttribute.cs" />
<Compile Include="$(BclSourcesRoot)\System\Number.cs" />
<Compile Include="$(BclSourcesRoot)\System\ParseNumbers.cs" />
<Compile Include="$(BclSourcesRoot)\System\ResId.cs" />
<Compile Include="$(BclSourcesRoot)\System\RtType.cs" />
<Compile Include="$(BclSourcesRoot)\System\RuntimeArgumentHandle.cs" />
<Compile Include="$(BclSourcesRoot)\System\RuntimeHandles.cs" />
- <Compile Include="$(BclSourcesRoot)\System\SByte.cs" />
- <Compile Include="$(BclSourcesRoot)\System\SerializableAttribute.cs" />
<Compile Include="$(BclSourcesRoot)\System\SharedStatics.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Single.cs" />
<Compile Include="$(BclSourcesRoot)\System\StubHelpers.cs" />
<Compile Include="$(BclSourcesRoot)\System\TimeZoneInfo.AdjustmentRule.cs" />
<Compile Include="$(BclSourcesRoot)\System\TimeZoneInfo.cs" />
@@ -357,9 +350,6 @@
<Compile Include="$(BclSourcesRoot)\System\TypeNameParser.cs" />
<Compile Include="$(BclSourcesRoot)\System\TypedReference.cs" />
<Compile Include="$(BclSourcesRoot)\System\TypeLoadException.cs" />
- <Compile Include="$(BclSourcesRoot)\System\UInt16.cs" />
- <Compile Include="$(BclSourcesRoot)\System\UInt32.cs" />
- <Compile Include="$(BclSourcesRoot)\System\UInt64.cs" />
<Compile Include="$(BclSourcesRoot)\System\UIntPtr.cs" />
<Compile Include="$(BclSourcesRoot)\System\ValueType.cs" />
<Compile Include="$(BclSourcesRoot)\System\WeakReference.cs" />
@@ -374,6 +364,7 @@
<Compile Include="$(BclSourcesRoot)\Internal\Runtime\Augments\EnvironmentAugments.cs" />
<Compile Include="$(BclSourcesRoot)\Internal\Runtime\Augments\RuntimeThread.cs" />
<Compile Include="$(BclSourcesRoot)\Internal\Console.cs" />
+ <Compile Include="$(BclSourcesRoot)\Internal\Padding.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(BclSourcesRoot)\System\Reflection\Assembly.CoreCLR.cs" />
@@ -463,13 +454,10 @@
<Compile Include="$(BclSourcesRoot)\System\Globalization\IdnMapping.cs" />
<Compile Include="$(BclSourcesRoot)\System\Globalization\RegionInfo.cs" />
<Compile Include="$(BclSourcesRoot)\System\Globalization\TextInfo.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Globalization\TimeSpanFormat.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Globalization\TimeSpanParse.cs" />
</ItemGroup>
<ItemGroup Condition="'$(FeatureCoreFxGlobalization)' != 'true'">
<Compile Include="$(BclSourcesRoot)\System\Globalization\EncodingDataItem.cs" />
<Compile Include="$(BclSourcesRoot)\System\Globalization\EncodingTable.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Globalization\GlobalizationAssembly.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(BclSourcesRoot)\System\Threading\SynchronizationContext.cs" />
@@ -510,22 +498,18 @@
<Compile Condition="'$(FeatureCominterop)' == 'true'" Include="$(BclSourcesRoot)\System\Threading\Tasks\IAsyncCausalityTracerStatics.cs" />
</ItemGroup>
<ItemGroup>
- <Compile Include="$(BclSourcesRoot)\System\Buffers\ArrayPoolEventSource.cs" />
<Compile Include="$(BclSourcesRoot)\System\Threading\ClrThreadPoolBoundHandle.cs" />
<Compile Include="$(BclSourcesRoot)\System\Threading\ClrThreadPoolBoundHandleOverlapped.cs" />
<Compile Include="$(BclSourcesRoot)\System\Threading\ClrThreadPoolPreAllocatedOverlapped.cs" />
</ItemGroup>
<ItemGroup>
<Compile Include="$(BclSourcesRoot)\System\IO\__Error.cs" />
- <Compile Include="$(BclSourcesRoot)\System\IO\__HResults.cs" />
<Compile Include="$(BclSourcesRoot)\System\IO\BinaryReader.cs" />
<Compile Include="$(BclSourcesRoot)\System\IO\Directory.cs" />
<Compile Include="$(BclSourcesRoot)\System\IO\SearchOption.cs" />
- <Compile Include="$(BclSourcesRoot)\System\IO\DriveNotFoundException.cs" />
<Compile Include="$(BclSourcesRoot)\System\IO\File.cs" />
<Compile Include="$(BclSourcesRoot)\System\IO\FileLoadException.CoreCLR.cs" />
<Compile Include="$(BclSourcesRoot)\System\IO\FileNotFoundException.CoreCLR.cs" />
- <Compile Include="$(BclSourcesRoot)\System\IO\IOException.cs" />
<Compile Include="$(BclSourcesRoot)\System\IO\MemoryStream.cs" />
<Compile Include="$(BclSourcesRoot)\System\IO\Stream.cs" />
<Compile Include="$(BclSourcesRoot)\System\IO\UnmanagedMemoryAccessor.cs" />
@@ -563,7 +547,6 @@
<Compile Include="$(BclSourcesRoot)\System\Diagnostics\SymbolStore\Token.cs" />
</ItemGroup>
<ItemGroup>
- <Compile Include="$(BclSourcesRoot)\System\Runtime\ExceptionServices\CorruptingExceptionCommon.cs" />
<Compile Include="$(BclSourcesRoot)\System\Runtime\ExceptionServices\ExceptionServicesCommon.cs" />
<Compile Include="$(BclSourcesRoot)\System\Runtime\ExceptionServices\ExceptionNotification.cs" />
</ItemGroup>
@@ -586,7 +569,6 @@
</ItemGroup>
<ItemGroup>
<Compile Include="$(BclSourcesRoot)\System\Resources\__FastResourceComparer.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Resources\__HResults.cs" />
<Compile Include="$(BclSourcesRoot)\System\Resources\FileBasedResourceGroveler.cs" />
<Compile Include="$(BclSourcesRoot)\System\Resources\IResourceGroveler.cs" />
<Compile Include="$(BclSourcesRoot)\System\Resources\ManifestBasedResourceGroveler.cs" />
@@ -603,8 +585,6 @@
<Compile Include="$(BclSourcesRoot)\System\Collections\Generic\DebugView.cs" />
<Compile Include="$(BclSourcesRoot)\System\Collections\Generic\List.cs" />
<Compile Include="$(BclSourcesRoot)\System\Collections\Generic\ArraySortHelper.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Collections\ObjectModel\Collection.cs" />
- <Compile Include="$(BclSourcesRoot)\System\Collections\ObjectModel\ReadOnlyCollection.cs" />
<Compile Include="$(BclSourcesRoot)\System\Collections\ObjectModel\ReadOnlyDictionary.cs" />
<Compile Include="$(BclSourcesRoot)\System\Collections\Concurrent\ConcurrentStack.cs" />
<Compile Include="$(BclSourcesRoot)\System\Collections\Concurrent\IProducerConsumerCollection.cs" />
@@ -613,7 +593,6 @@
</ItemGroup>
<ItemGroup>
<Compile Include="$(BclSourcesRoot)\Microsoft\Win32\SafeHandles\SafeFindHandle.cs" />
- <Compile Include="$(BclSourcesRoot)\Microsoft\Win32\SafeHandles\SafeLibraryHandle.cs" />
<Compile Include="$(BclSourcesRoot)\Microsoft\Win32\SafeHandles\SafeWaitHandle.cs" />
<Compile Condition="'$(FeatureWin32Registry)' == 'true'" Include="$(BclSourcesRoot)\Microsoft\Win32\SafeHandles\SafeRegistryHandle.cs" />
</ItemGroup>
@@ -621,6 +600,7 @@
<Compile Include="$(BclSourcesRoot)\System\Numerics\Hashing\HashHelpers.cs" />
</ItemGroup>
<ItemGroup Condition="'$(TargetsUnix)' == 'true'">
+ <Compile Include="$(BclSourcesRoot)\Interop\Unix\Interop.Libraries.cs" />
<Compile Include="$(BclSourcesRoot)\Interop\Unix\System.Globalization.Native\Interop.ICU.cs" />
<Compile Include="$(BclSourcesRoot)\System\Globalization\CompareInfo.Unix.cs" />
<Compile Include="$(BclSourcesRoot)\System\Globalization\CultureInfo.Unix.cs" />
@@ -664,19 +644,16 @@
<ItemGroup>
<Compile Include="src\System\Runtime\RuntimeImports.cs" />
</ItemGroup>
- <Import Project="shared\System.Private.CoreLib.Shared.projitems" Label="Shared" />
+ <Import Project="shared\System.Private.CoreLib.Shared.projitems" />
<PropertyGroup>
<CheckCDefines Condition="'$(CheckCDefines)'==''">true</CheckCDefines>
</PropertyGroup>
<Target Name="CDefineChecker" BeforeTargets="Build" Condition="'$(CheckCDefines)'=='true'">
<!-- Compiler Definition Verification -->
- <Message Importance="High" Text="============" />
<PropertyGroup>
- <IgnoreDefineConstants>FEATURE_IMPLICIT_TLS;FEATURE_HIJACK</IgnoreDefineConstants>
<CMakeDefinitionSaveFile>$(IntermediateOutputPath)\cmake.definitions</CMakeDefinitionSaveFile>
</PropertyGroup>
<Exec Command="python $(MSBuildThisFileDirectory)..\scripts\check-definitions.py &quot;$(CMakeDefinitionSaveFile)&quot; &quot;$(DefineConstants)&quot; &quot;$(IgnoreDefineConstants)&quot; " />
- <Message Importance="High" Text="============" />
</Target>
<PropertyGroup Condition="'$(BuildOS)' == 'Windows_NT'">
<EnableDotnetAnalyzers Condition="'$(EnableDotnetAnalyzers)'==''">true</EnableDotnetAnalyzers>
@@ -701,4 +678,4 @@
<Win32Resource Condition="'$(GenerateNativeVersionInfo)'=='true'">$(IntermediateOutputPath)\System.Private.CoreLib.res</Win32Resource>
</PropertyGroup>
<Import Project="GenerateCompilerResponseFile.targets" />
-</Project> \ No newline at end of file
+</Project>
diff --git a/src/mscorlib/System.Private.CoreLib.sln b/src/mscorlib/System.Private.CoreLib.sln
index d5cdd02cf3..d4052f8058 100644
--- a/src/mscorlib/System.Private.CoreLib.sln
+++ b/src/mscorlib/System.Private.CoreLib.sln
@@ -1,17 +1,11 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
-VisualStudioVersion = 15.0.26208.0
+VisualStudioVersion = 15.0.26817.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "System.Private.CoreLib", "System.Private.CoreLib.csproj", "{3DA06C3A-2E7B-4CB7-80ED-9B12916013F9}"
EndProject
-Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "System.Private.CoreLib.Shared", "shared\System.Private.CoreLib.Shared.shproj", "{C5ED3C1D-B572-46F1-8F96-522A85CE1179}"
-EndProject
Global
- GlobalSection(SharedMSBuildProjectFiles) = preSolution
- shared\System.Private.CoreLib.Shared.projitems*{3da06c3a-2e7b-4cb7-80ed-9b12916013f9}*SharedItemsImports = 4
- shared\System.Private.CoreLib.Shared.projitems*{c5ed3c1d-b572-46f1-8f96-522a85ce1179}*SharedItemsImports = 13
- EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Checked|amd64 = Checked|amd64
Checked|arm = Checked|arm
@@ -55,4 +49,7 @@ Global
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {DA05075A-7CDA-4F65-AF6A-CB5DB6CF936F}
+ EndGlobalSection
EndGlobal
diff --git a/src/mscorlib/Tools/Versioning/GenerateVersionInfo.targets b/src/mscorlib/Tools/Versioning/GenerateVersionInfo.targets
index 00f5282c7c..0e9a2263cc 100644
--- a/src/mscorlib/Tools/Versioning/GenerateVersionInfo.targets
+++ b/src/mscorlib/Tools/Versioning/GenerateVersionInfo.targets
@@ -25,37 +25,13 @@
<CoreCompileDependsOn>$(CoreCompileDependsOn);GenerateAssemblyInfo</CoreCompileDependsOn>
</PropertyGroup>
- <Target Name="GenerateAssemblyInfo"
- Inputs="$(MSBuildProjectFile)"
- Outputs="$(AssemblyInfoFile)"
- Condition="'$(GenerateAssemblyInfo)'=='true'">
-
- <Error Condition="!Exists('$(IntermediateOutputPath)')" Text="GenerateAssemblyInfo failed because IntermediateOutputPath isn't set to a valid directory" />
-
- <ItemGroup>
- <AssemblyInfoUsings Include="using System%3B" />
- <AssemblyInfoUsings Include="using System.Reflection%3B" />
- <AssemblyInfoLines Include="[assembly:AssemblyTitle(&quot;$(AssemblyName)&quot;)]" />
- <AssemblyInfoLines Include="[assembly:AssemblyDescription(&quot;$(AssemblyName)&quot;)]" />
- <AssemblyInfoLines Include="[assembly:AssemblyDefaultAlias(&quot;$(AssemblyName)&quot;)]" />
- <AssemblyInfoLines Include="[assembly:AssemblyCompany(&quot;Microsoft Corporation&quot;)]" />
- <AssemblyInfoLines Include="[assembly:AssemblyProduct(&quot;Microsoft\x00ae .NET Framework&quot;)]" />
- <AssemblyInfoLines Include="[assembly:AssemblyCopyright(&quot;\x00a9 Microsoft Corporation. All rights reserved.&quot;)]" />
- <AssemblyInfoLines Include="[assembly:AssemblyVersion(&quot;$(AssemblyVersion)&quot;)]" />
- <AssemblyInfoLines Include="[assembly:AssemblyFileVersion(&quot;$(AssemblyFileVersion)&quot;)]" />
- <AssemblyInfoLines Include="[assembly:AssemblyInformationalVersion(@&quot;$(AssemblyFileVersion)$(BuiltByString)&quot;)]" />
- <AssemblyInfoLines Condition="'$(CLSCompliant)'=='true'" Include="[assembly:CLSCompliant(true)]" />
- </ItemGroup>
-
- <WriteLinesToFile File="$(AssemblyInfoFile)"
- Lines="@(AssemblyInfoUsings);@(AssemblyInfoLines)"
- Overwrite="true" />
-
- <ItemGroup>
- <Compile Include="$(AssemblyInfoFile)" />
- <FileWrites Include="$(AssemblyInfoFile)" />
- </ItemGroup>
- </Target>
+ <ItemGroup>
+ <AssemblyInfoLines Include="[assembly:System.Resources.SatelliteContractVersion(&quot;$(AssemblyVersion)&quot;)]" />
+ <AssemblyInfoLines Include="[assembly:System.Security.AllowPartiallyTrustedCallers]" />
+ <AssemblyInfoLines Include="[assembly:System.Runtime.InteropServices.ComVisible(false)]" />
+ <AssemblyInfoLines Include="[assembly:System.Resources.NeutralResourcesLanguage(&quot;en-US&quot;)]" />
+ <AssemblyInfoLines Include="[assembly:System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute(System.Runtime.InteropServices.DllImportSearchPath.AssemblyDirectory | System.Runtime.InteropServices.DllImportSearchPath.System32)]" />
+ </ItemGroup>
<!-- #################################### -->
<!-- Generate Native Version Info -->
diff --git a/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs
index 79aedd74d3..683845dbc1 100644
--- a/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs
+++ b/src/mscorlib/shared/Interop/Unix/System.Globalization.Native/Interop.Collation.cs
@@ -44,7 +44,7 @@ internal static partial class Interop
internal unsafe static extern int CompareStringOrdinalIgnoreCase(char* lpStr1, int cwStr1Len, char* lpStr2, int cwStr2Len);
[DllImport(Libraries.GlobalizationInterop, EntryPoint = "GlobalizationNative_GetSortVersion")]
- internal static extern int GetSortVersion();
+ internal static extern int GetSortVersion(SafeSortHandle sortHandle);
internal class SafeSortHandle : SafeHandle
{
diff --git a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.PosixFAdvise.cs b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.PosixFAdvise.cs
index 69e39b30d2..ad8b73aed2 100644
--- a/src/mscorlib/shared/Interop/Unix/System.Native/Interop.PosixFAdvise.cs
+++ b/src/mscorlib/shared/Interop/Unix/System.Native/Interop.PosixFAdvise.cs
@@ -16,7 +16,7 @@ internal static partial class Interop
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 */
+ POSIX_FADV_NOREUSE = 5, /* data will only be accessed once */
}
/// <summary>
diff --git a/src/mscorlib/shared/Interop/Windows/Interop.Libraries.cs b/src/mscorlib/shared/Interop/Windows/Interop.Libraries.cs
index f65e05cfdd..45d910bfcc 100644
--- a/src/mscorlib/shared/Interop/Windows/Interop.Libraries.cs
+++ b/src/mscorlib/shared/Interop/Windows/Interop.Libraries.cs
@@ -9,6 +9,7 @@ internal static partial class Interop
internal const string BCrypt = "BCrypt.dll";
internal const string Crypt32 = "crypt32.dll";
internal const string Kernel32 = "kernel32.dll";
+ internal const string Ole32 = "ole32.dll";
internal const string OleAut32 = "oleaut32.dll";
internal const string User32 = "user32.dll";
}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs
new file mode 100644
index 0000000000..16365ee651
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs
@@ -0,0 +1,24 @@
+// 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
+ {
+ 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;
+ }
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs
index 0909d3a6c8..ddc18f6c42 100644
--- a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs
@@ -3,29 +3,30 @@
// 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, EntryPoint = "CreateFile2", SetLastError = true, CharSet = CharSet.Unicode, BestFitMapping = false)]
- internal static extern unsafe SafeFileHandle CreateFile2(
+ [DllImport(Libraries.Kernel32, EntryPoint = "CreateFile2", SetLastError = true, CharSet = CharSet.Unicode)]
+ private static extern SafeFileHandle CreateFile2Private(
string lpFileName,
int dwDesiredAccess,
- System.IO.FileShare dwShareMode,
- System.IO.FileMode dwCreationDisposition,
- CREATEFILE2_EXTENDED_PARAMETERS* pCreateExParams);
+ FileShare dwShareMode,
+ FileMode dwCreationDisposition,
+ ref Kernel32.CREATEFILE2_EXTENDED_PARAMETERS pCreateExParams);
- internal unsafe struct CREATEFILE2_EXTENDED_PARAMETERS
+ internal static SafeFileHandle CreateFile2(
+ string lpFileName,
+ int dwDesiredAccess,
+ FileShare dwShareMode,
+ FileMode dwCreationDisposition,
+ ref Kernel32.CREATEFILE2_EXTENDED_PARAMETERS pCreateExParams)
{
- internal uint dwSize;
- internal uint dwFileAttributes;
- internal uint dwFileFlags;
- internal uint dwSecurityQosFlags;
- internal SECURITY_ATTRIBUTES* lpSecurityAttributes;
- internal IntPtr hTemplateFile;
+ lpFileName = PathInternal.EnsureExtendedPrefixOverMaxPath(lpFileName);
+ return CreateFile2Private(lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, ref pCreateExParams);
}
}
-} \ No newline at end of file
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FreeLibrary.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FreeLibrary.cs
new file mode 100644
index 0000000000..c70865350a
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.FreeLibrary.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 Kernel32
+ {
+ [DllImport(Libraries.Kernel32, CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
+ internal static extern bool FreeLibrary(IntPtr hModule);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.LoadLibraryEx.cs b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.LoadLibraryEx.cs
new file mode 100644
index 0000000000..4eef5852fe
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/Kernel32/Interop.LoadLibraryEx.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 Microsoft.Win32.SafeHandles;
+using System;
+using System.Runtime.InteropServices;
+
+internal partial class Interop
+{
+ internal partial class Kernel32
+ {
+ internal const int LOAD_LIBRARY_AS_DATAFILE = 0x00000002;
+
+ [DllImport(Libraries.Kernel32, EntryPoint = "LoadLibraryExW", CharSet = CharSet.Unicode, SetLastError = true)]
+ internal static extern SafeLibraryHandle LoadLibraryEx(string libFilename, IntPtr reserved, int flags);
+ }
+}
diff --git a/src/mscorlib/shared/Interop/Windows/User32/Interop.LoadString.cs b/src/mscorlib/shared/Interop/Windows/User32/Interop.LoadString.cs
new file mode 100644
index 0000000000..d3d575e221
--- /dev/null
+++ b/src/mscorlib/shared/Interop/Windows/User32/Interop.LoadString.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;
+using System.Text;
+using Microsoft.Win32.SafeHandles;
+
+internal partial class Interop
+{
+ internal partial class User32
+ {
+ [DllImport(Libraries.User32, SetLastError = true, EntryPoint = "LoadStringW", CharSet = CharSet.Unicode)]
+ internal static extern int LoadString(SafeLibraryHandle handle, int id, [Out] StringBuilder buffer, int bufferLength);
+ }
+}
diff --git a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
index 256f611463..3be2e354ab 100644
--- a/src/mscorlib/src/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
+++ b/src/mscorlib/shared/Microsoft/Win32/SafeHandles/SafeLibraryHandle.cs
@@ -2,9 +2,7 @@
// 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;
-
-namespace Microsoft.Win32
+namespace Microsoft.Win32.SafeHandles
{
sealed internal class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid
{
@@ -12,7 +10,7 @@ namespace Microsoft.Win32
override protected bool ReleaseHandle()
{
- return UnsafeNativeMethods.FreeLibrary(handle);
+ return Interop.Kernel32.FreeLibrary(handle);
}
}
}
diff --git a/src/mscorlib/shared/System.Private.CoreLib.Shared.projitems b/src/mscorlib/shared/System.Private.CoreLib.Shared.projitems
index 07e15cf65d..a13543ea93 100644
--- a/src/mscorlib/shared/System.Private.CoreLib.Shared.projitems
+++ b/src/mscorlib/shared/System.Private.CoreLib.Shared.projitems
@@ -13,13 +13,20 @@
<TargetsUnix Condition="'$(TargetsUnix)' != 'true'">false</TargetsUnix>
<TargetsOSX Condition="'$(TargetsOSX)' != 'true'">false</TargetsOSX>
</PropertyGroup>
+ <ItemDefinitionGroup>
+ <Compile>
+ <Visible>true</Visible>
+ </Compile>
+ </ItemDefinitionGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\CriticalHandleMinusOneIsInvalid.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\CriticalHandleZeroOrMinusOneIsInvalid.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\SafeHandleMinusOneIsInvalid.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\SafeHandleZeroOrMinusOneIsInvalid.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Action.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\AccessViolationException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\ApplicationException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\AggregateException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\ArgumentException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\ArgumentNullException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\ArgumentOutOfRangeException.cs" />
@@ -32,10 +39,16 @@
<Compile Include="$(MSBuildThisFileDirectory)System\AttributeUsageAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\BadImageFormatException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\BitConverter.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Boolean.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Buffers\ArrayPool.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Buffers\ArrayPoolEventSource.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Buffers\ConfigurableArrayPool.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Buffers\IRetainable.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Buffers\MemoryHandle.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Buffers\OwnedMemory.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Buffers\TlsOverPerCoreLockedStacksArrayPool.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Buffers\Utilities.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Byte.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Char.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\CharEnumerator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\CLSCompliantAttribute.cs" />
@@ -62,6 +75,9 @@
<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\Collections\ListDictionaryInternal.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\ObjectModel\Collection.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Collections\ObjectModel\ReadOnlyCollection.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\ComponentModel\DefaultValueAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\ComponentModel\EditorBrowsableAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Configuration\Assemblies\AssemblyHashAlgorithm.cs" />
@@ -80,6 +96,7 @@
<Compile Include="$(MSBuildThisFileDirectory)System\Diagnostics\Debug.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\DivideByZeroException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\DllNotFoundException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Double.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\DuplicateWaitObjectException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\EntryPointNotFoundException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\EventArgs.cs" />
@@ -127,9 +144,13 @@
<Compile Include="$(MSBuildThisFileDirectory)System\Globalization\TaiwanLunisolarCalendar.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Globalization\TextElementEnumerator.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Globalization\ThaiBuddhistCalendar.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\TimeSpanFormat.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Globalization\TimeSpanParse.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\Guid.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\HResults.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\IAsyncResult.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\ICloneable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\IComparable.cs" />
@@ -147,6 +168,7 @@
<Compile Include="$(MSBuildThisFileDirectory)System\InvalidTimeZoneException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\IO\BinaryWriter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\IO\DirectoryNotFoundException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\DriveNotFoundException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\IO\EncodingCache.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\IO\EndOfStreamException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\IO\Error.cs" />
@@ -157,6 +179,7 @@
<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\IOException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\IO\Path.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\IO\PathInternal.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\IO\PathTooLongException.cs" />
@@ -168,15 +191,20 @@
<Compile Include="$(MSBuildThisFileDirectory)System\IObservable.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\IObserver.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\IProgress.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Int16.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Int32.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Int64.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Lazy.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\MarshalByRefObject.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\MemberAccessException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Memory.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\NonSerializedAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\NotSupportedException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\NullReferenceException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\ObjectDisposedException.cs" />
@@ -190,6 +218,7 @@
<Compile Include="$(MSBuildThisFileDirectory)System\Random.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\RankException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\ReadOnlySpan.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\ReadOnlyMemory.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AmbiguousMatchException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Reflection\Assembly.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Reflection\AssemblyAlgorithmIdAttribute.cs" />
@@ -241,6 +270,7 @@
<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\MethodInfo.Internal.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Reflection\Missing.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Reflection\Module.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Reflection\ModuleResolveEventHandler.cs" />
@@ -258,6 +288,15 @@
<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\SignatureArrayType.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\SignatureByRefType.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\SignatureConstructedGenericType.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\SignatureGenericMethodParameterType.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\SignatureGenericParameterType.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\SignatureHasElementType.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\SignaturePointerType.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\SignatureType.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Reflection\SignatureTypeExtensions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Reflection\StrongNameKeyPair.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Reflection\TargetException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Reflection\TargetInvocationException.cs" />
@@ -278,7 +317,9 @@
<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\AsyncMethodBuilderAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\AsyncStateMachineAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\AsyncValueTaskMethodBuilder.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" />
@@ -286,6 +327,10 @@
<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\ConfiguredValueTaskAwaitable.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\CustomConstantAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\DateTimeConstantAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\DecimalConstantAttribute.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" />
@@ -298,6 +343,7 @@
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IndexerNameAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\INotifyCompletion.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\InternalsVisibleToAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IntrinsicAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IsConst.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IsByRefLikeAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IsVolatile.cs" />
@@ -305,11 +351,13 @@
<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\MethodImplAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\MethodImplOptions.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\CompilerServices\IsReadOnlyAttribute.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\RuntimeWrappedException.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" />
@@ -319,15 +367,29 @@
<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\CompilerServices\ValueTaskAwaiter.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\ExceptionServices\HandleProcessCorruptedStateExceptionsAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\BestFitMappingAttribute.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\DefaultCharSetAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\DefaultDllImportSearchPathsAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\DllImportAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\DllImportSearchPath.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\ExternalException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\FieldOffsetAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\InAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\LayoutKind.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\MarshalAsAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\OptionalAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\OutAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\PreserveSigAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\StringBuffer.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Runtime\InteropServices\StructLayoutAttribute.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" />
@@ -347,6 +409,7 @@
<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\SByte.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Security\AllowPartiallyTrustedCallersAttribute.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Security\CryptographicException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Security\PartialTrustVisibilityLevel.cs" />
@@ -362,8 +425,11 @@
<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\SerializableAttribute.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Single.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Span.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Span.NonGeneric.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\StringSpanHelpers.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\StackOverflowException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\StringComparer.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\StringComparison.cs" />
@@ -391,7 +457,7 @@
<Compile Include="$(MSBuildThisFileDirectory)System\Text\StringBuilder.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Text\UnicodeEncoding.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Text\UTF32Encoding.cs" />
- <Compile Include="$(MSBuildThisFileDirectory)System\Text\UTF7Encoding.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\Text\UTF7Encoding.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Text\UTF8Encoding.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\TimeSpan.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\ThreadAttributes.cs" />
@@ -415,6 +481,7 @@
<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\Tasks\ValueTask.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Threading\ThreadAbortException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Threading\ThreadPriority.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Threading\ThreadStart.cs" />
@@ -436,9 +503,13 @@
<Compile Include="$(MSBuildThisFileDirectory)System\TypeCode.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\TypeInitializationException.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\TypeUnloadedException.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\UInt16.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\UInt32.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\UInt64.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" />
@@ -488,19 +559,15 @@
<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="'$(EnableWinRT)' != 'true'" />
- <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.CreateFile2.cs" Condition="'$(EnableWinRT)' == 'true'" />
<Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.FileAttributes.cs" />
<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.FindClose.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.FindFirstFileEx.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.FreeEnvironmentStrings.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.GetCPInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.GetEnvironmentStrings.cs" />
@@ -528,25 +595,41 @@
<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)Interop\Windows\User32\Interop.Constants.cs" Condition="'$(EnableWinRT)' != 'true'" />
- <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\User32\Interop.SendMessageTimeout.cs" Condition="'$(EnableWinRT)' != 'true'" />
<Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\SafeFileHandle.Windows.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Globalization\HijriCalendar.Win32.cs" Condition="'$(EnableWinRT)' != 'true' and '$(EnableDummyGlobalizationImplementation)' != 'true'" />
<Compile Include="$(MSBuildThisFileDirectory)System\Globalization\HijriCalendar.WinRT.cs" Condition="'$(EnableWinRT)' == 'true'" />
<Compile Include="$(MSBuildThisFileDirectory)System\Globalization\JapaneseCalendar.Win32.cs" Condition="'$(EnableWinRT)' != 'true' and '$(EnableDummyGlobalizationImplementation)' != 'true'" />
<Compile Include="$(MSBuildThisFileDirectory)System\Globalization\JapaneseCalendar.WinRT.cs" Condition="'$(EnableWinRT)' == 'true'" />
- <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.Win32.cs" Condition="'$(EnableWinRT)' != 'true'" />
<Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.Windows.cs" />
- <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.WinRT.cs" Condition="'$(EnableWinRT)' == '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\IO\DisableMediaInsertionPrompt.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Security\SafeBSTRHandle.cs" />
<Compile Include="$(MSBuildThisFileDirectory)System\Security\SecureString.Windows.cs" />
</ItemGroup>
+ <ItemGroup Condition="$(TargetsWindows) and '$(EnableWinRT)' != 'true'">
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.Win32.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)Microsoft\Win32\SafeHandles\SafeLibraryHandle.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.LoadLibraryEx.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.FreeLibrary.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.CreateFile.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\User32\Interop.Constants.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\User32\Interop.SendMessageTimeout.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\User32\Interop.LoadString.cs" />
+ </ItemGroup>
+ <ItemGroup Condition="$(TargetsWindows) and '$(EnableWinRT)' == 'true'">
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\FileStream.WinRT.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.CreateFile2.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.CREATEFILE2_EXTENDED_PARAMETERS.cs" />
+ </ItemGroup>
+ <ItemGroup Condition="$(TargetsWindows) or '$(FeaturePal)'=='true'">
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Interop.Errors.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)Interop\Windows\Kernel32\Interop.FormatMessage.cs" />
+ <Compile Include="$(MSBuildThisFileDirectory)System\IO\Win32Marshal.cs" />
+ </ItemGroup>
<ItemGroup Condition="$(TargetsUnix)">
<Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\Interop.Errors.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Interop\Unix\Interop.IOErrors.cs" />
diff --git a/src/mscorlib/shared/System.Private.CoreLib.Shared.shproj b/src/mscorlib/shared/System.Private.CoreLib.Shared.shproj
deleted file mode 100644
index 20c3de100b..0000000000
--- a/src/mscorlib/shared/System.Private.CoreLib.Shared.shproj
+++ /dev/null
@@ -1,17 +0,0 @@
-<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
- <!-- Set the properties to prevent any items from being excluded from the IDE view -->
- <PropertyGroup Label="Globals">
- <ProjectGuid>c5ed3c1d-b572-46f1-8f96-522a85ce1179</ProjectGuid>
- </PropertyGroup>
- <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> \ No newline at end of file
diff --git a/src/mscorlib/src/System/AccessViolationException.cs b/src/mscorlib/shared/System/AccessViolationException.cs
index 23d086fb42..103a4c0a9d 100644
--- a/src/mscorlib/src/System/AccessViolationException.cs
+++ b/src/mscorlib/shared/System/AccessViolationException.cs
@@ -21,19 +21,19 @@ namespace System
public AccessViolationException()
: base(SR.Arg_AccessViolationException)
{
- HResult = __HResults.E_POINTER;
+ HResult = HResults.E_POINTER;
}
public AccessViolationException(String message)
: base(message)
{
- HResult = __HResults.E_POINTER;
+ HResult = HResults.E_POINTER;
}
public AccessViolationException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.E_POINTER;
+ HResult = HResults.E_POINTER;
}
protected AccessViolationException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/Action.cs b/src/mscorlib/shared/System/Action.cs
index b82c14d9dc..da6813829e 100644
--- a/src/mscorlib/shared/System/Action.cs
+++ b/src/mscorlib/shared/System/Action.cs
@@ -33,3 +33,9 @@ namespace System
public delegate bool Predicate<in T>(T obj);
}
+
+namespace System.Buffers
+{
+ public delegate void SpanAction<T, in TArg>(Span<T> span, TArg arg);
+ public delegate void ReadOnlySpanAction<T, in TArg>(ReadOnlySpan<T> span, TArg arg);
+}
diff --git a/src/mscorlib/src/System/AggregateException.cs b/src/mscorlib/shared/System/AggregateException.cs
index 0b840972ef..36b9494980 100644
--- a/src/mscorlib/src/System/AggregateException.cs
+++ b/src/mscorlib/shared/System/AggregateException.cs
@@ -2,14 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
-//
-//
-//
-// Public type to communicate multiple failures to an end-user.
-//
-// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@@ -41,7 +33,7 @@ namespace System
public AggregateException()
: base(SR.AggregateException_ctor_DefaultMessage)
{
- m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[0]);
+ m_innerExceptions = new ReadOnlyCollection<Exception>(Array.Empty<Exception>());
}
/// <summary>
@@ -52,7 +44,7 @@ namespace System
public AggregateException(string message)
: base(message)
{
- m_innerExceptions = new ReadOnlyCollection<Exception>(new Exception[0]);
+ m_innerExceptions = new ReadOnlyCollection<Exception>(Array.Empty<Exception>());
}
/// <summary>
@@ -285,11 +277,6 @@ namespace System
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info"/> argument is null.</exception>
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
- if (info == null)
- {
- throw new ArgumentNullException(nameof(info));
- }
-
base.GetObjectData(info, context);
Exception[] innerExceptions = new Exception[m_innerExceptions.Count];
@@ -384,7 +371,7 @@ namespace System
/// If any inner exceptions are themselves instances of
/// <see cref="AggregateException"/>, this method will recursively flatten all of them. The
/// inner exceptions returned in the new <see cref="AggregateException"/>
- /// will be the union of all of the the inner exceptions from exception tree rooted at the provided
+ /// will be the union of all of the inner exceptions from exception tree rooted at the provided
/// <see cref="AggregateException"/> instance.
/// </remarks>
public AggregateException Flatten()
@@ -461,17 +448,20 @@ namespace System
/// <returns>A string representation of the current exception.</returns>
public override string ToString()
{
- string text = base.ToString();
+ StringBuilder text = new StringBuilder();
+ text.Append(base.ToString());
for (int i = 0; i < m_innerExceptions.Count; i++)
{
- text = String.Format(
- CultureInfo.InvariantCulture,
- SR.AggregateException_ToString,
- text, Environment.NewLine, i, m_innerExceptions[i].ToString(), "<---", Environment.NewLine);
+ text.Append(Environment.NewLine);
+ text.Append("---> ");
+ text.Append(string.Format(CultureInfo.InvariantCulture, SR.AggregateException_InnerException, i));
+ text.Append(m_innerExceptions[i].ToString());
+ text.Append("<---");
+ text.Append(Environment.NewLine);
}
- return text;
+ return text.ToString();
}
/// <summary>
diff --git a/src/mscorlib/shared/System/ApplicationException.cs b/src/mscorlib/shared/System/ApplicationException.cs
index cb98902de1..83ced79876 100644
--- a/src/mscorlib/shared/System/ApplicationException.cs
+++ b/src/mscorlib/shared/System/ApplicationException.cs
@@ -31,7 +31,7 @@ namespace System
public ApplicationException()
: base(SR.Arg_ApplicationException)
{
- HResult = __HResults.COR_E_APPLICATION;
+ HResult = HResults.COR_E_APPLICATION;
}
// Creates a new ApplicationException with its message string set to
@@ -41,13 +41,13 @@ namespace System
public ApplicationException(String message)
: base(message)
{
- HResult = __HResults.COR_E_APPLICATION;
+ HResult = HResults.COR_E_APPLICATION;
}
public ApplicationException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_APPLICATION;
+ 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
index de2d775c84..fe65d6443a 100644
--- a/src/mscorlib/shared/System/ArgumentException.cs
+++ b/src/mscorlib/shared/System/ArgumentException.cs
@@ -29,7 +29,7 @@ namespace System
public ArgumentException()
: base(SR.Arg_ArgumentException)
{
- HResult = __HResults.COR_E_ARGUMENT;
+ HResult = HResults.COR_E_ARGUMENT;
}
// Creates a new ArgumentException with its message
@@ -38,27 +38,27 @@ namespace System
public ArgumentException(String message)
: base(message)
{
- HResult = __HResults.COR_E_ARGUMENT;
+ HResult = HResults.COR_E_ARGUMENT;
}
public ArgumentException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_ARGUMENT;
+ HResult = HResults.COR_E_ARGUMENT;
}
public ArgumentException(String message, String paramName, Exception innerException)
: base(message, innerException)
{
_paramName = paramName;
- HResult = __HResults.COR_E_ARGUMENT;
+ HResult = HResults.COR_E_ARGUMENT;
}
public ArgumentException(String message, String paramName)
: base(message)
{
_paramName = paramName;
- HResult = __HResults.COR_E_ARGUMENT;
+ HResult = HResults.COR_E_ARGUMENT;
}
protected ArgumentException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/ArgumentNullException.cs b/src/mscorlib/shared/System/ArgumentNullException.cs
index 74b39fed8e..9b0732b2d2 100644
--- a/src/mscorlib/shared/System/ArgumentNullException.cs
+++ b/src/mscorlib/shared/System/ArgumentNullException.cs
@@ -26,25 +26,25 @@ namespace System
: base(SR.ArgumentNull_Generic)
{
// Use E_POINTER - COM used that for null pointers. Description is "invalid pointer"
- HResult = __HResults.E_POINTER;
+ HResult = HResults.E_POINTER;
}
public ArgumentNullException(String paramName)
: base(SR.ArgumentNull_Generic, paramName)
{
- HResult = __HResults.E_POINTER;
+ HResult = HResults.E_POINTER;
}
public ArgumentNullException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.E_POINTER;
+ HResult = HResults.E_POINTER;
}
public ArgumentNullException(String paramName, String message)
: base(message, paramName)
{
- HResult = __HResults.E_POINTER;
+ HResult = HResults.E_POINTER;
}
protected ArgumentNullException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/ArgumentOutOfRangeException.cs b/src/mscorlib/shared/System/ArgumentOutOfRangeException.cs
index 4721a503b6..a25cd57763 100644
--- a/src/mscorlib/shared/System/ArgumentOutOfRangeException.cs
+++ b/src/mscorlib/shared/System/ArgumentOutOfRangeException.cs
@@ -27,25 +27,25 @@ namespace System
public ArgumentOutOfRangeException()
: base(SR.Arg_ArgumentOutOfRangeException)
{
- HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
+ HResult = HResults.COR_E_ARGUMENTOUTOFRANGE;
}
public ArgumentOutOfRangeException(String paramName)
: base(SR.Arg_ArgumentOutOfRangeException, paramName)
{
- HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
+ HResult = HResults.COR_E_ARGUMENTOUTOFRANGE;
}
public ArgumentOutOfRangeException(String paramName, String message)
: base(message, paramName)
{
- HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
+ HResult = HResults.COR_E_ARGUMENTOUTOFRANGE;
}
public ArgumentOutOfRangeException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
+ HResult = HResults.COR_E_ARGUMENTOUTOFRANGE;
}
// We will not use this in the classlibs, but we'll provide it for
@@ -55,7 +55,7 @@ namespace System
: base(message, paramName)
{
_actualValue = actualValue;
- HResult = __HResults.COR_E_ARGUMENTOUTOFRANGE;
+ HResult = HResults.COR_E_ARGUMENTOUTOFRANGE;
}
protected ArgumentOutOfRangeException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/ArithmeticException.cs b/src/mscorlib/shared/System/ArithmeticException.cs
index 2c8abe51fa..6285c8120e 100644
--- a/src/mscorlib/shared/System/ArithmeticException.cs
+++ b/src/mscorlib/shared/System/ArithmeticException.cs
@@ -26,7 +26,7 @@ namespace System
public ArithmeticException()
: base(SR.Arg_ArithmeticException)
{
- HResult = __HResults.COR_E_ARITHMETIC;
+ HResult = HResults.COR_E_ARITHMETIC;
}
// Creates a new ArithmeticException with its message string set to
@@ -36,13 +36,13 @@ namespace System
public ArithmeticException(String message)
: base(message)
{
- HResult = __HResults.COR_E_ARITHMETIC;
+ HResult = HResults.COR_E_ARITHMETIC;
}
public ArithmeticException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_ARITHMETIC;
+ 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
index d06a450603..6964b1fa12 100644
--- a/src/mscorlib/shared/System/ArrayTypeMismatchException.cs
+++ b/src/mscorlib/shared/System/ArrayTypeMismatchException.cs
@@ -26,7 +26,7 @@ namespace System
public ArrayTypeMismatchException()
: base(SR.Arg_ArrayTypeMismatchException)
{
- HResult = __HResults.COR_E_ARRAYTYPEMISMATCH;
+ HResult = HResults.COR_E_ARRAYTYPEMISMATCH;
}
// Creates a new ArrayMismatchException with its message string set to
@@ -36,13 +36,13 @@ namespace System
public ArrayTypeMismatchException(String message)
: base(message)
{
- HResult = __HResults.COR_E_ARRAYTYPEMISMATCH;
+ HResult = HResults.COR_E_ARRAYTYPEMISMATCH;
}
public ArrayTypeMismatchException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_ARRAYTYPEMISMATCH;
+ HResult = HResults.COR_E_ARRAYTYPEMISMATCH;
}
protected ArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/BadImageFormatException.cs b/src/mscorlib/shared/System/BadImageFormatException.cs
index adedcb2a3f..a4661fc799 100644
--- a/src/mscorlib/shared/System/BadImageFormatException.cs
+++ b/src/mscorlib/shared/System/BadImageFormatException.cs
@@ -25,31 +25,31 @@ namespace System
public BadImageFormatException()
: base(SR.Arg_BadImageFormatException)
{
- HResult = __HResults.COR_E_BADIMAGEFORMAT;
+ HResult = HResults.COR_E_BADIMAGEFORMAT;
}
public BadImageFormatException(String message)
: base(message)
{
- HResult = __HResults.COR_E_BADIMAGEFORMAT;
+ HResult = HResults.COR_E_BADIMAGEFORMAT;
}
public BadImageFormatException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_BADIMAGEFORMAT;
+ HResult = HResults.COR_E_BADIMAGEFORMAT;
}
public BadImageFormatException(String message, String fileName) : base(message)
{
- HResult = __HResults.COR_E_BADIMAGEFORMAT;
+ HResult = HResults.COR_E_BADIMAGEFORMAT;
_fileName = fileName;
}
public BadImageFormatException(String message, String fileName, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_BADIMAGEFORMAT;
+ HResult = HResults.COR_E_BADIMAGEFORMAT;
_fileName = fileName;
}
@@ -78,7 +78,7 @@ namespace System
if (_message == null)
{
if ((_fileName == null) &&
- (HResult == __HResults.COR_E_EXCEPTION))
+ (HResult == HResults.COR_E_EXCEPTION))
_message = SR.Arg_BadImageFormatException;
else
diff --git a/src/mscorlib/shared/System/BitConverter.cs b/src/mscorlib/shared/System/BitConverter.cs
index e19229dd37..edcdd1ec93 100644
--- a/src/mscorlib/shared/System/BitConverter.cs
+++ b/src/mscorlib/shared/System/BitConverter.cs
@@ -30,6 +30,16 @@ namespace System
return r;
}
+ // Converts a Boolean into a Span of bytes with length one.
+ public static bool TryWriteBytes(Span<byte> destination, bool value)
+ {
+ if (destination.Length < sizeof(byte))
+ return false;
+
+ Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value ? (byte)1: (byte)0);
+ return true;
+ }
+
// Converts a char into an array of bytes with length two.
public static byte[] GetBytes(char value)
{
@@ -38,6 +48,16 @@ namespace System
return bytes;
}
+ // Converts a char into a Span
+ public static bool TryWriteBytes(Span<byte> destination, char value)
+ {
+ if (destination.Length < sizeof(char))
+ return false;
+
+ Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);
+ return true;
+ }
+
// Converts a short into an array of bytes with length
// two.
public static byte[] GetBytes(short value)
@@ -47,6 +67,16 @@ namespace System
return bytes;
}
+ // Converts a short into a Span
+ public static bool TryWriteBytes(Span<byte> destination, short value)
+ {
+ if (destination.Length < sizeof(short))
+ return false;
+
+ Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);
+ return true;
+ }
+
// Converts an int into an array of bytes with length
// four.
public static byte[] GetBytes(int value)
@@ -56,6 +86,16 @@ namespace System
return bytes;
}
+ // Converts an int into a Span
+ public static bool TryWriteBytes(Span<byte> destination, int value)
+ {
+ if (destination.Length < sizeof(int))
+ return false;
+
+ Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);
+ return true;
+ }
+
// Converts a long into an array of bytes with length
// eight.
public static byte[] GetBytes(long value)
@@ -65,6 +105,16 @@ namespace System
return bytes;
}
+ // Converts a long into a Span
+ public static bool TryWriteBytes(Span<byte> destination, long value)
+ {
+ if (destination.Length < sizeof(long))
+ return false;
+
+ Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);
+ return true;
+ }
+
// Converts an ushort into an array of bytes with
// length two.
[CLSCompliant(false)]
@@ -75,6 +125,17 @@ namespace System
return bytes;
}
+ // Converts a ushort into a Span
+ [CLSCompliant(false)]
+ public static bool TryWriteBytes(Span<byte> destination, ushort value)
+ {
+ if (destination.Length < sizeof(ushort))
+ return false;
+
+ Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);
+ return true;
+ }
+
// Converts an uint into an array of bytes with
// length four.
[CLSCompliant(false)]
@@ -85,6 +146,17 @@ namespace System
return bytes;
}
+ // Converts a uint into a Span
+ [CLSCompliant(false)]
+ public static bool TryWriteBytes(Span<byte> destination, uint value)
+ {
+ if (destination.Length < sizeof(uint))
+ return false;
+
+ Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);
+ return true;
+ }
+
// Converts an unsigned long into an array of bytes with
// length eight.
[CLSCompliant(false)]
@@ -95,6 +167,17 @@ namespace System
return bytes;
}
+ // Converts a ulong into a Span
+ [CLSCompliant(false)]
+ public static bool TryWriteBytes(Span<byte> destination, ulong value)
+ {
+ if (destination.Length < sizeof(ulong))
+ return false;
+
+ Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);
+ return true;
+ }
+
// Converts a float into an array of bytes with length
// four.
public static byte[] GetBytes(float value)
@@ -104,6 +187,16 @@ namespace System
return bytes;
}
+ // Converts a float into a Span
+ public static bool TryWriteBytes(Span<byte> destination, float value)
+ {
+ if (destination.Length < sizeof(float))
+ return false;
+
+ Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);
+ return true;
+ }
+
// Converts a double into an array of bytes with length
// eight.
public static byte[] GetBytes(double value)
@@ -113,9 +206,27 @@ namespace System
return bytes;
}
+ // Converts a double into a Span
+ public static bool TryWriteBytes(Span<byte> destination, double value)
+ {
+ if (destination.Length < sizeof(double))
+ return false;
+
+ Unsafe.WriteUnaligned(ref destination.DangerousGetPinnableReference(), value);
+ return true;
+ }
+
// Converts an array of bytes into a char.
public static char ToChar(byte[] value, int startIndex) => unchecked((char)ReadInt16(value, startIndex));
+ // Converts a Span into a char
+ public static char ToChar(ReadOnlySpan<byte> value)
+ {
+ if (value.Length < sizeof(char))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
+ return Unsafe.ReadUnaligned<char>(ref value.DangerousGetPinnableReference());
+ }
+
private static short ReadInt16(byte[] value, int startIndex)
{
if (value == null)
@@ -155,27 +266,78 @@ namespace System
// Converts an array of bytes into a short.
public static short ToInt16(byte[] value, int startIndex) => ReadInt16(value, startIndex);
+ // Converts a Span into a short
+ public static short ToInt16(ReadOnlySpan<byte> value)
+ {
+ if (value.Length < sizeof(short))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
+ return Unsafe.ReadUnaligned<short>(ref value.DangerousGetPinnableReference());
+ }
+
// Converts an array of bytes into an int.
public static int ToInt32(byte[] value, int startIndex) => ReadInt32(value, startIndex);
+ // Converts a Span into an int
+ public static int ToInt32(ReadOnlySpan<byte> value)
+ {
+ if (value.Length < sizeof(int))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
+ return Unsafe.ReadUnaligned<int>(ref value.DangerousGetPinnableReference());
+ }
+
// Converts an array of bytes into a long.
public static long ToInt64(byte[] value, int startIndex) => ReadInt64(value, startIndex);
+ // Converts a Span into a long
+ public static long ToInt64(ReadOnlySpan<byte> value)
+ {
+ if (value.Length < sizeof(long))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
+ return Unsafe.ReadUnaligned<long>(ref value.DangerousGetPinnableReference());
+ }
+
// Converts an array of bytes into an ushort.
//
[CLSCompliant(false)]
public static ushort ToUInt16(byte[] value, int startIndex) => unchecked((ushort)ReadInt16(value, startIndex));
+ // Converts a Span into a ushort
+ [CLSCompliant(false)]
+ public static ushort ToUInt16(ReadOnlySpan<byte> value)
+ {
+ if (value.Length < sizeof(ushort))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
+ return Unsafe.ReadUnaligned<ushort>(ref value.DangerousGetPinnableReference());
+ }
+
// Converts an array of bytes into an uint.
//
[CLSCompliant(false)]
public static uint ToUInt32(byte[] value, int startIndex) => unchecked((uint)ReadInt32(value, startIndex));
+ // Convert a Span into a uint
+ [CLSCompliant(false)]
+ public static uint ToUInt32(ReadOnlySpan<byte> value)
+ {
+ if (value.Length < sizeof(uint))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
+ return Unsafe.ReadUnaligned<uint>(ref value.DangerousGetPinnableReference());
+ }
+
// Converts an array of bytes into an unsigned long.
//
[CLSCompliant(false)]
public static ulong ToUInt64(byte[] value, int startIndex) => unchecked((ulong)ReadInt64(value, startIndex));
+ // Converts a Span into an unsigned long
+ [CLSCompliant(false)]
+ public static ulong ToUInt64(ReadOnlySpan<byte> value)
+ {
+ if (value.Length < sizeof(ulong))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
+ return Unsafe.ReadUnaligned<ulong>(ref value.DangerousGetPinnableReference());
+ }
+
// Converts an array of bytes into a float.
public static unsafe float ToSingle(byte[] value, int startIndex)
{
@@ -183,6 +345,14 @@ namespace System
return *(float*)&val;
}
+ // Converts a Span into a float
+ public static float ToSingle(ReadOnlySpan<byte> value)
+ {
+ if (value.Length < sizeof(float))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
+ return Unsafe.ReadUnaligned<float>(ref value.DangerousGetPinnableReference());
+ }
+
// Converts an array of bytes into a double.
public static unsafe double ToDouble(byte[] value, int startIndex)
{
@@ -190,6 +360,14 @@ namespace System
return *(double*)&val;
}
+ // Converts a Span into a double
+ public static double ToDouble(ReadOnlySpan<byte> value)
+ {
+ if (value.Length < sizeof(double))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
+ return Unsafe.ReadUnaligned<double>(ref value.DangerousGetPinnableReference());
+ }
+
private static char GetHexValue(int i)
{
Debug.Assert(i >= 0 && i < 16, "i is out of range.");
@@ -298,6 +476,13 @@ namespace System
return value[startIndex] != 0;
}
+ public static bool ToBoolean(ReadOnlySpan<byte> value)
+ {
+ if (value.Length < sizeof(byte))
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
+ return Unsafe.ReadUnaligned<byte>(ref value.DangerousGetPinnableReference()) != 0;
+ }
+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe long DoubleToInt64Bits(double value)
{
diff --git a/src/mscorlib/src/System/Boolean.cs b/src/mscorlib/shared/System/Boolean.cs
index a1f5064964..a6ffb6de83 100644
--- a/src/mscorlib/src/System/Boolean.cs
+++ b/src/mscorlib/shared/System/Boolean.cs
@@ -12,16 +12,15 @@
**
===========================================================*/
-using System;
-using System.Globalization;
using System.Diagnostics.Contracts;
+using System.Globalization;
+using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
namespace System
{
- // The Boolean class provides the
- // object representation of the boolean primitive type.
[Serializable]
- [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public struct Boolean : IComparable, IConvertible, IComparable<Boolean>, IEquatable<Boolean>
{
//
@@ -34,7 +33,7 @@ namespace System
internal const int True = 1;
// The false value.
- //
+ //
internal const int False = 0;
@@ -95,11 +94,7 @@ namespace System
public String ToString(IFormatProvider provider)
{
- if (false == m_value)
- {
- return FalseLiteral;
- }
- return TrueLiteral;
+ return ToString();
}
// Determines whether two Boolean objects are equal.
@@ -114,7 +109,7 @@ namespace System
return (m_value == ((Boolean)obj).m_value);
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public bool Equals(Boolean obj)
{
return m_value == obj;
@@ -171,35 +166,36 @@ namespace System
public static Boolean Parse(String value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
- Contract.EndContractBlock();
- Boolean result = false;
- if (!TryParse(value, out result))
- {
- throw new FormatException(SR.Format_BadBoolean);
- }
- else
- {
- return result;
- }
+ return Parse(value.AsReadOnlySpan());
}
+ public static bool Parse(ReadOnlySpan<char> value) =>
+ TryParse(value, out bool result) ? result : throw new FormatException(SR.Format_BadBoolean);
+
// Determines whether a String represents true or false.
//
public static Boolean TryParse(String value, out Boolean result)
{
- result = false;
if (value == null)
{
+ result = false;
return false;
}
- // For perf reasons, let's first see if they're equal, then do the
- // trim to get rid of white space, and check again.
- if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase))
+
+ return TryParse(value.AsReadOnlySpan(), out result);
+ }
+
+ public static bool TryParse(ReadOnlySpan<char> value, out bool result)
+ {
+ ReadOnlySpan<char> trueSpan = TrueLiteral.AsReadOnlySpan();
+ if (StringSpanHelpers.Equals(trueSpan, value, StringComparison.OrdinalIgnoreCase))
{
result = true;
return true;
}
- if (FalseLiteral.Equals(value, StringComparison.OrdinalIgnoreCase))
+
+ ReadOnlySpan<char> falseSpan = FalseLiteral.AsReadOnlySpan();
+ if (StringSpanHelpers.Equals(falseSpan, value, StringComparison.OrdinalIgnoreCase))
{
result = false;
return true;
@@ -208,27 +204,27 @@ namespace System
// Special case: Trim whitespace as well as null characters.
value = TrimWhiteSpaceAndNull(value);
- if (TrueLiteral.Equals(value, StringComparison.OrdinalIgnoreCase))
+ if (StringSpanHelpers.Equals(trueSpan, value, StringComparison.OrdinalIgnoreCase))
{
result = true;
return true;
}
- if (FalseLiteral.Equals(value, StringComparison.OrdinalIgnoreCase))
+ if (StringSpanHelpers.Equals(falseSpan, value, StringComparison.OrdinalIgnoreCase))
{
result = false;
return true;
}
+ result = false;
return false;
}
- private static String TrimWhiteSpaceAndNull(String value)
+ private static ReadOnlySpan<char> TrimWhiteSpaceAndNull(ReadOnlySpan<char> value)
{
- int start = 0;
- int end = value.Length - 1;
- char nullChar = (char)0x0000;
+ const char nullChar = (char)0x0000;
+ int start = 0;
while (start < value.Length)
{
if (!Char.IsWhiteSpace(value[start]) && value[start] != nullChar)
@@ -238,6 +234,7 @@ namespace System
start++;
}
+ int end = value.Length - 1;
while (end >= start)
{
if (!Char.IsWhiteSpace(value[end]) && value[end] != nullChar)
@@ -247,7 +244,7 @@ namespace System
end--;
}
- return value.Substring(start, end - start + 1);
+ return value.Slice(start, end - start + 1);
}
//
diff --git a/src/mscorlib/src/System/Buffers/ArrayPoolEventSource.cs b/src/mscorlib/shared/System/Buffers/ArrayPoolEventSource.cs
index 9482744144..9482744144 100644
--- a/src/mscorlib/src/System/Buffers/ArrayPoolEventSource.cs
+++ b/src/mscorlib/shared/System/Buffers/ArrayPoolEventSource.cs
diff --git a/src/mscorlib/shared/System/Buffers/IRetainable.cs b/src/mscorlib/shared/System/Buffers/IRetainable.cs
new file mode 100644
index 0000000000..8d71fc614a
--- /dev/null
+++ b/src/mscorlib/shared/System/Buffers/IRetainable.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;
+using System.Runtime.CompilerServices;
+
+namespace System.Buffers
+{
+ public interface IRetainable
+ {
+ void Retain();
+ bool Release();
+ }
+} \ No newline at end of file
diff --git a/src/mscorlib/shared/System/Buffers/MemoryHandle.cs b/src/mscorlib/shared/System/Buffers/MemoryHandle.cs
new file mode 100644
index 0000000000..fcdc7fe17f
--- /dev/null
+++ b/src/mscorlib/shared/System/Buffers/MemoryHandle.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.Runtime;
+using System.Runtime.InteropServices;
+
+namespace System.Buffers
+{
+ public unsafe struct MemoryHandle : IDisposable
+ {
+ private IRetainable _owner;
+ private void* _pointer;
+ private GCHandle _handle;
+
+ [CLSCompliant(false)]
+ public MemoryHandle(IRetainable owner, void* pinnedPointer = null, GCHandle handle = default(GCHandle))
+ {
+ _owner = owner;
+ _pointer = pinnedPointer;
+ _handle = handle;
+ }
+
+ [CLSCompliant(false)]
+ public void* PinnedPointer => _pointer;
+
+ public void Dispose()
+ {
+ if (_handle.IsAllocated)
+ {
+ _handle.Free();
+ }
+
+ if (_owner != null)
+ {
+ _owner.Release();
+ _owner = null;
+ }
+
+ _pointer = null;
+ }
+
+ }
+} \ No newline at end of file
diff --git a/src/mscorlib/shared/System/Buffers/OwnedMemory.cs b/src/mscorlib/shared/System/Buffers/OwnedMemory.cs
new file mode 100644
index 0000000000..e3a89f7ef4
--- /dev/null
+++ b/src/mscorlib/shared/System/Buffers/OwnedMemory.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.
+
+using System.Runtime;
+using System.Runtime.CompilerServices;
+
+namespace System.Buffers
+{
+ public abstract class OwnedMemory<T> : IDisposable, IRetainable
+ {
+ public abstract int Length { get; }
+
+ public abstract Span<T> AsSpan();
+
+ public Memory<T> AsMemory
+ {
+ get
+ {
+ if (IsDisposed)
+ {
+ ThrowHelper.ThrowObjectDisposedException(nameof(OwnedMemory<T>), ExceptionResource.Memory_ThrowIfDisposed);
+ }
+ return new Memory<T>(this, 0, Length);
+ }
+ }
+
+ public abstract MemoryHandle Pin();
+
+ protected internal abstract bool TryGetArray(out ArraySegment<T> arraySegment);
+
+ public void Dispose()
+ {
+ if (IsRetained)
+ {
+ ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Memory_OutstandingReferences);
+ }
+ Dispose(true);
+ GC.SuppressFinalize(this);
+ }
+
+ protected abstract void Dispose(bool disposing);
+
+ protected abstract bool IsRetained { get; }
+
+ public abstract bool IsDisposed { get; }
+
+ public abstract void Retain();
+
+ public abstract bool Release();
+
+ }
+} \ No newline at end of file
diff --git a/src/mscorlib/src/System/Byte.cs b/src/mscorlib/shared/System/Byte.cs
index fafdcbb535..a0f8ff8c29 100644
--- a/src/mscorlib/src/System/Byte.cs
+++ b/src/mscorlib/shared/System/Byte.cs
@@ -12,22 +12,18 @@
**
===========================================================*/
-
-using System;
+using System.Diagnostics.Contracts;
using System.Globalization;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
+using System.Runtime.Versioning;
namespace System
{
- // The Byte class extends the Value class and
- // provides object representation of the byte primitive type.
- //
[Serializable]
- [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
- [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
- public struct Byte : IComparable, IFormattable, IConvertible
- , IComparable<Byte>, IEquatable<Byte>
+ [StructLayout(LayoutKind.Sequential)]
+ [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ public struct Byte : IComparable, IConvertible, IFormattable, IComparable<Byte>, IEquatable<Byte>
{
private byte m_value; // Do not rename (binary serialization)
@@ -73,7 +69,7 @@ namespace System
return m_value == ((Byte)obj).m_value;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public bool Equals(Byte obj)
{
return m_value == obj;
@@ -88,23 +84,25 @@ namespace System
[Pure]
public static byte Parse(String s)
{
- return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[Pure]
public static byte Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
- return Parse(s, style, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
[Pure]
public static byte Parse(String s, IFormatProvider provider)
{
- return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
-
// Parses an unsigned byte from a String in the given style. If
// a NumberFormatInfo isn't specified, the current culture's
// NumberFormatInfo is assumed.
@@ -112,10 +110,17 @@ namespace System
public static byte Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
+ }
+
+ public static byte Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
- private static byte Parse(String s, NumberStyles style, NumberFormatInfo info)
+ private static byte Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info)
{
int i = 0;
try
@@ -133,16 +138,35 @@ namespace System
public static bool TryParse(String s, out Byte result)
{
- return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return TryParse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Byte result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return TryParse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
+ }
+
+ public static bool TryParse(ReadOnlySpan<char> s, out byte result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
- private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out Byte result)
+ private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out Byte result)
{
result = 0;
int i;
diff --git a/src/mscorlib/shared/System/Collections/Generic/KeyNotFoundException.cs b/src/mscorlib/shared/System/Collections/Generic/KeyNotFoundException.cs
index cdd6faf030..c32bc623ba 100644
--- a/src/mscorlib/shared/System/Collections/Generic/KeyNotFoundException.cs
+++ b/src/mscorlib/shared/System/Collections/Generic/KeyNotFoundException.cs
@@ -12,19 +12,19 @@ namespace System.Collections.Generic
public KeyNotFoundException()
: base(SR.Arg_KeyNotFound)
{
- HResult = __HResults.COR_E_KEYNOTFOUND;
+ HResult = HResults.COR_E_KEYNOTFOUND;
}
public KeyNotFoundException(String message)
: base(message)
{
- HResult = __HResults.COR_E_KEYNOTFOUND;
+ HResult = HResults.COR_E_KEYNOTFOUND;
}
public KeyNotFoundException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_KEYNOTFOUND;
+ HResult = HResults.COR_E_KEYNOTFOUND;
}
protected KeyNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/Collections/ICollection.cs b/src/mscorlib/shared/System/Collections/ICollection.cs
index 80ea092363..8fd6a96b48 100644
--- a/src/mscorlib/shared/System/Collections/ICollection.cs
+++ b/src/mscorlib/shared/System/Collections/ICollection.cs
@@ -29,7 +29,7 @@ namespace System.Collections
// 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,
+ // In the absence of a static Synchronized method on a collection,
// the expected usage for SyncRoot would look like this:
//
// ICollection col = ...
diff --git a/src/mscorlib/src/System/Collections/ListDictionaryInternal.cs b/src/mscorlib/shared/System/Collections/ListDictionaryInternal.cs
index 17eb89a2b2..681e51a329 100644
--- a/src/mscorlib/src/System/Collections/ListDictionaryInternal.cs
+++ b/src/mscorlib/shared/System/Collections/ListDictionaryInternal.cs
@@ -21,7 +21,12 @@ namespace System.Collections
/// This should not be used if performance is important for large numbers of elements.
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
- internal class ListDictionaryInternal : IDictionary
+#if CORECLR
+ internal
+#else
+ public
+#endif
+ class ListDictionaryInternal : IDictionary
{
private DictionaryNode head; // Do not rename (binary serialization)
private int version; // Do not rename (binary serialization)
diff --git a/src/mscorlib/src/System/Collections/ObjectModel/Collection.cs b/src/mscorlib/shared/System/Collections/ObjectModel/Collection.cs
index 8e5de70e72..75e88eccb3 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/Collection.cs
+++ b/src/mscorlib/shared/System/Collections/ObjectModel/Collection.cs
@@ -2,13 +2,8 @@
// 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.Collections.Generic;
using System.Diagnostics;
-using System.Runtime;
namespace System.Collections.ObjectModel
{
@@ -243,7 +238,7 @@ namespace System.Collections.ObjectModel
{
//
// Catch the obvious case assignment will fail.
- // We can found all possible problems by doing the check though.
+ // We can't find all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
diff --git a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs b/src/mscorlib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs
index 03c7d45e16..f1d2a0969b 100644
--- a/src/mscorlib/src/System/Collections/ObjectModel/ReadOnlyCollection.cs
+++ b/src/mscorlib/shared/System/Collections/ObjectModel/ReadOnlyCollection.cs
@@ -2,13 +2,8 @@
// 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.Collections.Generic;
using System.Diagnostics;
-using System.Runtime;
namespace System.Collections.ObjectModel
{
@@ -175,7 +170,7 @@ namespace System.Collections.ObjectModel
{
//
// Catch the obvious case assignment will fail.
- // We can found all possible problems by doing the check though.
+ // We can't find all possible problems by doing the check though.
// For example, if the element type of the Array is derived from T,
// we can't figure out if we can successfully copy the element beforehand.
//
diff --git a/src/mscorlib/shared/System/Convert.cs b/src/mscorlib/shared/System/Convert.cs
index 576f78f1f1..02fbbdbc3e 100644
--- a/src/mscorlib/shared/System/Convert.cs
+++ b/src/mscorlib/shared/System/Convert.cs
@@ -84,7 +84,7 @@ namespace System
// 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
+ // database applications to indicate the absence of a known value. Note
// that Value.DBNull is NOT the same as a null object reference, which is
// represented by Value.Empty.
//
@@ -2670,7 +2670,7 @@ namespace System
/// 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>
+ /// <returns>The array of bytes represented by the specified Base64 string.</returns>
public static Byte[] FromBase64String(String s)
{
// "s" is an unfortunate parameter name, but we need to keep it for backward compat.
diff --git a/src/mscorlib/shared/System/DBNull.cs b/src/mscorlib/shared/System/DBNull.cs
index 4f4d64bf66..3cee2b15c8 100644
--- a/src/mscorlib/shared/System/DBNull.cs
+++ b/src/mscorlib/shared/System/DBNull.cs
@@ -6,17 +6,23 @@ 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)
{
- throw new PlatformNotSupportedException();
+ UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.NullUnity);
}
public override string ToString()
diff --git a/src/mscorlib/shared/System/DataMisalignedException.cs b/src/mscorlib/shared/System/DataMisalignedException.cs
index ff5b29f1cf..d8d36b5cb7 100644
--- a/src/mscorlib/shared/System/DataMisalignedException.cs
+++ b/src/mscorlib/shared/System/DataMisalignedException.cs
@@ -18,19 +18,19 @@ namespace System
public DataMisalignedException()
: base(SR.Arg_DataMisalignedException)
{
- HResult = __HResults.COR_E_DATAMISALIGNED;
+ HResult = HResults.COR_E_DATAMISALIGNED;
}
public DataMisalignedException(String message)
: base(message)
{
- HResult = __HResults.COR_E_DATAMISALIGNED;
+ HResult = HResults.COR_E_DATAMISALIGNED;
}
public DataMisalignedException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_DATAMISALIGNED;
+ HResult = HResults.COR_E_DATAMISALIGNED;
}
}
}
diff --git a/src/mscorlib/shared/System/DateTime.cs b/src/mscorlib/shared/System/DateTime.cs
index 16a75fdfa6..e72654a8d6 100644
--- a/src/mscorlib/shared/System/DateTime.cs
+++ b/src/mscorlib/shared/System/DateTime.cs
@@ -129,7 +129,7 @@ namespace System
private const String TicksField = "ticks"; // Do not rename (binary serialization)
private const String DateDataField = "dateData"; // Do not rename (binary serialization)
- // The data is stored as an unsigned 64-bit integeter
+ // The data is stored as an unsigned 64-bit integer
// 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
@@ -1025,11 +1025,7 @@ namespace System
}
// 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.
- //
+ // resolution of the returned value depends on the system timer.
public static DateTime Now
{
get
diff --git a/src/mscorlib/shared/System/DateTimeOffset.cs b/src/mscorlib/shared/System/DateTimeOffset.cs
index ab35bdb0fe..e3366e2a7d 100644
--- a/src/mscorlib/shared/System/DateTimeOffset.cs
+++ b/src/mscorlib/shared/System/DateTimeOffset.cs
@@ -129,11 +129,7 @@ namespace System
}
// Returns a DateTimeOffset 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.
- //
+ // resolution of the returned value depends on the system timer.
public static DateTimeOffset Now
{
get
diff --git a/src/mscorlib/shared/System/DefaultBinder.cs b/src/mscorlib/shared/System/DefaultBinder.cs
index 9adf702a02..b6c12b121d 100644
--- a/src/mscorlib/shared/System/DefaultBinder.cs
+++ b/src/mscorlib/shared/System/DefaultBinder.cs
@@ -42,7 +42,7 @@ namespace System
state = null;
-#region Map named parameters to candidate parameter postions
+#region Map named parameters to candidate parameter positions
// We are creating an paramOrder array to act as a mapping
// between the order of the args and the actual order of the
// parameters in the method. This order may differ because
@@ -530,7 +530,7 @@ namespace System
for (i = 0; i < types.Length; i++)
{
realTypes[i] = types[i].UnderlyingSystemType;
- if (!(realTypes[i].IsRuntimeImplemented()))
+ if (!(realTypes[i].IsRuntimeImplemented() || realTypes[i] is SignatureType))
throw new ArgumentException(SR.Arg_MustBeType, nameof(types));
}
types = realTypes;
@@ -552,19 +552,30 @@ namespace System
for (j = 0; j < types.Length; j++)
{
Type pCls = par[j].ParameterType;
- if (pCls == types[j])
+ if (types[j].MatchesParameterTypeExactly(par[j]))
continue;
if (pCls == typeof(object))
continue;
+
+ Type type = types[j];
+ if (type is SignatureType signatureType)
+ {
+ if (!(candidates[i] is MethodInfo methodInfo))
+ break;
+ type = signatureType.TryResolveAgainstGenericMethod(methodInfo);
+ if (type == null)
+ break;
+ }
+
if (pCls.IsPrimitive)
{
- if (!(types[j].UnderlyingSystemType.IsRuntimeImplemented()) ||
- !CanChangePrimitive(types[j].UnderlyingSystemType, pCls.UnderlyingSystemType))
+ if (!(type.UnderlyingSystemType.IsRuntimeImplemented()) ||
+ !CanChangePrimitive(type.UnderlyingSystemType, pCls.UnderlyingSystemType))
break;
}
else
{
- if (!pCls.IsAssignableFrom(types[j]))
+ if (!pCls.IsAssignableFrom(type))
break;
}
}
@@ -918,11 +929,22 @@ namespace System
if (c1 == c2)
return 0;
- if (c1 == t)
- return 1;
+ if (t is SignatureType signatureType)
+ {
+ if (signatureType.MatchesExactly(c1))
+ return 1;
- if (c2 == t)
- return 2;
+ if (signatureType.MatchesExactly(c2))
+ return 2;
+ }
+ else
+ {
+ if (c1 == t)
+ return 1;
+
+ if (c2 == t)
+ return 2;
+ }
bool c1FromC2;
bool c2FromC1;
diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs
index 5292551314..a74125a35a 100644
--- a/src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs
+++ b/src/mscorlib/shared/System/Diagnostics/Tracing/EventProvider.cs
@@ -87,7 +87,8 @@ namespace System.Diagnostics.Tracing
private long m_allKeywordMask; // Match all keyword
private List<SessionInfo> m_liveSessions; // current live sessions (Tuple<sessionIdBit, etwSessionId>)
private bool m_enabled; // Enabled flag from Trace callback
- private Guid m_providerId; // Control Guid
+ private string m_providerName; // Control name
+ private Guid m_providerId; // Control Guid
internal bool m_disposed; // when true provider has unregistered
[ThreadStatic]
@@ -140,16 +141,19 @@ namespace System.Diagnostics.Tracing
// <SatisfiesLinkDemand Name="Win32Exception..ctor(System.Int32)" />
// <ReferencesCritical Name="Method: EtwEnableCallBack(Guid&, Int32, Byte, Int64, Int64, Void*, Void*):Void" Ring="1" />
// </SecurityKernel>
- internal unsafe void Register(Guid providerGuid)
+ internal unsafe void Register(EventSource eventSource)
{
- m_providerId = providerGuid;
uint status;
m_etwCallback = new UnsafeNativeMethods.ManifestEtw.EtwEnableCallback(EtwEnableCallBack);
- status = EventRegister(ref m_providerId, m_etwCallback);
+ status = EventRegister(eventSource, m_etwCallback);
if (status != 0)
{
- throw new ArgumentException(Win32Native.GetMessage(unchecked((int)status)));
+#if PLATFORM_WINDOWS
+ throw new ArgumentException(Interop.Kernel32.GetMessage(unchecked((int)status)));
+#else
+ throw new ArgumentException(Convert.ToString(unchecked((int)status)));
+#endif
}
}
@@ -488,7 +492,7 @@ namespace System.Diagnostics.Tracing
// at least some of the time.
// Determine our session from what is in the registry.
- string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}";
+ string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerName + "}";
if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8)
regKey = @"Software" + @"\Wow6432Node" + regKey;
else
@@ -563,7 +567,7 @@ namespace System.Diagnostics.Tracing
if (filterData == null)
{
#if (!ES_BUILD_PCL && !ES_BUILD_PN && PLATFORM_WINDOWS)
- string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}";
+ string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerName + "}";
if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8)
regKey = @"HKEY_LOCAL_MACHINE\Software" + @"\Wow6432Node" + regKey;
else
@@ -1184,11 +1188,12 @@ namespace System.Diagnostics.Tracing
// These are look-alikes to the Manifest based ETW OS APIs that have been shimmed to work
// either with Manifest ETW or Classic ETW (if Manifest based ETW is not available).
- private unsafe uint EventRegister(ref Guid providerId, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback)
+ private unsafe uint EventRegister(EventSource eventSource, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback)
{
- m_providerId = providerId;
+ m_providerName = eventSource.Name;
+ m_providerId = eventSource.Guid;
m_etwCallback = enableCallback;
- return m_eventProvider.EventRegister(ref providerId, enableCallback, null, ref m_regHandle);
+ return m_eventProvider.EventRegister(eventSource, enableCallback, null, ref m_regHandle);
}
private uint EventUnregister(long registrationHandle)
@@ -1221,11 +1226,12 @@ namespace System.Diagnostics.Tracing
{
// Register an event provider.
unsafe uint IEventProvider.EventRegister(
- ref Guid providerId,
+ EventSource eventSource,
UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback,
void* callbackContext,
ref long registrationHandle)
{
+ Guid providerId = eventSource.Guid;
return UnsafeNativeMethods.ManifestEtw.EventRegister(
ref providerId,
enableCallback,
@@ -1278,7 +1284,7 @@ namespace System.Diagnostics.Tracing
internal sealed class NoOpEventProvider : IEventProvider
{
unsafe uint IEventProvider.EventRegister(
- ref Guid providerId,
+ EventSource eventSource,
UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback,
void* callbackContext,
ref long registrationHandle)
diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs
index d8eec73931..4e436e7baf 100644
--- a/src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs
+++ b/src/mscorlib/shared/System/Diagnostics/Tracing/EventSource.cs
@@ -265,7 +265,7 @@ namespace System.Diagnostics.Tracing
public Guid Guid { get { return m_guid; } }
/// <summary>
- /// Returns true if the eventSource has been enabled at all. This is the prefered test
+ /// Returns true if the eventSource has been enabled at all. This is the preferred test
/// to be performed before a relatively expensive EventSource operation.
/// </summary>
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "This does not need to be correct when racing with other threads")]
@@ -572,11 +572,11 @@ namespace System.Diagnostics.Tracing
/// <summary>
/// EventSources can have arbitrary string key-value pairs associated with them called Traits.
/// These traits are not interpreted by the EventSource but may be interpreted by EventListeners
- /// (e.g. like the built in ETW listener). These traits are specififed at EventSource
+ /// (e.g. like the built in ETW listener). These traits are specified at EventSource
/// construction time and can be retrieved by using this GetTrait API.
/// </summary>
/// <param name="key">The key to look up in the set of key-value pairs passed to the EventSource constructor</param>
- /// <returns>The value string associated iwth key. Will return null if there is no such key.</returns>
+ /// <returns>The value string associated with key. Will return null if there is no such key.</returns>
public string GetTrait(string key)
{
if (m_traits != null)
@@ -661,7 +661,7 @@ namespace System.Diagnostics.Tracing
///
/// Also specify a list of key-value pairs called traits (you must pass an even number of strings).
/// The first string is the key and the second is the value. These are not interpreted by EventSource
- /// itself but may be interprated the listeners. Can be fetched with GetTrait(string).
+ /// itself but may be interpreted the listeners. Can be fetched with GetTrait(string).
/// </summary>
/// <param name="settings">See EventSourceSettings for more.</param>
/// <param name="traits">A collection of key-value strings (must be an even number).</param>
@@ -1560,7 +1560,7 @@ namespace System.Diagnostics.Tracing
// Register the provider with ETW
var provider = new OverideEventProvider(this);
- provider.Register(eventSourceGuid);
+ provider.Register(this);
#endif
// Add the eventSource to the global (weak) list.
// This also sets m_id, which is the index in the list.
@@ -4942,10 +4942,10 @@ namespace System.Diagnostics.Tracing
get
{
// For contract based events we create the list lazily.
- if (m_payloadNames == null)
+ // You can have m_payloadNames be null in the TraceLogging case (EventID < 0) so only
+ // do the lazy init if you know it is contract based (EventID >= 0)
+ if (EventId >= 0 && m_payloadNames == null)
{
- // Self described events are identified by id -1.
- Debug.Assert(EventId != -1);
var names = new List<string>();
foreach (var parameter in m_eventSource.m_eventData[EventId].Parameters)
@@ -5521,7 +5521,7 @@ namespace System.Diagnostics.Tracing
/// Returns a session mask representing all sessions in which the activity
/// associated with the current thread is allowed through the activity filter.
/// If 'triggeringEvent' is true the event MAY be a triggering event. Ideally
- /// most of the time this is false as you can guarentee this event is NOT a
+ /// most of the time this is false as you can guarantee this event is NOT a
/// triggering event. If 'triggeringEvent' is true, then it checks the
/// 'EventSource' and 'eventID' of the event being logged to see if it is actually
/// a trigger. If so it activates the current activity.
@@ -5622,7 +5622,7 @@ namespace System.Diagnostics.Tracing
/// <summary>
/// For the EventListener/EtwSession associated with 'filterList', add 'childActivityid'
/// to list of active activities IF 'currentActivityId' is also active. Passing in a null
- /// value for 'currentActivityid' is an indication tha caller has already verified
+ /// value for 'currentActivityid' is an indication the caller has already verified
/// that the current activity is active.
/// </summary>
unsafe public static void FlowActivityIfNeeded(ActivityFilter filterList, Guid* currentActivityId, Guid* childActivityID)
@@ -5642,7 +5642,7 @@ namespace System.Diagnostics.Tracing
// make sure current activity is still in the set:
activeActivities[EventSource.InternalCurrentThreadActivityId] = Environment.TickCount;
}
- // add child activity to list of actives
+ // add child activity to list of activities
activeActivities[*childActivityID] = Environment.TickCount;
}
@@ -6070,11 +6070,11 @@ namespace System.Diagnostics.Tracing
/// (m_EventEnabled) for a particular EventSource X EventListener tuple
///
/// Thus a single EventListener may have many EventDispatchers (one for every EventSource
- /// that that EventListener has activate) and a Single EventSource may also have many
+ /// that EventListener has activate) and a Single EventSource may also have many
/// event Dispatchers (one for every EventListener that has activated it).
///
/// Logically a particular EventDispatcher belongs to exactly one EventSource and exactly
- /// one EventListener (alhtough EventDispatcher does not 'remember' the EventSource it is
+ /// one EventListener (although EventDispatcher does not 'remember' the EventSource it is
/// associated with.
/// </summary>
internal class EventDispatcher
diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/IEventProvider.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/IEventProvider.cs
index 71a2fe4d44..966dac2fef 100644
--- a/src/mscorlib/shared/System/Diagnostics/Tracing/IEventProvider.cs
+++ b/src/mscorlib/shared/System/Diagnostics/Tracing/IEventProvider.cs
@@ -15,7 +15,7 @@ namespace System.Diagnostics.Tracing
{
// Register an event provider.
unsafe uint EventRegister(
- ref Guid providerId,
+ EventSource eventSource,
UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback,
void* callbackContext,
ref long registrationHandle);
diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs
index 38c1767462..acc3eeb233 100644
--- a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs
+++ b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/EventSourceActivity.cs
@@ -77,8 +77,8 @@ namespace System.Diagnostics.Tracing
/// <summary>
/// Writes a Start event with the specified name and data. If the start event is not active (because the provider
- /// is not on or keyword-level indiates the event is off, then the returned activity is simply the 'this' poitner
- /// and it is effectively like the Start d
+ /// is not on or keyword-level indicates the event is off, then the returned activity is simply the 'this' pointer
+ /// and it is effectively like start did not get called.
///
/// A new activityID GUID is generated and the returned
/// EventSourceActivity remembers this activity and will mark every event (including the start stop and any writes)
@@ -139,7 +139,7 @@ namespace System.Diagnostics.Tracing
}
/// <summary>
/// Used if you wish to use the non-default stop name (which is the start name with Start replace with 'Stop')
- /// This can be useful to indicate unusual ways of stoping (but it is still STRONGLY recommeded that
+ /// This can be useful to indicate unusual ways of stopping (but it is still STRONGLY recommended that
/// you start with the same prefix used for the start event and you end with the 'Stop' suffix.
/// </summary>
public void Stop<T>(string eventName)
@@ -149,7 +149,7 @@ namespace System.Diagnostics.Tracing
}
/// <summary>
/// Used if you wish to use the non-default stop name (which is the start name with Start replace with 'Stop')
- /// This can be useful to indicate unusual ways of stoping (but it is still STRONGLY recommeded that
+ /// This can be useful to indicate unusual ways of stopping (but it is still STRONGLY recommended that
/// you start with the same prefix used for the start event and you end with the 'Stop' suffix.
/// </summary>
public void Stop<T>(string eventName, T data)
@@ -158,7 +158,7 @@ namespace System.Diagnostics.Tracing
}
/// <summary>
- /// Writes an event associated with this activity to the eventSource associted with this activity.
+ /// Writes an event associated with this activity to the eventSource associated with this activity.
/// May only be called when the activity is in the Started state.
/// </summary>
/// <param name="eventName">
diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataType.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataType.cs
index 529948daf8..cc416a96d9 100644
--- a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataType.cs
+++ b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingDataType.cs
@@ -182,7 +182,7 @@ namespace System.Diagnostics.Tracing
/// <summary>
/// Core type.
- /// Special case: Struct indicates that this field plus the the
+ /// Special case: Struct indicates that this field plus the
/// subsequent N logical fields are to be considered as one logical
/// field (i.e. a nested structure). The OutType is used to encode N.
/// The maximum value for N is 127. This field has no payload by
diff --git a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs
index aba1671ae2..a1218d1a7f 100644
--- a/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs
+++ b/src/mscorlib/shared/System/Diagnostics/Tracing/TraceLogging/TraceLoggingEventSource.cs
@@ -80,7 +80,7 @@ namespace System.Diagnostics.Tracing
///
/// Also specify a list of key-value pairs called traits (you must pass an even number of strings).
/// The first string is the key and the second is the value. These are not interpreted by EventSource
- /// itself but may be interprated the listeners. Can be fetched with GetTrait(string).
+ /// itself but may be interpreted the listeners. Can be fetched with GetTrait(string).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
@@ -442,7 +442,10 @@ namespace System.Diagnostics.Tracing
var pinCount = eventTypes.pinCount;
var scratch = stackalloc byte[eventTypes.scratchSize];
var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
+
var pins = stackalloc GCHandle[pinCount];
+ for (int i = 0; i < pinCount; i++)
+ pins[i] = default(GCHandle);
fixed (byte*
pMetadata0 = this.providerMetadata,
@@ -619,7 +622,10 @@ namespace System.Diagnostics.Tracing
var pinCount = eventTypes.pinCount;
var scratch = stackalloc byte[eventTypes.scratchSize];
var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
+
var pins = stackalloc GCHandle[pinCount];
+ for (int i = 0; i < pinCount; i++)
+ pins[i] = default(GCHandle);
fixed (byte*
pMetadata0 = this.providerMetadata,
@@ -744,9 +750,9 @@ namespace System.Diagnostics.Tracing
{
DataCollector.ThreadInstance.Disable();
- for (int i = 0; i != cPins; i++)
+ for (int i = 0; i < cPins; i++)
{
- if (IntPtr.Zero != (IntPtr)pPins[i])
+ if (pPins[i].IsAllocated)
{
pPins[i].Free();
}
diff --git a/src/mscorlib/shared/System/DivideByZeroException.cs b/src/mscorlib/shared/System/DivideByZeroException.cs
index 0fad2f8d56..ad74bde0fd 100644
--- a/src/mscorlib/shared/System/DivideByZeroException.cs
+++ b/src/mscorlib/shared/System/DivideByZeroException.cs
@@ -20,19 +20,19 @@ namespace System
public DivideByZeroException()
: base(SR.Arg_DivideByZero)
{
- HResult = __HResults.COR_E_DIVIDEBYZERO;
+ HResult = HResults.COR_E_DIVIDEBYZERO;
}
public DivideByZeroException(String message)
: base(message)
{
- HResult = __HResults.COR_E_DIVIDEBYZERO;
+ HResult = HResults.COR_E_DIVIDEBYZERO;
}
public DivideByZeroException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_DIVIDEBYZERO;
+ HResult = HResults.COR_E_DIVIDEBYZERO;
}
protected DivideByZeroException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/DllNotFoundException.cs b/src/mscorlib/shared/System/DllNotFoundException.cs
index 8c69e45eda..82d5bdd0c5 100644
--- a/src/mscorlib/shared/System/DllNotFoundException.cs
+++ b/src/mscorlib/shared/System/DllNotFoundException.cs
@@ -21,19 +21,19 @@ namespace System
public DllNotFoundException()
: base(SR.Arg_DllNotFoundException)
{
- HResult = __HResults.COR_E_DLLNOTFOUND;
+ HResult = HResults.COR_E_DLLNOTFOUND;
}
public DllNotFoundException(String message)
: base(message)
{
- HResult = __HResults.COR_E_DLLNOTFOUND;
+ HResult = HResults.COR_E_DLLNOTFOUND;
}
public DllNotFoundException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_DLLNOTFOUND;
+ HResult = HResults.COR_E_DLLNOTFOUND;
}
protected DllNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/src/System/Double.cs b/src/mscorlib/shared/System/Double.cs
index ee5ffa0ccf..7ee52027f3 100644
--- a/src/mscorlib/src/System/Double.cs
+++ b/src/mscorlib/shared/System/Double.cs
@@ -12,20 +12,18 @@
**
===========================================================*/
-using System;
+using System.Diagnostics.Contracts;
using System.Globalization;
-using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
-using System.Runtime.ConstrainedExecution;
-using System.Diagnostics.Contracts;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
namespace System
{
[Serializable]
[StructLayout(LayoutKind.Sequential)]
- [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
- public struct Double : IComparable, IFormattable, IConvertible
- , IComparable<Double>, IEquatable<Double>
+ [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ public struct Double : IComparable, IConvertible, IFormattable, IComparable<Double>, IEquatable<Double>
{
private double m_value; // Do not rename (binary serialization)
@@ -42,11 +40,12 @@ namespace System
public const double PositiveInfinity = (double)1.0 / (double)(0.0);
public const double NaN = (double)0.0 / (double)0.0;
- internal static double NegativeZero = BitConverter.Int64BitsToDouble(unchecked((long)0x8000000000000000));
+ // We use this explicit definition to avoid the confusion between 0.0 and -0.0.
+ internal const double NegativeZero = -0.0;
/// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsFinite(double d)
{
@@ -56,7 +55,7 @@ namespace System
/// <summary>Determines whether the specified value is infinite.</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsInfinity(double d)
{
@@ -66,7 +65,7 @@ namespace System
/// <summary>Determines whether the specified value is NaN.</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNaN(double d)
{
@@ -76,7 +75,7 @@ namespace System
/// <summary>Determines whether the specified value is negative.</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNegative(double d)
{
@@ -86,7 +85,7 @@ namespace System
/// <summary>Determines whether the specified value is negative infinity.</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsNegativeInfinity(double d)
{
@@ -95,7 +94,7 @@ namespace System
/// <summary>Determines whether the specified value is normal.</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public unsafe static bool IsNormal(double d)
{
@@ -106,7 +105,7 @@ namespace System
/// <summary>Determines whether the specified value is positive infinity.</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsPositiveInfinity(double d)
{
@@ -115,7 +114,7 @@ namespace System
/// <summary>Determines whether the specified value is subnormal.</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public unsafe static bool IsSubnormal(double d)
{
@@ -183,37 +182,37 @@ namespace System
return IsNaN(temp) && IsNaN(m_value);
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public static bool operator ==(Double left, Double right)
{
return left == right;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public static bool operator !=(Double left, Double right)
{
return left != right;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public static bool operator <(Double left, Double right)
{
return left < right;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public static bool operator >(Double left, Double right)
{
return left > right;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public static bool operator <=(Double left, Double right)
{
return left <= right;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public static bool operator >=(Double left, Double right)
{
return left >= right;
@@ -269,24 +268,28 @@ namespace System
public static double Parse(String s)
{
- return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseDouble(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
}
public static double Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
- return Parse(s, style, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseDouble(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
public static double Parse(String s, IFormatProvider provider)
{
- return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseDouble(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
}
public static double Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
- return Parse(s, style, NumberFormatInfo.GetInstance(provider));
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseDouble(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
}
// Parses a double from a String in the given style. If
@@ -296,48 +299,67 @@ namespace System
// This method will not throw an OverflowException, but will return
// PositiveInfinity or NegativeInfinity for a number that is too
// large or too small.
- //
- private static double Parse(String s, NumberStyles style, NumberFormatInfo info)
+
+ public static double Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
- return Number.ParseDouble(s, style, info);
+ NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
+ return Number.ParseDouble(s, style, NumberFormatInfo.GetInstance(provider));
}
+
+
public static bool TryParse(String s, out double result)
{
- return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return TryParse(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out double result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
- return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
- }
- private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out double result)
- {
if (s == null)
{
result = 0;
return false;
}
+
+ return TryParse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
+ }
+
+ public static bool TryParse(ReadOnlySpan<char> s, out double result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
+ return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
+ }
+
+ private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out double result)
+ {
bool success = Number.TryParseDouble(s, style, info, out result);
if (!success)
{
- String sTrim = s.Trim();
- if (sTrim.Equals(info.PositiveInfinitySymbol))
+ ReadOnlySpan<char> sTrim = StringSpanHelpers.Trim(s);
+ if (StringSpanHelpers.Equals(sTrim, info.PositiveInfinitySymbol))
{
result = PositiveInfinity;
}
- else if (sTrim.Equals(info.NegativeInfinitySymbol))
+ else if (StringSpanHelpers.Equals(sTrim, info.NegativeInfinitySymbol))
{
result = NegativeInfinity;
}
- else if (sTrim.Equals(info.NaNSymbol))
+ else if (StringSpanHelpers.Equals(sTrim, info.NaNSymbol))
{
result = NaN;
}
else
+ {
return false; // We really failed
+ }
}
return true;
}
diff --git a/src/mscorlib/shared/System/DuplicateWaitObjectException.cs b/src/mscorlib/shared/System/DuplicateWaitObjectException.cs
index 7eadead8c7..95bdedd526 100644
--- a/src/mscorlib/shared/System/DuplicateWaitObjectException.cs
+++ b/src/mscorlib/shared/System/DuplicateWaitObjectException.cs
@@ -37,25 +37,25 @@ namespace System
public DuplicateWaitObjectException()
: base(DuplicateWaitObjectMessage)
{
- HResult = __HResults.COR_E_DUPLICATEWAITOBJECT;
+ HResult = HResults.COR_E_DUPLICATEWAITOBJECT;
}
public DuplicateWaitObjectException(String parameterName)
: base(DuplicateWaitObjectMessage, parameterName)
{
- HResult = __HResults.COR_E_DUPLICATEWAITOBJECT;
+ HResult = HResults.COR_E_DUPLICATEWAITOBJECT;
}
public DuplicateWaitObjectException(String parameterName, String message)
: base(message, parameterName)
{
- HResult = __HResults.COR_E_DUPLICATEWAITOBJECT;
+ HResult = HResults.COR_E_DUPLICATEWAITOBJECT;
}
public DuplicateWaitObjectException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_DUPLICATEWAITOBJECT;
+ HResult = HResults.COR_E_DUPLICATEWAITOBJECT;
}
protected DuplicateWaitObjectException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/EntryPointNotFoundException.cs b/src/mscorlib/shared/System/EntryPointNotFoundException.cs
index 0b881cec05..e62ca0e11d 100644
--- a/src/mscorlib/shared/System/EntryPointNotFoundException.cs
+++ b/src/mscorlib/shared/System/EntryPointNotFoundException.cs
@@ -21,19 +21,19 @@ namespace System
public EntryPointNotFoundException()
: base(SR.Arg_EntryPointNotFoundException)
{
- HResult = __HResults.COR_E_ENTRYPOINTNOTFOUND;
+ HResult = HResults.COR_E_ENTRYPOINTNOTFOUND;
}
public EntryPointNotFoundException(String message)
: base(message)
{
- HResult = __HResults.COR_E_ENTRYPOINTNOTFOUND;
+ HResult = HResults.COR_E_ENTRYPOINTNOTFOUND;
}
public EntryPointNotFoundException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_ENTRYPOINTNOTFOUND;
+ HResult = HResults.COR_E_ENTRYPOINTNOTFOUND;
}
protected EntryPointNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/ExecutionEngineException.cs b/src/mscorlib/shared/System/ExecutionEngineException.cs
index b89f6d9a8d..c33435875e 100644
--- a/src/mscorlib/shared/System/ExecutionEngineException.cs
+++ b/src/mscorlib/shared/System/ExecutionEngineException.cs
@@ -26,19 +26,19 @@ namespace System
public ExecutionEngineException()
: base(SR.Arg_ExecutionEngineException)
{
- HResult = __HResults.COR_E_EXECUTIONENGINE;
+ HResult = HResults.COR_E_EXECUTIONENGINE;
}
public ExecutionEngineException(String message)
: base(message)
{
- HResult = __HResults.COR_E_EXECUTIONENGINE;
+ HResult = HResults.COR_E_EXECUTIONENGINE;
}
public ExecutionEngineException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_EXECUTIONENGINE;
+ HResult = HResults.COR_E_EXECUTIONENGINE;
}
}
}
diff --git a/src/mscorlib/shared/System/FieldAccessException.cs b/src/mscorlib/shared/System/FieldAccessException.cs
index b56d749771..883bbd8bc2 100644
--- a/src/mscorlib/shared/System/FieldAccessException.cs
+++ b/src/mscorlib/shared/System/FieldAccessException.cs
@@ -18,19 +18,19 @@ namespace System
public FieldAccessException()
: base(SR.Arg_FieldAccessException)
{
- HResult = __HResults.COR_E_FIELDACCESS;
+ HResult = HResults.COR_E_FIELDACCESS;
}
public FieldAccessException(String message)
: base(message)
{
- HResult = __HResults.COR_E_FIELDACCESS;
+ HResult = HResults.COR_E_FIELDACCESS;
}
public FieldAccessException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_FIELDACCESS;
+ HResult = HResults.COR_E_FIELDACCESS;
}
protected FieldAccessException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/FormatException.cs b/src/mscorlib/shared/System/FormatException.cs
index 9baaac2353..4af45cdd94 100644
--- a/src/mscorlib/shared/System/FormatException.cs
+++ b/src/mscorlib/shared/System/FormatException.cs
@@ -20,19 +20,19 @@ namespace System
public FormatException()
: base(SR.Arg_FormatException)
{
- HResult = __HResults.COR_E_FORMAT;
+ HResult = HResults.COR_E_FORMAT;
}
public FormatException(String message)
: base(message)
{
- HResult = __HResults.COR_E_FORMAT;
+ HResult = HResults.COR_E_FORMAT;
}
public FormatException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_FORMAT;
+ HResult = HResults.COR_E_FORMAT;
}
protected FormatException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs b/src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs
index 5d3239ebfc..9f8c072c93 100644
--- a/src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs
+++ b/src/mscorlib/shared/System/Globalization/DateTimeFormatInfo.cs
@@ -31,7 +31,7 @@ namespace System.Globalization
// This is an internal flag.
//
// This flag is different from MonthNameStyles because this flag
- // can be expanded to accomodate parsing behaviors like CJK month names
+ // can be expanded to accommodate parsing behaviors like CJK month names
// or alternative month names, etc.
[Flags]
@@ -2645,7 +2645,7 @@ namespace System.Globalization
{
String str;
// We have to call public methods here to work with inherited DTFI.
- // Insert the month name first, so that they are at the front of abbrevaited
+ // Insert the month name first, so that they are at the front of abbreviated
// month names.
str = InvariantInfo.GetMonthName(i);
InsertHash(temp, str, TokenType.MonthToken, i);
@@ -2688,7 +2688,7 @@ namespace System.Globalization
String str;
//str = internalGetMonthName(i, MonthNameStyles.Regular, false);
// We have to call public methods here to work with inherited DTFI.
- // Insert the month name first, so that they are at the front of abbrevaited
+ // Insert the month name first, so that they are at the front of abbreviated
// month names.
str = GetMonthName(i);
if (str.Length > 0)
diff --git a/src/mscorlib/shared/System/Globalization/DateTimeParse.cs b/src/mscorlib/shared/System/Globalization/DateTimeParse.cs
index 910fbf2ff0..f821a95412 100644
--- a/src/mscorlib/shared/System/Globalization/DateTimeParse.cs
+++ b/src/mscorlib/shared/System/Globalization/DateTimeParse.cs
@@ -81,23 +81,23 @@ namespace System
{
if (s == null)
{
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s));
+ result.SetFailure(ParseFailureKind.ArgumentNull, nameof(SR.ArgumentNull_String), null, nameof(s));
return false;
}
if (format == null)
{
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(format));
+ result.SetFailure(ParseFailureKind.ArgumentNull, nameof(SR.ArgumentNull_String), null, nameof(format));
return false;
}
if (s.Length == 0)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
if (format.Length == 0)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadFormatSpecifier), null);
return false;
}
@@ -177,24 +177,24 @@ namespace System
{
if (s == null)
{
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s));
+ result.SetFailure(ParseFailureKind.ArgumentNull, nameof(SR.ArgumentNull_String), null, nameof(s));
return false;
}
if (formats == null)
{
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(formats));
+ result.SetFailure(ParseFailureKind.ArgumentNull, nameof(SR.ArgumentNull_String), null, nameof(formats));
return false;
}
if (s.Length == 0)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
if (formats.Length == 0)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadFormatSpecifier), null);
return false;
}
@@ -208,7 +208,7 @@ namespace System
{
if (formats[i] == null || formats[i].Length == 0)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadFormatSpecifier), null);
return false;
}
// Create a new result each time to ensure the runs are independent. Carry through
@@ -223,7 +223,7 @@ namespace System
return (true);
}
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
@@ -605,13 +605,13 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.TimeZoneUsed) != 0)
{
// Should not have two timezone offsets.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
result.flags |= ParseFlags.TimeZoneUsed;
if (!ParseTimeZone(ref str, ref result.timeZoneOffset))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
}
@@ -657,7 +657,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
case TokenType.YearNumberToken:
if (raw.numCount == 3 || tokenValue == -1)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0010", dps);
return false;
}
@@ -724,7 +724,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
else
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0030 (TM.AM/TM.PM Happened more than 1x)", dps);
}
break;
@@ -737,7 +737,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
case TokenType.SEP_Time:
if (!raw.hasSameDateAndTimeSeparators)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0040 (Invalid separator after number)", dps);
return false;
}
@@ -775,7 +775,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
break;
default:
// Invalid separator after number number.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0040 (Invalid separator after number)", dps);
return false;
}
@@ -785,7 +785,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
LexTraceExit("0050 (success)", dps);
return true;
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0060", dps);
return false;
}
@@ -818,7 +818,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
else
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
break;
}
if (dps == DS.T_NNt || dps == DS.T_Nt)
@@ -873,7 +873,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
catch (ArgumentOutOfRangeException e)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", e);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), e);
LexTraceExit("0075 (Calendar.ToFourDigitYear failed)", dps);
return false;
}
@@ -897,7 +897,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
break;
default:
// Invalid separator after number number.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0080", dps);
return false;
}
@@ -935,7 +935,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
goto default;
default:
// Invalid separator after number number.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0090", dps);
return false;
}
@@ -943,7 +943,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
else
{
// Invalid separator after number number.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0100", dps);
return false;
}
@@ -984,7 +984,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
break;
default:
// Invalid separator after number number.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0110", dps);
return false;
}
@@ -1001,7 +1001,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
else
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0120 (DayOfWeek seen more than 1x)", dps);
return false;
}
@@ -1026,7 +1026,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
case TokenType.SEP_Time:
if (!raw.hasSameDateAndTimeSeparators)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0130 (Invalid separator after month name)", dps);
return false;
}
@@ -1052,7 +1052,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
break;
default:
//Invalid separator after month name
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0130 (Invalid separator after month name)", dps);
return false;
}
@@ -1060,7 +1060,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
else
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0140 (MonthToken seen more than 1x)", dps);
return false;
}
@@ -1073,7 +1073,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
else
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0150 (EraToken seen when result.era already set)", dps);
return false;
}
@@ -1089,7 +1089,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
else
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0160 (JapaneseEraToken seen when result.era already set)", dps);
return false;
}
@@ -1104,7 +1104,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
else
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0170 (TEraToken seen when result.era already set)", dps);
return false;
}
@@ -1118,7 +1118,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.TimeZoneUsed) != 0)
{
// Should not have two timezone offsets.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0180 (seen GMT or Z more than 1x)", dps);
return false;
}
@@ -1142,7 +1142,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
else
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0190 (AM/PM timeMark already set)", dps);
return false;
}
@@ -1150,7 +1150,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
case TokenType.UnknownToken:
if (Char.IsLetter(str.m_current))
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_UnknowDateTimeWord", str.Index);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_UnknowDateTimeWord), str.Index);
LexTraceExit("0200", dps);
return (false);
}
@@ -1180,7 +1180,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return true;
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
LexTraceExit("0240", dps);
return false;
}
@@ -1573,7 +1573,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.HaveDate) != 0)
{
// Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1585,7 +1585,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
int order;
if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out order))
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.MonthDayPattern);
return false;
}
@@ -1606,7 +1606,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return true;
}
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1616,7 +1616,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.HaveDate) != 0)
{
// Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1627,7 +1627,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
int order;
if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out order))
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.ShortDatePattern);
return false;
}
int year;
@@ -1664,7 +1664,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return true;
}
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1673,7 +1673,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.HaveDate) != 0)
{
// Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1692,7 +1692,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
int monthDayOrder;
if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder))
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.MonthDayPattern);
return false;
}
if (monthDayOrder == ORDER_DM)
@@ -1700,7 +1700,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
int yearMonthOrder;
if (!GetYearMonthOrder(dtfi.YearMonthPattern, dtfi, out yearMonthOrder))
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.YearMonthPattern);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.YearMonthPattern);
return false;
}
if (yearMonthOrder == ORDER_MY)
@@ -1708,7 +1708,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
int year;
if (!TryAdjustYear(ref result, raw.GetNumber(0), out year) || !SetDateYMD(ref result, year, raw.month, 1))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
return true;
@@ -1718,7 +1718,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
GetDefaultYear(ref result, ref styles);
if (!SetDateYMD(ref result, result.Year, raw.month, raw.GetNumber(0)))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
return true;
@@ -1735,7 +1735,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
int monthDayOrder;
if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder))
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.MonthDayPattern);
return false;
}
result.Month = raw.month;
@@ -1747,7 +1747,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return true;
}
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1756,7 +1756,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.HaveDate) != 0)
{
// Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1775,7 +1775,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
int monthDayOrder;
if (!GetMonthDayOrder(dtfi.MonthDayPattern, dtfi, out monthDayOrder))
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.MonthDayPattern);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.MonthDayPattern);
return false;
}
if (monthDayOrder == ORDER_MD)
@@ -1783,7 +1783,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
int yearMonthOrder;
if (!GetYearMonthOrder(dtfi.YearMonthPattern, dtfi, out yearMonthOrder))
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.YearMonthPattern);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.YearMonthPattern);
return false;
}
if (yearMonthOrder == ORDER_YM)
@@ -1791,7 +1791,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
int year;
if (!TryAdjustYear(ref result, raw.GetNumber(0), out year) || !SetDateYMD(ref result, year, raw.month, 1))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
return true;
@@ -1801,7 +1801,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
GetDefaultYear(ref result, ref styles);
if (!SetDateYMD(ref result, result.Year, raw.month, raw.GetNumber(0)))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
return true;
@@ -1812,7 +1812,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.HaveDate) != 0)
{
// Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1822,7 +1822,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
int order;
if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out order))
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.ShortDatePattern);
return false;
}
int year;
@@ -1873,7 +1873,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1882,7 +1882,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.HaveDate) != 0)
{
// Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1908,7 +1908,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return true; // Year + MD
}
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1917,7 +1917,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.HaveDate) != 0)
{
// Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1927,7 +1927,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
int order;
if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out order))
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.ShortDatePattern);
return false;
}
@@ -1947,7 +1947,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return true; // DM + Year
}
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1957,7 +1957,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.HaveDate) != 0)
{
// Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1966,7 +1966,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
result.flags |= ParseFlags.HaveDate;
return true;
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1975,7 +1975,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.HaveDate) != 0)
{
// Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1984,7 +1984,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
result.flags |= ParseFlags.HaveDate;
return true;
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -1993,7 +1993,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.HaveDate) != 0)
{
// Multiple dates in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -2002,7 +2002,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
result.flags |= ParseFlags.HaveDate;
return true;
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -2065,7 +2065,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.HaveTime) != 0)
{
// Multiple times in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
//
@@ -2073,7 +2073,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
if (raw.timeMark == TM.NotSet)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
result.Hour = raw.GetNumber(0);
@@ -2087,7 +2087,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.HaveTime) != 0)
{
// Multiple times in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -2102,7 +2102,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((result.flags & ParseFlags.HaveTime) != 0)
{
// Multiple times in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
Debug.Assert(raw.numCount >= 3, "raw.numCount >= 3");
@@ -2120,7 +2120,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (raw.numCount != 1 || result.Day != -1)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
result.Day = raw.GetNumber(0);
@@ -2132,19 +2132,19 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if (result.Month == -1)
{
//Should have a month suffix
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
if (result.Year != -1)
{
// Aleady has a year suffix
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
if (!TryAdjustYear(ref result, raw.GetNumber(0), out result.Year))
{
// the year value is out of range
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
result.Day = 1;
@@ -2174,7 +2174,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
int order;
if (!GetYearMonthDayOrder(dtfi.ShortDatePattern, dtfi, out order))
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadDatePattern", dtfi.ShortDatePattern);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadDatePattern), dtfi.ShortDatePattern);
return false;
}
int year;
@@ -2194,7 +2194,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
}
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -2275,7 +2275,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
raw.year = raw.GetNumber(1);
if (!dtfi.YearMonthAdjustment(ref raw.year, ref raw.month, true))
{
- result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null);
+ result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar), null);
return false;
}
if (!GetDayOfMNN(ref result, ref raw, dtfi))
@@ -2287,7 +2287,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// Deal with the default long/short date format when the year number is NOT ambigous (i.e. year >= 100).
if (!dtfi.YearMonthAdjustment(ref raw.year, ref raw.month, true))
{
- result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null);
+ result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar), null);
return false;
}
if (!GetDayOfYMN(ref result, ref raw, dtfi))
@@ -2295,13 +2295,30 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
return false;
}
break;
+ case DS.DX_NNY:
+ // When formatting, we only format up to the hundred digit of the Hebrew year, although Hebrew year is now over 5000.
+ // E.g. if the year is 5763, we only format as 763. so we do the reverse when parsing.
+ if (raw.year < 1000)
+ {
+ raw.year += 5000;
+ }
+ if (!GetDayOfNNY(ref result, ref raw, dtfi))
+ {
+ return false;
+ }
+ if (!dtfi.YearMonthAdjustment(ref result.Year, ref raw.month, true))
+ {
+ result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar), null);
+ return false;
+ }
+ break;
case DS.DX_NM:
case DS.DX_MN:
// Deal with Month/Day pattern.
GetDefaultYear(ref result, ref styles);
if (!dtfi.YearMonthAdjustment(ref result.Year, ref raw.month, true))
{
- result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null);
+ result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar), null);
return false;
}
if (!GetHebrewDayOfNM(ref result, ref raw, dtfi))
@@ -2313,7 +2330,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// Deal with Year/Month pattern.
if (!dtfi.YearMonthAdjustment(ref raw.year, ref raw.month, true))
{
- result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null);
+ result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar), null);
return false;
}
if (!GetDayOfYM(ref result, ref raw, dtfi))
@@ -2341,7 +2358,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
break;
default:
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
if (dps > DS.ERROR)
@@ -2505,12 +2522,12 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (s == null)
{
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(s));
+ result.SetFailure(ParseFailureKind.ArgumentNull, nameof(SR.ArgumentNull_String), null, nameof(s));
return false;
}
if (s.Length == 0)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -2579,7 +2596,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (!ProcessDateTimeSuffix(ref result, ref raw, ref dtok))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
TPTraceExit("0010", dps);
return false;
}
@@ -2598,7 +2615,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
else
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
TPTraceExit("0030", dps);
return false;
}
@@ -2643,7 +2660,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if (dps == DS.ERROR)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
TPTraceExit("0040 (invalid state transition)", dps);
return false;
}
@@ -2679,7 +2696,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if (!reachTerminalState)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
TPTraceExit("0070 (did not reach terminal state)", dps);
return false;
}
@@ -2687,7 +2704,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
AdjustTimeMark(dtfi, ref raw);
if (!AdjustHour(ref result.Hour, raw.timeMark))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
TPTraceExit("0080 (AdjustHour)", dps);
return false;
}
@@ -2708,7 +2725,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if (!result.calendar.TryToDateTime(result.Year, result.Month, result.Day,
result.Hour, result.Minute, result.Second, 0, result.era, out time))
{
- result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null);
+ result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar), null);
TPTraceExit("0100 (result.calendar.TryToDateTime)", dps);
return false;
}
@@ -2728,7 +2745,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
if (raw.dayOfWeek != (int)result.calendar.GetDayOfWeek(time))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDayOfWeek", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDayOfWeek), null);
TPTraceExit("0110 (dayOfWeek check)", dps);
return false;
}
@@ -2762,7 +2779,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// the DateTime offset must be within +- 14:00 hours.
if (offsetTicks < DateTimeOffset.MinOffset || offsetTicks > DateTimeOffset.MaxOffset)
{
- result.SetFailure(ParseFailureKind.Format, "Format_OffsetOutOfRange", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_OffsetOutOfRange), null);
return false;
}
}
@@ -2853,14 +2870,14 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// of a DateTime instance.
if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks)
{
- result.SetFailure(ParseFailureKind.Format, "Format_UTCOutOfRange", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_UTCOutOfRange), null);
return false;
}
// the offset must be within +- 14:00 hours.
if (offsetTicks < DateTimeOffset.MinOffset || offsetTicks > DateTimeOffset.MaxOffset)
{
- result.SetFailure(ParseFailureKind.Format, "Format_OffsetOutOfRange", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_OffsetOutOfRange), null);
return false;
}
@@ -2903,7 +2920,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if (resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks)
{
- result.SetFailure(ParseFailureKind.Format, "Format_DateOutOfRange", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_DateOutOfRange), null);
return false;
}
result.parsedDate = new DateTime(resultTicks, DateTimeKind.Utc);
@@ -2960,7 +2977,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if (resultTicks < DateTime.MinTicks || resultTicks > DateTime.MaxTicks)
{
result.parsedDate = DateTime.MinValue;
- result.SetFailure(ParseFailureKind.Format, "Format_DateOutOfRange", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_DateOutOfRange), null);
return false;
}
result.parsedDate = new DateTime(resultTicks, DateTimeKind.Local, isAmbiguousLocalDst);
@@ -2984,19 +3001,19 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
str.SkipWhiteSpaces();
if (!ParseDigits(ref str, 2, out hour))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
str.SkipWhiteSpaces();
if (!str.Match(':'))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
str.SkipWhiteSpaces();
if (!ParseDigits(ref str, 2, out minute))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
str.SkipWhiteSpaces();
@@ -3005,14 +3022,14 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
str.SkipWhiteSpaces();
if (!ParseDigits(ref str, 2, out second))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
if (str.Match('.'))
{
if (!ParseFraction(ref str, out partSecond))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
str.Index--;
@@ -3027,7 +3044,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
result.flags |= ParseFlags.TimeZoneUsed;
if (!ParseTimeZone(ref str, ref result.timeZoneOffset))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
}
@@ -3046,7 +3063,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (!VerifyValidPunctuation(ref str))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
str.SkipWhiteSpaces();
@@ -3055,14 +3072,14 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (!VerifyValidPunctuation(ref str))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
}
if (str.GetNext())
{
// If this is true, there were non-white space characters remaining in the DateTime
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
}
@@ -3072,7 +3089,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if (!calendar.TryToDateTime(raw.year, raw.GetNumber(0), raw.GetNumber(1),
hour, minute, second, 0, result.era, out time))
{
- result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null);
+ result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar), null);
return false;
}
@@ -3658,7 +3675,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (newValue != currentValue)
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", patternChar);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_RepeatDateTimePattern), patternChar);
return (false);
}
}
@@ -3702,7 +3719,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if (((result.Month != -1) || (result.Day != -1))
&& ((result.Year == -1 || ((result.flags & ParseFlags.YearDefault) != 0)) && (result.flags & ParseFlags.TimeZoneUsed) != 0))
{
- result.SetFailure(ParseFailureKind.Format, "Format_MissingIncompleteDate", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_MissingIncompleteDate), null);
return false;
}
}
@@ -3885,7 +3902,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
if (!parseResult)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
if (!CheckNewValue(ref result.Year, tempYear, ch, ref result))
@@ -3902,7 +3919,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if (!parseInfo.fCustomNumberParser ||
!parseInfo.parseNumberDelegate(ref str, tokenLen, out tempMonth))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
}
@@ -3913,7 +3930,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (!MatchAbbreviatedMonthName(ref str, dtfi, ref tempMonth))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
}
@@ -3921,7 +3938,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (!MatchMonthName(ref str, dtfi, ref tempMonth))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
}
@@ -3944,7 +3961,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if (!parseInfo.fCustomNumberParser ||
!parseInfo.parseNumberDelegate(ref str, tokenLen, out tempDay))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
}
@@ -3960,7 +3977,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// "ddd"
if (!MatchAbbreviatedDayName(ref str, dtfi, ref tempDayOfWeek))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
}
@@ -3969,7 +3986,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// "dddd*"
if (!MatchDayName(ref str, dtfi, ref tempDayOfWeek))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
}
@@ -3984,7 +4001,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// Put the era value in result.era.
if (!MatchEraName(ref str, dtfi, ref result.era))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
break;
@@ -3993,7 +4010,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
tokenLen = format.GetRepeatCount();
if (!ParseDigits(ref str, (tokenLen < 2 ? 1 : 2), out tempHour))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
if (!CheckNewValue(ref result.Hour, tempHour, ch, ref result))
@@ -4005,7 +4022,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
tokenLen = format.GetRepeatCount();
if (!ParseDigits(ref str, (tokenLen < 2 ? 1 : 2), out tempHour))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
if (!CheckNewValue(ref result.Hour, tempHour, ch, ref result))
@@ -4017,7 +4034,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
tokenLen = format.GetRepeatCount();
if (!ParseDigits(ref str, (tokenLen < 2 ? 1 : 2), out tempMinute))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
if (!CheckNewValue(ref result.Minute, tempMinute, ch, ref result))
@@ -4029,7 +4046,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
tokenLen = format.GetRepeatCount();
if (!ParseDigits(ref str, (tokenLen < 2 ? 1 : 2), out tempSecond))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
if (!CheckNewValue(ref result.Second, tempSecond, ch, ref result))
@@ -4046,7 +4063,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (ch == 'f')
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
}
@@ -4058,14 +4075,14 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (tempFraction != result.fraction)
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", ch);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_RepeatDateTimePattern), ch);
return (false);
}
}
}
else
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
break;
@@ -4076,7 +4093,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (!MatchAbbreviatedTimeMark(ref str, dtfi, ref tempTimeMark))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
}
@@ -4084,7 +4101,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (!MatchTimeMark(ref str, dtfi, ref tempTimeMark))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
}
@@ -4097,7 +4114,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (parseInfo.timeMark != tempTimeMark)
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", ch);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_RepeatDateTimePattern), ch);
return (false);
}
}
@@ -4109,12 +4126,12 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
TimeSpan tempTimeZoneOffset = new TimeSpan(0);
if (!ParseTimeZoneOffset(ref str, tokenLen, ref tempTimeZoneOffset))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && tempTimeZoneOffset != result.timeZoneOffset)
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'z');
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_RepeatDateTimePattern), 'z');
return (false);
}
result.timeZoneOffset = tempTimeZoneOffset;
@@ -4124,7 +4141,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
case 'Z':
if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && result.timeZoneOffset != TimeSpan.Zero)
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'Z');
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_RepeatDateTimePattern), 'Z');
return (false);
}
@@ -4139,7 +4156,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
str.Index++;
if (!GetTimeZoneName(ref str))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
str.Index--;
@@ -4150,7 +4167,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && result.timeZoneOffset != TimeSpan.Zero)
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'K');
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_RepeatDateTimePattern), 'K');
return (false);
}
@@ -4164,12 +4181,12 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
TimeSpan tempTimeZoneOffset = new TimeSpan(0);
if (!ParseTimeZoneOffset(ref str, 3, ref tempTimeZoneOffset))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return (false);
}
if ((result.flags & ParseFlags.TimeZoneUsed) != 0 && tempTimeZoneOffset != result.timeZoneOffset)
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_RepeatDateTimePattern", 'K');
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_RepeatDateTimePattern), 'K');
return (false);
}
result.timeZoneOffset = tempTimeZoneOffset;
@@ -4184,7 +4201,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
!str.Match(dtfi.TimeSeparator))
{
// A time separator is expected.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
break;
@@ -4195,7 +4212,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
!str.Match(dtfi.DateSeparator))
{
// A date separator is expected.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
break;
@@ -4205,7 +4222,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// Use ParseQuoteString so that we can handle escape characters within the quoted string.
if (!TryParseQuoteString(format.Value, format.Index, enquotedString, out tokenLen))
{
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadQuote", ch);
+ result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadQuote), ch);
return (false);
}
format.Index += tokenLen - 1;
@@ -4224,7 +4241,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
else if (!str.Match(quotedStr[i]))
{
// Can not find the matching quoted string.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
}
@@ -4255,7 +4272,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// Make sure the next character is not a '%' again.
if (format.Index >= format.Value.Length - 1 || format.Value[format.Index + 1] == '%')
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadFormatSpecifier), null);
return false;
}
break;
@@ -4268,13 +4285,13 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if (!str.Match(format.GetChar()))
{
// Can not find a match for the escaped character.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
}
else
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadFormatSpecifier), null);
return false;
}
break;
@@ -4291,7 +4308,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
break;
}
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
break;
@@ -4326,7 +4343,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
}
}
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
// Found a macth.
@@ -4343,14 +4360,14 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
result.timeZoneOffset = TimeSpan.Zero;
if (!str.Match(GMTName))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
}
else if (!str.Match(ch))
{
// ch is expected.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
}
@@ -4461,7 +4478,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if (((result.flags & ParseFlags.CaptureOffset) != 0) && formatParam[0] == 'U')
{
// The 'U' format is not allowed for DateTimeOffset
- result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadFormatSpecifier), null);
return false;
}
formatParam = ExpandPredefinedFormat(formatParam, ref dtfi, ref parseInfo, ref result);
@@ -4518,7 +4535,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if (str.Index < str.Value.Length - 1)
{
// There are still remaining character in str.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
@@ -4527,7 +4544,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
// A two digit year value is expected. Check if the parsed year value is valid.
if (result.Year >= 100)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
try
@@ -4536,7 +4553,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
}
catch (ArgumentOutOfRangeException e)
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", e);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), e);
return false;
}
}
@@ -4555,7 +4572,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if (result.Hour > 12)
{
// AM/PM is used, but the value for HH is too big.
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
if (parseInfo.timeMark == TM.AM)
@@ -4579,7 +4596,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
if ((parseInfo.timeMark == TM.AM && result.Hour >= 12)
|| (parseInfo.timeMark == TM.PM && result.Hour < 12))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDateTime", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDateTime), null);
return false;
}
}
@@ -4596,14 +4613,14 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
{
if (!dtfi.YearMonthAdjustment(ref result.Year, ref result.Month, ((result.flags & ParseFlags.ParsedMonthName) != 0)))
{
- result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null);
+ result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar), null);
return false;
}
}
if (!parseInfo.calendar.TryToDateTime(result.Year, result.Month, result.Day,
result.Hour, result.Minute, result.Second, 0, result.era, out result.parsedDate))
{
- result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, "Format_BadDateTimeCalendar", null);
+ result.SetFailure(ParseFailureKind.FormatBadDateTimeCalendar, nameof(SR.Format_BadDateTimeCalendar), null);
return false;
}
if (result.fraction > 0)
@@ -4623,7 +4640,7 @@ new DS[] { DS.ERROR, DS.TX_NNN, DS.TX_NNN, DS.TX_NNN, DS.ERROR, DS.ERROR,
//
if (parseInfo.dayOfWeek != (int)parseInfo.calendar.GetDayOfWeek(result.parsedDate))
{
- result.SetFailure(ParseFailureKind.Format, "Format_BadDayOfWeek", null);
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadDayOfWeek), null);
return false;
}
}
diff --git a/src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs b/src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs
index 0697b602db..383e0cd17c 100644
--- a/src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/EastAsianLunisolarCalendar.cs
@@ -67,7 +67,7 @@ namespace System.Globalization
return ((sexagenaryYear - 1) % 10) + 1;
}
- // Return the Terrestial Branch from the the 60-year cycle.
+ // Return the Terrestial Branch from the 60-year cycle.
// The returned value is from 1 ~ 12.
//
diff --git a/src/mscorlib/shared/System/Globalization/HijriCalendar.Win32.cs b/src/mscorlib/shared/System/Globalization/HijriCalendar.Win32.cs
index 869b809bff..09b1f20c48 100644
--- a/src/mscorlib/shared/System/Globalization/HijriCalendar.Win32.cs
+++ b/src/mscorlib/shared/System/Globalization/HijriCalendar.Win32.cs
@@ -45,7 +45,6 @@ namespace System.Globalization
try
{
// Open in read-only mode.
- // Use InternalOpenSubKey so that we avoid the security check.
key = RegistryKey.GetBaseKey(RegistryKey.HKEY_CURRENT_USER).OpenSubKey(InternationalRegKey, false);
}
//If this fails for any reason, we'll just return 0.
@@ -68,10 +67,9 @@ namespace System.Globalization
hijriAdvance = -1;
else
{
- str = str.Substring(HijriAdvanceRegKeyEntry.Length);
try
{
- int advance = Int32.Parse(str.ToString(), CultureInfo.InvariantCulture);
+ int advance = Int32.Parse(str.AsReadOnlySpan().Slice(HijriAdvanceRegKeyEntry.Length), provider:CultureInfo.InvariantCulture);
if ((advance >= MinAdvancedHijri) && (advance <= MaxAdvancedHijri))
{
hijriAdvance = advance;
diff --git a/src/mscorlib/shared/System/Globalization/HijriCalendar.cs b/src/mscorlib/shared/System/Globalization/HijriCalendar.cs
index 125248a685..59b354f534 100644
--- a/src/mscorlib/shared/System/Globalization/HijriCalendar.cs
+++ b/src/mscorlib/shared/System/Globalization/HijriCalendar.cs
@@ -187,7 +187,7 @@ namespace System.Globalization
set
{
- // NOTE: Check the value of Min/MaxAdavncedHijri with Arabic speakers to see if the assumption is good.
+ // NOTE: Check the value of Min/MaxAdvancedHijri with Arabic speakers to see if the assumption is good.
if (value < MinAdvancedHijri || value > MaxAdvancedHijri)
{
throw new ArgumentOutOfRangeException(
@@ -303,7 +303,7 @@ namespace System.Globalization
//
HijriYear = (int)(((NumDays - 227013) * 30) / 10631) + 1;
- long daysToHijriYear = DaysUpToHijriYear(HijriYear); // The absoulte date for HijriYear
+ long daysToHijriYear = DaysUpToHijriYear(HijriYear); // The absolute date for HijriYear
long daysOfHijriYear = GetDaysInYear(HijriYear, CurrentEra); // The number of days for (HijriYear+1) year.
if (NumDays < daysToHijriYear)
diff --git a/src/mscorlib/shared/System/Globalization/JapaneseCalendar.Win32.cs b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.Win32.cs
index a83c4fad9e..94e0668de1 100644
--- a/src/mscorlib/shared/System/Globalization/JapaneseCalendar.Win32.cs
+++ b/src/mscorlib/shared/System/Globalization/JapaneseCalendar.Win32.cs
@@ -159,9 +159,10 @@ namespace System.Globalization
int month;
int day;
- if (!Int32.TryParse(value.Substring(0, 4), NumberStyles.None, NumberFormatInfo.InvariantInfo, out year) ||
- !Int32.TryParse(value.Substring(5, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out month) ||
- !Int32.TryParse(value.Substring(8, 2), NumberStyles.None, NumberFormatInfo.InvariantInfo, out day))
+ ReadOnlySpan<char> valueSpan = value.AsReadOnlySpan();
+ if (!Int32.TryParse(valueSpan.Slice(0, 4), out year, style:NumberStyles.None, provider: NumberFormatInfo.InvariantInfo) ||
+ !Int32.TryParse(valueSpan.Slice(5, 2), out month, style:NumberStyles.None, provider: NumberFormatInfo.InvariantInfo) ||
+ !Int32.TryParse(valueSpan.Slice(8, 2), out day, style:NumberStyles.None, provider: NumberFormatInfo.InvariantInfo))
{
// Couldn't convert integer, fail
return null;
diff --git a/src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs b/src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs
index 9fea694cca..d7412bfcf3 100644
--- a/src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs
+++ b/src/mscorlib/shared/System/Globalization/NumberFormatInfo.cs
@@ -238,35 +238,30 @@ namespace System.Globalization
public static NumberFormatInfo GetInstance(IFormatProvider formatProvider)
{
- // Fast case for a regular CultureInfo
- NumberFormatInfo info;
- CultureInfo cultureProvider = formatProvider as CultureInfo;
- if (cultureProvider != null && !cultureProvider._isInherited)
+ if (formatProvider != null)
{
- info = cultureProvider.numInfo;
- if (info != null)
+ // Fast case for a regular CultureInfo
+ NumberFormatInfo info;
+ CultureInfo cultureProvider = formatProvider as CultureInfo;
+ if (cultureProvider != null && !cultureProvider._isInherited)
{
- return info;
+ return cultureProvider.numInfo ?? cultureProvider.NumberFormat;
}
- else
+
+ // Fast case for an NFI;
+ info = formatProvider as NumberFormatInfo;
+ if (info != null)
{
- return cultureProvider.NumberFormat;
+ return info;
}
- }
- // Fast case for an NFI;
- info = formatProvider as NumberFormatInfo;
- if (info != null)
- {
- return info;
- }
- if (formatProvider != null)
- {
+
info = formatProvider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo;
if (info != null)
{
return info;
}
}
+
return CurrentInfo;
}
diff --git a/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs b/src/mscorlib/shared/System/Globalization/TimeSpanFormat.cs
index ca053eded3..6801ea8e1b 100644
--- a/src/mscorlib/src/System/Globalization/TimeSpanFormat.cs
+++ b/src/mscorlib/shared/System/Globalization/TimeSpanFormat.cs
@@ -2,25 +2,37 @@
// 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.Text;
-using System;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Globalization;
namespace System.Globalization
{
internal static class TimeSpanFormat
{
- private static String IntToString(int n, int digits)
+ private static unsafe void AppendNonNegativeInt32(StringBuilder sb, int n, int digits)
{
- return ParseNumbers.IntToString(n, 10, digits, '0', 0);
+ Debug.Assert(n >= 0);
+ uint value = (uint)n;
+
+ const int MaxUInt32Digits = 10;
+ char* buffer = stackalloc char[MaxUInt32Digits];
+
+ int index = 0;
+ do
+ {
+ uint div = value / 10;
+ buffer[index++] = (char)(value - (div * 10) + '0');
+ value = div;
+ }
+ while (value != 0);
+ Debug.Assert(index <= MaxUInt32Digits);
+
+ for (int i = digits - index; i > 0; --i) sb.Append('0');
+ for (int i = index - 1; i >= 0; --i) sb.Append(buffer[i]);
}
- internal static readonly FormatLiterals PositiveInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(false /*isNegative*/);
- internal static readonly FormatLiterals NegativeInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(true /*isNegative*/);
+ internal static readonly FormatLiterals PositiveInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(isNegative: false);
+ internal static readonly FormatLiterals NegativeInvariantFormatLiterals = TimeSpanFormat.FormatLiterals.InitInvariant(isNegative: true);
internal enum Pattern
{
@@ -29,57 +41,77 @@ namespace System.Globalization
Full = 2,
}
- //
- // Format
- //
- // Actions: Main method called from TimeSpan.ToString
- //
- internal static String Format(TimeSpan value, String format, IFormatProvider formatProvider)
+ /// <summary>Main method called from TimeSpan.ToString.</summary>
+ internal static string Format(TimeSpan value, string format, IFormatProvider formatProvider) =>
+ StringBuilderCache.GetStringAndRelease(FormatToBuilder(value, format, formatProvider));
+
+ /// <summary>Main method called from TimeSpan.TryFormat.</summary>
+ internal static bool TryFormat(TimeSpan value, Span<char> destination, out int charsWritten, string format, IFormatProvider formatProvider)
+ {
+ StringBuilder sb = FormatToBuilder(value, format, formatProvider);
+ if (sb.Length <= destination.Length)
+ {
+ charsWritten = sb.Length;
+ sb.CopyTo(0, destination, sb.Length);
+ StringBuilderCache.Release(sb);
+ return true;
+ }
+ else
+ {
+ StringBuilderCache.Release(sb);
+ charsWritten = 0;
+ return false;
+ }
+ }
+
+ private static StringBuilder FormatToBuilder(TimeSpan value, string format, IFormatProvider formatProvider)
{
if (format == null || format.Length == 0)
+ {
format = "c";
+ }
- // standard formats
+ // Standard formats
if (format.Length == 1)
{
char f = format[0];
-
- if (f == 'c' || f == 't' || f == 'T')
- return FormatStandard(value, true, format, Pattern.Minimum);
- if (f == 'g' || f == 'G')
+ switch (f)
{
- Pattern pattern;
- DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(formatProvider);
+ case 'c':
+ case 't':
+ case 'T':
+ return FormatStandard(
+ value,
+ isInvariant: true,
+ format: format,
+ pattern: Pattern.Minimum);
+
+ case 'g':
+ case 'G':
+ DateTimeFormatInfo dtfi = DateTimeFormatInfo.GetInstance(formatProvider);
+ return FormatStandard(
+ value,
+ isInvariant: false,
+ format: value.Ticks < 0 ? dtfi.FullTimeSpanNegativePattern : dtfi.FullTimeSpanPositivePattern,
+ pattern: f == 'g' ? Pattern.Minimum : Pattern.Full);
- if (value._ticks < 0)
- format = dtfi.FullTimeSpanNegativePattern;
- else
- format = dtfi.FullTimeSpanPositivePattern;
- if (f == 'g')
- pattern = Pattern.Minimum;
- else
- pattern = Pattern.Full;
-
- return FormatStandard(value, false, format, pattern);
+ default:
+ throw new FormatException(SR.Format_InvalidString);
}
- throw new FormatException(SR.Format_InvalidString);
}
+ // Custom formats
return FormatCustomized(value, format, DateTimeFormatInfo.GetInstance(formatProvider));
}
- //
- // FormatStandard
- //
- // Actions: Format the TimeSpan instance using the specified format.
- //
- private static String FormatStandard(TimeSpan value, bool isInvariant, String format, Pattern pattern)
+ /// <summary>Format the TimeSpan instance using the specified format.</summary>
+ private static StringBuilder FormatStandard(TimeSpan value, bool isInvariant, string format, Pattern pattern)
{
- StringBuilder sb = StringBuilderCache.Acquire();
- int day = (int)(value._ticks / TimeSpan.TicksPerDay);
- long time = value._ticks % TimeSpan.TicksPerDay;
+ StringBuilder sb = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity);
+ int day = (int)(value.Ticks / TimeSpan.TicksPerDay);
+ long time = value.Ticks % TimeSpan.TicksPerDay;
- if (value._ticks < 0)
+ if (value.Ticks < 0)
{
day = -day;
time = -time;
@@ -92,19 +124,20 @@ namespace System.Globalization
FormatLiterals literal;
if (isInvariant)
{
- if (value._ticks < 0)
- literal = NegativeInvariantFormatLiterals;
- else
- literal = PositiveInvariantFormatLiterals;
+ literal = value.Ticks < 0 ?
+ NegativeInvariantFormatLiterals :
+ PositiveInvariantFormatLiterals;
}
else
{
literal = new FormatLiterals();
literal.Init(format, pattern == Pattern.Full);
}
+
if (fraction != 0)
- { // truncate the partial second to the specified length
- fraction = (int)((long)fraction / (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - literal.ff));
+ {
+ // truncate the partial second to the specified length
+ fraction = (int)(fraction / TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - literal.ff));
}
// Pattern.Full: [-]dd.hh:mm:ss.fffffff
@@ -112,15 +145,15 @@ namespace System.Globalization
sb.Append(literal.Start); // [-]
if (pattern == Pattern.Full || day != 0)
- { //
+ {
sb.Append(day); // [dd]
sb.Append(literal.DayHourSep); // [.]
} //
- sb.Append(IntToString(hours, literal.hh)); // hh
+ AppendNonNegativeInt32(sb, hours, literal.hh); // hh
sb.Append(literal.HourMinuteSep); // :
- sb.Append(IntToString(minutes, literal.mm)); // mm
+ AppendNonNegativeInt32(sb, minutes, literal.mm); // mm
sb.Append(literal.MinuteSecondSep); // :
- sb.Append(IntToString(seconds, literal.ss)); // ss
+ AppendNonNegativeInt32(sb, seconds, literal.ss); // ss
if (!isInvariant && pattern == Pattern.Minimum)
{
int effectiveDigits = literal.ff;
@@ -144,30 +177,23 @@ namespace System.Globalization
}
else if (pattern == Pattern.Full || fraction != 0)
{
- sb.Append(literal.SecondFractionSep); // [.]
- sb.Append(IntToString(fraction, literal.ff)); // [fffffff]
- } //
- sb.Append(literal.End); //
+ sb.Append(literal.SecondFractionSep); // [.]
+ AppendNonNegativeInt32(sb, fraction, literal.ff); // [fffffff]
+ }
+ sb.Append(literal.End);
- return StringBuilderCache.GetStringAndRelease(sb);
+ return sb;
}
-
-
-
- //
- // FormatCustomized
- //
- // Actions: Format the TimeSpan instance using the specified format.
- //
- internal static String FormatCustomized(TimeSpan value, String format, DateTimeFormatInfo dtfi)
+ /// <summary>Format the TimeSpan instance using the specified format.</summary>
+ private static StringBuilder FormatCustomized(TimeSpan value, string format, DateTimeFormatInfo dtfi)
{
- Debug.Assert(dtfi != null, "dtfi == null");
+ Debug.Assert(dtfi != null);
- int day = (int)(value._ticks / TimeSpan.TicksPerDay);
- long time = value._ticks % TimeSpan.TicksPerDay;
+ int day = (int)(value.Ticks / TimeSpan.TicksPerDay);
+ long time = value.Ticks % TimeSpan.TicksPerDay;
- if (value._ticks < 0)
+ if (value.Ticks < 0)
{
day = -day;
time = -time;
@@ -180,7 +206,7 @@ namespace System.Globalization
long tmp = 0;
int i = 0;
int tokenLen;
- StringBuilder result = StringBuilderCache.Acquire();
+ StringBuilder result = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity);
while (i < format.Length)
{
@@ -191,19 +217,25 @@ namespace System.Globalization
case 'h':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
+ {
throw new FormatException(SR.Format_InvalidString);
+ }
DateTimeFormat.FormatDigits(result, hours, tokenLen);
break;
case 'm':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
+ {
throw new FormatException(SR.Format_InvalidString);
+ }
DateTimeFormat.FormatDigits(result, minutes, tokenLen);
break;
case 's':
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 2)
+ {
throw new FormatException(SR.Format_InvalidString);
+ }
DateTimeFormat.FormatDigits(result, seconds, tokenLen);
break;
case 'f':
@@ -212,10 +244,12 @@ namespace System.Globalization
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
+ {
throw new FormatException(SR.Format_InvalidString);
+ }
- tmp = (long)fraction;
- tmp /= (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
+ tmp = fraction;
+ tmp /= TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
result.Append((tmp).ToString(DateTimeFormat.fixedNumberFormats[tokenLen - 1], CultureInfo.InvariantCulture));
break;
case 'F':
@@ -224,10 +258,12 @@ namespace System.Globalization
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits)
+ {
throw new FormatException(SR.Format_InvalidString);
+ }
- tmp = (long)fraction;
- tmp /= (long)Math.Pow(10, DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
+ tmp = fraction;
+ tmp /= TimeSpanParse.Pow10(DateTimeFormat.MaxSecondsFractionDigits - tokenLen);
int effectiveDigits = tokenLen;
while (effectiveDigits > 0)
{
@@ -253,7 +289,10 @@ namespace System.Globalization
//
tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
if (tokenLen > 8)
+ {
throw new FormatException(SR.Format_InvalidString);
+ }
+
DateTimeFormat.FormatDigits(result, day, tokenLen, true);
break;
case '\'':
@@ -304,77 +343,38 @@ namespace System.Globalization
}
i += tokenLen;
}
- return StringBuilderCache.GetStringAndRelease(result);
+ return result;
}
-
-
-
internal struct FormatLiterals
{
- internal String Start
- {
- get
- {
- return literals[0];
- }
- }
- internal String DayHourSep
- {
- get
- {
- return literals[1];
- }
- }
- internal String HourMinuteSep
- {
- get
- {
- return literals[2];
- }
- }
- internal String MinuteSecondSep
- {
- get
- {
- return literals[3];
- }
- }
- internal String SecondFractionSep
- {
- get
- {
- return literals[4];
- }
- }
- internal String End
- {
- get
- {
- return literals[5];
- }
- }
- internal String AppCompatLiteral;
+ internal string AppCompatLiteral;
internal int dd;
internal int hh;
internal int mm;
internal int ss;
internal int ff;
- private String[] literals;
+ private string[] _literals;
+ internal string Start => _literals[0];
+ internal string DayHourSep => _literals[1];
+ internal string HourMinuteSep => _literals[2];
+ internal string MinuteSecondSep => _literals[3];
+ internal string SecondFractionSep => _literals[4];
+ internal string End => _literals[5];
/* factory method for static invariant FormatLiterals */
internal static FormatLiterals InitInvariant(bool isNegative)
{
FormatLiterals x = new FormatLiterals();
- x.literals = new String[6];
- x.literals[0] = isNegative ? "-" : String.Empty;
- x.literals[1] = ".";
- x.literals[2] = ":";
- x.literals[3] = ":";
- x.literals[4] = ".";
- x.literals[5] = String.Empty;
+ x._literals = new string[6];
+ x._literals[0] = isNegative ? "-" : string.Empty;
+ x._literals[1] = ".";
+ x._literals[2] = ":";
+ x._literals[3] = ":";
+ x._literals[4] = ".";
+ x._literals[5] = string.Empty;
x.AppCompatLiteral = ":."; // MinuteSecondSep+SecondFractionSep;
x.dd = 2;
x.hh = 2;
@@ -388,18 +388,16 @@ namespace System.Globalization
// the constants guaranteed to include DHMSF ordered greatest to least significant.
// Once the data becomes more complex than this we will need to write a proper tokenizer for
// parsing and formatting
- internal void Init(String format, bool useInvariantFieldLengths)
+ internal void Init(string format, bool useInvariantFieldLengths)
{
- literals = new String[6];
- for (int i = 0; i < literals.Length; i++)
- literals[i] = String.Empty;
- dd = 0;
- hh = 0;
- mm = 0;
- ss = 0;
- ff = 0;
-
- StringBuilder sb = StringBuilderCache.Acquire();
+ dd = hh = mm = ss = ff = 0;
+ _literals = new string[6];
+ for (int i = 0; i < _literals.Length; i++)
+ {
+ _literals[i] = string.Empty;
+ }
+
+ StringBuilder sb = StringBuilderCache.Acquire(InternalGlobalizationHelper.StringBuilderDefaultCapacity);
bool inQuote = false;
char quote = '\'';
int field = 0;
@@ -413,15 +411,15 @@ namespace System.Globalization
if (inQuote && (quote == format[i]))
{
/* we were in a quote and found a matching exit quote, so we are outside a quote now */
- Debug.Assert(field >= 0 && field <= 5, "field >= 0 && field <= 5");
if (field >= 0 && field <= 5)
{
- literals[field] = sb.ToString();
+ _literals[field] = sb.ToString();
sb.Length = 0;
inQuote = false;
}
else
{
+ Debug.Fail($"Unexpected field value: {field}");
return; // how did we get here?
}
}
@@ -437,7 +435,7 @@ namespace System.Globalization
}
break;
case '%':
- Debug.Assert(false, "Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Fail("Unexpected special token '%', Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
goto default;
case '\\':
if (!inQuote)
@@ -449,8 +447,7 @@ namespace System.Globalization
case 'd':
if (!inQuote)
{
- Debug.Assert((field == 0 && sb.Length == 0) || field == 1,
- "field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert((field == 0 && sb.Length == 0) || field == 1, "field == 0 || field == 1, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 1; // DayHourSep
dd++;
}
@@ -458,8 +455,7 @@ namespace System.Globalization
case 'h':
if (!inQuote)
{
- Debug.Assert((field == 1 && sb.Length == 0) || field == 2,
- "field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert((field == 1 && sb.Length == 0) || field == 2, "field == 1 || field == 2, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 2; // HourMinuteSep
hh++;
}
@@ -467,8 +463,7 @@ namespace System.Globalization
case 'm':
if (!inQuote)
{
- Debug.Assert((field == 2 && sb.Length == 0) || field == 3,
- "field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert((field == 2 && sb.Length == 0) || field == 3, "field == 2 || field == 3, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 3; // MinuteSecondSep
mm++;
}
@@ -476,8 +471,7 @@ namespace System.Globalization
case 's':
if (!inQuote)
{
- Debug.Assert((field == 3 && sb.Length == 0) || field == 4,
- "field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert((field == 3 && sb.Length == 0) || field == 4, "field == 3 || field == 4, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 4; // SecondFractionSep
ss++;
}
@@ -486,8 +480,7 @@ namespace System.Globalization
case 'F':
if (!inQuote)
{
- Debug.Assert((field == 4 && sb.Length == 0) || field == 5,
- "field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
+ Debug.Assert((field == 4 && sb.Length == 0) || field == 5, "field == 4 || field == 5, Bug in DateTimeFormatInfo.FullTimeSpan[Positive|Negative]Pattern");
field = 5; // End
ff++;
}
@@ -525,6 +518,6 @@ namespace System.Globalization
}
StringBuilderCache.Release(sb);
}
- } //end of struct FormatLiterals
+ }
}
}
diff --git a/src/mscorlib/shared/System/Globalization/TimeSpanParse.cs b/src/mscorlib/shared/System/Globalization/TimeSpanParse.cs
new file mode 100644
index 0000000000..f8443a1ea6
--- /dev/null
+++ b/src/mscorlib/shared/System/Globalization/TimeSpanParse.cs
@@ -0,0 +1,1675 @@
+// 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: Used by TimeSpan to parse a time interval string.
+//
+// Standard Format:
+// -=-=-=-=-=-=-=-
+// "c": Constant format. [-][d'.']hh':'mm':'ss['.'fffffff]
+// Not culture sensitive. Default format (and null/empty format string) map to this format.
+//
+// "g": General format, short: [-][d':']h':'mm':'ss'.'FFFFFFF
+// Only print what's needed. Localized (if you want Invariant, pass in Invariant).
+// The fractional seconds separator is localized, equal to the culture's DecimalSeparator.
+//
+// "G": General format, long: [-]d':'hh':'mm':'ss'.'fffffff
+// Always print days and 7 fractional digits. Localized (if you want Invariant, pass in Invariant).
+// The fractional seconds separator is localized, equal to the culture's DecimalSeparator.
+//
+// * "TryParseTimeSpan" is the main method for Parse/TryParse
+//
+// - TimeSpanTokenizer.GetNextToken() is used to split the input string into number and literal tokens.
+// - TimeSpanRawInfo.ProcessToken() adds the next token into the parsing intermediary state structure
+// - ProcessTerminalState() uses the fully initialized TimeSpanRawInfo to find a legal parse match.
+// The terminal states are attempted as follows:
+// foreach (+InvariantPattern, -InvariantPattern, +LocalizedPattern, -LocalizedPattern) try
+// 1 number => d
+// 2 numbers => h:m
+// 3 numbers => h:m:s | d.h:m | h:m:.f
+// 4 numbers => h:m:s.f | d.h:m:s | d.h:m:.f
+// 5 numbers => d.h:m:s.f
+//
+// Custom Format:
+// -=-=-=-=-=-=-=
+//
+// * "TryParseExactTimeSpan" is the main method for ParseExact/TryParseExact methods
+// * "TryParseExactMultipleTimeSpan" is the main method for ParseExact/TryparseExact
+// methods that take a string[] of formats
+//
+// - For single-letter formats "TryParseTimeSpan" is called (see above)
+// - For multi-letter formats "TryParseByFormat" is called
+// - TryParseByFormat uses helper methods (ParseExactLiteral, ParseExactDigits, etc)
+// which drive the underlying TimeSpanTokenizer. However, unlike standard formatting which
+// operates on whole-tokens, ParseExact operates at the character-level. As such,
+// TimeSpanTokenizer.NextChar and TimeSpanTokenizer.BackOne() are called directly.
+//
+////////////////////////////////////////////////////////////////////////////
+
+using System.Diagnostics;
+using System.Runtime.CompilerServices;
+using System.Text;
+
+namespace System.Globalization
+{
+ internal static class TimeSpanParse
+ {
+ private const int MaxFractionDigits = 7;
+ private const int MaxDays = 10675199;
+ private const int MaxHours = 23;
+ private const int MaxMinutes = 59;
+ private const int MaxSeconds = 59;
+ private const int MaxFraction = 9999999;
+
+ private enum ParseFailureKind : byte
+ {
+ None = 0,
+ ArgumentNull = 1,
+ Format = 2,
+ FormatWithParameter = 3,
+ Overflow = 4,
+ }
+
+ [Flags]
+ private enum TimeSpanStandardStyles : byte
+ {
+ // Standard Format Styles
+ None = 0x00000000,
+ Invariant = 0x00000001, //Allow Invariant Culture
+ Localized = 0x00000002, //Allow Localized Culture
+ RequireFull = 0x00000004, //Require the input to be in DHMSF format
+ Any = Invariant | Localized,
+ }
+
+ // TimeSpan Token Types
+ private enum TTT : byte
+ {
+ None = 0, // None of the TimeSpanToken fields are set
+ End = 1, // '\0'
+ Num = 2, // Number
+ Sep = 3, // literal
+ NumOverflow = 4, // Number that overflowed
+ }
+
+ [IsByRefLike]
+ private struct TimeSpanToken
+ {
+ internal TTT _ttt;
+ internal int _num; // Store the number that we are parsing (if any)
+ internal int _zeroes; // Store the number of leading zeroes (if any)
+ internal ReadOnlySpan<char> _sep; // Store the literal that we are parsing (if any)
+
+ public TimeSpanToken(TTT type) : this(type, 0, 0, default(ReadOnlySpan<char>)) { }
+
+ public TimeSpanToken(int number) : this(TTT.Num, number, 0, default(ReadOnlySpan<char>)) { }
+
+ public TimeSpanToken(int number, int leadingZeroes) : this(TTT.Num, number, leadingZeroes, default(ReadOnlySpan<char>)) { }
+
+ public TimeSpanToken(TTT type, int number, int leadingZeroes, ReadOnlySpan<char> separator)
+ {
+ _ttt = type;
+ _num = number;
+ _zeroes = leadingZeroes;
+ _sep = separator;
+ }
+
+ public bool IsInvalidFraction()
+ {
+ Debug.Assert(_ttt == TTT.Num);
+ Debug.Assert(_num > -1);
+
+ if (_num > MaxFraction || _zeroes > MaxFractionDigits)
+ return true;
+
+ if (_num == 0 || _zeroes == 0)
+ return false;
+
+ // num > 0 && zeroes > 0 && num <= maxValue && zeroes <= maxPrecision
+ return _num >= MaxFraction / Pow10(_zeroes - 1);
+ }
+ }
+
+ [IsByRefLike]
+ private struct TimeSpanTokenizer
+ {
+ private ReadOnlySpan<char> _value;
+ private int _pos;
+
+ internal TimeSpanTokenizer(ReadOnlySpan<char> input) : this(input, 0) { }
+
+ internal TimeSpanTokenizer(ReadOnlySpan<char> input, int startPosition)
+ {
+ _value = input;
+ _pos = startPosition;
+ }
+
+ /// <summary>Returns the next token in the input string</summary>
+ /// <remarks>Used by the parsing routines that operate on standard-formats.</remarks>
+ internal TimeSpanToken GetNextToken()
+ {
+ // Get the position of the next character to be processed. If there is no
+ // next character, we're at the end.
+ int pos = _pos;
+ Debug.Assert(pos > -1);
+ if (pos >= _value.Length)
+ {
+ return new TimeSpanToken(TTT.End);
+ }
+
+ // Now retrieve that character. If it's a digit, we're processing a number.
+ int num = _value[pos] - '0';
+ if ((uint)num <= 9)
+ {
+ int zeroes = 0;
+ if (num == 0)
+ {
+ // Read all leading zeroes.
+ zeroes = 1;
+ while (true)
+ {
+ int digit;
+ if (++_pos >= _value.Length || (uint)(digit = _value[_pos] - '0') > 9)
+ {
+ return new TimeSpanToken(TTT.Num, 0, zeroes, default(ReadOnlySpan<char>));
+ }
+
+ if (digit == 0)
+ {
+ zeroes++;
+ continue;
+ }
+
+ num = digit;
+ break;
+ }
+ }
+
+ // Continue to read as long as we're reading digits.
+ while (++_pos < _value.Length)
+ {
+ int digit = _value[_pos] - '0';
+ if ((uint)digit > 9)
+ {
+ break;
+ }
+
+ num = num * 10 + digit;
+ if ((num & 0xF0000000) != 0)
+ {
+ return new TimeSpanToken(TTT.NumOverflow);
+ }
+ }
+
+ return new TimeSpanToken(TTT.Num, num, zeroes, default(ReadOnlySpan<char>));
+ }
+
+ // Otherwise, we're processing a separator, and we've already processed the first
+ // character of it. Continue processing characters as long as they're not digits.
+ int length = 1;
+ while (true)
+ {
+ if (++_pos >= _value.Length || (uint)(_value[_pos] - '0') <= 9)
+ {
+ break;
+ }
+ length++;
+ }
+
+ // Return the separator.
+ return new TimeSpanToken(TTT.Sep, 0, 0, _value.Slice(pos, length));
+ }
+
+ internal bool EOL => _pos >= (_value.Length - 1);
+
+ internal void BackOne()
+ {
+ if (_pos > 0) --_pos;
+ }
+
+ internal char NextChar
+ {
+ get
+ {
+ int pos = ++_pos;
+ return (uint)pos < (uint)_value.Length ?
+ _value[pos] :
+ (char)0;
+ }
+ }
+ }
+
+ /// <summary>Stores intermediary parsing state for the standard formats.</summary>
+ [IsByRefLike]
+ private struct TimeSpanRawInfo
+ {
+ internal TimeSpanFormat.FormatLiterals PositiveInvariant => TimeSpanFormat.PositiveInvariantFormatLiterals;
+ internal TimeSpanFormat.FormatLiterals NegativeInvariant => TimeSpanFormat.NegativeInvariantFormatLiterals;
+
+ internal TimeSpanFormat.FormatLiterals PositiveLocalized
+ {
+ get
+ {
+ if (!_posLocInit)
+ {
+ _posLoc = new TimeSpanFormat.FormatLiterals();
+ _posLoc.Init(_fullPosPattern, false);
+ _posLocInit = true;
+ }
+ return _posLoc;
+ }
+ }
+
+ internal TimeSpanFormat.FormatLiterals NegativeLocalized
+ {
+ get
+ {
+ if (!_negLocInit)
+ {
+ _negLoc = new TimeSpanFormat.FormatLiterals();
+ _negLoc.Init(_fullNegPattern, false);
+ _negLocInit = true;
+ }
+ return _negLoc;
+ }
+ }
+
+ internal bool FullAppCompatMatch(TimeSpanFormat.FormatLiterals pattern) =>
+ _sepCount == 5
+ && _numCount == 4
+ && StringSpanHelpers.Equals(_literals0, pattern.Start)
+ && StringSpanHelpers.Equals(_literals1, pattern.DayHourSep)
+ && StringSpanHelpers.Equals(_literals2, pattern.HourMinuteSep)
+ && StringSpanHelpers.Equals(_literals3, pattern.AppCompatLiteral)
+ && StringSpanHelpers.Equals(_literals4, pattern.End);
+
+ internal bool PartialAppCompatMatch(TimeSpanFormat.FormatLiterals pattern) =>
+ _sepCount == 4
+ && _numCount == 3
+ && StringSpanHelpers.Equals(_literals0, pattern.Start)
+ && StringSpanHelpers.Equals(_literals1, pattern.HourMinuteSep)
+ && StringSpanHelpers.Equals(_literals2, pattern.AppCompatLiteral)
+ && StringSpanHelpers.Equals(_literals3, pattern.End);
+
+ /// <summary>DHMSF (all values matched)</summary>
+ internal bool FullMatch(TimeSpanFormat.FormatLiterals pattern) =>
+ _sepCount == MaxLiteralTokens
+ && _numCount == MaxNumericTokens
+ && StringSpanHelpers.Equals(_literals0, pattern.Start)
+ && StringSpanHelpers.Equals(_literals1, pattern.DayHourSep)
+ && StringSpanHelpers.Equals(_literals2, pattern.HourMinuteSep)
+ && StringSpanHelpers.Equals(_literals3, pattern.MinuteSecondSep)
+ && StringSpanHelpers.Equals(_literals4, pattern.SecondFractionSep)
+ && StringSpanHelpers.Equals(_literals5, pattern.End);
+
+ /// <summary>D (no hours, minutes, seconds, or fractions)</summary>
+ internal bool FullDMatch(TimeSpanFormat.FormatLiterals pattern) =>
+ _sepCount == 2
+ && _numCount == 1
+ && StringSpanHelpers.Equals(_literals0, pattern.Start)
+ && StringSpanHelpers.Equals(_literals1, pattern.End);
+
+ /// <summary>HM (no days, seconds, or fractions)</summary>
+ internal bool FullHMMatch(TimeSpanFormat.FormatLiterals pattern) =>
+ _sepCount == 3
+ && _numCount == 2
+ && StringSpanHelpers.Equals(_literals0, pattern.Start)
+ && StringSpanHelpers.Equals(_literals1, pattern.HourMinuteSep)
+ && StringSpanHelpers.Equals(_literals2, pattern.End);
+
+ /// <summary>DHM (no seconds or fraction)</summary>
+ internal bool FullDHMMatch(TimeSpanFormat.FormatLiterals pattern) =>
+ _sepCount == 4
+ && _numCount == 3
+ && StringSpanHelpers.Equals(_literals0, pattern.Start)
+ && StringSpanHelpers.Equals(_literals1, pattern.DayHourSep)
+ && StringSpanHelpers.Equals(_literals2, pattern.HourMinuteSep)
+ && StringSpanHelpers.Equals(_literals3, pattern.End);
+
+ /// <summary>HMS (no days or fraction)</summary>
+ internal bool FullHMSMatch(TimeSpanFormat.FormatLiterals pattern) =>
+ _sepCount == 4
+ && _numCount == 3
+ && StringSpanHelpers.Equals(_literals0, pattern.Start)
+ && StringSpanHelpers.Equals(_literals1, pattern.HourMinuteSep)
+ && StringSpanHelpers.Equals(_literals2, pattern.MinuteSecondSep)
+ && StringSpanHelpers.Equals(_literals3, pattern.End);
+
+ /// <summary>DHMS (no fraction)</summary>
+ internal bool FullDHMSMatch(TimeSpanFormat.FormatLiterals pattern) =>
+ _sepCount == 5
+ && _numCount == 4
+ && StringSpanHelpers.Equals(_literals0, pattern.Start)
+ && StringSpanHelpers.Equals(_literals1, pattern.DayHourSep)
+ && StringSpanHelpers.Equals(_literals2, pattern.HourMinuteSep)
+ && StringSpanHelpers.Equals(_literals3, pattern.MinuteSecondSep)
+ && StringSpanHelpers.Equals(_literals4, pattern.End);
+
+ /// <summary>HMSF (no days)</summary>
+ internal bool FullHMSFMatch(TimeSpanFormat.FormatLiterals pattern) =>
+ _sepCount == 5
+ && _numCount == 4
+ && StringSpanHelpers.Equals(_literals0, pattern.Start)
+ && StringSpanHelpers.Equals(_literals1, pattern.HourMinuteSep)
+ && StringSpanHelpers.Equals(_literals2, pattern.MinuteSecondSep)
+ && StringSpanHelpers.Equals(_literals3, pattern.SecondFractionSep)
+ && StringSpanHelpers.Equals(_literals4, pattern.End);
+
+ internal TTT _lastSeenTTT;
+ internal int _tokenCount;
+ internal int _sepCount;
+ internal int _numCount;
+
+ private TimeSpanFormat.FormatLiterals _posLoc;
+ private TimeSpanFormat.FormatLiterals _negLoc;
+ private bool _posLocInit;
+ private bool _negLocInit;
+ private string _fullPosPattern;
+ private string _fullNegPattern;
+
+ private const int MaxTokens = 11;
+ private const int MaxLiteralTokens = 6;
+ private const int MaxNumericTokens = 5;
+
+ internal TimeSpanToken _numbers0, _numbers1, _numbers2, _numbers3, _numbers4; // MaxNumbericTokens = 5
+ internal ReadOnlySpan<char> _literals0, _literals1, _literals2, _literals3, _literals4, _literals5; // MaxLiteralTokens=6
+
+ internal void Init(DateTimeFormatInfo dtfi)
+ {
+ Debug.Assert(dtfi != null);
+
+ _lastSeenTTT = TTT.None;
+ _tokenCount = 0;
+ _sepCount = 0;
+ _numCount = 0;
+
+ _fullPosPattern = dtfi.FullTimeSpanPositivePattern;
+ _fullNegPattern = dtfi.FullTimeSpanNegativePattern;
+ _posLocInit = false;
+ _negLocInit = false;
+ }
+
+ internal bool ProcessToken(ref TimeSpanToken tok, ref TimeSpanResult result)
+ {
+ switch (tok._ttt)
+ {
+ case TTT.Num:
+ if ((_tokenCount == 0 && !AddSep(default(ReadOnlySpan<char>), ref result)) || !AddNum(tok, ref result))
+ {
+ return false;
+ }
+ break;
+
+ case TTT.Sep:
+ if (!AddSep(tok._sep, ref result))
+ {
+ return false;
+ }
+ break;
+
+ case TTT.NumOverflow:
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+
+ default:
+ // Some unknown token or a repeat token type in the input
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+
+ _lastSeenTTT = tok._ttt;
+ Debug.Assert(_tokenCount == (_sepCount + _numCount), "tokenCount == (SepCount + NumCount)");
+ return true;
+ }
+
+ private bool AddSep(ReadOnlySpan<char> sep, ref TimeSpanResult result)
+ {
+ if (_sepCount >= MaxLiteralTokens || _tokenCount >= MaxTokens)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+
+ switch (_sepCount++)
+ {
+ case 0: _literals0 = sep; break;
+ case 1: _literals1 = sep; break;
+ case 2: _literals2 = sep; break;
+ case 3: _literals3 = sep; break;
+ case 4: _literals4 = sep; break;
+ default: _literals5 = sep; break;
+ }
+
+ _tokenCount++;
+ return true;
+ }
+ private bool AddNum(TimeSpanToken num, ref TimeSpanResult result)
+ {
+ if (_numCount >= MaxNumericTokens || _tokenCount >= MaxTokens)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+
+ switch (_numCount++)
+ {
+ case 0: _numbers0 = num; break;
+ case 1: _numbers1 = num; break;
+ case 2: _numbers2 = num; break;
+ case 3: _numbers3 = num; break;
+ default: _numbers4 = num; break;
+ }
+
+ _tokenCount++;
+ return true;
+ }
+ }
+
+ /// <summary>Store the result of the parsing.</summary>
+ private struct TimeSpanResult
+ {
+ internal TimeSpan parsedTimeSpan;
+ private readonly bool _throwOnFailure;
+
+ internal TimeSpanResult(bool throwOnFailure)
+ {
+ parsedTimeSpan = default(TimeSpan);
+ _throwOnFailure = throwOnFailure;
+ }
+
+ internal bool SetFailure(ParseFailureKind kind, string resourceKey, object messageArgument = null, string argumentName = null)
+ {
+ if (!_throwOnFailure)
+ {
+ return false;
+ }
+
+ string message = SR.GetResourceString(resourceKey);
+ switch (kind)
+ {
+ case ParseFailureKind.ArgumentNull:
+ Debug.Assert(argumentName != null);
+ throw new ArgumentNullException(argumentName, message);
+
+ case ParseFailureKind.FormatWithParameter:
+ throw new FormatException(SR.Format(message, messageArgument));
+
+ case ParseFailureKind.Overflow:
+ throw new OverflowException(message);
+
+ default:
+ Debug.Assert(kind == ParseFailureKind.Format, $"Unexpected failure {kind}");
+ throw new FormatException(message);
+ }
+ }
+ }
+
+ internal static long Pow10(int pow)
+ {
+ switch (pow)
+ {
+ case 0: return 1;
+ case 1: return 10;
+ case 2: return 100;
+ case 3: return 1000;
+ case 4: return 10000;
+ case 5: return 100000;
+ case 6: return 1000000;
+ case 7: return 10000000;
+ default: return (long)Math.Pow(10, pow);
+ }
+ }
+
+ private static bool TryTimeToTicks(bool positive, TimeSpanToken days, TimeSpanToken hours, TimeSpanToken minutes, TimeSpanToken seconds, TimeSpanToken fraction, out long result)
+ {
+ if (days._num > MaxDays ||
+ hours._num > MaxHours ||
+ minutes._num > MaxMinutes ||
+ seconds._num > MaxSeconds ||
+ fraction.IsInvalidFraction())
+ {
+ result = 0;
+ return false;
+ }
+
+ long ticks = ((long)days._num * 3600 * 24 + (long)hours._num * 3600 + (long)minutes._num * 60 + seconds._num) * 1000;
+ if (ticks > InternalGlobalizationHelper.MaxMilliSeconds || ticks < InternalGlobalizationHelper.MinMilliSeconds)
+ {
+ result = 0;
+ return false;
+ }
+
+ // Normalize the fraction component
+ //
+ // string representation => (zeroes,num) => resultant fraction ticks
+ // --------------------- ------------ ------------------------
+ // ".9999999" => (0,9999999) => 9,999,999 ticks (same as constant maxFraction)
+ // ".1" => (0,1) => 1,000,000 ticks
+ // ".01" => (1,1) => 100,000 ticks
+ // ".001" => (2,1) => 10,000 ticks
+ long f = fraction._num;
+ if (f != 0)
+ {
+ long lowerLimit = InternalGlobalizationHelper.TicksPerTenthSecond;
+ if (fraction._zeroes > 0)
+ {
+ long divisor = Pow10(fraction._zeroes);
+ lowerLimit = lowerLimit / divisor;
+ }
+
+ while (f < lowerLimit)
+ {
+ f *= 10;
+ }
+ }
+
+ result = ticks * TimeSpan.TicksPerMillisecond + f;
+ if (positive && result < 0)
+ {
+ result = 0;
+ return false;
+ }
+
+ return true;
+ }
+
+ internal static TimeSpan Parse(ReadOnlySpan<char> input, IFormatProvider formatProvider)
+ {
+ var parseResult = new TimeSpanResult(throwOnFailure: true);
+ bool success = TryParseTimeSpan(input, TimeSpanStandardStyles.Any, formatProvider, ref parseResult);
+ Debug.Assert(success, "Should have thrown on failure");
+ return parseResult.parsedTimeSpan;
+ }
+
+ internal static bool TryParse(ReadOnlySpan<char> input, IFormatProvider formatProvider, out TimeSpan result)
+ {
+ var parseResult = new TimeSpanResult(throwOnFailure: false);
+
+ if (TryParseTimeSpan(input, TimeSpanStandardStyles.Any, formatProvider, ref parseResult))
+ {
+ result = parseResult.parsedTimeSpan;
+ return true;
+ }
+
+ result = default(TimeSpan);
+ return false;
+ }
+
+ internal static TimeSpan ParseExact(ReadOnlySpan<char> input, string format, IFormatProvider formatProvider, TimeSpanStyles styles)
+ {
+ var parseResult = new TimeSpanResult(throwOnFailure: true);
+ bool success = TryParseExactTimeSpan(input, format, formatProvider, styles, ref parseResult);
+ Debug.Assert(success, "Should have thrown on failure");
+ return parseResult.parsedTimeSpan;
+ }
+
+ internal static bool TryParseExact(ReadOnlySpan<char> input, string format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result)
+ {
+ var parseResult = new TimeSpanResult(throwOnFailure: false);
+
+ if (TryParseExactTimeSpan(input, format, formatProvider, styles, ref parseResult))
+ {
+ result = parseResult.parsedTimeSpan;
+ return true;
+ }
+
+ result = default(TimeSpan);
+ return false;
+ }
+
+ internal static TimeSpan ParseExactMultiple(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles)
+ {
+ var parseResult = new TimeSpanResult(throwOnFailure: true);
+ bool success = TryParseExactMultipleTimeSpan(input, formats, formatProvider, styles, ref parseResult);
+ Debug.Assert(success, "Should have thrown on failure");
+ return parseResult.parsedTimeSpan;
+ }
+
+ internal static bool TryParseExactMultiple(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result)
+ {
+ var parseResult = new TimeSpanResult(throwOnFailure: false);
+
+ if (TryParseExactMultipleTimeSpan(input, formats, formatProvider, styles, ref parseResult))
+ {
+ result = parseResult.parsedTimeSpan;
+ return true;
+ }
+
+ result = default(TimeSpan);
+ return false;
+ }
+
+ /// <summary>Common private Parse method called by both Parse and TryParse.</summary>
+ private static bool TryParseTimeSpan(ReadOnlySpan<char> input, TimeSpanStandardStyles style, IFormatProvider formatProvider, ref TimeSpanResult result)
+ {
+ input = input.Trim();
+ if (input.IsEmpty)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+
+ var tokenizer = new TimeSpanTokenizer(input);
+
+ var raw = new TimeSpanRawInfo();
+ raw.Init(DateTimeFormatInfo.GetInstance(formatProvider));
+
+ TimeSpanToken tok = tokenizer.GetNextToken();
+
+ // The following loop will break out when we reach the end of the str or
+ // when we can determine that the input is invalid.
+ while (tok._ttt != TTT.End)
+ {
+ if (!raw.ProcessToken(ref tok, ref result))
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+ tok = tokenizer.GetNextToken();
+ }
+ Debug.Assert(tokenizer.EOL);
+
+ if (!ProcessTerminalState(ref raw, style, ref result))
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Validate the terminal state of a standard format parse.
+ /// Sets result.parsedTimeSpan on success.
+ /// Calculates the resultant TimeSpan from the TimeSpanRawInfo.
+ /// </summary>
+ /// <remarks>
+ /// try => +InvariantPattern, -InvariantPattern, +LocalizedPattern, -LocalizedPattern
+ /// 1) Verify Start matches
+ /// 2) Verify End matches
+ /// 3) 1 number => d
+ /// 2 numbers => h:m
+ /// 3 numbers => h:m:s | d.h:m | h:m:.f
+ /// 4 numbers => h:m:s.f | d.h:m:s | d.h:m:.f
+ /// 5 numbers => d.h:m:s.f
+ /// </remarks>
+ private static bool ProcessTerminalState(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
+ {
+ if (raw._lastSeenTTT == TTT.Num)
+ {
+ TimeSpanToken tok = new TimeSpanToken();
+ tok._ttt = TTT.Sep;
+ if (!raw.ProcessToken(ref tok, ref result))
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+ }
+
+ switch (raw._numCount)
+ {
+ case 1: return ProcessTerminal_D(ref raw, style, ref result);
+ case 2: return ProcessTerminal_HM(ref raw, style, ref result);
+ case 3: return ProcessTerminal_HM_S_D(ref raw, style, ref result);
+ case 4: return ProcessTerminal_HMS_F_D(ref raw, style, ref result);
+ case 5: return ProcessTerminal_DHMSF(ref raw, style, ref result);
+ default: return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+ }
+
+ /// <summary>Validate the 5-number "Days.Hours:Minutes:Seconds.Fraction" terminal case.</summary>
+ private static bool ProcessTerminal_DHMSF(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
+ {
+ if (raw._sepCount != 6)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+ Debug.Assert(raw._numCount == 5);
+
+ bool inv = (style & TimeSpanStandardStyles.Invariant) != 0;
+ bool loc = (style & TimeSpanStandardStyles.Localized) != 0;
+ bool positive = false;
+ bool match = false;
+
+ if (inv)
+ {
+ if (raw.FullMatch(raw.PositiveInvariant))
+ {
+ match = true;
+ positive = true;
+ }
+ if (!match && raw.FullMatch(raw.NegativeInvariant))
+ {
+ match = true;
+ positive = false;
+ }
+ }
+
+ if (loc)
+ {
+ if (!match && raw.FullMatch(raw.PositiveLocalized))
+ {
+ match = true;
+ positive = true;
+ }
+ if (!match && raw.FullMatch(raw.NegativeLocalized))
+ {
+ match = true;
+ positive = false;
+ }
+ }
+
+ if (match)
+ {
+ long ticks;
+
+ if (!TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, raw._numbers4, out ticks))
+ {
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+ }
+
+ if (!positive)
+ {
+ ticks = -ticks;
+ if (ticks > 0)
+ {
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+ }
+ }
+
+ result.parsedTimeSpan._ticks = ticks;
+ return true;
+ }
+
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+
+
+ /// <summary>
+ /// Validate the ambiguous 4-number "Hours:Minutes:Seconds.Fraction", "Days.Hours:Minutes:Seconds",
+ /// or "Days.Hours:Minutes:.Fraction" terminal case.
+ /// </summary>
+ private static bool ProcessTerminal_HMS_F_D(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
+ {
+ if (raw._sepCount != 5 || (style & TimeSpanStandardStyles.RequireFull) != 0)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+ Debug.Assert(raw._numCount == 4);
+
+ bool inv = ((style & TimeSpanStandardStyles.Invariant) != 0);
+ bool loc = ((style & TimeSpanStandardStyles.Localized) != 0);
+
+ long ticks = 0;
+ bool positive = false, match = false, overflow = false;
+ var zero = new TimeSpanToken(0);
+
+ if (inv)
+ {
+ if (raw.FullHMSFMatch(raw.PositiveInvariant))
+ {
+ positive = true;
+ match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullDHMSMatch(raw.PositiveInvariant))
+ {
+ positive = true;
+ match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, zero, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullAppCompatMatch(raw.PositiveInvariant))
+ {
+ positive = true;
+ match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, zero, raw._numbers3, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullHMSFMatch(raw.NegativeInvariant))
+ {
+ positive = false;
+ match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullDHMSMatch(raw.NegativeInvariant))
+ {
+ positive = false;
+ match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, zero, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullAppCompatMatch(raw.NegativeInvariant))
+ {
+ positive = false;
+ match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, zero, raw._numbers3, out ticks);
+ overflow = overflow || !match;
+ }
+ }
+
+ if (loc)
+ {
+ if (!match && raw.FullHMSFMatch(raw.PositiveLocalized))
+ {
+ positive = true;
+ match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullDHMSMatch(raw.PositiveLocalized))
+ {
+ positive = true;
+ match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, zero, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullAppCompatMatch(raw.PositiveLocalized))
+ {
+ positive = true;
+ match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, zero, raw._numbers3, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullHMSFMatch(raw.NegativeLocalized))
+ {
+ positive = false;
+ match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullDHMSMatch(raw.NegativeLocalized))
+ {
+ positive = false;
+ match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, raw._numbers3, zero, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullAppCompatMatch(raw.NegativeLocalized))
+ {
+ positive = false;
+ match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, zero, raw._numbers3, out ticks);
+ overflow = overflow || !match;
+ }
+ }
+
+ if (match)
+ {
+ if (!positive)
+ {
+ ticks = -ticks;
+ if (ticks > 0)
+ {
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+ }
+ }
+
+ result.parsedTimeSpan._ticks = ticks;
+ return true;
+ }
+
+ return overflow ?
+ result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)) : // we found at least one literal pattern match but the numbers just didn't fit
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); // we couldn't find a thing
+ }
+
+ /// <summary>Validate the ambiguous 3-number "Hours:Minutes:Seconds", "Days.Hours:Minutes", or "Hours:Minutes:.Fraction" terminal case.</summary>
+ private static bool ProcessTerminal_HM_S_D(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
+ {
+ if (raw._sepCount != 4 || (style & TimeSpanStandardStyles.RequireFull) != 0)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+ Debug.Assert(raw._numCount == 3);
+
+ bool inv = ((style & TimeSpanStandardStyles.Invariant) != 0);
+ bool loc = ((style & TimeSpanStandardStyles.Localized) != 0);
+
+ bool positive = false, match = false, overflow = false;
+ var zero = new TimeSpanToken(0);
+ long ticks = 0;
+
+ if (inv)
+ {
+ if (raw.FullHMSMatch(raw.PositiveInvariant))
+ {
+ positive = true;
+ match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, raw._numbers2, zero, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullDHMMatch(raw.PositiveInvariant))
+ {
+ positive = true;
+ match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, zero, zero, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.PartialAppCompatMatch(raw.PositiveInvariant))
+ {
+ positive = true;
+ match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, zero, raw._numbers2, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullHMSMatch(raw.NegativeInvariant))
+ {
+ positive = false;
+ match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, raw._numbers2, zero, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullDHMMatch(raw.NegativeInvariant))
+ {
+ positive = false;
+ match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, zero, zero, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.PartialAppCompatMatch(raw.NegativeInvariant))
+ {
+ positive = false;
+ match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, zero, raw._numbers2, out ticks);
+ overflow = overflow || !match;
+ }
+ }
+
+ if (loc)
+ {
+ if (!match && raw.FullHMSMatch(raw.PositiveLocalized))
+ {
+ positive = true;
+ match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, raw._numbers2, zero, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullDHMMatch(raw.PositiveLocalized))
+ {
+ positive = true;
+ match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, zero, zero, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.PartialAppCompatMatch(raw.PositiveLocalized))
+ {
+ positive = true;
+ match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, zero, raw._numbers2, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullHMSMatch(raw.NegativeLocalized))
+ {
+ positive = false;
+ match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, raw._numbers2, zero, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.FullDHMMatch(raw.NegativeLocalized))
+ {
+ positive = false;
+ match = TryTimeToTicks(positive, raw._numbers0, raw._numbers1, raw._numbers2, zero, zero, out ticks);
+ overflow = overflow || !match;
+ }
+
+ if (!match && raw.PartialAppCompatMatch(raw.NegativeLocalized))
+ {
+ positive = false;
+ match = TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, zero, raw._numbers2, out ticks);
+ overflow = overflow || !match;
+ }
+ }
+
+ if (match)
+ {
+ if (!positive)
+ {
+ ticks = -ticks;
+ if (ticks > 0)
+ {
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+ }
+ }
+
+ result.parsedTimeSpan._ticks = ticks;
+ return true;
+ }
+
+ return overflow ?
+ result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge)) : // we found at least one literal pattern match but the numbers just didn't fit
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan)); // we couldn't find a thing
+ }
+
+ /// <summary>Validate the 2-number "Hours:Minutes" terminal case.</summary>
+ private static bool ProcessTerminal_HM(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
+ {
+ if (raw._sepCount != 3 || (style & TimeSpanStandardStyles.RequireFull) != 0)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+ Debug.Assert(raw._numCount == 2);
+
+ bool inv = ((style & TimeSpanStandardStyles.Invariant) != 0);
+ bool loc = ((style & TimeSpanStandardStyles.Localized) != 0);
+
+ bool positive = false, match = false;
+
+ if (inv)
+ {
+ if (raw.FullHMMatch(raw.PositiveInvariant))
+ {
+ match = true;
+ positive = true;
+ }
+
+ if (!match && raw.FullHMMatch(raw.NegativeInvariant))
+ {
+ match = true;
+ positive = false;
+ }
+ }
+
+ if (loc)
+ {
+ if (!match && raw.FullHMMatch(raw.PositiveLocalized))
+ {
+ match = true;
+ positive = true;
+ }
+
+ if (!match && raw.FullHMMatch(raw.NegativeLocalized))
+ {
+ match = true;
+ positive = false;
+ }
+ }
+
+ if (match)
+ {
+ long ticks = 0;
+ var zero = new TimeSpanToken(0);
+
+ if (!TryTimeToTicks(positive, zero, raw._numbers0, raw._numbers1, zero, zero, out ticks))
+ {
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+ }
+
+ if (!positive)
+ {
+ ticks = -ticks;
+ if (ticks > 0)
+ {
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+ }
+ }
+
+ result.parsedTimeSpan._ticks = ticks;
+ return true;
+ }
+
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+
+ /// <summary>Validate the 1-number "Days" terminal case.</summary>
+ private static bool ProcessTerminal_D(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
+ {
+ if (raw._sepCount != 2 || (style & TimeSpanStandardStyles.RequireFull) != 0)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+ Debug.Assert(raw._numCount == 1);
+
+ bool inv = ((style & TimeSpanStandardStyles.Invariant) != 0);
+ bool loc = ((style & TimeSpanStandardStyles.Localized) != 0);
+
+ bool positive = false, match = false;
+
+ if (inv)
+ {
+ if (raw.FullDMatch(raw.PositiveInvariant))
+ {
+ match = true;
+ positive = true;
+ }
+
+ if (!match && raw.FullDMatch(raw.NegativeInvariant))
+ {
+ match = true;
+ positive = false;
+ }
+ }
+
+ if (loc)
+ {
+ if (!match && raw.FullDMatch(raw.PositiveLocalized))
+ {
+ match = true;
+ positive = true;
+ }
+
+ if (!match && raw.FullDMatch(raw.NegativeLocalized))
+ {
+ match = true;
+ positive = false;
+ }
+ }
+
+ if (match)
+ {
+ long ticks = 0;
+ var zero = new TimeSpanToken(0);
+
+ if (!TryTimeToTicks(positive, raw._numbers0, zero, zero, zero, zero, out ticks))
+ {
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+ }
+
+ if (!positive)
+ {
+ ticks = -ticks;
+ if (ticks > 0)
+ {
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+ }
+ }
+
+ result.parsedTimeSpan._ticks = ticks;
+ return true;
+ }
+
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+
+ /// <summary>Common private ParseExact method called by both ParseExact and TryParseExact.</summary>
+ private static bool TryParseExactTimeSpan(ReadOnlySpan<char> input, string format, IFormatProvider formatProvider, TimeSpanStyles styles, ref TimeSpanResult result)
+ {
+ if (format == null)
+ {
+ return result.SetFailure(ParseFailureKind.ArgumentNull, nameof(SR.ArgumentNull_String), argumentName: nameof(format));
+ }
+
+ if (format.Length == 0)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadFormatSpecifier));
+ }
+
+ if (format.Length == 1)
+ {
+ switch (format[0])
+ {
+ case 'c':
+ case 't':
+ case 'T':
+ return TryParseTimeSpanConstant(input, ref result); // fast path for legacy style TimeSpan formats.
+
+ case 'g':
+ return TryParseTimeSpan(input, TimeSpanStandardStyles.Localized, formatProvider, ref result);
+
+ case 'G':
+ return TryParseTimeSpan(input, TimeSpanStandardStyles.Localized | TimeSpanStandardStyles.RequireFull, formatProvider, ref result);
+
+ default:
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadFormatSpecifier));
+ }
+ }
+
+ return TryParseByFormat(input, format, styles, ref result);
+ }
+
+ /// <summary>Parse the TimeSpan instance using the specified format. Used by TryParseExactTimeSpan.</summary>
+ private static bool TryParseByFormat(ReadOnlySpan<char> input, string format, TimeSpanStyles styles, ref TimeSpanResult result)
+ {
+ Debug.Assert(format != null, "format != null");
+
+ bool seenDD = false; // already processed days?
+ bool seenHH = false; // already processed hours?
+ bool seenMM = false; // already processed minutes?
+ bool seenSS = false; // already processed seconds?
+ bool seenFF = false; // already processed fraction?
+
+ int dd = 0; // parsed days
+ int hh = 0; // parsed hours
+ int mm = 0; // parsed minutes
+ int ss = 0; // parsed seconds
+ int leadingZeroes = 0; // number of leading zeroes in the parsed fraction
+ int ff = 0; // parsed fraction
+ int i = 0; // format string position
+ int tokenLen = 0; // length of current format token, used to update index 'i'
+
+ var tokenizer = new TimeSpanTokenizer(input, -1);
+
+ while (i < format.Length)
+ {
+ char ch = format[i];
+ int nextFormatChar;
+ switch (ch)
+ {
+ case 'h':
+ tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
+ if (tokenLen > 2 || seenHH || !ParseExactDigits(ref tokenizer, tokenLen, out hh))
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString));
+ }
+ seenHH = true;
+ break;
+
+ case 'm':
+ tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
+ if (tokenLen > 2 || seenMM || !ParseExactDigits(ref tokenizer, tokenLen, out mm))
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString));
+ }
+ seenMM = true;
+ break;
+
+ case 's':
+ tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
+ if (tokenLen > 2 || seenSS || !ParseExactDigits(ref tokenizer, tokenLen, out ss))
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString));
+ }
+ seenSS = true;
+ break;
+
+ case 'f':
+ tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
+ if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits || seenFF || !ParseExactDigits(ref tokenizer, tokenLen, tokenLen, out leadingZeroes, out ff))
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString));
+ }
+ seenFF = true;
+ break;
+
+ case 'F':
+ tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
+ if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits || seenFF)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString));
+ }
+ ParseExactDigits(ref tokenizer, tokenLen, tokenLen, out leadingZeroes, out ff);
+ seenFF = true;
+ break;
+
+ case 'd':
+ tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
+ int tmp = 0;
+ if (tokenLen > 8 || seenDD || !ParseExactDigits(ref tokenizer, (tokenLen < 2) ? 1 : tokenLen, (tokenLen < 2) ? 8 : tokenLen, out tmp, out dd))
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString));
+ }
+ seenDD = true;
+ break;
+
+ case '\'':
+ case '\"':
+ StringBuilder enquotedString = new StringBuilder();
+ if (!DateTimeParse.TryParseQuoteString(format, i, enquotedString, out tokenLen))
+ {
+ return result.SetFailure(ParseFailureKind.FormatWithParameter, nameof(SR.Format_BadQuote), ch);
+ }
+ if (!ParseExactLiteral(ref tokenizer, enquotedString))
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString));
+ }
+ break;
+
+ case '%':
+ // Optional format character.
+ // For example, format string "%d" will print day
+ // Most of the cases, "%" can be ignored.
+ nextFormatChar = DateTimeFormat.ParseNextChar(format, i);
+
+ // nextFormatChar will be -1 if we already reach the end of the format string.
+ // Besides, we will not allow "%%" appear in the pattern.
+ if (nextFormatChar >= 0 && nextFormatChar != '%')
+ {
+ tokenLen = 1; // skip the '%' and process the format character
+ break;
+ }
+ else
+ {
+ // This means that '%' is at the end of the format string or
+ // "%%" appears in the format string.
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString));
+ }
+
+ case '\\':
+ // Escaped character. Can be used to insert character into the format string.
+ // For example, "\d" will insert the character 'd' into the string.
+ //
+ nextFormatChar = DateTimeFormat.ParseNextChar(format, i);
+ if (nextFormatChar >= 0 && tokenizer.NextChar == (char)nextFormatChar)
+ {
+ tokenLen = 2;
+ }
+ else
+ {
+ // This means that '\' is at the end of the format string or the literal match failed.
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString));
+ }
+ break;
+
+ default:
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_InvalidString));
+ }
+
+ i += tokenLen;
+ }
+
+
+ if (!tokenizer.EOL)
+ {
+ // the custom format didn't consume the entire input
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+
+ bool positive = (styles & TimeSpanStyles.AssumeNegative) == 0;
+ if (TryTimeToTicks(positive, new TimeSpanToken(dd),
+ new TimeSpanToken(hh),
+ new TimeSpanToken(mm),
+ new TimeSpanToken(ss),
+ new TimeSpanToken(ff, leadingZeroes),
+ out long ticks))
+ {
+ if (!positive)
+ {
+ ticks = -ticks;
+ }
+
+ result.parsedTimeSpan._ticks = ticks;
+ return true;
+ }
+ else
+ {
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+ }
+ }
+
+ private static bool ParseExactDigits(ref TimeSpanTokenizer tokenizer, int minDigitLength, out int result)
+ {
+ result = 0;
+ int zeroes = 0;
+ int maxDigitLength = (minDigitLength == 1) ? 2 : minDigitLength;
+ return ParseExactDigits(ref tokenizer, minDigitLength, maxDigitLength, out zeroes, out result);
+ }
+
+ private static bool ParseExactDigits(ref TimeSpanTokenizer tokenizer, int minDigitLength, int maxDigitLength, out int zeroes, out int result)
+ {
+ int tmpResult = 0, tmpZeroes = 0;
+
+ int tokenLength = 0;
+ while (tokenLength < maxDigitLength)
+ {
+ char ch = tokenizer.NextChar;
+ if (ch < '0' || ch > '9')
+ {
+ tokenizer.BackOne();
+ break;
+ }
+
+ tmpResult = tmpResult * 10 + (ch - '0');
+ if (tmpResult == 0) tmpZeroes++;
+ tokenLength++;
+ }
+
+ zeroes = tmpZeroes;
+ result = tmpResult;
+ return tokenLength >= minDigitLength;
+ }
+
+ private static bool ParseExactLiteral(ref TimeSpanTokenizer tokenizer, StringBuilder enquotedString)
+ {
+ for (int i = 0; i < enquotedString.Length; i++)
+ {
+ if (enquotedString[i] != tokenizer.NextChar)
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /// <summary>
+ /// Parses the "c" (constant) format. This code is 100% identical to the non-globalized v1.0-v3.5 TimeSpan.Parse() routine
+ /// and exists for performance/appcompat with legacy callers who cannot move onto the globalized Parse overloads.
+ /// </summary>
+ private static bool TryParseTimeSpanConstant(ReadOnlySpan<char> input, ref TimeSpanResult result) =>
+ new StringParser().TryParse(input, ref result);
+
+ [IsByRefLike]
+ private struct StringParser
+ {
+ private ReadOnlySpan<char> _str;
+ private char _ch;
+ private int _pos;
+ private int _len;
+
+ internal void NextChar()
+ {
+ if (_pos < _len)
+ {
+ _pos++;
+ }
+
+ _ch = _pos < _len ?
+ _str[_pos] :
+ (char)0;
+ }
+
+ internal char NextNonDigit()
+ {
+ int i = _pos;
+ while (i < _len)
+ {
+ char ch = _str[i];
+ if (ch < '0' || ch > '9') return ch;
+ i++;
+ }
+
+ return (char)0;
+ }
+
+ internal bool TryParse(ReadOnlySpan<char> input, ref TimeSpanResult result)
+ {
+ result.parsedTimeSpan._ticks = 0;
+
+ _str = input;
+ _len = input.Length;
+ _pos = -1;
+ NextChar();
+ SkipBlanks();
+
+ bool negative = false;
+ if (_ch == '-')
+ {
+ negative = true;
+ NextChar();
+ }
+
+ long time;
+ if (NextNonDigit() == ':')
+ {
+ if (!ParseTime(out time, ref result))
+ {
+ return false;
+ };
+ }
+ else
+ {
+ int days;
+ if (!ParseInt((int)(0x7FFFFFFFFFFFFFFFL / TimeSpan.TicksPerDay), out days, ref result))
+ {
+ return false;
+ }
+
+ time = days * TimeSpan.TicksPerDay;
+
+ if (_ch == '.')
+ {
+ NextChar();
+ long remainingTime;
+ if (!ParseTime(out remainingTime, ref result))
+ {
+ return false;
+ };
+ time += remainingTime;
+ }
+ }
+
+ if (negative)
+ {
+ time = -time;
+ // Allow -0 as well
+ if (time > 0)
+ {
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+ }
+ }
+ else
+ {
+ if (time < 0)
+ {
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+ }
+ }
+
+ SkipBlanks();
+
+ if (_pos < _len)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+
+ result.parsedTimeSpan._ticks = time;
+ return true;
+ }
+
+ internal bool ParseInt(int max, out int i, ref TimeSpanResult result)
+ {
+ i = 0;
+ int p = _pos;
+ while (_ch >= '0' && _ch <= '9')
+ {
+ if ((i & 0xF0000000) != 0)
+ {
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+ }
+
+ i = i * 10 + _ch - '0';
+ if (i < 0)
+ {
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+ }
+
+ NextChar();
+ }
+
+ if (p == _pos)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+
+ if (i > max)
+ {
+ return result.SetFailure(ParseFailureKind.Overflow, nameof(SR.Overflow_TimeSpanElementTooLarge));
+ }
+
+ return true;
+ }
+
+ internal bool ParseTime(out long time, ref TimeSpanResult result)
+ {
+ time = 0;
+ int unit;
+
+ if (!ParseInt(23, out unit, ref result))
+ {
+ return false;
+ }
+
+ time = unit * TimeSpan.TicksPerHour;
+ if (_ch != ':')
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+
+ NextChar();
+
+ if (!ParseInt(59, out unit, ref result))
+ {
+ return false;
+ }
+
+ time += unit * TimeSpan.TicksPerMinute;
+
+ if (_ch == ':')
+ {
+ NextChar();
+
+ // allow seconds with the leading zero
+ if (_ch != '.')
+ {
+ if (!ParseInt(59, out unit, ref result))
+ {
+ return false;
+ }
+ time += unit * TimeSpan.TicksPerSecond;
+ }
+
+ if (_ch == '.')
+ {
+ NextChar();
+ int f = (int)TimeSpan.TicksPerSecond;
+ while (f > 1 && _ch >= '0' && _ch <= '9')
+ {
+ f /= 10;
+ time += (_ch - '0') * f;
+ NextChar();
+ }
+ }
+ }
+
+ return true;
+ }
+
+ internal void SkipBlanks()
+ {
+ while (_ch == ' ' || _ch == '\t') NextChar();
+ }
+ }
+
+ /// <summary>Common private ParseExactMultiple method called by both ParseExactMultiple and TryParseExactMultiple.</summary>
+ private static bool TryParseExactMultipleTimeSpan(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, ref TimeSpanResult result)
+ {
+ if (formats == null)
+ {
+ return result.SetFailure(ParseFailureKind.ArgumentNull, nameof(SR.ArgumentNull_String), argumentName: nameof(formats));
+ }
+
+ if (input.Length == 0)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+
+ if (formats.Length == 0)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadFormatSpecifier));
+ }
+
+ // Do a loop through the provided formats and see if we can parse succesfully in
+ // one of the formats.
+ for (int i = 0; i < formats.Length; i++)
+ {
+ if (formats[i] == null || formats[i].Length == 0)
+ {
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadFormatSpecifier));
+ }
+
+ // Create a new non-throwing result each time to ensure the runs are independent.
+ TimeSpanResult innerResult = new TimeSpanResult(throwOnFailure: false);
+
+ if (TryParseExactTimeSpan(input, formats[i], formatProvider, styles, ref innerResult))
+ {
+ result.parsedTimeSpan = innerResult.parsedTimeSpan;
+ return true;
+ }
+ }
+
+ return result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_BadTimeSpan));
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/Guid.cs b/src/mscorlib/shared/System/Guid.cs
index aad188be3d..b8b4dd5f0f 100644
--- a/src/mscorlib/src/System/Guid.cs
+++ b/src/mscorlib/shared/System/Guid.cs
@@ -2,11 +2,6 @@
// 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.Text;
-using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics;
@@ -17,12 +12,12 @@ namespace System
// Represents a Globally Unique Identifier.
[StructLayout(LayoutKind.Sequential)]
[Serializable]
- [System.Runtime.Versioning.NonVersionable] // This only applies to field layout
- [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
- public struct Guid : IFormattable, IComparable
- , IComparable<Guid>, IEquatable<Guid>
+ [Runtime.Versioning.NonVersionable] // This only applies to field layout
+ [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ public partial struct Guid : IFormattable, IComparable, IComparable<Guid>, IEquatable<Guid>
{
public static readonly Guid Empty = new Guid();
+
////////////////////////////////////////////////////////////////////////////////
// Member variables
////////////////////////////////////////////////////////////////////////////////
@@ -38,25 +33,25 @@ namespace System
private byte _j; // Do not rename (binary serialization)
private byte _k; // Do not rename (binary serialization)
-
-
////////////////////////////////////////////////////////////////////////////////
// Constructors
////////////////////////////////////////////////////////////////////////////////
// Creates a new guid from an array of bytes.
- //
- public Guid(byte[] b)
+ public Guid(byte[] b) :
+ this(new ReadOnlySpan<byte>(b ?? throw new ArgumentNullException(nameof(b))))
+ {
+ }
+
+ // Creates a new guid from a read-only span.
+ public Guid(ReadOnlySpan<byte> b)
{
- if (b == null)
- throw new ArgumentNullException(nameof(b));
if (b.Length != 16)
throw new ArgumentException(SR.Format(SR.Arg_GuidArrayCtor, "16"), nameof(b));
- Contract.EndContractBlock();
- _a = ((int)b[3] << 24) | ((int)b[2] << 16) | ((int)b[1] << 8) | b[0];
- _b = (short)(((int)b[5] << 8) | b[4]);
- _c = (short)(((int)b[7] << 8) | b[6]);
+ _a = b[3] << 24 | b[2] << 16 | b[1] << 8 | b[0];
+ _b = (short)(b[5] << 8 | b[4]);
+ _c = (short)(b[7] << 8 | b[6]);
_d = b[8];
_e = b[9];
_f = b[10];
@@ -83,7 +78,6 @@ namespace System
_k = k;
}
-
// Creates a new GUID initialized to the value represented by the arguments.
//
public Guid(int a, short b, short c, byte[] d)
@@ -166,43 +160,46 @@ namespace System
// This will store the result of the parsing. And it will eventually be used to construct a Guid instance.
private struct GuidResult
{
- internal Guid parsedGuid;
- internal GuidParseThrowStyle throwStyle;
+ internal Guid _parsedGuid;
+ internal GuidParseThrowStyle _throwStyle;
- internal ParseFailureKind m_failure;
- internal string m_failureMessageID;
- internal object m_failureMessageFormatArgument;
- internal string m_failureArgumentName;
- internal Exception m_innerException;
+ private ParseFailureKind _failure;
+ private string _failureMessageID;
+ private object _failureMessageFormatArgument;
+ private string _failureArgumentName;
+ private Exception _innerException;
internal void Init(GuidParseThrowStyle canThrow)
{
- parsedGuid = Guid.Empty;
- throwStyle = canThrow;
+ _throwStyle = canThrow;
}
+
internal void SetFailure(Exception nativeException)
{
- m_failure = ParseFailureKind.NativeException;
- m_innerException = nativeException;
+ _failure = ParseFailureKind.NativeException;
+ _innerException = nativeException;
}
+
internal void SetFailure(ParseFailureKind failure, string failureMessageID)
{
SetFailure(failure, failureMessageID, null, null, null);
}
+
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument)
{
SetFailure(failure, failureMessageID, failureMessageFormatArgument, null, null);
}
+
internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument,
string failureArgumentName, Exception innerException)
{
Debug.Assert(failure != ParseFailureKind.NativeException, "ParseFailureKind.NativeException should not be used with this overload");
- m_failure = failure;
- m_failureMessageID = failureMessageID;
- m_failureMessageFormatArgument = failureMessageFormatArgument;
- m_failureArgumentName = failureArgumentName;
- m_innerException = innerException;
- if (throwStyle != GuidParseThrowStyle.None)
+ _failure = failure;
+ _failureMessageID = failureMessageID;
+ _failureMessageFormatArgument = failureMessageFormatArgument;
+ _failureArgumentName = failureArgumentName;
+ _innerException = innerException;
+ if (_throwStyle != GuidParseThrowStyle.None)
{
throw GetGuidParseException();
}
@@ -210,25 +207,25 @@ namespace System
internal Exception GetGuidParseException()
{
- switch (m_failure)
+ switch (_failure)
{
case ParseFailureKind.ArgumentNull:
- return new ArgumentNullException(m_failureArgumentName, SR.GetResourceString(m_failureMessageID));
+ return new ArgumentNullException(_failureArgumentName, SR.GetResourceString(_failureMessageID));
case ParseFailureKind.FormatWithInnerException:
- return new FormatException(SR.GetResourceString(m_failureMessageID), m_innerException);
+ return new FormatException(SR.GetResourceString(_failureMessageID), _innerException);
case ParseFailureKind.FormatWithParameter:
- return new FormatException(SR.Format(SR.GetResourceString(m_failureMessageID), m_failureMessageFormatArgument));
+ return new FormatException(SR.Format(SR.GetResourceString(_failureMessageID), _failureMessageFormatArgument));
case ParseFailureKind.Format:
- return new FormatException(SR.GetResourceString(m_failureMessageID));
+ return new FormatException(SR.GetResourceString(_failureMessageID));
case ParseFailureKind.NativeException:
- return m_innerException;
+ return _innerException;
default:
- Debug.Assert(false, "Unknown GuidParseFailure: " + m_failure);
+ Debug.Assert(false, "Unknown GuidParseFailure: " + _failure);
return new FormatException(SR.Format_GuidUnrecognized);
}
}
@@ -242,20 +239,19 @@ namespace System
// d is a hex digit. (That is 8 hex digits, followed by 4, then 4, then 4,
// then 12) such as: "CA761232-ED42-11CE-BACD-00AA0057B223"
//
- public Guid(String g)
+ public Guid(string g)
{
if (g == null)
{
throw new ArgumentNullException(nameof(g));
}
Contract.EndContractBlock();
- this = Guid.Empty;
GuidResult result = new GuidResult();
result.Init(GuidParseThrowStyle.All);
if (TryParseGuid(g, GuidStyles.Any, ref result))
{
- this = result.parsedGuid;
+ this = result._parsedGuid;
}
else
{
@@ -263,8 +259,7 @@ namespace System
}
}
-
- public static Guid Parse(String input)
+ public static Guid Parse(string input)
{
if (input == null)
{
@@ -276,7 +271,7 @@ namespace System
result.Init(GuidParseThrowStyle.AllButOverflow);
if (TryParseGuid(input, GuidStyles.Any, ref result))
{
- return result.parsedGuid;
+ return result._parsedGuid;
}
else
{
@@ -284,23 +279,23 @@ namespace System
}
}
- public static bool TryParse(String input, out Guid result)
+ public static bool TryParse(string input, out Guid result)
{
GuidResult parseResult = new GuidResult();
parseResult.Init(GuidParseThrowStyle.None);
if (TryParseGuid(input, GuidStyles.Any, ref parseResult))
{
- result = parseResult.parsedGuid;
+ result = parseResult._parsedGuid;
return true;
}
else
{
- result = Guid.Empty;
+ result = Empty;
return false;
}
}
- public static Guid ParseExact(String input, String format)
+ public static Guid ParseExact(string input, string format)
{
if (input == null)
throw new ArgumentNullException(nameof(input));
@@ -345,7 +340,7 @@ namespace System
result.Init(GuidParseThrowStyle.AllButOverflow);
if (TryParseGuid(input, style, ref result))
{
- return result.parsedGuid;
+ return result._parsedGuid;
}
else
{
@@ -353,11 +348,11 @@ namespace System
}
}
- public static bool TryParseExact(String input, String format, out Guid result)
+ public static bool TryParseExact(string input, string format, out Guid result)
{
if (format == null || format.Length != 1)
{
- result = Guid.Empty;
+ result = Empty;
return false;
}
@@ -387,7 +382,7 @@ namespace System
else
{
// invalid guid format specification
- result = Guid.Empty;
+ result = Empty;
return false;
}
@@ -395,29 +390,28 @@ namespace System
parseResult.Init(GuidParseThrowStyle.None);
if (TryParseGuid(input, style, ref parseResult))
{
- result = parseResult.parsedGuid;
+ result = parseResult._parsedGuid;
return true;
}
else
{
- result = Guid.Empty;
+ result = Empty;
return false;
}
}
-
- private static bool TryParseGuid(String g, GuidStyles flags, ref GuidResult result)
+ private static bool TryParseGuid(string g, GuidStyles flags, ref GuidResult result)
{
if (g == null)
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
- String guidString = g.Trim(); //Remove Whitespace
+ string guidString = g.Trim(); //Remove Whitespace
if (guidString.Length == 0)
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
@@ -429,7 +423,7 @@ namespace System
if ((flags & (GuidStyles.AllowDashes | GuidStyles.RequireDashes)) == 0)
{
// dashes are not allowed
- result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
}
@@ -438,7 +432,7 @@ namespace System
if ((flags & GuidStyles.RequireDashes) != 0)
{
// dashes are required
- result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
}
@@ -451,7 +445,7 @@ namespace System
if ((flags & (GuidStyles.AllowBraces | GuidStyles.RequireBraces)) == 0)
{
// braces are not allowed
- result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
}
@@ -460,7 +454,7 @@ namespace System
if ((flags & GuidStyles.RequireBraces) != 0)
{
// braces are required
- result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
}
@@ -473,7 +467,7 @@ namespace System
if ((flags & (GuidStyles.AllowParenthesis | GuidStyles.RequireParenthesis)) == 0)
{
// parenthesis are not allowed
- result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
}
@@ -482,7 +476,7 @@ namespace System
if ((flags & GuidStyles.RequireParenthesis) != 0)
{
// parenthesis are required
- result.SetFailure(ParseFailureKind.Format, "Format_GuidUnrecognized");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidUnrecognized));
return false;
}
}
@@ -508,19 +502,18 @@ namespace System
}
catch (IndexOutOfRangeException ex)
{
- result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex);
+ result.SetFailure(ParseFailureKind.FormatWithInnerException, nameof(SR.Format_GuidUnrecognized), null, null, ex);
return false;
}
catch (ArgumentException ex)
{
- result.SetFailure(ParseFailureKind.FormatWithInnerException, "Format_GuidUnrecognized", null, null, ex);
+ result.SetFailure(ParseFailureKind.FormatWithInnerException, nameof(SR.Format_GuidUnrecognized), null, null, ex);
return false;
}
}
-
// Check if it's of the form {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
- private static bool TryParseGuidWithHexPrefix(String guidString, ref GuidResult result)
+ private static bool TryParseGuidWithHexPrefix(string guidString, ref GuidResult result)
{
int numStart = 0;
int numLen = 0;
@@ -529,16 +522,16 @@ namespace System
guidString = EatAllWhitespace(guidString);
// Check for leading '{'
- if (String.IsNullOrEmpty(guidString) || guidString[0] != '{')
+ if (string.IsNullOrEmpty(guidString) || guidString[0] != '{')
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidBrace));
return false;
}
// Check for '0x'
if (!IsHexPrefix(guidString, 1))
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, etc}");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, etc}");
return false;
}
@@ -547,18 +540,17 @@ namespace System
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma));
return false;
}
-
- if (!StringToInt(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result))
+ if (!StringToInt(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._a, ref result))
return false;
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, etc}");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
@@ -566,17 +558,17 @@ namespace System
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma));
return false;
}
// Read in the number
- if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result))
+ if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._b, ref result))
return false;
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{0xdddddddd, 0xdddd, 0xdddd, etc}");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{0xdddddddd, 0xdddd, 0xdddd, etc}");
return false;
}
// +3 to get by ',0x'
@@ -584,18 +576,18 @@ namespace System
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma));
return false;
}
// Read in the number
- if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result))
+ if (!StringToShort(guidString.Substring(numStart, numLen) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._c, ref result))
return false;
// Check for '{'
if (guidString.Length <= numStart + numLen + 1 || guidString[numStart + numLen + 1] != '{')
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidBrace");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidBrace));
return false;
}
@@ -608,7 +600,7 @@ namespace System
// Check for '0x'
if (!IsHexPrefix(guidString, numStart + numLen + 1))
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidHexPrefix", "{... { ... 0xdd, ...}}");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidHexPrefix), "{... { ... 0xdd, ...}}");
return false;
}
@@ -621,7 +613,7 @@ namespace System
numLen = guidString.IndexOf(',', numStart) - numStart;
if (numLen <= 0)
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidComma");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidComma));
return false;
}
}
@@ -630,7 +622,7 @@ namespace System
numLen = guidString.IndexOf('}', numStart) - numStart;
if (numLen <= 0)
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidBraceAfterLastNumber");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidBraceAfterLastNumber));
return false;
}
}
@@ -646,32 +638,32 @@ namespace System
// check for overflow
if (number > 255)
{
- result.SetFailure(ParseFailureKind.Format, "Overflow_Byte");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Overflow_Byte));
return false;
}
bytes[i] = (byte)number;
}
- result.parsedGuid._d = bytes[0];
- result.parsedGuid._e = bytes[1];
- result.parsedGuid._f = bytes[2];
- result.parsedGuid._g = bytes[3];
- result.parsedGuid._h = bytes[4];
- result.parsedGuid._i = bytes[5];
- result.parsedGuid._j = bytes[6];
- result.parsedGuid._k = bytes[7];
+ result._parsedGuid._d = bytes[0];
+ result._parsedGuid._e = bytes[1];
+ result._parsedGuid._f = bytes[2];
+ result._parsedGuid._g = bytes[3];
+ result._parsedGuid._h = bytes[4];
+ result._parsedGuid._i = bytes[5];
+ result._parsedGuid._j = bytes[6];
+ result._parsedGuid._k = bytes[7];
// Check for last '}'
if (numStart + numLen + 1 >= guidString.Length || guidString[numStart + numLen + 1] != '}')
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidEndBrace");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidEndBrace));
return false;
}
// Check if we have extra characters at the end
if (numStart + numLen + 1 != guidString.Length - 1)
{
- result.SetFailure(ParseFailureKind.Format, "Format_ExtraJunkAtEnd");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_ExtraJunkAtEnd));
return false;
}
@@ -679,7 +671,7 @@ namespace System
}
// Check if it's of the form dddddddddddddddddddddddddddddddd
- private static bool TryParseGuidWithNoStyle(String guidString, ref GuidResult result)
+ private static bool TryParseGuidWithNoStyle(string guidString, ref GuidResult result)
{
int startPos = 0;
int temp;
@@ -688,7 +680,7 @@ namespace System
if (guidString.Length != 32)
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen));
return false;
}
@@ -701,26 +693,26 @@ namespace System
}
else
{
- char upperCaseCh = Char.ToUpperInvariant(ch);
+ char upperCaseCh = char.ToUpperInvariant(ch);
if (upperCaseCh >= 'A' && upperCaseCh <= 'F')
{
continue;
}
}
- result.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvalidChar));
return false;
}
- if (!StringToInt(guidString.Substring(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result.parsedGuid._a, ref result))
+ if (!StringToInt(guidString.Substring(startPos, 8) /*first DWORD*/, -1, ParseNumbers.IsTight, out result._parsedGuid._a, ref result))
return false;
startPos += 8;
- if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._b, ref result))
+ if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result._parsedGuid._b, ref result))
return false;
startPos += 4;
- if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result.parsedGuid._c, ref result))
+ if (!StringToShort(guidString.Substring(startPos, 4), -1, ParseNumbers.IsTight, out result._parsedGuid._c, ref result))
return false;
startPos += 4;
@@ -735,27 +727,26 @@ namespace System
if (currentPos - startPos != 12)
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen));
return false;
}
- result.parsedGuid._d = (byte)(temp >> 8);
- result.parsedGuid._e = (byte)(temp);
+ result._parsedGuid._d = (byte)(temp >> 8);
+ result._parsedGuid._e = (byte)(temp);
temp = (int)(templ >> 32);
- result.parsedGuid._f = (byte)(temp >> 8);
- result.parsedGuid._g = (byte)(temp);
+ result._parsedGuid._f = (byte)(temp >> 8);
+ result._parsedGuid._g = (byte)(temp);
temp = (int)(templ);
- result.parsedGuid._h = (byte)(temp >> 24);
- result.parsedGuid._i = (byte)(temp >> 16);
- result.parsedGuid._j = (byte)(temp >> 8);
- result.parsedGuid._k = (byte)(temp);
+ result._parsedGuid._h = (byte)(temp >> 24);
+ result._parsedGuid._i = (byte)(temp >> 16);
+ result._parsedGuid._j = (byte)(temp >> 8);
+ result._parsedGuid._k = (byte)(temp);
return true;
}
-
// Check if it's of the form [{|(]dddddddd-dddd-dddd-dddd-dddddddddddd[}|)]
- private static bool TryParseGuidWithDashes(String guidString, ref GuidResult result)
+ private static bool TryParseGuidWithDashes(string guidString, ref GuidResult result)
{
int startPos = 0;
int temp;
@@ -767,7 +758,7 @@ namespace System
{
if (guidString.Length != 38 || guidString[37] != '}')
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen));
return false;
}
startPos = 1;
@@ -776,14 +767,14 @@ namespace System
{
if (guidString.Length != 38 || guidString[37] != ')')
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen));
return false;
}
startPos = 1;
}
else if (guidString.Length != 36)
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen));
return false;
}
@@ -792,24 +783,24 @@ namespace System
guidString[18 + startPos] != '-' ||
guidString[23 + startPos] != '-')
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidDashes");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidDashes));
return false;
}
currentPos = startPos;
if (!StringToInt(guidString, ref currentPos, 8, ParseNumbers.NoSpace, out temp, ref result))
return false;
- result.parsedGuid._a = temp;
+ result._parsedGuid._a = temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
- result.parsedGuid._b = (short)temp;
+ result._parsedGuid._b = (short)temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
return false;
- result.parsedGuid._c = (short)temp;
+ result._parsedGuid._c = (short)temp;
++currentPos; //Increment past the '-';
if (!StringToInt(guidString, ref currentPos, 4, ParseNumbers.NoSpace, out temp, ref result))
@@ -822,67 +813,60 @@ namespace System
if (currentPos - startPos != 12)
{
- result.SetFailure(ParseFailureKind.Format, "Format_GuidInvLen");
+ result.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvLen));
return false;
}
- result.parsedGuid._d = (byte)(temp >> 8);
- result.parsedGuid._e = (byte)(temp);
+ result._parsedGuid._d = (byte)(temp >> 8);
+ result._parsedGuid._e = (byte)(temp);
temp = (int)(templ >> 32);
- result.parsedGuid._f = (byte)(temp >> 8);
- result.parsedGuid._g = (byte)(temp);
+ result._parsedGuid._f = (byte)(temp >> 8);
+ result._parsedGuid._g = (byte)(temp);
temp = (int)(templ);
- result.parsedGuid._h = (byte)(temp >> 24);
- result.parsedGuid._i = (byte)(temp >> 16);
- result.parsedGuid._j = (byte)(temp >> 8);
- result.parsedGuid._k = (byte)(temp);
+ result._parsedGuid._h = (byte)(temp >> 24);
+ result._parsedGuid._i = (byte)(temp >> 16);
+ result._parsedGuid._j = (byte)(temp >> 8);
+ result._parsedGuid._k = (byte)(temp);
return true;
}
-
- //
- // StringToShort, StringToInt, and StringToLong are wrappers around COMUtilNative integer parsing routines;
-
- private static unsafe bool StringToShort(String str, int requiredLength, int flags, out short result, ref GuidResult parseResult)
+ private static bool StringToShort(string str, int requiredLength, int flags, out short result, ref GuidResult parseResult)
{
- return StringToShort(str, null, requiredLength, flags, out result, ref parseResult);
+ int parsePos = 0;
+ return StringToShort(str, ref parsePos, requiredLength, flags, out result, ref parseResult);
}
- private static unsafe bool StringToShort(String str, int* parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult)
+
+ private static bool StringToShort(string str, ref int parsePos, int requiredLength, int flags, out short result, ref GuidResult parseResult)
{
result = 0;
int x;
- bool retValue = StringToInt(str, parsePos, requiredLength, flags, out x, ref parseResult);
+ bool retValue = StringToInt(str, ref parsePos, requiredLength, flags, out x, ref parseResult);
result = (short)x;
return retValue;
}
- private static unsafe bool StringToInt(String str, int requiredLength, int flags, out int result, ref GuidResult parseResult)
+ private static bool StringToInt(string str, int requiredLength, int flags, out int result, ref GuidResult parseResult)
{
- return StringToInt(str, null, requiredLength, flags, out result, ref parseResult);
- }
- private static unsafe bool StringToInt(String str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult)
- {
- fixed (int* ppos = &parsePos)
- {
- return StringToInt(str, ppos, requiredLength, flags, out result, ref parseResult);
- }
+ int parsePos = 0;
+ return StringToInt(str, ref parsePos, requiredLength, flags, out result, ref parseResult);
}
- private static unsafe bool StringToInt(String str, int* parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult)
+
+ private static bool StringToInt(string str, ref int parsePos, int requiredLength, int flags, out int result, ref GuidResult parseResult)
{
result = 0;
- int currStart = (parsePos == null) ? 0 : (*parsePos);
+ int currStart = parsePos;
try
{
- result = ParseNumbers.StringToInt(str, 16, flags, parsePos);
+ result = ParseNumbers.StringToInt(str, 16, flags, ref parsePos);
}
catch (OverflowException ex)
{
- if (parseResult.throwStyle == GuidParseThrowStyle.All)
+ if (parseResult._throwStyle == GuidParseThrowStyle.All)
{
throw;
}
- else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow)
+ else if (parseResult._throwStyle == GuidParseThrowStyle.AllButOverflow)
{
throw new FormatException(SR.Format_GuidUnrecognized, ex);
}
@@ -894,7 +878,7 @@ namespace System
}
catch (Exception ex)
{
- if (parseResult.throwStyle == GuidParseThrowStyle.None)
+ if (parseResult._throwStyle == GuidParseThrowStyle.None)
{
parseResult.SetFailure(ex);
return false;
@@ -906,35 +890,29 @@ namespace System
}
//If we didn't parse enough characters, there's clearly an error.
- if (requiredLength != -1 && parsePos != null && (*parsePos) - currStart != requiredLength)
+ if (requiredLength != -1 && parsePos - currStart != requiredLength)
{
- parseResult.SetFailure(ParseFailureKind.Format, "Format_GuidInvalidChar");
+ parseResult.SetFailure(ParseFailureKind.Format, nameof(SR.Format_GuidInvalidChar));
return false;
}
return true;
}
- private static unsafe bool StringToLong(String str, ref int parsePos, int flags, out long result, ref GuidResult parseResult)
- {
- fixed (int* ppos = &parsePos)
- {
- return StringToLong(str, ppos, flags, out result, ref parseResult);
- }
- }
- private static unsafe bool StringToLong(String str, int* parsePos, int flags, out long result, ref GuidResult parseResult)
+
+ private static unsafe bool StringToLong(string str, ref int parsePos, int flags, out long result, ref GuidResult parseResult)
{
result = 0;
try
{
- result = ParseNumbers.StringToLong(str, 16, flags, parsePos);
+ result = ParseNumbers.StringToLong(str, 16, flags, ref parsePos);
}
catch (OverflowException ex)
{
- if (parseResult.throwStyle == GuidParseThrowStyle.All)
+ if (parseResult._throwStyle == GuidParseThrowStyle.All)
{
throw;
}
- else if (parseResult.throwStyle == GuidParseThrowStyle.AllButOverflow)
+ else if (parseResult._throwStyle == GuidParseThrowStyle.AllButOverflow)
{
throw new FormatException(SR.Format_GuidUnrecognized, ex);
}
@@ -946,7 +924,7 @@ namespace System
}
catch (Exception ex)
{
- if (parseResult.throwStyle == GuidParseThrowStyle.None)
+ if (parseResult._throwStyle == GuidParseThrowStyle.None)
{
parseResult.SetFailure(ex);
return false;
@@ -959,8 +937,7 @@ namespace System
return true;
}
-
- private static String EatAllWhitespace(String str)
+ private static string EatAllWhitespace(string str)
{
int newLength = 0;
char[] chArr = new char[str.Length];
@@ -970,67 +947,78 @@ namespace System
for (int i = 0; i < str.Length; i++)
{
curChar = str[i];
- if (!Char.IsWhiteSpace(curChar))
+ if (!char.IsWhiteSpace(curChar))
{
chArr[newLength++] = curChar;
}
}
// Return a new string based on chArr
- return new String(chArr, 0, newLength);
+ return new string(chArr, 0, newLength);
}
- private static bool IsHexPrefix(String str, int i)
+ private static bool IsHexPrefix(string str, int i)
{
- if (str.Length > i + 1 && str[i] == '0' && (Char.ToLowerInvariant(str[i + 1]) == 'x'))
+ if (str.Length > i + 1 && str[i] == '0' && (char.ToLowerInvariant(str[i + 1]) == 'x'))
return true;
else
return false;
}
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private void WriteByteHelper(Span<byte> destination)
+ {
+ destination[0] = (byte)(_a);
+ destination[1] = (byte)(_a >> 8);
+ destination[2] = (byte)(_a >> 16);
+ destination[3] = (byte)(_a >> 24);
+ destination[4] = (byte)(_b);
+ destination[5] = (byte)(_b >> 8);
+ destination[6] = (byte)(_c);
+ destination[7] = (byte)(_c >> 8);
+ destination[8] = _d;
+ destination[9] = _e;
+ destination[10] = _f;
+ destination[11] = _g;
+ destination[12] = _h;
+ destination[13] = _i;
+ destination[14] = _j;
+ destination[15] = _k;
+ }
// Returns an unsigned byte array containing the GUID.
public byte[] ToByteArray()
{
- byte[] g = new byte[16];
-
- g[0] = (byte)(_a);
- g[1] = (byte)(_a >> 8);
- g[2] = (byte)(_a >> 16);
- g[3] = (byte)(_a >> 24);
- g[4] = (byte)(_b);
- g[5] = (byte)(_b >> 8);
- g[6] = (byte)(_c);
- g[7] = (byte)(_c >> 8);
- g[8] = _d;
- g[9] = _e;
- g[10] = _f;
- g[11] = _g;
- g[12] = _h;
- g[13] = _i;
- g[14] = _j;
- g[15] = _k;
-
+ var g = new byte[16];
+ WriteByteHelper(g);
return g;
}
+ // Returns whether bytes are sucessfully written to given span.
+ public bool TryWriteBytes(Span<byte> destination)
+ {
+ if (destination.Length < 16)
+ return false;
+
+ WriteByteHelper(destination);
+ return true;
+ }
// Returns the guid in "registry" format.
- public override String ToString()
+ public override string ToString()
{
return ToString("D", null);
}
- public unsafe override int GetHashCode()
+ public override int GetHashCode()
{
// Simply XOR all the bits of the GUID 32 bits at a time.
- fixed (int* ptr = &_a)
- return ptr[0] ^ ptr[1] ^ ptr[2] ^ ptr[3];
+ return _a ^ Unsafe.Add(ref _a, 1) ^ Unsafe.Add(ref _a, 2) ^ Unsafe.Add(ref _a, 3);
}
// Returns true if and only if the guid represented
// by o is the same as this instance.
- public override bool Equals(Object o)
+ public override bool Equals(object o)
{
Guid g;
// Check that o is a Guid first
@@ -1039,59 +1027,19 @@ namespace System
else g = (Guid)o;
// Now compare each of the elements
- if (g._a != _a)
- return false;
- if (g._b != _b)
- return false;
- if (g._c != _c)
- return false;
- if (g._d != _d)
- return false;
- if (g._e != _e)
- return false;
- if (g._f != _f)
- return false;
- if (g._g != _g)
- return false;
- if (g._h != _h)
- return false;
- if (g._i != _i)
- return false;
- if (g._j != _j)
- return false;
- if (g._k != _k)
- return false;
-
- return true;
+ return g._a == _a &&
+ Unsafe.Add(ref g._a, 1) == Unsafe.Add(ref _a, 1) &&
+ Unsafe.Add(ref g._a, 2) == Unsafe.Add(ref _a, 2) &&
+ Unsafe.Add(ref g._a, 3) == Unsafe.Add(ref _a, 3);
}
public bool Equals(Guid g)
{
// Now compare each of the elements
- if (g._a != _a)
- return false;
- if (g._b != _b)
- return false;
- if (g._c != _c)
- return false;
- if (g._d != _d)
- return false;
- if (g._e != _e)
- return false;
- if (g._f != _f)
- return false;
- if (g._g != _g)
- return false;
- if (g._h != _h)
- return false;
- if (g._i != _i)
- return false;
- if (g._j != _j)
- return false;
- if (g._k != _k)
- return false;
-
- return true;
+ return g._a == _a &&
+ Unsafe.Add(ref g._a, 1) == Unsafe.Add(ref _a, 1) &&
+ Unsafe.Add(ref g._a, 2) == Unsafe.Add(ref _a, 2) &&
+ Unsafe.Add(ref g._a, 3) == Unsafe.Add(ref _a, 3);
}
private int GetResult(uint me, uint them)
@@ -1103,7 +1051,7 @@ namespace System
return 1;
}
- public int CompareTo(Object value)
+ public int CompareTo(object value)
{
if (value == null)
{
@@ -1132,42 +1080,42 @@ namespace System
if (g._d != _d)
{
- return GetResult((uint)_d, (uint)g._d);
+ return GetResult(_d, g._d);
}
if (g._e != _e)
{
- return GetResult((uint)_e, (uint)g._e);
+ return GetResult(_e, g._e);
}
if (g._f != _f)
{
- return GetResult((uint)_f, (uint)g._f);
+ return GetResult(_f, g._f);
}
if (g._g != _g)
{
- return GetResult((uint)_g, (uint)g._g);
+ return GetResult(_g, g._g);
}
if (g._h != _h)
{
- return GetResult((uint)_h, (uint)g._h);
+ return GetResult(_h, g._h);
}
if (g._i != _i)
{
- return GetResult((uint)_i, (uint)g._i);
+ return GetResult(_i, g._i);
}
if (g._j != _j)
{
- return GetResult((uint)_j, (uint)g._j);
+ return GetResult(_j, g._j);
}
if (g._k != _k)
{
- return GetResult((uint)_k, (uint)g._k);
+ return GetResult(_k, g._k);
}
return 0;
@@ -1192,42 +1140,42 @@ namespace System
if (value._d != _d)
{
- return GetResult((uint)_d, (uint)value._d);
+ return GetResult(_d, value._d);
}
if (value._e != _e)
{
- return GetResult((uint)_e, (uint)value._e);
+ return GetResult(_e, value._e);
}
if (value._f != _f)
{
- return GetResult((uint)_f, (uint)value._f);
+ return GetResult(_f, value._f);
}
if (value._g != _g)
{
- return GetResult((uint)_g, (uint)value._g);
+ return GetResult(_g, value._g);
}
if (value._h != _h)
{
- return GetResult((uint)_h, (uint)value._h);
+ return GetResult(_h, value._h);
}
if (value._i != _i)
{
- return GetResult((uint)_i, (uint)value._i);
+ return GetResult(_i, value._i);
}
if (value._j != _j)
{
- return GetResult((uint)_j, (uint)value._j);
+ return GetResult(_j, value._j);
}
if (value._k != _k)
{
- return GetResult((uint)_k, (uint)value._k);
+ return GetResult(_k, value._k);
}
return 0;
@@ -1236,52 +1184,22 @@ namespace System
public static bool operator ==(Guid a, Guid b)
{
// Now compare each of the elements
- if (a._a != b._a)
- return false;
- if (a._b != b._b)
- return false;
- if (a._c != b._c)
- return false;
- if (a._d != b._d)
- return false;
- if (a._e != b._e)
- return false;
- if (a._f != b._f)
- return false;
- if (a._g != b._g)
- return false;
- if (a._h != b._h)
- return false;
- if (a._i != b._i)
- return false;
- if (a._j != b._j)
- return false;
- if (a._k != b._k)
- return false;
-
- return true;
+ return a._a == b._a &&
+ Unsafe.Add(ref a._a, 1) == Unsafe.Add(ref b._a, 1) &&
+ Unsafe.Add(ref a._a, 2) == Unsafe.Add(ref b._a, 2) &&
+ Unsafe.Add(ref a._a, 3) == Unsafe.Add(ref b._a, 3);
}
public static bool operator !=(Guid a, Guid b)
{
- return !(a == b);
- }
-
- // This will create a new guid. Since we've now decided that constructors should 0-init,
- // we need a method that allows users to create a guid.
- public static Guid NewGuid()
- {
- // CoCreateGuid should never return Guid.Empty, since it attempts to maintain some
- // uniqueness guarantees. It should also never return a known GUID, but it's unclear
- // how extensively it checks for known values.
- Contract.Ensures(Contract.Result<Guid>() != Guid.Empty);
-
- Guid guid;
- Marshal.ThrowExceptionForHR(Win32Native.CoCreateGuid(out guid), new IntPtr(-1));
- return guid;
+ // Now compare each of the elements
+ return a._a != b._a ||
+ Unsafe.Add(ref a._a, 1) != Unsafe.Add(ref b._a, 1) ||
+ Unsafe.Add(ref a._a, 2) != Unsafe.Add(ref b._a, 2) ||
+ Unsafe.Add(ref a._a, 3) != Unsafe.Add(ref b._a, 3);
}
- public String ToString(String format)
+ public string ToString(string format)
{
return ToString(format, null);
}
@@ -1324,124 +1242,168 @@ namespace System
// IFormattable interface
// We currently ignore provider
- public String ToString(String format, IFormatProvider provider)
+ public string ToString(string format, IFormatProvider provider)
{
if (format == null || format.Length == 0)
format = "D";
- string guidString;
- int offset = 0;
- bool dash = true;
- bool hex = false;
-
+ // all acceptable format strings are of length 1
if (format.Length != 1)
- {
- // all acceptable format strings are of length 1
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
- }
- char formatCh = format[0];
- if (formatCh == 'D' || formatCh == 'd')
- {
- guidString = string.FastAllocateString(36);
- }
- else if (formatCh == 'N' || formatCh == 'n')
- {
- guidString = string.FastAllocateString(32);
- dash = false;
- }
- else if (formatCh == 'B' || formatCh == 'b')
- {
- guidString = string.FastAllocateString(38);
- unsafe
- {
- fixed (char* guidChars = guidString)
- {
- guidChars[offset++] = '{';
- guidChars[37] = '}';
- }
- }
- }
- else if (formatCh == 'P' || formatCh == 'p')
- {
- guidString = string.FastAllocateString(38);
- unsafe
- {
- fixed (char* guidChars = guidString)
- {
- guidChars[offset++] = '(';
- guidChars[37] = ')';
- }
- }
- }
- else if (formatCh == 'X' || formatCh == 'x')
- {
- guidString = string.FastAllocateString(68);
- unsafe
- {
- fixed (char* guidChars = guidString)
- {
- guidChars[offset++] = '{';
- guidChars[67] = '}';
- }
- }
- dash = false;
- hex = true;
- }
- else
- {
+ int guidSize;
+ switch (format[0])
+ {
+ case 'D':
+ case 'd':
+ guidSize = 36;
+ break;
+ case 'N':
+ case 'n':
+ guidSize = 32;
+ break;
+ case 'B':
+ case 'b':
+ case 'P':
+ case 'p':
+ guidSize = 38;
+ break;
+ case 'X':
+ case 'x':
+ guidSize = 68;
+ break;
+ default:
+ throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
+ }
+
+ string guidString = string.FastAllocateString(guidSize);
+
+ int bytesWritten;
+ bool result = TryFormat(new Span<char>(ref guidString.GetRawStringData(), guidString.Length), out bytesWritten, format);
+ Debug.Assert(result && bytesWritten == guidString.Length, "Formatting guid should have succeeded.");
+
+ return guidString;
+ }
+
+ // Returns whether the guid is successfully formatted as a span.
+ public bool TryFormat(Span<char> destination, out int charsWritten, string format = null)
+ {
+ if (format == null || format.Length == 0)
+ format = "D";
+
+ // all acceptable format strings are of length 1
+ if (format.Length != 1)
throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
+
+ bool dash = true;
+ bool hex = false;
+ int braces = 0;
+
+ int guidSize;
+
+ switch (format[0])
+ {
+ case 'D':
+ case 'd':
+ guidSize = 36;
+ break;
+ case 'N':
+ case 'n':
+ dash = false;
+ guidSize = 32;
+ break;
+ case 'B':
+ case 'b':
+ braces = '{' + ('}' << 16);
+ guidSize = 38;
+ break;
+ case 'P':
+ case 'p':
+ braces = '(' + (')' << 16);
+ guidSize = 38;
+ break;
+ case 'X':
+ case 'x':
+ braces = '{' + ('}' << 16);
+ dash = false;
+ hex = true;
+ guidSize = 68;
+ break;
+ default:
+ throw new FormatException(SR.Format_InvalidGuidFormatSpecification);
+ }
+
+ if (destination.Length < guidSize)
+ {
+ charsWritten = 0;
+ return false;
}
unsafe
{
- fixed (char* guidChars = guidString)
+ fixed (char* guidChars = &destination.DangerousGetPinnableReference())
{
+ char * p = guidChars;
+
+ if (braces != 0)
+ *p++ = (char)braces;
+
if (hex)
{
// {0xdddddddd,0xdddd,0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
- guidChars[offset++] = '0';
- guidChars[offset++] = 'x';
- offset += HexsToChars(guidChars + offset, _a >> 24, _a >> 16);
- offset += HexsToChars(guidChars + offset, _a >> 8, _a);
- guidChars[offset++] = ',';
- guidChars[offset++] = '0';
- guidChars[offset++] = 'x';
- offset += HexsToChars(guidChars + offset, _b >> 8, _b);
- guidChars[offset++] = ',';
- guidChars[offset++] = '0';
- guidChars[offset++] = 'x';
- offset += HexsToChars(guidChars + offset, _c >> 8, _c);
- guidChars[offset++] = ',';
- guidChars[offset++] = '{';
- offset += HexsToCharsHexOutput(guidChars + offset, _d, _e);
- guidChars[offset++] = ',';
- offset += HexsToCharsHexOutput(guidChars + offset, _f, _g);
- guidChars[offset++] = ',';
- offset += HexsToCharsHexOutput(guidChars + offset, _h, _i);
- guidChars[offset++] = ',';
- offset += HexsToCharsHexOutput(guidChars + offset, _j, _k);
- guidChars[offset++] = '}';
+ *p++ = '0';
+ *p++ = 'x';
+ p += HexsToChars(p, _a >> 24, _a >> 16);
+ p += HexsToChars(p, _a >> 8, _a);
+ *p++ = ',';
+ *p++ = '0';
+ *p++ = 'x';
+ p += HexsToChars(p, _b >> 8, _b);
+ *p++ = ',';
+ *p++ = '0';
+ *p++ = 'x';
+ p += HexsToChars(p, _c >> 8, _c);
+ *p++ = ',';
+ *p++ = '{';
+ p += HexsToCharsHexOutput(p, _d, _e);
+ *p++ = ',';
+ p += HexsToCharsHexOutput(p, _f, _g);
+ *p++ = ',';
+ p += HexsToCharsHexOutput(p, _h, _i);
+ *p++ = ',';
+ p += HexsToCharsHexOutput(p, _j, _k);
+ *p++ = '}';
}
else
{
// [{|(]dddddddd[-]dddd[-]dddd[-]dddd[-]dddddddddddd[}|)]
- offset += HexsToChars(guidChars + offset, _a >> 24, _a >> 16);
- offset += HexsToChars(guidChars + offset, _a >> 8, _a);
- if (dash) guidChars[offset++] = '-';
- offset += HexsToChars(guidChars + offset, _b >> 8, _b);
- if (dash) guidChars[offset++] = '-';
- offset += HexsToChars(guidChars + offset, _c >> 8, _c);
- if (dash) guidChars[offset++] = '-';
- offset += HexsToChars(guidChars + offset, _d, _e);
- if (dash) guidChars[offset++] = '-';
- offset += HexsToChars(guidChars + offset, _f, _g);
- offset += HexsToChars(guidChars + offset, _h, _i);
- offset += HexsToChars(guidChars + offset, _j, _k);
+ p += HexsToChars(p, _a >> 24, _a >> 16);
+ p += HexsToChars(p, _a >> 8, _a);
+ if (dash)
+ *p++ = '-';
+ p += HexsToChars(p, _b >> 8, _b);
+ if (dash)
+ *p++ = '-';
+ p += HexsToChars(p, _c >> 8, _c);
+ if (dash)
+ *p++ = '-';
+ p += HexsToChars(p, _d, _e);
+ if (dash)
+ *p++ = '-';
+ p += HexsToChars(p, _f, _g);
+ p += HexsToChars(p, _h, _i);
+ p += HexsToChars(p, _j, _k);
}
+
+ if (braces != 0)
+ *p++ = (char)(braces >> 16);
+
+ Debug.Assert(p - guidChars == guidSize);
}
}
- return guidString;
+
+ charsWritten = guidSize;
+ return true;
}
}
}
diff --git a/src/mscorlib/src/System/__HResults.cs b/src/mscorlib/shared/System/HResults.cs
index 0592d814ef..ffc47d85bf 100644
--- a/src/mscorlib/src/System/__HResults.cs
+++ b/src/mscorlib/shared/System/HResults.cs
@@ -15,27 +15,17 @@
// HResults. Also note that some of our HResults have to map to certain
// COM HR's, etc.
-// Another arbitrary decision... Feel free to change this, as long as you
-// renumber the HResults yourself (and update rexcep.h).
// Reflection will use 0x1600 -> 0x161f. IO will use 0x1620 -> 0x163f.
// Security will use 0x1640 -> 0x165f
-// There are __HResults files in the IO, Remoting, Reflection &
-// Security/Util directories as well, so choose your HResults carefully.
using System;
namespace System
{
- internal static class __HResults
+ internal static partial class HResults
{
- internal const int RO_E_CLOSED = unchecked((int)0x80000013);
- internal const int E_BOUNDS = unchecked((int)0x8000000B);
- internal const int E_CHANGED_STATE = unchecked((int)0x8000000C);
- internal const int E_FAIL = unchecked((int)0x80004005);
- internal const int E_POINTER = unchecked((int)0x80004003);
- internal const int E_NOTIMPL = unchecked((int)0x80004001);
- internal const int REGDB_E_CLASSNOTREG = unchecked((int)0x80040154);
+ internal const int COR_E_ABANDONEDMUTEX = unchecked((int)0x8013152D);
internal const int COR_E_AMBIGUOUSMATCH = unchecked((int)0x8000211D);
internal const int COR_E_APPDOMAINUNLOADED = unchecked((int)0x80131014);
internal const int COR_E_APPLICATION = unchecked((int)0x80131600);
@@ -43,30 +33,36 @@ namespace System
internal const int COR_E_ARGUMENTOUTOFRANGE = unchecked((int)0x80131502);
internal const int COR_E_ARITHMETIC = unchecked((int)0x80070216);
internal const int COR_E_ARRAYTYPEMISMATCH = unchecked((int)0x80131503);
- internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000B);
internal const int COR_E_BADEXEFORMAT = unchecked((int)0x800700C1);
- internal const int COR_E_TYPEUNLOADED = unchecked((int)0x80131013);
+ internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000B);
internal const int COR_E_CANNOTUNLOADAPPDOMAIN = unchecked((int)0x80131015);
internal const int COR_E_COMEMULATE = unchecked((int)0x80131535);
internal const int COR_E_CONTEXTMARSHAL = unchecked((int)0x80131504);
- internal const int COR_E_DATAMISALIGNED = unchecked((int)0x80131541);
- internal const int COR_E_TIMEOUT = unchecked((int)0x80131505);
internal const int COR_E_CUSTOMATTRIBUTEFORMAT = unchecked((int)0x80131605);
+ internal const int COR_E_DATAMISALIGNED = unchecked((int)0x80131541);
+ internal const int COR_E_DIRECTORYNOTFOUND = unchecked((int)0x80070003);
internal const int COR_E_DIVIDEBYZERO = unchecked((int)0x80020012); // DISP_E_DIVBYZERO
+ internal const int COR_E_DLLNOTFOUND = unchecked((int)0x80131524);
internal const int COR_E_DUPLICATEWAITOBJECT = unchecked((int)0x80131529);
+ internal const int COR_E_ENDOFSTREAM = unchecked((int)0x80070026); // OS defined
+ internal const int COR_E_ENTRYPOINTNOTFOUND = unchecked((int)0x80131523);
internal const int COR_E_EXCEPTION = unchecked((int)0x80131500);
internal const int COR_E_EXECUTIONENGINE = unchecked((int)0x80131506);
internal const int COR_E_FIELDACCESS = unchecked((int)0x80131507);
+ internal const int COR_E_FILELOAD = unchecked((int)0x80131621);
+ internal const int COR_E_FILENOTFOUND = unchecked((int)0x80070002);
internal const int COR_E_FORMAT = unchecked((int)0x80131537);
+ internal const int COR_E_HOSTPROTECTION = unchecked((int)0x80131640);
internal const int COR_E_INDEXOUTOFRANGE = unchecked((int)0x80131508);
- internal const int COR_E_INSUFFICIENTMEMORY = unchecked((int)0x8013153D);
internal const int COR_E_INSUFFICIENTEXECUTIONSTACK = unchecked((int)0x80131578);
+ internal const int COR_E_INSUFFICIENTMEMORY = unchecked((int)0x8013153D);
internal const int COR_E_INVALIDCAST = unchecked((int)0x80004002);
internal const int COR_E_INVALIDCOMOBJECT = unchecked((int)0x80131527);
internal const int COR_E_INVALIDFILTERCRITERIA = unchecked((int)0x80131601);
internal const int COR_E_INVALIDOLEVARIANTTYPE = unchecked((int)0x80131531);
internal const int COR_E_INVALIDOPERATION = unchecked((int)0x80131509);
internal const int COR_E_INVALIDPROGRAM = unchecked((int)0x8013153A);
+ internal const int COR_E_IO = unchecked((int)0x80131620);
internal const int COR_E_KEYNOTFOUND = unchecked((int)0x80131577);
internal const int COR_E_MARSHALDIRECTIVE = unchecked((int)0x80131535);
internal const int COR_E_MEMBERACCESS = unchecked((int)0x8013151A);
@@ -78,13 +74,14 @@ namespace System
internal const int COR_E_MISSINGSATELLITEASSEMBLY = unchecked((int)0x80131536);
internal const int COR_E_MULTICASTNOTSUPPORTED = unchecked((int)0x80131514);
internal const int COR_E_NOTFINITENUMBER = unchecked((int)0x80131528);
- internal const int COR_E_PLATFORMNOTSUPPORTED = unchecked((int)0x80131539);
internal const int COR_E_NOTSUPPORTED = unchecked((int)0x80131515);
internal const int COR_E_NULLREFERENCE = unchecked((int)0x80004003);
internal const int COR_E_OBJECTDISPOSED = unchecked((int)0x80131622);
internal const int COR_E_OPERATIONCANCELED = unchecked((int)0x8013153B);
internal const int COR_E_OUTOFMEMORY = unchecked((int)0x8007000E);
internal const int COR_E_OVERFLOW = unchecked((int)0x80131516);
+ internal const int COR_E_PATHTOOLONG = unchecked((int)0x800700CE);
+ internal const int COR_E_PLATFORMNOTSUPPORTED = unchecked((int)0x80131539);
internal const int COR_E_RANK = unchecked((int)0x80131517);
internal const int COR_E_REFLECTIONTYPELOAD = unchecked((int)0x80131602);
internal const int COR_E_RUNTIMEWRAPPED = unchecked((int)0x8013153E);
@@ -92,40 +89,38 @@ namespace System
internal const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked((int)0x80131533);
internal const int COR_E_SAFEHANDLEMISSINGATTRIBUTE = unchecked((int)0x80131623);
internal const int COR_E_SECURITY = unchecked((int)0x8013150A);
- internal const int COR_E_SERIALIZATION = unchecked((int)0x8013150C);
internal const int COR_E_SEMAPHOREFULL = unchecked((int)0x8013152B);
- internal const int COR_E_WAITHANDLECANNOTBEOPENED = unchecked((int)0x8013152C);
- internal const int COR_E_ABANDONEDMUTEX = unchecked((int)0x8013152D);
+ internal const int COR_E_SERIALIZATION = unchecked((int)0x8013150C);
internal const int COR_E_STACKOVERFLOW = unchecked((int)0x800703E9);
internal const int COR_E_SYNCHRONIZATIONLOCK = unchecked((int)0x80131518);
internal const int COR_E_SYSTEM = unchecked((int)0x80131501);
internal const int COR_E_TARGET = unchecked((int)0x80131603);
internal const int COR_E_TARGETINVOCATION = unchecked((int)0x80131604);
- internal const int COR_E_TARGETPARAMCOUNT = unchecked((int)0x8002000e);
+ internal const int COR_E_TARGETPARAMCOUNT = unchecked((int)0x8002000E);
internal const int COR_E_THREADABORTED = unchecked((int)0x80131530);
internal const int COR_E_THREADINTERRUPTED = unchecked((int)0x80131519);
+ internal const int COR_E_THREADSTART = unchecked((int)0x80131525);
internal const int COR_E_THREADSTATE = unchecked((int)0x80131520);
internal const int COR_E_THREADSTOP = unchecked((int)0x80131521);
- internal const int COR_E_THREADSTART = unchecked((int)0x80131525);
+ internal const int COR_E_TIMEOUT = unchecked((int)0x80131505);
internal const int COR_E_TYPEACCESS = unchecked((int)0x80131543);
internal const int COR_E_TYPEINITIALIZATION = unchecked((int)0x80131534);
internal const int COR_E_TYPELOAD = unchecked((int)0x80131522);
- internal const int COR_E_ENTRYPOINTNOTFOUND = unchecked((int)0x80131523);
- internal const int COR_E_DLLNOTFOUND = unchecked((int)0x80131524);
+ internal const int COR_E_TYPEUNLOADED = unchecked((int)0x80131013);
internal const int COR_E_UNAUTHORIZEDACCESS = unchecked((int)0x80070005);
internal const int COR_E_UNSUPPORTEDFORMAT = unchecked((int)0x80131523);
internal const int COR_E_VERIFICATION = unchecked((int)0x8013150D);
- internal const int COR_E_HOSTPROTECTION = unchecked((int)0x80131640);
- internal const int CORSEC_E_MIN_GRANT_FAIL = unchecked((int)0x80131417);
- internal const int CORSEC_E_NO_EXEC_PERM = unchecked((int)0x80131418);
- internal const int CORSEC_E_POLICY_EXCEPTION = unchecked((int)0x80131416);
- internal const int CORSEC_E_XMLSYNTAX = unchecked((int)0x80131418);
- internal const int NTE_FAIL = unchecked((int)0x80090020);
- internal const int CORSEC_E_CRYPTO = unchecked((int)0x80131430);
- internal const int CORSEC_E_CRYPTO_UNEX_OPER = unchecked((int)0x80131431);
- internal const int DISP_E_OVERFLOW = unchecked((int)0x8002000a);
- internal const int FUSION_E_REF_DEF_MISMATCH = unchecked((int)0x80131040);
- internal const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047);
- internal const int TYPE_E_TYPEMISMATCH = unchecked((int)0x80028ca0);
+ internal const int COR_E_WAITHANDLECANNOTBEOPENED = unchecked((int)0x8013152C);
+ internal const int DISP_E_OVERFLOW = unchecked((int)0x8002000A);
+ internal const int E_BOUNDS = unchecked((int)0x8000000B);
+ internal const int E_CHANGED_STATE = unchecked((int)0x8000000C);
+ internal const int E_FAIL = unchecked((int)0x80004005);
+ internal const int E_HANDLE = unchecked((int)0x80070006);
+ internal const int E_INVALIDARG = unchecked((int)0x80070057);
+ internal const int E_NOTIMPL = unchecked((int)0x80004001);
+ internal const int E_POINTER = unchecked((int)0x80004003);
+ internal const int ERROR_MRM_MAP_NOT_FOUND = unchecked((int)0x80073B1F);
+ internal const int RO_E_CLOSED = unchecked((int)0x80000013);
+ internal const int TYPE_E_TYPEMISMATCH = unchecked((int)0x80028CA0);
}
}
diff --git a/src/mscorlib/shared/System/IO/BinaryWriter.cs b/src/mscorlib/shared/System/IO/BinaryWriter.cs
index 90b920854f..675e80922e 100644
--- a/src/mscorlib/shared/System/IO/BinaryWriter.cs
+++ b/src/mscorlib/shared/System/IO/BinaryWriter.cs
@@ -4,6 +4,7 @@
using System.Text;
using System.Diagnostics;
+using System.Buffers;
namespace System.IO
{
@@ -389,6 +390,41 @@ namespace System.IO
}
}
+ public virtual void Write(ReadOnlySpan<byte> value)
+ {
+ if (GetType() == typeof(BinaryWriter))
+ {
+ OutStream.Write(value);
+ }
+ else
+ {
+ byte[] buffer = ArrayPool<byte>.Shared.Rent(value.Length);
+ try
+ {
+ value.CopyTo(buffer);
+ Write(buffer, 0, value.Length);
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(buffer);
+ }
+ }
+ }
+
+ public virtual void Write(ReadOnlySpan<char> value)
+ {
+ byte[] bytes = ArrayPool<byte>.Shared.Rent(_encoding.GetMaxByteCount(value.Length));
+ try
+ {
+ int bytesWritten = _encoding.GetBytes(value, bytes);
+ Write(bytes, 0, bytesWritten);
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(bytes);
+ }
+ }
+
protected void Write7BitEncodedInt(int value)
{
// Write out an int 7 bits at a time. The high bit of the byte,
diff --git a/src/mscorlib/shared/System/IO/DirectoryNotFoundException.cs b/src/mscorlib/shared/System/IO/DirectoryNotFoundException.cs
index de09760fcb..87e610b86e 100644
--- a/src/mscorlib/shared/System/IO/DirectoryNotFoundException.cs
+++ b/src/mscorlib/shared/System/IO/DirectoryNotFoundException.cs
@@ -17,19 +17,19 @@ namespace System.IO
public DirectoryNotFoundException()
: base(SR.Arg_DirectoryNotFoundException)
{
- HResult = __HResults.COR_E_DIRECTORYNOTFOUND;
+ HResult = HResults.COR_E_DIRECTORYNOTFOUND;
}
public DirectoryNotFoundException(string message)
: base(message)
{
- HResult = __HResults.COR_E_DIRECTORYNOTFOUND;
+ HResult = HResults.COR_E_DIRECTORYNOTFOUND;
}
public DirectoryNotFoundException(string message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_DIRECTORYNOTFOUND;
+ HResult = HResults.COR_E_DIRECTORYNOTFOUND;
}
protected DirectoryNotFoundException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/IO/DisableMediaInsertionPrompt.cs b/src/mscorlib/shared/System/IO/DisableMediaInsertionPrompt.cs
new file mode 100644
index 0000000000..aa10e8d883
--- /dev/null
+++ b/src/mscorlib/shared/System/IO/DisableMediaInsertionPrompt.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.IO
+{
+ /// <summary>
+ /// Simple wrapper to safely disable the normal media insertion prompt for
+ /// removable media (floppies, cds, memory cards, etc.)
+ /// </summary>
+ /// <remarks>
+ /// Note that removable media file systems lazily load. After starting the OS
+ /// they won't be loaded until you have media in the drive- and as such the
+ /// prompt won't happen. You have to have had media in at least once to get
+ /// the file system to load and then have removed it.
+ /// </remarks>
+ internal struct DisableMediaInsertionPrompt : IDisposable
+ {
+ private bool _disableSuccess;
+ private uint _oldMode;
+
+ public static DisableMediaInsertionPrompt Create()
+ {
+ DisableMediaInsertionPrompt prompt = new DisableMediaInsertionPrompt();
+ prompt._disableSuccess = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out prompt._oldMode);
+ return prompt;
+ }
+
+ public void Dispose()
+ {
+ uint ignore;
+ if (_disableSuccess)
+ Interop.Kernel32.SetThreadErrorMode(_oldMode, out ignore);
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/IO/DriveNotFoundException.cs b/src/mscorlib/shared/System/IO/DriveNotFoundException.cs
index 7e9b0c9f36..c0f8c55af8 100644
--- a/src/mscorlib/src/System/IO/DriveNotFoundException.cs
+++ b/src/mscorlib/shared/System/IO/DriveNotFoundException.cs
@@ -2,33 +2,29 @@
// 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 for accessing a drive that is not available.
-//
-//
-//============================================================
-
-using System;
using System.Runtime.Serialization;
namespace System.IO
{
- //Thrown when trying to access a drive that is not availabe.
+ //Thrown when trying to access a drive that is not available.
internal class DriveNotFoundException : IOException
{
public DriveNotFoundException()
: base(SR.Arg_DriveNotFoundException)
{
- HResult = __HResults.COR_E_DIRECTORYNOTFOUND;
+ HResult = HResults.COR_E_DIRECTORYNOTFOUND;
}
- public DriveNotFoundException(String message)
+ public DriveNotFoundException(string message)
: base(message)
{
- HResult = __HResults.COR_E_DIRECTORYNOTFOUND;
+ HResult = HResults.COR_E_DIRECTORYNOTFOUND;
+ }
+
+ public DriveNotFoundException(string message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = HResults.COR_E_DIRECTORYNOTFOUND;
}
protected DriveNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/IO/EndOfStreamException.cs b/src/mscorlib/shared/System/IO/EndOfStreamException.cs
index 68e1b2c882..ee37818dc5 100644
--- a/src/mscorlib/shared/System/IO/EndOfStreamException.cs
+++ b/src/mscorlib/shared/System/IO/EndOfStreamException.cs
@@ -11,19 +11,19 @@ namespace System.IO
public EndOfStreamException()
: base(SR.Arg_EndOfStreamException)
{
- HResult = __HResults.COR_E_ENDOFSTREAM;
+ HResult = HResults.COR_E_ENDOFSTREAM;
}
public EndOfStreamException(string message)
: base(message)
{
- HResult = __HResults.COR_E_ENDOFSTREAM;
+ HResult = HResults.COR_E_ENDOFSTREAM;
}
public EndOfStreamException(string message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_ENDOFSTREAM;
+ HResult = HResults.COR_E_ENDOFSTREAM;
}
protected EndOfStreamException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/IO/FileLoadException.cs b/src/mscorlib/shared/System/IO/FileLoadException.cs
index 6fdf2d58cf..b126424c22 100644
--- a/src/mscorlib/shared/System/IO/FileLoadException.cs
+++ b/src/mscorlib/shared/System/IO/FileLoadException.cs
@@ -11,31 +11,31 @@ namespace System.IO
public FileLoadException()
: base(SR.IO_FileLoad)
{
- HResult = __HResults.COR_E_FILELOAD;
+ HResult = HResults.COR_E_FILELOAD;
}
public FileLoadException(string message)
: base(message)
{
- HResult = __HResults.COR_E_FILELOAD;
+ HResult = HResults.COR_E_FILELOAD;
}
public FileLoadException(string message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_FILELOAD;
+ HResult = HResults.COR_E_FILELOAD;
}
public FileLoadException(string message, string fileName) : base(message)
{
- HResult = __HResults.COR_E_FILELOAD;
+ HResult = HResults.COR_E_FILELOAD;
FileName = fileName;
}
public FileLoadException(string message, string fileName, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_FILELOAD;
+ HResult = HResults.COR_E_FILELOAD;
FileName = fileName;
}
diff --git a/src/mscorlib/shared/System/IO/FileNotFoundException.cs b/src/mscorlib/shared/System/IO/FileNotFoundException.cs
index 374c976055..dc1ccf577a 100644
--- a/src/mscorlib/shared/System/IO/FileNotFoundException.cs
+++ b/src/mscorlib/shared/System/IO/FileNotFoundException.cs
@@ -12,32 +12,32 @@ namespace System.IO
public FileNotFoundException()
: base(SR.IO_FileNotFound)
{
- HResult = __HResults.COR_E_FILENOTFOUND;
+ HResult = HResults.COR_E_FILENOTFOUND;
}
public FileNotFoundException(string message)
: base(message)
{
- HResult = __HResults.COR_E_FILENOTFOUND;
+ HResult = HResults.COR_E_FILENOTFOUND;
}
public FileNotFoundException(string message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_FILENOTFOUND;
+ HResult = HResults.COR_E_FILENOTFOUND;
}
public FileNotFoundException(string message, string fileName)
: base(message)
{
- HResult = __HResults.COR_E_FILENOTFOUND;
+ HResult = HResults.COR_E_FILENOTFOUND;
FileName = fileName;
}
public FileNotFoundException(string message, string fileName, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_FILENOTFOUND;
+ HResult = HResults.COR_E_FILENOTFOUND;
FileName = fileName;
}
@@ -55,7 +55,7 @@ namespace System.IO
if (_message == null)
{
if ((FileName == null) &&
- (HResult == System.__HResults.COR_E_EXCEPTION))
+ (HResult == System.HResults.COR_E_EXCEPTION))
_message = SR.IO_FileNotFound;
else if (FileName != null)
diff --git a/src/mscorlib/shared/System/IO/FileStream.Unix.cs b/src/mscorlib/shared/System/IO/FileStream.Unix.cs
index ad68a001cf..8499595361 100644
--- a/src/mscorlib/shared/System/IO/FileStream.Unix.cs
+++ b/src/mscorlib/shared/System/IO/FileStream.Unix.cs
@@ -286,13 +286,20 @@ namespace System.IO
}
}
+ private void FlushWriteBufferForWriteByte()
+ {
+ _asyncState?.Wait();
+ try { FlushWriteBuffer(); }
+ finally { _asyncState?.Release(); }
+ }
+
/// <summary>Writes any data in the write buffer to the underlying stream and resets the buffer.</summary>
private void FlushWriteBuffer()
{
AssertBufferInvariants();
if (_writePos > 0)
{
- WriteNative(GetBuffer(), 0, _writePos);
+ WriteNative(new ReadOnlySpan<byte>(GetBuffer(), 0, _writePos));
_writePos = 0;
}
}
@@ -375,44 +382,7 @@ namespace System.IO
}
/// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary>
- /// <param name="array">
- /// When this method returns, contains the specified byte array with the values between offset and
- /// (offset + count - 1) replaced by the bytes read from the current source.
- /// </param>
- /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param>
- /// <param name="count">The maximum number of bytes to read. </param>
- /// <returns>
- /// The total number of bytes read into the buffer. This might be less than the number of bytes requested
- /// if that number of bytes are not currently available, or zero if the end of the stream is reached.
- /// </returns>
- public override int Read(byte[] array, int offset, int count)
- {
- ValidateReadWriteArgs(array, offset, count);
-
- if (_useAsyncIO)
- {
- _asyncState.Wait();
- try { return ReadCore(array, offset, count); }
- finally { _asyncState.Release(); }
- }
- else
- {
- return ReadCore(array, offset, count);
- }
- }
-
- /// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary>
- /// <param name="array">
- /// When this method returns, contains the specified byte array with the values between offset and
- /// (offset + count - 1) replaced by the bytes read from the current source.
- /// </param>
- /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param>
- /// <param name="count">The maximum number of bytes to read. </param>
- /// <returns>
- /// The total number of bytes read into the buffer. This might be less than the number of bytes requested
- /// if that number of bytes are not currently available, or zero if the end of the stream is reached.
- /// </returns>
- private int ReadCore(byte[] array, int offset, int count)
+ private int ReadSpan(Span<byte> destination)
{
PrepareForReading();
@@ -429,16 +399,16 @@ namespace System.IO
// If we're not able to seek, then we're not able to rewind the stream (i.e. flushing
// a read buffer), in which case we don't want to use a read buffer. Similarly, if
// the user has asked for more data than we can buffer, we also want to skip the buffer.
- if (!CanSeek || (count >= _bufferLength))
+ if (!CanSeek || (destination.Length >= _bufferLength))
{
// Read directly into the user's buffer
_readPos = _readLength = 0;
- return ReadNative(array, offset, count);
+ return ReadNative(destination);
}
else
{
// Read into our buffer.
- _readLength = numBytesAvailable = ReadNative(GetBuffer(), 0, _bufferLength);
+ _readLength = numBytesAvailable = ReadNative(GetBuffer());
_readPos = 0;
if (numBytesAvailable == 0)
{
@@ -454,8 +424,8 @@ namespace System.IO
// Now that we know there's data in the buffer, read from it into the user's buffer.
Debug.Assert(numBytesAvailable > 0, "Data must be in the buffer to be here");
- int bytesRead = Math.Min(numBytesAvailable, count);
- Buffer.BlockCopy(GetBuffer(), _readPos, array, offset, bytesRead);
+ int bytesRead = Math.Min(numBytesAvailable, destination.Length);
+ new Span<byte>(GetBuffer(), _readPos, bytesRead).CopyTo(destination);
_readPos += bytesRead;
// We may not have had enough data in the buffer to completely satisfy the user's request.
@@ -466,38 +436,33 @@ namespace System.IO
// behavior, we do the same thing here on Unix. Note that we may still get less the requested
// amount, as the OS may give us back fewer than we request, either due to reaching the end of
// file, or due to its own whims.
- if (!readFromOS && bytesRead < count)
+ if (!readFromOS && bytesRead < destination.Length)
{
- Debug.Assert(_readPos == _readLength, "bytesToRead should only be < count if numBytesAvailable < count");
+ Debug.Assert(_readPos == _readLength, "bytesToRead should only be < destination.Length if numBytesAvailable < destination.Length");
_readPos = _readLength = 0; // no data left in the read buffer
- bytesRead += ReadNative(array, offset + bytesRead, count - bytesRead);
+ bytesRead += ReadNative(destination.Slice(bytesRead));
}
return bytesRead;
}
- /// <summary>Unbuffered, reads a block of bytes from the stream and writes the data in a given buffer.</summary>
- /// <param name="array">
- /// When this method returns, contains the specified byte array with the values between offset and
- /// (offset + count - 1) replaced by the bytes read from the current source.
- /// </param>
- /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param>
- /// <param name="count">The maximum number of bytes to read. </param>
+ /// <summary>Unbuffered, reads a block of bytes from the file handle into the given buffer.</summary>
+ /// <param name="buffer">The buffer into which data from the file is read.</param>
/// <returns>
/// The total number of bytes read into the buffer. This might be less than the number of bytes requested
/// if that number of bytes are not currently available, or zero if the end of the stream is reached.
/// </returns>
- private unsafe int ReadNative(byte[] array, int offset, int count)
+ private unsafe int ReadNative(Span<byte> buffer)
{
FlushWriteBuffer(); // we're about to read; dump the write buffer
VerifyOSHandlePosition();
int bytesRead;
- fixed (byte* bufPtr = array)
+ fixed (byte* bufPtr = &buffer.DangerousGetPinnableReference())
{
- bytesRead = CheckFileCall(Interop.Sys.Read(_fileHandle, bufPtr + offset, count));
- Debug.Assert(bytesRead <= count);
+ bytesRead = CheckFileCall(Interop.Sys.Read(_fileHandle, bufPtr, buffer.Length));
+ Debug.Assert(bytesRead <= buffer.Length);
}
_filePosition += bytesRead;
return bytesRead;
@@ -507,135 +472,97 @@ namespace System.IO
/// Asynchronously reads a sequence of bytes from the current stream and advances
/// the position within the stream by the number of bytes read.
/// </summary>
- /// <param name="buffer">The buffer to write the data into.</param>
- /// <param name="offset">The byte offset in buffer at which to begin writing data from the stream.</param>
- /// <param name="count">The maximum number of bytes to read.</param>
+ /// <param name="destination">The buffer to write the data into.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
+ /// <param name="synchronousResult">If the operation completes synchronously, the number of bytes read.</param>
/// <returns>A task that represents the asynchronous read operation.</returns>
- private Task<int> ReadAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ private Task<int> ReadAsyncInternal(Memory<byte> destination, CancellationToken cancellationToken, out int synchronousResult)
{
- if (_useAsyncIO)
+ Debug.Assert(_useAsyncIO);
+
+ if (!CanRead) // match Windows behavior; this gets thrown synchronously
{
- if (!CanRead) // match Windows behavior; this gets thrown synchronously
- {
- throw Error.GetReadNotSupported();
- }
+ throw Error.GetReadNotSupported();
+ }
- // Serialize operations using the semaphore.
- Task waitTask = _asyncState.WaitAsync();
+ // Serialize operations using the semaphore.
+ Task waitTask = _asyncState.WaitAsync();
- // If we got ownership immediately, and if there's enough data in our buffer
- // to satisfy the full request of the caller, hand back the buffered data.
- // While it would be a legal implementation of the Read contract, we don't
- // hand back here less than the amount requested so as to match the behavior
- // in ReadCore that will make a native call to try to fulfill the remainder
- // of the request.
- if (waitTask.Status == TaskStatus.RanToCompletion)
+ // If we got ownership immediately, and if there's enough data in our buffer
+ // to satisfy the full request of the caller, hand back the buffered data.
+ // While it would be a legal implementation of the Read contract, we don't
+ // hand back here less than the amount requested so as to match the behavior
+ // in ReadCore that will make a native call to try to fulfill the remainder
+ // of the request.
+ if (waitTask.Status == TaskStatus.RanToCompletion)
+ {
+ int numBytesAvailable = _readLength - _readPos;
+ if (numBytesAvailable >= destination.Length)
{
- int numBytesAvailable = _readLength - _readPos;
- if (numBytesAvailable >= count)
+ try
{
- try
- {
- PrepareForReading();
-
- Buffer.BlockCopy(GetBuffer(), _readPos, buffer, offset, count);
- _readPos += count;
-
- return _asyncState._lastSuccessfulReadTask != null && _asyncState._lastSuccessfulReadTask.Result == count ?
- _asyncState._lastSuccessfulReadTask :
- (_asyncState._lastSuccessfulReadTask = Task.FromResult(count));
- }
- catch (Exception exc)
- {
- return Task.FromException<int>(exc);
- }
- finally
- {
- _asyncState.Release();
- }
- }
- }
+ PrepareForReading();
- // Otherwise, issue the whole request asynchronously.
- _asyncState.Update(buffer, offset, count);
- return waitTask.ContinueWith((t, s) =>
- {
- // The options available on Unix for writing asynchronously to an arbitrary file
- // handle typically amount to just using another thread to do the synchronous write,
- // which is exactly what this implementation does. This does mean there are subtle
- // differences in certain FileStream behaviors between Windows and Unix when multiple
- // asynchronous operations are issued against the stream to execute concurrently; on
- // Unix the operations will be serialized due to the usage of a semaphore, but the
- // position /length information won't be updated until after the write has completed,
- // whereas on Windows it may happen before the write has completed.
-
- Debug.Assert(t.Status == TaskStatus.RanToCompletion);
- var thisRef = (FileStream)s;
- try
+ new Span<byte>(GetBuffer(), _readPos, destination.Length).CopyTo(destination.Span);
+ _readPos += destination.Length;
+
+ synchronousResult = destination.Length;
+ return null;
+ }
+ catch (Exception exc)
{
- byte[] b = thisRef._asyncState._buffer;
- thisRef._asyncState._buffer = null; // remove reference to user's buffer
- return thisRef.ReadCore(b, thisRef._asyncState._offset, thisRef._asyncState._count);
+ synchronousResult = 0;
+ return Task.FromException<int>(exc);
}
- finally { thisRef._asyncState.Release(); }
- }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
- }
- else
- {
- return base.ReadAsync(buffer, offset, count, cancellationToken);
+ finally
+ {
+ _asyncState.Release();
+ }
+ }
}
- }
- /// <summary>
- /// Reads a byte from the stream and advances the position within the stream
- /// by one byte, or returns -1 if at the end of the stream.
- /// </summary>
- /// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns>
- public override int ReadByte()
- {
- if (_useAsyncIO)
- {
- _asyncState.Wait();
- try { return ReadByteCore(); }
- finally { _asyncState.Release(); }
- }
- else
+ // Otherwise, issue the whole request asynchronously.
+ synchronousResult = 0;
+ _asyncState.Memory = destination;
+ return waitTask.ContinueWith((t, s) =>
{
- return ReadByteCore();
- }
+ // The options available on Unix for writing asynchronously to an arbitrary file
+ // handle typically amount to just using another thread to do the synchronous write,
+ // which is exactly what this implementation does. This does mean there are subtle
+ // differences in certain FileStream behaviors between Windows and Unix when multiple
+ // asynchronous operations are issued against the stream to execute concurrently; on
+ // Unix the operations will be serialized due to the usage of a semaphore, but the
+ // position /length information won't be updated until after the write has completed,
+ // whereas on Windows it may happen before the write has completed.
+
+ Debug.Assert(t.Status == TaskStatus.RanToCompletion);
+ var thisRef = (FileStream)s;
+ try
+ {
+ Memory<byte> memory = thisRef._asyncState.Memory;
+ thisRef._asyncState.Memory = default(Memory<byte>);
+ return thisRef.ReadSpan(memory.Span);
+ }
+ finally { thisRef._asyncState.Release(); }
+ }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
}
- /// <summary>Writes a block of bytes to the file stream.</summary>
- /// <param name="array">The buffer containing data to write to the stream.</param>
- /// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param>
- /// <param name="count">The maximum number of bytes to write.</param>
- public override void Write(byte[] array, int offset, int count)
+ /// <summary>Reads from the file handle into the buffer, overwriting anything in it.</summary>
+ private int FillReadBufferForReadByte()
{
- ValidateReadWriteArgs(array, offset, count);
-
- if (_useAsyncIO)
- {
- _asyncState.Wait();
- try { WriteCore(array, offset, count); }
- finally { _asyncState.Release(); }
- }
- else
- {
- WriteCore(array, offset, count);
- }
+ _asyncState?.Wait();
+ try { return ReadNative(_buffer); }
+ finally { _asyncState?.Release(); }
}
/// <summary>Writes a block of bytes to the file stream.</summary>
- /// <param name="array">The buffer containing data to write to the stream.</param>
- /// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param>
- /// <param name="count">The maximum number of bytes to write.</param>
- private void WriteCore(byte[] array, int offset, int count)
+ /// <param name="source">The buffer containing data to write to the stream.</param>
+ private void WriteSpan(ReadOnlySpan<byte> source)
{
PrepareForWriting();
// If no data is being written, nothing more to do.
- if (count == 0)
+ if (source.Length == 0)
{
return;
}
@@ -647,21 +574,17 @@ namespace System.IO
// If there's space remaining in the buffer, then copy as much as
// we can from the user's buffer into ours.
int spaceRemaining = _bufferLength - _writePos;
- if (spaceRemaining > 0)
+ if (spaceRemaining >= source.Length)
{
- int bytesToCopy = Math.Min(spaceRemaining, count);
- Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, bytesToCopy);
- _writePos += bytesToCopy;
-
- // If we've successfully copied all of the user's data, we're done.
- if (count == bytesToCopy)
- {
- return;
- }
-
- // Otherwise, keep track of how much more data needs to be handled.
- offset += bytesToCopy;
- count -= bytesToCopy;
+ source.CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos));
+ _writePos += source.Length;
+ return;
+ }
+ else if (spaceRemaining > 0)
+ {
+ source.Slice(0, spaceRemaining).CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos));
+ _writePos += spaceRemaining;
+ source = source.Slice(spaceRemaining);
}
// At this point, the buffer is full, so flush it out.
@@ -672,35 +595,33 @@ namespace System.IO
// the user's looking to write more data than we can store in the buffer),
// skip the buffer. Otherwise, put the remaining data into the buffer.
Debug.Assert(_writePos == 0);
- if (count >= _bufferLength)
+ if (source.Length >= _bufferLength)
{
- WriteNative(array, offset, count);
+ WriteNative(source);
}
else
{
- Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, count);
- _writePos = count;
+ source.CopyTo(new Span<byte>(GetBuffer()));
+ _writePos = source.Length;
}
}
/// <summary>Unbuffered, writes a block of bytes to the file stream.</summary>
- /// <param name="array">The buffer containing data to write to the stream.</param>
- /// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param>
- /// <param name="count">The maximum number of bytes to write.</param>
- private unsafe void WriteNative(byte[] array, int offset, int count)
+ /// <param name="source">The buffer containing data to write to the stream.</param>
+ private unsafe void WriteNative(ReadOnlySpan<byte> source)
{
VerifyOSHandlePosition();
- fixed (byte* bufPtr = array)
+ fixed (byte* bufPtr = &source.DangerousGetPinnableReference())
{
+ int offset = 0;
+ int count = source.Length;
while (count > 0)
{
int bytesWritten = CheckFileCall(Interop.Sys.Write(_fileHandle, bufPtr + offset, count));
- Debug.Assert(bytesWritten <= count);
-
_filePosition += bytesWritten;
- count -= bytesWritten;
offset += bytesWritten;
+ count -= bytesWritten;
}
}
}
@@ -710,103 +631,77 @@ namespace System.IO
/// the current position within this stream by the number of bytes written, and
/// monitors cancellation requests.
/// </summary>
- /// <param name="buffer">The buffer to write data from.</param>
- /// <param name="offset">The zero-based byte offset in buffer from which to begin copying bytes to the stream.</param>
- /// <param name="count">The maximum number of bytes to write.</param>
+ /// <param name="source">The buffer to write data from.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
/// <returns>A task that represents the asynchronous write operation.</returns>
- private Task WriteAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
+ private Task WriteAsyncInternal(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
{
+ Debug.Assert(_useAsyncIO);
+
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
if (_fileHandle.IsClosed)
throw Error.GetFileNotOpen();
- if (_useAsyncIO)
+ if (!CanWrite) // match Windows behavior; this gets thrown synchronously
{
- if (!CanWrite) // match Windows behavior; this gets thrown synchronously
- {
- throw Error.GetWriteNotSupported();
- }
+ throw Error.GetWriteNotSupported();
+ }
- // Serialize operations using the semaphore.
- Task waitTask = _asyncState.WaitAsync();
+ // Serialize operations using the semaphore.
+ Task waitTask = _asyncState.WaitAsync();
- // If we got ownership immediately, and if there's enough space in our buffer
- // to buffer the entire write request, then do so and we're done.
- if (waitTask.Status == TaskStatus.RanToCompletion)
+ // If we got ownership immediately, and if there's enough space in our buffer
+ // to buffer the entire write request, then do so and we're done.
+ if (waitTask.Status == TaskStatus.RanToCompletion)
+ {
+ int spaceRemaining = _bufferLength - _writePos;
+ if (spaceRemaining >= source.Length)
{
- int spaceRemaining = _bufferLength - _writePos;
- if (spaceRemaining >= count)
+ try
{
- try
- {
- PrepareForWriting();
-
- Buffer.BlockCopy(buffer, offset, GetBuffer(), _writePos, count);
- _writePos += count;
-
- return Task.CompletedTask;
- }
- catch (Exception exc)
- {
- return Task.FromException(exc);
- }
- finally
- {
- _asyncState.Release();
- }
- }
- }
+ PrepareForWriting();
- // Otherwise, issue the whole request asynchronously.
- _asyncState.Update(buffer, offset, count);
- return waitTask.ContinueWith((t, s) =>
- {
- // The options available on Unix for writing asynchronously to an arbitrary file
- // handle typically amount to just using another thread to do the synchronous write,
- // which is exactly what this implementation does. This does mean there are subtle
- // differences in certain FileStream behaviors between Windows and Unix when multiple
- // asynchronous operations are issued against the stream to execute concurrently; on
- // Unix the operations will be serialized due to the usage of a semaphore, but the
- // position /length information won't be updated until after the write has completed,
- // whereas on Windows it may happen before the write has completed.
-
- Debug.Assert(t.Status == TaskStatus.RanToCompletion);
- var thisRef = (FileStream)s;
- try
+ source.Span.CopyTo(new Span<byte>(GetBuffer(), _writePos, source.Length));
+ _writePos += source.Length;
+
+ return Task.CompletedTask;
+ }
+ catch (Exception exc)
{
- byte[] b = thisRef._asyncState._buffer;
- thisRef._asyncState._buffer = null; // remove reference to user's buffer
- thisRef.WriteCore(b, thisRef._asyncState._offset, thisRef._asyncState._count);
+ return Task.FromException(exc);
}
- finally { thisRef._asyncState.Release(); }
- }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
- }
- else
- {
- return base.WriteAsync(buffer, offset, count, cancellationToken);
+ finally
+ {
+ _asyncState.Release();
+ }
+ }
}
- }
- /// <summary>
- /// Writes a byte to the current position in the stream and advances the position
- /// within the stream by one byte.
- /// </summary>
- /// <param name="value">The byte to write to the stream.</param>
- public override void WriteByte(byte value) // avoids an array allocation in the base implementation
- {
- if (_useAsyncIO)
+ // Otherwise, issue the whole request asynchronously.
+ _asyncState.ReadOnlyMemory = source;
+ return waitTask.ContinueWith((t, s) =>
{
- _asyncState.Wait();
- try { WriteByteCore(value); }
- finally { _asyncState.Release(); }
- }
- else
- {
- WriteByteCore(value);
- }
+ // The options available on Unix for writing asynchronously to an arbitrary file
+ // handle typically amount to just using another thread to do the synchronous write,
+ // which is exactly what this implementation does. This does mean there are subtle
+ // differences in certain FileStream behaviors between Windows and Unix when multiple
+ // asynchronous operations are issued against the stream to execute concurrently; on
+ // Unix the operations will be serialized due to the usage of a semaphore, but the
+ // position/length information won't be updated until after the write has completed,
+ // whereas on Windows it may happen before the write has completed.
+
+ Debug.Assert(t.Status == TaskStatus.RanToCompletion);
+ var thisRef = (FileStream)s;
+ try
+ {
+ ReadOnlyMemory<byte> readOnlyMemory = thisRef._asyncState.ReadOnlyMemory;
+ thisRef._asyncState.ReadOnlyMemory = default(ReadOnlyMemory<byte>);
+ thisRef.WriteSpan(readOnlyMemory.Span);
+ }
+ finally { thisRef._asyncState.Release(); }
+ }, this, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
}
/// <summary>Sets the current position of this stream to the given value.</summary>
@@ -907,25 +802,11 @@ namespace System.IO
/// <summary>State used when the stream is in async mode.</summary>
private sealed class AsyncState : SemaphoreSlim
{
- /// <summary>The caller's buffer currently being used by the active async operation.</summary>
- internal byte[] _buffer;
- /// <summary>The caller's offset currently being used by the active async operation.</summary>
- internal int _offset;
- /// <summary>The caller's count currently being used by the active async operation.</summary>
- internal int _count;
- /// <summary>The last task successfully, synchronously returned task from ReadAsync.</summary>
- internal Task<int> _lastSuccessfulReadTask;
+ internal ReadOnlyMemory<byte> ReadOnlyMemory;
+ internal Memory<byte> Memory;
/// <summary>Initialize the AsyncState.</summary>
internal AsyncState() : base(initialCount: 1, maxCount: 1) { }
-
- /// <summary>Sets the active buffer, offset, and count.</summary>
- internal void Update(byte[] buffer, int offset, int count)
- {
- _buffer = buffer;
- _offset = offset;
- _count = count;
- }
}
}
}
diff --git a/src/mscorlib/shared/System/IO/FileStream.Win32.cs b/src/mscorlib/shared/System/IO/FileStream.Win32.cs
index 61cd007895..4b75ad6dad 100644
--- a/src/mscorlib/shared/System/IO/FileStream.Win32.cs
+++ b/src/mscorlib/shared/System/IO/FileStream.Win32.cs
@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
-using System.Runtime.InteropServices;
namespace System.IO
{
@@ -11,6 +10,11 @@ namespace System.IO
{
private SafeFileHandle OpenHandle(FileMode mode, FileShare share, FileOptions options)
{
+ return CreateFileOpenHandle(mode, share, options);
+ }
+
+ private unsafe SafeFileHandle CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
+ {
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
int fAccess =
@@ -30,44 +34,13 @@ namespace System.IO
// For mitigating local elevation of privilege attack through named pipes
// make sure we always call CreateFile with SECURITY_ANONYMOUS so that the
// named pipe server can't impersonate a high privileged client security context
+ // (note that this is the effective default on CreateFile2)
flagsAndAttributes |= (Interop.Kernel32.SecurityOptions.SECURITY_SQOS_PRESENT | Interop.Kernel32.SecurityOptions.SECURITY_ANONYMOUS);
- // Don't pop up a dialog for reading from an empty floppy drive
- uint oldMode;
- bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode);
- try
- {
- SafeFileHandle fileHandle = Interop.Kernel32.CreateFile(_path, fAccess, share, ref secAttrs, mode, flagsAndAttributes, IntPtr.Zero);
- fileHandle.IsAsync = _useAsyncIO;
-
- if (fileHandle.IsInvalid)
- {
- // Return a meaningful exception with the full path.
-
- // NT5 oddity - when trying to open "C:\" as a Win32FileStream,
- // we usually get ERROR_PATH_NOT_FOUND from the OS. We should
- // probably be consistent w/ every other directory.
- int errorCode = Marshal.GetLastWin32Error();
-
- if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && _path.Length == PathInternal.GetRootLength(_path))
- errorCode = Interop.Errors.ERROR_ACCESS_DENIED;
-
- throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path);
- }
-
- int fileType = Interop.Kernel32.GetFileType(fileHandle);
- if (fileType != Interop.Kernel32.FileTypes.FILE_TYPE_DISK)
- {
- fileHandle.Dispose();
- throw new NotSupportedException(SR.NotSupported_FileStreamOnNonFiles);
- }
-
- return fileHandle;
- }
- finally
+ using (DisableMediaInsertionPrompt.Create())
{
- if (success)
- Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode);
+ return ValidateFileHandle(
+ Interop.Kernel32.CreateFile(_path, fAccess, share, ref secAttrs, mode, flagsAndAttributes, IntPtr.Zero));
}
}
}
diff --git a/src/mscorlib/shared/System/IO/FileStream.WinRT.cs b/src/mscorlib/shared/System/IO/FileStream.WinRT.cs
index b9a9f8a783..304088eea7 100644
--- a/src/mscorlib/shared/System/IO/FileStream.WinRT.cs
+++ b/src/mscorlib/shared/System/IO/FileStream.WinRT.cs
@@ -13,7 +13,7 @@ namespace System.IO
{
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(share);
- int fAccess =
+ int access =
((_access & FileAccess.Read) == FileAccess.Read ? GENERIC_READ : 0) |
((_access & FileAccess.Write) == FileAccess.Write ? GENERIC_WRITE : 0);
@@ -30,31 +30,15 @@ namespace System.IO
parameters.dwFileFlags = (uint)options;
parameters.lpSecurityAttributes = &secAttrs;
- SafeFileHandle fileHandle = Interop.Kernel32.CreateFile2(
- lpFileName: _path,
- dwDesiredAccess: fAccess,
- dwShareMode: share,
- dwCreationDisposition: mode,
- pCreateExParams: &parameters);
-
- fileHandle.IsAsync = _useAsyncIO;
-
- if (fileHandle.IsInvalid)
+ using (DisableMediaInsertionPrompt.Create())
{
- // Return a meaningful exception with the full path.
-
- // NT5 oddity - when trying to open "C:\" as a Win32FileStream,
- // we usually get ERROR_PATH_NOT_FOUND from the OS. We should
- // probably be consistent w/ every other directory.
- int errorCode = Marshal.GetLastWin32Error();
-
- if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && _path.Length == PathInternal.GetRootLength(_path))
- errorCode = Interop.Errors.ERROR_ACCESS_DENIED;
-
- throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path);
+ return ValidateFileHandle(Interop.Kernel32.CreateFile2(
+ lpFileName: _path,
+ dwDesiredAccess: access,
+ dwShareMode: share,
+ dwCreationDisposition: mode,
+ pCreateExParams: ref parameters));
}
-
- return fileHandle;
}
}
}
diff --git a/src/mscorlib/shared/System/IO/FileStream.Windows.cs b/src/mscorlib/shared/System/IO/FileStream.Windows.cs
index cdf1cb092e..eec11b4b13 100644
--- a/src/mscorlib/shared/System/IO/FileStream.Windows.cs
+++ b/src/mscorlib/shared/System/IO/FileStream.Windows.cs
@@ -48,7 +48,6 @@ namespace System.IO
private static unsafe IOCompletionCallback s_ioCallback = FileStreamCompletionSource.IOCallback;
- private Task<int> _lastSynchronouslyCompletedTask = null; // cached task for read ops that complete synchronously
private Task _activeBufferOperation = null; // tracks in-progress async ops using the buffer
private PreAllocatedOverlapped _preallocatedOverlapped; // optimization for async ops to avoid per-op allocations
private FileStreamCompletionSource _currentOverlappedOwner; // async op currently using the preallocated overlapped
@@ -313,7 +312,7 @@ namespace System.IO
// If the buffer is already flushed, don't spin up the OS write
if (_writePos == 0) return Task.CompletedTask;
- Task flushTask = WriteInternalCoreAsync(GetBuffer(), 0, _writePos, cancellationToken);
+ Task flushTask = WriteAsyncInternalCore(new ReadOnlyMemory<byte>(GetBuffer(), 0, _writePos), cancellationToken);
_writePos = 0;
// Update the active buffer operation
@@ -324,6 +323,8 @@ namespace System.IO
return flushTask;
}
+ private void FlushWriteBufferForWriteByte() => FlushWriteBuffer();
+
// Writes are buffered. Anytime the buffer fills up
// (_writePos + delta > _bufferSize) or the buffer switches to reading
// and there is left over data (_writePos > 0), this function must be called.
@@ -355,7 +356,7 @@ namespace System.IO
}
else
{
- WriteCore(GetBuffer(), 0, _writePos);
+ WriteCore(new ReadOnlySpan<byte>(GetBuffer(), 0, _writePos));
}
_writePos = 0;
@@ -411,14 +412,9 @@ namespace System.IO
// accessing its fields by ref. This avoids a compiler warning.
private FileStreamCompletionSource CompareExchangeCurrentOverlappedOwner(FileStreamCompletionSource newSource, FileStreamCompletionSource existingSource) => Interlocked.CompareExchange(ref _currentOverlappedOwner, newSource, existingSource);
- public override int Read(byte[] array, int offset, int count)
- {
- ValidateReadWriteArgs(array, offset, count);
- return ReadCore(array, offset, count);
- }
-
- private int ReadCore(byte[] array, int offset, int count)
+ private int ReadSpan(Span<byte> destination)
{
+ Debug.Assert(!_useAsyncIO, "Must only be used when in synchronous mode");
Debug.Assert((_readPos == 0 && _readLength == 0 && _writePos >= 0) || (_writePos == 0 && _readPos <= _readLength),
"We're either reading or writing, but not both.");
@@ -430,23 +426,23 @@ namespace System.IO
{
if (!CanRead) throw Error.GetReadNotSupported();
if (_writePos > 0) FlushWriteBuffer();
- if (!CanSeek || (count >= _bufferLength))
+ if (!CanSeek || (destination.Length >= _bufferLength))
{
- n = ReadNative(array, offset, count);
+ n = ReadNative(destination);
// Throw away read buffer.
_readPos = 0;
_readLength = 0;
return n;
}
- n = ReadNative(GetBuffer(), 0, _bufferLength);
+ n = ReadNative(GetBuffer());
if (n == 0) return 0;
isBlocked = n < _bufferLength;
_readPos = 0;
_readLength = n;
}
// Now copy min of count or numBytesAvailable (i.e. near EOF) to array.
- if (n > count) n = count;
- Buffer.BlockCopy(GetBuffer(), _readPos, array, offset, n);
+ if (n > destination.Length) n = destination.Length;
+ new ReadOnlySpan<byte>(GetBuffer(), _readPos, n).CopyTo(destination);
_readPos += n;
// We may have read less than the number of bytes the user asked
@@ -466,10 +462,10 @@ namespace System.IO
// read some more from the underlying stream. However, if we got
// fewer bytes from the underlying stream than we asked for (i.e. we're
// probably blocked), don't ask for more bytes.
- if (n < count && !isBlocked)
+ if (n < destination.Length && !isBlocked)
{
Debug.Assert(_readPos == _readLength, "Read buffer should be empty!");
- int moreBytesRead = ReadNative(array, offset + n, count - n);
+ int moreBytesRead = ReadNative(destination.Slice(n));
n += moreBytesRead;
// We've just made our buffer inconsistent with our position
// pointer. We must throw away the read buffer.
@@ -482,28 +478,28 @@ namespace System.IO
}
[Conditional("DEBUG")]
- private void AssertCanRead(byte[] buffer, int offset, int count)
+ private void AssertCanRead()
{
Debug.Assert(!_fileHandle.IsClosed, "!_fileHandle.IsClosed");
Debug.Assert(CanRead, "CanRead");
- Debug.Assert(buffer != null, "buffer != null");
- Debug.Assert(_writePos == 0, "_writePos == 0");
- Debug.Assert(offset >= 0, "offset is negative");
- Debug.Assert(count >= 0, "count is negative");
}
- private unsafe int ReadNative(byte[] buffer, int offset, int count)
- {
- AssertCanRead(buffer, offset, count);
+ /// <summary>Reads from the file handle into the buffer, overwriting anything in it.</summary>
+ private int FillReadBufferForReadByte() =>
+ _useAsyncIO ?
+ ReadNativeAsync(new Memory<byte>(_buffer), 0, CancellationToken.None).GetAwaiter().GetResult() :
+ ReadNative(_buffer);
- if (_useAsyncIO)
- return ReadNativeAsync(buffer, offset, count, 0, CancellationToken.None).GetAwaiter().GetResult();
+ private unsafe int ReadNative(Span<byte> buffer)
+ {
+ Debug.Assert(!_useAsyncIO, $"{nameof(ReadNative)} doesn't work on asynchronous file streams.");
+ AssertCanRead();
// Make sure we are reading from the right spot
VerifyOSHandlePosition();
int errorCode = 0;
- int r = ReadFileNative(_fileHandle, buffer, offset, count, null, out errorCode);
+ int r = ReadFileNative(_fileHandle, buffer, null, out errorCode);
if (r == -1)
{
@@ -579,7 +575,6 @@ namespace System.IO
{
if (_readPos > 0)
{
- //Console.WriteLine("Seek: seeked for 0, adjusting buffer back by: "+_readPos+" _readLen: "+_readLen);
Buffer.BlockCopy(GetBuffer(), _readPos, GetBuffer(), 0, _readLength - _readPos);
_readLength -= _readPos;
_readPos = 0;
@@ -592,7 +587,6 @@ namespace System.IO
else if (oldPos - _readPos < pos && pos < oldPos + _readLength - _readPos)
{
int diff = (int)(pos - oldPos);
- //Console.WriteLine("Seek: diff was "+diff+", readpos was "+_readPos+" adjusting buffer - shrinking by "+ (_readPos + diff));
Buffer.BlockCopy(GetBuffer(), _readPos + diff, GetBuffer(), 0, _readLength - (_readPos + diff));
_readLength -= (_readPos + diff);
_readPos = 0;
@@ -646,9 +640,9 @@ namespace System.IO
_preallocatedOverlapped = new PreAllocatedOverlapped(s_ioCallback, this, _buffer);
}
- public override void Write(byte[] array, int offset, int count)
+ private void WriteSpan(ReadOnlySpan<byte> source)
{
- ValidateReadWriteArgs(array, offset, count);
+ Debug.Assert(!_useAsyncIO, "Must only be used when in synchronous mode");
if (_writePos == 0)
{
@@ -672,65 +666,56 @@ namespace System.IO
int numBytes = _bufferLength - _writePos; // space left in buffer
if (numBytes > 0)
{
- if (numBytes > count)
- numBytes = count;
- Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, numBytes);
- _writePos += numBytes;
- if (count == numBytes) return;
- offset += numBytes;
- count -= numBytes;
+ if (numBytes >= source.Length)
+ {
+ source.CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos));
+ _writePos += source.Length;
+ return;
+ }
+ else
+ {
+ source.Slice(0, numBytes).CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos));
+ _writePos += numBytes;
+ source = source.Slice(numBytes);
+ }
}
// Reset our buffer. We essentially want to call FlushWrite
// without calling Flush on the underlying Stream.
- if (_useAsyncIO)
- {
- WriteInternalCoreAsync(GetBuffer(), 0, _writePos, CancellationToken.None).GetAwaiter().GetResult();
- }
- else
- {
- WriteCore(GetBuffer(), 0, _writePos);
- }
+ WriteCore(new ReadOnlySpan<byte>(GetBuffer(), 0, _writePos));
_writePos = 0;
}
+
// If the buffer would slow writes down, avoid buffer completely.
- if (count >= _bufferLength)
+ if (source.Length >= _bufferLength)
{
Debug.Assert(_writePos == 0, "FileStream cannot have buffered data to write here! Your stream will be corrupted.");
- WriteCore(array, offset, count);
+ WriteCore(source);
return;
}
- else if (count == 0)
+ else if (source.Length == 0)
{
return; // Don't allocate a buffer then call memcpy for 0 bytes.
}
// Copy remaining bytes into buffer, to write at a later date.
- Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, count);
- _writePos = count;
+ source.CopyTo(new Span<byte>(GetBuffer()).Slice(_writePos));
+ _writePos = source.Length;
return;
}
- private unsafe void WriteCore(byte[] buffer, int offset, int count)
+ private unsafe void WriteCore(ReadOnlySpan<byte> source)
{
+ Debug.Assert(!_useAsyncIO);
Debug.Assert(!_fileHandle.IsClosed, "!_handle.IsClosed");
Debug.Assert(CanWrite, "_parent.CanWrite");
-
- Debug.Assert(buffer != null, "buffer != null");
Debug.Assert(_readPos == _readLength, "_readPos == _readLen");
- Debug.Assert(offset >= 0, "offset is negative");
- Debug.Assert(count >= 0, "count is negative");
- if (_useAsyncIO)
- {
- WriteInternalCoreAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
- return;
- }
// Make sure we are writing to the position that we think we are
VerifyOSHandlePosition();
int errorCode = 0;
- int r = WriteFileNative(_fileHandle, buffer, offset, count, null, out errorCode);
+ int r = WriteFileNative(_fileHandle, source, null, out errorCode);
if (r == -1)
{
@@ -742,9 +727,8 @@ namespace System.IO
else
{
// ERROR_INVALID_PARAMETER may be returned for writes
- // where the position is too large (i.e. writing at Int64.MaxValue
- // on Win9x) OR for synchronous writes to a handle opened
- // asynchronously.
+ // where the position is too large or for synchronous writes
+ // to a handle opened asynchronously.
if (errorCode == ERROR_INVALID_PARAMETER)
throw new IOException(SR.IO_FileTooLongOrHandleNotSync);
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
@@ -755,15 +739,9 @@ namespace System.IO
return;
}
- private Task<int> ReadAsyncInternal(byte[] array, int offset, int numBytes, CancellationToken cancellationToken)
+ private Task<int> ReadAsyncInternal(Memory<byte> destination, CancellationToken cancellationToken, out int synchronousResult)
{
- // If async IO is not supported on this platform or
- // if this Win32FileStream was not opened with FileOptions.Asynchronous.
- if (!_useAsyncIO)
- {
- return base.ReadAsync(array, offset, numBytes, cancellationToken);
- }
-
+ Debug.Assert(_useAsyncIO);
if (!CanRead) throw Error.GetReadNotSupported();
Debug.Assert((_readPos == 0 && _readLength == 0 && _writePos >= 0) || (_writePos == 0 && _readPos <= _readLength), "We're either reading or writing, but not both.");
@@ -785,18 +763,17 @@ namespace System.IO
// pipes. But don't completely ignore buffered data either.
if (_readPos < _readLength)
{
- int n = _readLength - _readPos;
- if (n > numBytes) n = numBytes;
- Buffer.BlockCopy(GetBuffer(), _readPos, array, offset, n);
+ int n = Math.Min(_readLength - _readPos, destination.Length);
+ new Span<byte>(GetBuffer(), _readPos, n).CopyTo(destination.Span);
_readPos += n;
-
- // Return a completed task
- return TaskFromResultOrCache(n);
+ synchronousResult = n;
+ return null;
}
else
{
Debug.Assert(_writePos == 0, "Win32FileStream must not have buffered write data here! Pipes should be unidirectional.");
- return ReadNativeAsync(array, offset, numBytes, 0, cancellationToken);
+ synchronousResult = 0;
+ return ReadNativeAsync(destination, 0, cancellationToken);
}
}
@@ -817,17 +794,16 @@ namespace System.IO
// problem, and any async read less than 64K gets turned into a
// synchronous read by NT anyways... --
- if (numBytes < _bufferLength)
+ if (destination.Length < _bufferLength)
{
- Task<int> readTask = ReadNativeAsync(GetBuffer(), 0, _bufferLength, 0, cancellationToken);
+ Task<int> readTask = ReadNativeAsync(new Memory<byte>(GetBuffer()), 0, cancellationToken);
_readLength = readTask.GetAwaiter().GetResult();
- int n = _readLength;
- if (n > numBytes) n = numBytes;
- Buffer.BlockCopy(GetBuffer(), 0, array, offset, n);
+ int n = Math.Min(_readLength, destination.Length);
+ new Span<byte>(GetBuffer(), 0, n).CopyTo(destination.Span);
_readPos = n;
- // Return a completed task (recycling the one above if possible)
- return (_readLength == n ? readTask : TaskFromResultOrCache(n));
+ synchronousResult = n;
+ return null;
}
else
{
@@ -835,20 +811,21 @@ namespace System.IO
// with our read buffer. Throw away the read buffer's contents.
_readPos = 0;
_readLength = 0;
- return ReadNativeAsync(array, offset, numBytes, 0, cancellationToken);
+ synchronousResult = 0;
+ return ReadNativeAsync(destination, 0, cancellationToken);
}
}
else
{
- int n = _readLength - _readPos;
- if (n > numBytes) n = numBytes;
- Buffer.BlockCopy(GetBuffer(), _readPos, array, offset, n);
+ int n = Math.Min(_readLength - _readPos, destination.Length);
+ new Span<byte>(GetBuffer(), _readPos, n).CopyTo(destination.Span);
_readPos += n;
- if (n >= numBytes)
+ if (n == destination.Length)
{
// Return a completed task
- return TaskFromResultOrCache(n);
+ synchronousResult = n;
+ return null;
}
else
{
@@ -859,19 +836,21 @@ namespace System.IO
// Throw away read buffer.
_readPos = 0;
_readLength = 0;
- return ReadNativeAsync(array, offset + n, numBytes - n, n, cancellationToken);
+ synchronousResult = 0;
+ return ReadNativeAsync(destination.Slice(n), n, cancellationToken);
}
}
}
- unsafe private Task<int> ReadNativeAsync(byte[] bytes, int offset, int numBytes, int numBufferedBytesRead, CancellationToken cancellationToken)
+ unsafe private Task<int> ReadNativeAsync(Memory<byte> destination, int numBufferedBytesRead, CancellationToken cancellationToken)
{
- AssertCanRead(bytes, offset, numBytes);
+ AssertCanRead();
Debug.Assert(_useAsyncIO, "ReadNativeAsync doesn't work on synchronous file streams!");
// Create and store async stream class library specific data in the async result
-
- FileStreamCompletionSource completionSource = new FileStreamCompletionSource(this, numBufferedBytesRead, bytes, cancellationToken);
+ FileStreamCompletionSource completionSource = destination.TryGetArray(out ArraySegment<byte> memoryArray) ?
+ new FileStreamCompletionSource(this, numBufferedBytesRead, memoryArray.Array) :
+ new MemoryFileStreamCompletionSource(this, numBufferedBytesRead, destination);
NativeOverlapped* intOverlapped = completionSource.Overlapped;
// Calculate position in the file we should be at after the read is done
@@ -882,12 +861,16 @@ namespace System.IO
// Make sure we are reading from the position that we think we are
VerifyOSHandlePosition();
- if (_filePosition + numBytes > len)
+ if (_filePosition + destination.Length > len)
{
if (_filePosition <= len)
- numBytes = (int)(len - _filePosition);
+ {
+ destination = destination.Slice(0, (int)(len - _filePosition));
+ }
else
- numBytes = 0;
+ {
+ destination = default(Memory<byte>);
+ }
}
// Now set the position to read from in the NativeOverlapped struct
@@ -904,12 +887,13 @@ namespace System.IO
// the file pointer when writing to a UNC path!
// So changed the code below to seek to an absolute
// location, not a relative one. ReadFile seems consistent though.
- SeekCore(_fileHandle, numBytes, SeekOrigin.Current);
+ SeekCore(_fileHandle, destination.Length, SeekOrigin.Current);
}
// queue an async ReadFile operation and pass in a packed overlapped
int errorCode = 0;
- int r = ReadFileNative(_fileHandle, bytes, offset, numBytes, intOverlapped, out errorCode);
+ int r = ReadFileNative(_fileHandle, destination.Span, intOverlapped, out errorCode);
+
// ReadFile, the OS version, will return 0 on failure. But
// my ReadFileNative wrapper returns -1. My wrapper will return
// the following:
@@ -920,7 +904,7 @@ namespace System.IO
// read back from this call when using overlapped structures! You must
// not pass in a non-null lpNumBytesRead to ReadFile when using
// overlapped structures! This is by design NT behavior.
- if (r == -1 && numBytes != -1)
+ if (r == -1)
{
// For pipes, when they hit EOF, they will come here.
if (errorCode == ERROR_BROKEN_PIPE)
@@ -951,10 +935,10 @@ namespace System.IO
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
- else
+ else if (cancellationToken.CanBeCanceled) // ERROR_IO_PENDING
{
// Only once the IO is pending do we register for cancellation
- completionSource.RegisterForCancellation();
+ completionSource.RegisterForCancellation(cancellationToken);
}
}
else
@@ -966,33 +950,19 @@ namespace System.IO
// synchronously or asynchronously. We absolutely must not
// set asyncResult._numBytes here, since will never have correct
// results.
- //Console.WriteLine("ReadFile returned: "+r+" (0x"+Int32.Format(r, "x")+") The IO completed synchronously, but the user callback was called on a separate thread");
}
return completionSource.Task;
}
- // Reads a byte from the file stream. Returns the byte cast to an int
- // or -1 if reading from the end of the stream.
- public override int ReadByte()
+ private Task WriteAsyncInternal(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
{
- return ReadByteCore();
- }
-
- private Task WriteAsyncInternal(byte[] array, int offset, int numBytes, CancellationToken cancellationToken)
- {
- // If async IO is not supported on this platform or
- // if this Win32FileStream was not opened with FileOptions.Asynchronous.
- if (!_useAsyncIO)
- {
- return base.WriteAsync(array, offset, numBytes, cancellationToken);
- }
-
- if (!CanWrite) throw Error.GetWriteNotSupported();
-
+ Debug.Assert(_useAsyncIO);
Debug.Assert((_readPos == 0 && _readLength == 0 && _writePos >= 0) || (_writePos == 0 && _readPos <= _readLength), "We're either reading or writing, but not both.");
Debug.Assert(!_isPipe || (_readPos == 0 && _readLength == 0), "Win32FileStream must not have buffered data here! Pipes should be unidirectional.");
+ if (!CanWrite) throw Error.GetWriteNotSupported();
+
bool writeDataStoredInBuffer = false;
if (!_isPipe) // avoid async buffering with pipes, as doing so can lead to deadlocks (see comments in ReadInternalAsyncCore)
{
@@ -1016,10 +986,10 @@ namespace System.IO
// - There's no active flush operation, such that we don't have to worry about the existing buffer being in use.
// - And the data we're trying to write fits in the buffer, meaning it wasn't already filled by previous writes.
// In that case, just store it in the buffer.
- if (numBytes < _bufferLength && !HasActiveBufferOperation && numBytes <= remainingBuffer)
+ if (source.Length < _bufferLength && !HasActiveBufferOperation && source.Length <= remainingBuffer)
{
- Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, numBytes);
- _writePos += numBytes;
+ source.Span.CopyTo(new Span<byte>(GetBuffer(), _writePos, source.Length));
+ _writePos += source.Length;
writeDataStoredInBuffer = true;
// There is one special-but-common case, common because devs often use
@@ -1028,7 +998,7 @@ namespace System.IO
// then we're done and can return a completed task now. But if we filled the buffer
// completely, we want to do the asynchronous flush/write as part of this operation
// rather than waiting until the next write that fills the buffer.
- if (numBytes != remainingBuffer)
+ if (source.Length != remainingBuffer)
return Task.CompletedTask;
Debug.Assert(_writePos == _bufferLength);
@@ -1084,40 +1054,37 @@ namespace System.IO
// Finally, issue the write asynchronously, and return a Task that logically
// represents the write operation, including any flushing done.
- Task writeTask = WriteInternalCoreAsync(array, offset, numBytes, cancellationToken);
+ Task writeTask = WriteAsyncInternalCore(source, cancellationToken);
return
(flushTask == null || flushTask.Status == TaskStatus.RanToCompletion) ? writeTask :
(writeTask.Status == TaskStatus.RanToCompletion) ? flushTask :
Task.WhenAll(flushTask, writeTask);
}
- private unsafe Task WriteInternalCoreAsync(byte[] bytes, int offset, int numBytes, CancellationToken cancellationToken)
+ private unsafe Task WriteAsyncInternalCore(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
{
Debug.Assert(!_fileHandle.IsClosed, "!_handle.IsClosed");
Debug.Assert(CanWrite, "_parent.CanWrite");
- Debug.Assert(bytes != null, "bytes != null");
Debug.Assert(_readPos == _readLength, "_readPos == _readLen");
Debug.Assert(_useAsyncIO, "WriteInternalCoreAsync doesn't work on synchronous file streams!");
- Debug.Assert(offset >= 0, "offset is negative");
- Debug.Assert(numBytes >= 0, "numBytes is negative");
// Create and store async stream class library specific data in the async result
- FileStreamCompletionSource completionSource = new FileStreamCompletionSource(this, 0, bytes, cancellationToken);
+ FileStreamCompletionSource completionSource = source.DangerousTryGetArray(out ArraySegment<byte> array) ?
+ new FileStreamCompletionSource(this, 0, array.Array) :
+ new MemoryFileStreamCompletionSource(this, 0, source);
NativeOverlapped* intOverlapped = completionSource.Overlapped;
if (CanSeek)
{
// Make sure we set the length of the file appropriately.
long len = Length;
- //Console.WriteLine("WriteInternalCoreAsync - Calculating end pos. pos: "+pos+" len: "+len+" numBytes: "+numBytes);
// Make sure we are writing to the position that we think we are
VerifyOSHandlePosition();
- if (_filePosition + numBytes > len)
+ if (_filePosition + source.Length > len)
{
- //Console.WriteLine("WriteInternalCoreAsync - Setting length to: "+(pos + numBytes));
- SetLengthCore(_filePosition + numBytes);
+ SetLengthCore(_filePosition + source.Length);
}
// Now set the position to read from in the NativeOverlapped struct
@@ -1128,14 +1095,12 @@ namespace System.IO
// When using overlapped IO, the OS is not supposed to
// touch the file pointer location at all. We will adjust it
// ourselves. This isn't threadsafe.
- SeekCore(_fileHandle, numBytes, SeekOrigin.Current);
+ SeekCore(_fileHandle, source.Length, SeekOrigin.Current);
}
- //Console.WriteLine("WriteInternalCoreAsync finishing. pos: "+pos+" numBytes: "+numBytes+" _pos: "+_pos+" Position: "+Position);
-
int errorCode = 0;
// queue an async WriteFile operation and pass in a packed overlapped
- int r = WriteFileNative(_fileHandle, bytes, offset, numBytes, intOverlapped, out errorCode);
+ int r = WriteFileNative(_fileHandle, source.Span, intOverlapped, out errorCode);
// WriteFile, the OS version, will return 0 on failure. But
// my WriteFileNative wrapper returns -1. My wrapper will return
@@ -1147,10 +1112,8 @@ namespace System.IO
// written back from this call when using overlapped IO! You must
// not pass in a non-null lpNumBytesWritten to WriteFile when using
// overlapped structures! This is ByDesign NT behavior.
- if (r == -1 && numBytes != -1)
+ if (r == -1)
{
- //Console.WriteLine("WriteFile returned 0; Write will complete asynchronously (if errorCode==3e5) errorCode: 0x{0:x}", errorCode);
-
// For pipes, when they are closed on the other side, they will come here.
if (errorCode == ERROR_NO_DATA)
{
@@ -1177,10 +1140,10 @@ namespace System.IO
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
- else // ERROR_IO_PENDING
+ else if (cancellationToken.CanBeCanceled) // ERROR_IO_PENDING
{
// Only once the IO is pending do we register for cancellation
- completionSource.RegisterForCancellation();
+ completionSource.RegisterForCancellation(cancellationToken);
}
}
else
@@ -1192,17 +1155,11 @@ namespace System.IO
// synchronously or asynchronously. We absolutely must not
// set asyncResult._numBytes here, since will never have correct
// results.
- //Console.WriteLine("WriteFile returned: "+r+" (0x"+Int32.Format(r, "x")+") The IO completed synchronously, but the user callback was called on another thread.");
}
return completionSource.Task;
}
- public override void WriteByte(byte value)
- {
- WriteByteCore(value);
- }
-
// Windows API definitions, from winbase.h and others
private const int FILE_ATTRIBUTE_NORMAL = 0x00000080;
@@ -1223,35 +1180,19 @@ namespace System.IO
private const int ERROR_IO_PENDING = 997;
// __ConsoleStream also uses this code.
- private unsafe int ReadFileNative(SafeFileHandle handle, byte[] bytes, int offset, int count, NativeOverlapped* overlapped, out int errorCode)
+ private unsafe int ReadFileNative(SafeFileHandle handle, Span<byte> bytes, NativeOverlapped* overlapped, out int errorCode)
{
Debug.Assert(handle != null, "handle != null");
- Debug.Assert(offset >= 0, "offset >= 0");
- Debug.Assert(count >= 0, "count >= 0");
- Debug.Assert(bytes != null, "bytes != null");
- // Don't corrupt memory when multiple threads are erroneously writing
- // to this stream simultaneously.
- if (bytes.Length - offset < count)
- throw new IndexOutOfRangeException(SR.IndexOutOfRange_IORaceCondition);
-
Debug.Assert((_useAsyncIO && overlapped != null) || (!_useAsyncIO && overlapped == null), "Async IO and overlapped parameters inconsistent in call to ReadFileNative.");
- // You can't use the fixed statement on an array of length 0.
- if (bytes.Length == 0)
- {
- errorCode = 0;
- return 0;
- }
-
- int r = 0;
+ int r;
int numBytesRead = 0;
- fixed (byte* p = &bytes[0])
+ fixed (byte* p = &bytes.DangerousGetPinnableReference())
{
- if (_useAsyncIO)
- r = Interop.Kernel32.ReadFile(handle, p + offset, count, IntPtr.Zero, overlapped);
- else
- r = Interop.Kernel32.ReadFile(handle, p + offset, count, out numBytesRead, IntPtr.Zero);
+ r = _useAsyncIO ?
+ Interop.Kernel32.ReadFile(handle, p, bytes.Length, IntPtr.Zero, overlapped) :
+ Interop.Kernel32.ReadFile(handle, p, bytes.Length, out numBytesRead, IntPtr.Zero);
}
if (r == 0)
@@ -1266,37 +1207,19 @@ namespace System.IO
}
}
- private unsafe int WriteFileNative(SafeFileHandle handle, byte[] bytes, int offset, int count, NativeOverlapped* overlapped, out int errorCode)
+ private unsafe int WriteFileNative(SafeFileHandle handle, ReadOnlySpan<byte> buffer, NativeOverlapped* overlapped, out int errorCode)
{
Debug.Assert(handle != null, "handle != null");
- Debug.Assert(offset >= 0, "offset >= 0");
- Debug.Assert(count >= 0, "count >= 0");
- Debug.Assert(bytes != null, "bytes != null");
- // Don't corrupt memory when multiple threads are erroneously writing
- // to this stream simultaneously. (the OS is reading from
- // the array we pass to WriteFile, but if we read beyond the end and
- // that memory isn't allocated, we could get an AV.)
- if (bytes.Length - offset < count)
- throw new IndexOutOfRangeException(SR.IndexOutOfRange_IORaceCondition);
-
Debug.Assert((_useAsyncIO && overlapped != null) || (!_useAsyncIO && overlapped == null), "Async IO and overlapped parameters inconsistent in call to WriteFileNative.");
- // You can't use the fixed statement on an array of length 0.
- if (bytes.Length == 0)
- {
- errorCode = 0;
- return 0;
- }
-
int numBytesWritten = 0;
- int r = 0;
+ int r;
- fixed (byte* p = &bytes[0])
+ fixed (byte* p = &buffer.DangerousGetPinnableReference())
{
- if (_useAsyncIO)
- r = Interop.Kernel32.WriteFile(handle, p + offset, count, IntPtr.Zero, overlapped);
- else
- r = Interop.Kernel32.WriteFile(handle, p + offset, count, out numBytesWritten, IntPtr.Zero);
+ r = _useAsyncIO ?
+ Interop.Kernel32.WriteFile(handle, p, buffer.Length, IntPtr.Zero, overlapped) :
+ Interop.Kernel32.WriteFile(handle, p, buffer.Length, out numBytesWritten, IntPtr.Zero);
}
if (r == 0)
@@ -1472,7 +1395,7 @@ namespace System.IO
}
// Kick off the read.
- synchronousSuccess = ReadFileNative(_fileHandle, copyBuffer, 0, copyBuffer.Length, readAwaitable._nativeOverlapped, out errorCode) >= 0;
+ synchronousSuccess = ReadFileNative(_fileHandle, copyBuffer, readAwaitable._nativeOverlapped, out errorCode) >= 0;
}
// If the operation did not synchronously succeed, it either failed or initiated the asynchronous operation.
@@ -1696,20 +1619,6 @@ namespace System.IO
}
}
- private Task<int> TaskFromResultOrCache(int result)
- {
- Task<int> completedTask = _lastSynchronouslyCompletedTask;
- Debug.Assert(completedTask == null || completedTask.Status == TaskStatus.RanToCompletion, "Cached task should have completed successfully");
-
- if ((completedTask == null) || (completedTask.Result != result))
- {
- completedTask = Task.FromResult(result);
- _lastSynchronouslyCompletedTask = completedTask;
- }
-
- return completedTask;
- }
-
private void LockInternal(long position, long length)
{
int positionLow = unchecked((int)(position));
@@ -1735,5 +1644,25 @@ namespace System.IO
throw Win32Marshal.GetExceptionForLastWin32Error();
}
}
+ private SafeFileHandle ValidateFileHandle(SafeFileHandle fileHandle)
+ {
+ if (fileHandle.IsInvalid)
+ {
+ // Return a meaningful exception with the full path.
+
+ // NT5 oddity - when trying to open "C:\" as a Win32FileStream,
+ // we usually get ERROR_PATH_NOT_FOUND from the OS. We should
+ // probably be consistent w/ every other directory.
+ int errorCode = Marshal.GetLastWin32Error();
+
+ if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && _path.Length == PathInternal.GetRootLength(_path))
+ errorCode = Interop.Errors.ERROR_ACCESS_DENIED;
+
+ throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path);
+ }
+
+ fileHandle.IsAsync = _useAsyncIO;
+ return fileHandle;
+ }
}
}
diff --git a/src/mscorlib/shared/System/IO/FileStream.cs b/src/mscorlib/shared/System/IO/FileStream.cs
index 39f7b60d12..65c63bcc53 100644
--- a/src/mscorlib/shared/System/IO/FileStream.cs
+++ b/src/mscorlib/shared/System/IO/FileStream.cs
@@ -51,6 +51,9 @@ namespace System.IO
/// </summary>
private readonly bool _useAsyncIO;
+ /// <summary>cached task for read ops that complete synchronously</summary>
+ private Task<int> _lastSynchronouslyCompletedTask = null;
+
/// <summary>
/// Currently cached position in the stream. This should always mirror the underlying file's actual position,
/// and should only ever be out of sync if another stream with access to this same file manipulates it, at which
@@ -292,6 +295,36 @@ namespace System.IO
return FlushAsyncInternal(cancellationToken);
}
+ public override int Read(byte[] array, int offset, int count)
+ {
+ ValidateReadWriteArgs(array, offset, count);
+ return _useAsyncIO ?
+ ReadAsyncTask(array, offset, count, CancellationToken.None).GetAwaiter().GetResult() :
+ ReadSpan(new Span<byte>(array, offset, count));
+ }
+
+ public override int Read(Span<byte> destination)
+ {
+ if (GetType() == typeof(FileStream) && !_useAsyncIO)
+ {
+ if (_fileHandle.IsClosed)
+ {
+ throw Error.GetFileNotOpen();
+ }
+ return ReadSpan(destination);
+ }
+ else
+ {
+ // This type is derived from FileStream and/or the stream is in async mode. If this is a
+ // derived type, it may have overridden Read(byte[], int, int) prior to this Read(Span<byte>)
+ // overload being introduced. In that case, this Read(Span<byte>) overload should use the behavior
+ // of Read(byte[],int,int) overload. Or if the stream is in async mode, we can't call the
+ // synchronous ReadSpan, so we similarly call the base Read, which will turn delegate to
+ // Read(byte[],int,int), which will do the right thing if we're in async mode.
+ return base.Read(destination);
+ }
+ }
+
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
@@ -304,10 +337,12 @@ namespace System.IO
throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/);
// If we have been inherited into a subclass, the following implementation could be incorrect
- // since it does not call through to Read() or ReadAsync() which a subclass might have overridden.
+ // since it does not call through to Read() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read/ReadAsync) when we are not sure.
- if (GetType() != typeof(FileStream))
+ // Similarly, if we weren't opened for asynchronous I/O, call to the base implementation so that
+ // Read is invoked asynchronously.
+ if (GetType() != typeof(FileStream) || !_useAsyncIO)
return base.ReadAsync(buffer, offset, count, cancellationToken);
if (cancellationToken.IsCancellationRequested)
@@ -316,7 +351,86 @@ namespace System.IO
if (IsClosed)
throw Error.GetFileNotOpen();
- return ReadAsyncInternal(buffer, offset, count, cancellationToken);
+ return ReadAsyncTask(buffer, offset, count, cancellationToken);
+ }
+
+ public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ if (!_useAsyncIO || GetType() != typeof(FileStream))
+ {
+ // If we're not using async I/O, delegate to the base, which will queue a call to Read.
+ // Or if this isn't a concrete FileStream, a derived type may have overridden ReadAsync(byte[],...),
+ // which was introduced first, so delegate to the base which will delegate to that.
+ return base.ReadAsync(destination, cancellationToken);
+ }
+
+ if (cancellationToken.IsCancellationRequested)
+ {
+ return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
+ }
+
+ if (IsClosed)
+ {
+ throw Error.GetFileNotOpen();
+ }
+
+ Task<int> t = ReadAsyncInternal(destination, cancellationToken, out int synchronousResult);
+ return t != null ?
+ new ValueTask<int>(t) :
+ new ValueTask<int>(synchronousResult);
+ }
+
+ private Task<int> ReadAsyncTask(byte[] array, int offset, int count, CancellationToken cancellationToken)
+ {
+ Task<int> t = ReadAsyncInternal(new Memory<byte>(array, offset, count), cancellationToken, out int synchronousResult);
+
+ if (t == null)
+ {
+ t = _lastSynchronouslyCompletedTask;
+ Debug.Assert(t == null || t.IsCompletedSuccessfully, "Cached task should have completed successfully");
+
+ if (t == null || t.Result != synchronousResult)
+ {
+ _lastSynchronouslyCompletedTask = t = Task.FromResult(synchronousResult);
+ }
+ }
+
+ return t;
+ }
+
+ public override void Write(byte[] array, int offset, int count)
+ {
+ ValidateReadWriteArgs(array, offset, count);
+ if (_useAsyncIO)
+ {
+ WriteAsyncInternal(new ReadOnlyMemory<byte>(array, offset, count), CancellationToken.None).GetAwaiter().GetResult();
+ }
+ else
+ {
+ WriteSpan(new ReadOnlySpan<byte>(array, offset, count));
+ }
+ }
+
+ public override void Write(ReadOnlySpan<byte> destination)
+ {
+ if (GetType() == typeof(FileStream) && !_useAsyncIO)
+ {
+ if (_fileHandle.IsClosed)
+ {
+ throw Error.GetFileNotOpen();
+ }
+ WriteSpan(destination);
+ }
+ else
+ {
+ // This type is derived from FileStream and/or the stream is in async mode. If this is a
+ // derived type, it may have overridden Write(byte[], int, int) prior to this Write(ReadOnlySpan<byte>)
+ // overload being introduced. In that case, this Write(ReadOnlySpan<byte>) overload should use the behavior
+ // of Write(byte[],int,int) overload. Or if the stream is in async mode, we can't call the
+ // synchronous WriteSpan, so we similarly call the base Write, which will turn delegate to
+ // Write(byte[],int,int), which will do the right thing if we're in async mode.
+ base.Write(destination);
+ }
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
@@ -334,7 +448,7 @@ namespace System.IO
// since it does not call through to Write() or WriteAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write/WriteAsync) when we are not sure.
- if (GetType() != typeof(FileStream))
+ if (!_useAsyncIO || GetType() != typeof(FileStream))
return base.WriteAsync(buffer, offset, count, cancellationToken);
if (cancellationToken.IsCancellationRequested)
@@ -343,7 +457,30 @@ namespace System.IO
if (IsClosed)
throw Error.GetFileNotOpen();
- return WriteAsyncInternal(buffer, offset, count, cancellationToken);
+ return WriteAsyncInternal(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken);
+ }
+
+ public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ if (!_useAsyncIO || GetType() != typeof(FileStream))
+ {
+ // If we're not using async I/O, delegate to the base, which will queue a call to Write.
+ // Or if this isn't a concrete FileStream, a derived type may have overridden WriteAsync(byte[],...),
+ // which was introduced first, so delegate to the base which will delegate to that.
+ return base.WriteAsync(source, cancellationToken);
+ }
+
+ if (cancellationToken.IsCancellationRequested)
+ {
+ return Task.FromCanceled<int>(cancellationToken);
+ }
+
+ if (IsClosed)
+ {
+ throw Error.GetFileNotOpen();
+ }
+
+ return WriteAsyncInternal(source, cancellationToken);
}
/// <summary>
@@ -594,7 +731,11 @@ namespace System.IO
_readPos = _readLength = 0;
}
- private int ReadByteCore()
+ /// <summary>
+ /// Reads a byte from the file stream. Returns the byte cast to an int
+ /// or -1 if reading from the end of the stream.
+ /// </summary>
+ public override int ReadByte()
{
PrepareForReading();
@@ -602,9 +743,7 @@ namespace System.IO
if (_readPos == _readLength)
{
FlushWriteBuffer();
- Debug.Assert(_bufferLength > 0, "_bufferSize > 0");
-
- _readLength = ReadNative(buffer, 0, _bufferLength);
+ _readLength = FillReadBufferForReadByte();
_readPos = 0;
if (_readLength == 0)
{
@@ -615,13 +754,18 @@ namespace System.IO
return buffer[_readPos++];
}
- private void WriteByteCore(byte value)
+ /// <summary>
+ /// Writes a byte to the current position in the stream and advances the position
+ /// within the stream by one byte.
+ /// </summary>
+ /// <param name="value">The byte to write to the stream.</param>
+ public override void WriteByte(byte value)
{
PrepareForWriting();
// Flush the write buffer if it's full
if (_writePos == _bufferLength)
- FlushWriteBuffer();
+ FlushWriteBufferForWriteByte();
// We now have space in the buffer. Store the byte.
GetBuffer()[_writePos++] = value;
@@ -672,7 +816,7 @@ namespace System.IO
if (!IsAsync)
return base.BeginRead(array, offset, numBytes, callback, state);
else
- return TaskToApm.Begin(ReadAsyncInternal(array, offset, numBytes, CancellationToken.None), callback, state);
+ return TaskToApm.Begin(ReadAsyncTask(array, offset, numBytes, CancellationToken.None), callback, state);
}
public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback callback, object state)
@@ -692,7 +836,7 @@ namespace System.IO
if (!IsAsync)
return base.BeginWrite(array, offset, numBytes, callback, state);
else
- return TaskToApm.Begin(WriteAsyncInternal(array, offset, numBytes, CancellationToken.None), callback, state);
+ return TaskToApm.Begin(WriteAsyncInternal(new ReadOnlyMemory<byte>(array, offset, numBytes), CancellationToken.None), callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
diff --git a/src/mscorlib/shared/System/IO/FileStreamCompletionSource.Win32.cs b/src/mscorlib/shared/System/IO/FileStreamCompletionSource.Win32.cs
index 7dca13335e..e3871bcd6c 100644
--- a/src/mscorlib/shared/System/IO/FileStreamCompletionSource.Win32.cs
+++ b/src/mscorlib/shared/System/IO/FileStreamCompletionSource.Win32.cs
@@ -2,11 +2,11 @@
// 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.Security;
+using System.Buffers;
+using System.Diagnostics;
+using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
-using System.Runtime.InteropServices;
-using System.Diagnostics;
namespace System.IO
{
@@ -15,7 +15,7 @@ namespace System.IO
// This is an internal object extending TaskCompletionSource with fields
// for all of the relevant data necessary to complete the IO operation.
// This is used by IOCallback and all of the async methods.
- unsafe private sealed class FileStreamCompletionSource : TaskCompletionSource<int>
+ private unsafe class FileStreamCompletionSource : TaskCompletionSource<int>
{
private const long NoResult = 0;
private const long ResultSuccess = (long)1 << 32;
@@ -28,7 +28,6 @@ namespace System.IO
private readonly FileStream _stream;
private readonly int _numBufferedBytes;
- private readonly CancellationToken _cancellationToken;
private CancellationTokenRegistration _cancellationRegistration;
#if DEBUG
private bool _cancellationHasBeenRegistered;
@@ -37,20 +36,19 @@ namespace System.IO
private long _result; // Using long since this needs to be used in Interlocked APIs
// Using RunContinuationsAsynchronously for compat reasons (old API used Task.Factory.StartNew for continuations)
- internal FileStreamCompletionSource(FileStream stream, int numBufferedBytes, byte[] bytes, CancellationToken cancellationToken)
+ internal FileStreamCompletionSource(FileStream stream, int numBufferedBytes, byte[] bytes)
: base(TaskCreationOptions.RunContinuationsAsynchronously)
{
_numBufferedBytes = numBufferedBytes;
_stream = stream;
_result = NoResult;
- _cancellationToken = cancellationToken;
- // Create the native overlapped. We try to use the preallocated overlapped if possible:
- // it's possible if the byte buffer is the same one that's associated with the preallocated overlapped
- // and if no one else is currently using the preallocated overlapped. This is the fast-path for cases
- // where the user-provided buffer is smaller than the FileStream's buffer (such that the FileStream's
+ // Create the native overlapped. We try to use the preallocated overlapped if possible: it's possible if the byte
+ // buffer is null (there's nothing to pin) or the same one that's associated with the preallocated overlapped (and
+ // thus is already pinned) and if no one else is currently using the preallocated overlapped. This is the fast-path
+ // for cases where the user-provided buffer is smaller than the FileStream's buffer (such that the FileStream's
// buffer is used) and where operations on the FileStream are not being performed concurrently.
- _overlapped = ReferenceEquals(bytes, _stream._buffer) && _stream.CompareExchangeCurrentOverlappedOwner(this, null) == null ?
+ _overlapped = (bytes == null || ReferenceEquals(bytes, _stream._buffer)) && _stream.CompareExchangeCurrentOverlappedOwner(this, null) == null ?
_stream._fileHandle.ThreadPoolBinding.AllocateNativeOverlapped(_stream._preallocatedOverlapped) :
_stream._fileHandle.ThreadPoolBinding.AllocateNativeOverlapped(s_ioCallback, this, bytes);
Debug.Assert(_overlapped != null, "AllocateNativeOverlapped returned null");
@@ -67,15 +65,16 @@ namespace System.IO
TrySetResult(numBytes + _numBufferedBytes);
}
- public void RegisterForCancellation()
+ public void RegisterForCancellation(CancellationToken cancellationToken)
{
#if DEBUG
+ Debug.Assert(cancellationToken.CanBeCanceled);
Debug.Assert(!_cancellationHasBeenRegistered, "Cannot register for cancellation twice");
_cancellationHasBeenRegistered = true;
#endif
- // Quick check to make sure that the cancellation token supports cancellation, and that the IO hasn't completed
- if ((_cancellationToken.CanBeCanceled) && (_overlapped != null))
+ // Quick check to make sure the IO hasn't completed
+ if (_overlapped != null)
{
var cancelCallback = s_cancelCallback;
if (cancelCallback == null) s_cancelCallback = cancelCallback = Cancel;
@@ -84,7 +83,7 @@ namespace System.IO
long packedResult = Interlocked.CompareExchange(ref _result, RegisteringCancellation, NoResult);
if (packedResult == NoResult)
{
- _cancellationRegistration = _cancellationToken.Register(cancelCallback, this);
+ _cancellationRegistration = cancellationToken.Register(cancelCallback, this);
// Switch the result, just in case IO completed while we were setting the registration
packedResult = Interlocked.Exchange(ref _result, NoResult);
@@ -104,7 +103,7 @@ namespace System.IO
}
}
- internal void ReleaseNativeResource()
+ internal virtual void ReleaseNativeResource()
{
// Ensure that cancellation has been completed and cleaned up.
_cancellationRegistration.Dispose();
@@ -172,6 +171,7 @@ namespace System.IO
private void CompleteCallback(ulong packedResult)
{
// Free up the native resource and cancellation registration
+ CancellationToken cancellationToken = _cancellationRegistration.Token; // access before disposing registration
ReleaseNativeResource();
// Unpack the result and send it to the user
@@ -181,7 +181,7 @@ namespace System.IO
int errorCode = unchecked((int)(packedResult & uint.MaxValue));
if (errorCode == Interop.Errors.ERROR_OPERATION_ABORTED)
{
- TrySetCanceled(_cancellationToken.IsCancellationRequested ? _cancellationToken : new CancellationToken(true));
+ TrySetCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
else
{
@@ -218,5 +218,28 @@ namespace System.IO
}
}
}
+
+ /// <summary>
+ /// Extends <see cref="FileStreamCompletionSource"/> with to support disposing of a
+ /// <see cref="MemoryHandle"/> when the operation has completed. This should only be used
+ /// when memory doesn't wrap a byte[].
+ /// </summary>
+ private sealed class MemoryFileStreamCompletionSource : FileStreamCompletionSource
+ {
+ private MemoryHandle _handle; // mutable struct; do not make this readonly
+
+ internal MemoryFileStreamCompletionSource(FileStream stream, int numBufferedBytes, ReadOnlyMemory<byte> memory) :
+ base(stream, numBufferedBytes, bytes: null) // this type handles the pinning, so null is passed for bytes
+ {
+ Debug.Assert(!memory.DangerousTryGetArray(out ArraySegment<byte> array), "The base should be used directly if we can get the array.");
+ _handle = memory.Retain(pin: true);
+ }
+
+ internal override void ReleaseNativeResource()
+ {
+ _handle.Dispose();
+ base.ReleaseNativeResource();
+ }
+ }
}
}
diff --git a/src/mscorlib/shared/System/IO/IOException.cs b/src/mscorlib/shared/System/IO/IOException.cs
new file mode 100644
index 0000000000..1fbd352613
--- /dev/null
+++ b/src/mscorlib/shared/System/IO/IOException.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.Serialization;
+
+namespace System.IO
+{
+ public class IOException : SystemException
+ {
+ public IOException()
+ : base(SR.Arg_IOException)
+ {
+ HResult = HResults.COR_E_IO;
+ }
+
+ public IOException(String message)
+ : base(message)
+ {
+ HResult = HResults.COR_E_IO;
+ }
+
+ public IOException(String message, int hresult)
+ : base(message)
+ {
+ HResult = hresult;
+ }
+
+ public IOException(String message, Exception innerException)
+ : base(message, innerException)
+ {
+ HResult = HResults.COR_E_IO;
+ }
+
+ protected IOException(SerializationInfo info, StreamingContext context) : base(info, context)
+ {
+ throw new PlatformNotSupportedException();
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/IO/Path.cs b/src/mscorlib/shared/System/IO/Path.cs
index 135bb42881..2676f0d2fe 100644
--- a/src/mscorlib/shared/System/IO/Path.cs
+++ b/src/mscorlib/shared/System/IO/Path.cs
@@ -166,6 +166,30 @@ namespace System.IO
return new string(pRandomFileName, 0, RandomFileNameLength);
}
+ /// <summary>
+ /// Returns true if the path is fixed to a specific drive or UNC path. This method does no
+ /// validation of the path (URIs will be returned as relative as a result).
+ /// Returns false if the path specified is relative to the current drive or working directory.
+ /// </summary>
+ /// <remarks>
+ /// Handles paths that use the alternate directory separator. It is a frequent mistake to
+ /// assume that rooted paths <see cref="Path.IsPathRooted(string)"/> are not relative. This isn't the case.
+ /// "C:a" is drive relative- meaning that it will be resolved against the current directory
+ /// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory
+ /// will not be used to modify the path).
+ /// </remarks>
+ /// <exception cref="ArgumentNullException">
+ /// Thrown if <paramref name="path"/> is null.
+ /// </exception>
+ public static bool IsPathFullyQualified(string path)
+ {
+ if (path == null)
+ {
+ throw new ArgumentNullException(nameof(path));
+ }
+ return !PathInternal.IsPartiallyQualified(path);
+ }
+
// Tests if a path includes a file extension. The result is
// true if the characters that follow the last directory
// separator ('\\' or '/') or volume separator (':') in the path include
diff --git a/src/mscorlib/shared/System/IO/PathInternal.Windows.cs b/src/mscorlib/shared/System/IO/PathInternal.Windows.cs
index 01069e757c..2ab3928608 100644
--- a/src/mscorlib/shared/System/IO/PathInternal.Windows.cs
+++ b/src/mscorlib/shared/System/IO/PathInternal.Windows.cs
@@ -437,11 +437,6 @@ namespace System.IO
return IsDirectorySeparator(ch) || VolumeSeparatorChar == ch;
}
- internal static string TrimEndingDirectorySeparator(string path) =>
- EndsInDirectorySeparator(path) ?
- path.Substring(0, path.Length - 1) :
- path;
-
/// <summary>
/// Returns true if the path is effectively empty for the current OS.
/// For unix, this is empty or null. For Windows, this is empty, null, or
diff --git a/src/mscorlib/shared/System/IO/PathTooLongException.cs b/src/mscorlib/shared/System/IO/PathTooLongException.cs
index 64c8e6c7e6..15f282ebf6 100644
--- a/src/mscorlib/shared/System/IO/PathTooLongException.cs
+++ b/src/mscorlib/shared/System/IO/PathTooLongException.cs
@@ -13,19 +13,19 @@ namespace System.IO
public PathTooLongException()
: base(SR.IO_PathTooLong)
{
- HResult = __HResults.COR_E_PATHTOOLONG;
+ HResult = HResults.COR_E_PATHTOOLONG;
}
public PathTooLongException(string message)
: base(message)
{
- HResult = __HResults.COR_E_PATHTOOLONG;
+ HResult = HResults.COR_E_PATHTOOLONG;
}
public PathTooLongException(string message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_PATHTOOLONG;
+ HResult = HResults.COR_E_PATHTOOLONG;
}
protected PathTooLongException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs b/src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs
index c8e720b7ac..e8f74dd05c 100644
--- a/src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs
+++ b/src/mscorlib/shared/System/IO/PinnedBufferMemoryStream.cs
@@ -46,6 +46,10 @@ namespace System.IO
Initialize(ptr, len, len, FileAccess.Read);
}
+ public override int Read(Span<byte> destination) => ReadCore(destination);
+
+ public override void Write(ReadOnlySpan<byte> source) => WriteCore(source);
+
~PinnedBufferMemoryStream()
{
Dispose(false);
diff --git a/src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs b/src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs
index b78f50fe7b..b899951ba7 100644
--- a/src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs
+++ b/src/mscorlib/shared/System/IO/UnmanagedMemoryStream.cs
@@ -361,8 +361,27 @@ namespace System.IO
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
- Contract.EndContractBlock(); // Keep this in sync with contract validation in ReadAsync
+ return ReadCore(new Span<byte>(buffer, offset, count));
+ }
+
+ public override int Read(Span<byte> destination)
+ {
+ if (GetType() == typeof(UnmanagedMemoryStream))
+ {
+ return ReadCore(destination);
+ }
+ else
+ {
+ // UnmanagedMemoryStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior
+ // to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload
+ // should use the behavior of Read(byte[],int,int) overload.
+ return base.Read(destination);
+ }
+ }
+
+ internal int ReadCore(Span<byte> destination)
+ {
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanRead) throw Error.GetReadNotSupported();
@@ -370,20 +389,22 @@ namespace System.IO
// changes our position after we decide we can read some bytes.
long pos = Interlocked.Read(ref _position);
long len = Interlocked.Read(ref _length);
- long n = len - pos;
- if (n > count)
- n = count;
+ long n = Math.Min(len - pos, destination.Length);
if (n <= 0)
+ {
return 0;
+ }
int nInt = (int)n; // Safe because n <= count, which is an Int32
if (nInt < 0)
+ {
return 0; // _position could be beyond EOF
+ }
Debug.Assert(pos + nInt >= 0, "_position + n >= 0"); // len is less than 2^63 -1.
unsafe
{
- fixed (byte* pBuffer = buffer)
+ fixed (byte* pBuffer = &destination.DangerousGetPinnableReference())
{
if (_buffer != null)
{
@@ -393,7 +414,7 @@ namespace System.IO
try
{
_buffer.AcquirePointer(ref pointer);
- Buffer.Memcpy(pBuffer + offset, pointer + pos + _offset, nInt);
+ Buffer.Memcpy(pBuffer, pointer + pos + _offset, nInt);
}
finally
{
@@ -405,7 +426,7 @@ namespace System.IO
}
else
{
- Buffer.Memcpy(pBuffer + offset, _mem + pos, nInt);
+ Buffer.Memcpy(pBuffer, _mem + pos, nInt);
}
}
}
@@ -450,6 +471,28 @@ namespace System.IO
}
/// <summary>
+ /// Reads bytes from stream and puts them into the buffer
+ /// </summary>
+ /// <param name="destination">Buffer to read the bytes to.</param>
+ /// <param name="cancellationToken">Token that can be used to cancel this operation.</param>
+ public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ if (cancellationToken.IsCancellationRequested)
+ {
+ return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
+ }
+
+ try
+ {
+ return new ValueTask<int>(Read(destination.Span));
+ }
+ catch (Exception ex)
+ {
+ return new ValueTask<int>(Task.FromException<int>(ex));
+ }
+ }
+
+ /// <summary>
/// Returns the byte at the stream current Position and advances the Position.
/// </summary>
/// <returns></returns>
@@ -583,17 +626,38 @@ namespace System.IO
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
- Contract.EndContractBlock(); // Keep contract validation in sync with WriteAsync(..)
+ WriteCore(new Span<byte>(buffer, offset, count));
+ }
+
+ public override void Write(ReadOnlySpan<byte> source)
+ {
+ if (GetType() == typeof(UnmanagedMemoryStream))
+ {
+ WriteCore(source);
+ }
+ else
+ {
+ // UnmanagedMemoryStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior
+ // to this Write(Span<byte>) overload being introduced. In that case, this Write(Span<byte>) overload
+ // should use the behavior of Write(byte[],int,int) overload.
+ base.Write(source);
+ }
+ }
+
+ internal unsafe void WriteCore(ReadOnlySpan<byte> source)
+ {
if (!_isOpen) throw Error.GetStreamIsClosed();
if (!CanWrite) throw Error.GetWriteNotSupported();
long pos = Interlocked.Read(ref _position); // Use a local to avoid a race condition
long len = Interlocked.Read(ref _length);
- long n = pos + count;
+ long n = pos + source.Length;
// Check for overflow
if (n < 0)
+ {
throw new IOException(SR.IO_StreamTooLong);
+ }
if (n > _capacity)
{
@@ -606,10 +670,7 @@ namespace System.IO
// zero any memory in the middle.
if (pos > len)
{
- unsafe
- {
- Buffer.ZeroMemory(_mem + len, pos - len);
- }
+ Buffer.ZeroMemory(_mem + len, pos - len);
}
// set length after zeroing memory to avoid race condition of accessing unzeroed memory
@@ -619,39 +680,37 @@ namespace System.IO
}
}
- unsafe
+ fixed (byte* pBuffer = &source.DangerousGetPinnableReference())
{
- fixed (byte* pBuffer = buffer)
+ if (_buffer != null)
{
- if (_buffer != null)
+ long bytesLeft = _capacity - pos;
+ if (bytesLeft < source.Length)
{
- long bytesLeft = _capacity - pos;
- if (bytesLeft < count)
- {
- throw new ArgumentException(SR.Arg_BufferTooSmall);
- }
+ throw new ArgumentException(SR.Arg_BufferTooSmall);
+ }
- byte* pointer = null;
- RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- _buffer.AcquirePointer(ref pointer);
- Buffer.Memcpy(pointer + pos + _offset, pBuffer + offset, count);
- }
- finally
- {
- if (pointer != null)
- {
- _buffer.ReleasePointer();
- }
- }
+ byte* pointer = null;
+ RuntimeHelpers.PrepareConstrainedRegions();
+ try
+ {
+ _buffer.AcquirePointer(ref pointer);
+ Buffer.Memcpy(pointer + pos + _offset, pBuffer, source.Length);
}
- else
+ finally
{
- Buffer.Memcpy(_mem + pos, pBuffer + offset, count);
+ if (pointer != null)
+ {
+ _buffer.ReleasePointer();
+ }
}
}
+ else
+ {
+ Buffer.Memcpy(_mem + pos, pBuffer, source.Length);
+ }
}
+
Interlocked.Exchange(ref _position, n);
return;
}
@@ -692,6 +751,29 @@ namespace System.IO
}
/// <summary>
+ /// Writes buffer into the stream. The operation completes synchronously.
+ /// </summary>
+ /// <param name="buffer">Buffer that will be written.</param>
+ /// <param name="cancellationToken">Token that can be used to cancel the operation.</param>
+ public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ if (cancellationToken.IsCancellationRequested)
+ {
+ return Task.FromCanceled(cancellationToken);
+ }
+
+ try
+ {
+ Write(source.Span);
+ return Task.CompletedTask;
+ }
+ catch (Exception ex)
+ {
+ return Task.FromException(ex);
+ }
+ }
+
+ /// <summary>
/// Writes a byte to the stream and advances the current Position.
/// </summary>
/// <param name="value"></param>
diff --git a/src/mscorlib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs b/src/mscorlib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs
index d547e771d7..2699912ea1 100644
--- a/src/mscorlib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs
+++ b/src/mscorlib/shared/System/IO/UnmanagedMemoryStreamWrapper.cs
@@ -114,6 +114,11 @@ namespace System.IO
return _unmanagedStream.Read(buffer, offset, count);
}
+ public override int Read(Span<byte> destination)
+ {
+ return _unmanagedStream.Read(destination);
+ }
+
public override int ReadByte()
{
return _unmanagedStream.ReadByte();
@@ -136,6 +141,11 @@ namespace System.IO
_unmanagedStream.Write(buffer, offset, count);
}
+ public override void Write(ReadOnlySpan<byte> source)
+ {
+ _unmanagedStream.Write(source);
+ }
+
public override void WriteByte(byte value)
{
_unmanagedStream.WriteByte(value);
@@ -200,11 +210,21 @@ namespace System.IO
return _unmanagedStream.ReadAsync(buffer, offset, count, cancellationToken);
}
+ public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ return _unmanagedStream.ReadAsync(destination, cancellationToken);
+ }
+
public override Task WriteAsync(Byte[] buffer, Int32 offset, Int32 count, CancellationToken cancellationToken)
{
return _unmanagedStream.WriteAsync(buffer, offset, count, cancellationToken);
}
+
+ public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ return _unmanagedStream.WriteAsync(source, cancellationToken);
+ }
} // class UnmanagedMemoryStreamWrapper
} // namespace
diff --git a/src/mscorlib/shared/System/IO/Win32Marshal.cs b/src/mscorlib/shared/System/IO/Win32Marshal.cs
index a24409ed03..14a064a700 100644
--- a/src/mscorlib/shared/System/IO/Win32Marshal.cs
+++ b/src/mscorlib/shared/System/IO/Win32Marshal.cs
@@ -63,10 +63,16 @@ namespace System.IO
return new IOException(SR.Format(SR.IO_AlreadyExists_Name, path), MakeHRFromErrorCode(errorCode));
case Interop.Errors.ERROR_FILENAME_EXCED_RANGE:
- return new PathTooLongException(SR.Format(SR.IO_PathTooLong_Path, path));
+ if (path.Length == 0)
+ return new PathTooLongException(SR.IO_PathTooLong);
+ else
+ return new PathTooLongException(SR.Format(SR.IO_PathTooLong_Path, path));
+
+ case Interop.Errors.ERROR_INVALID_DRIVE:
+ throw new DriveNotFoundException(SR.Format(SR.IO_DriveNotFound_Drive, path));
case Interop.Errors.ERROR_INVALID_PARAMETER:
- return new IOException(GetMessage(errorCode), MakeHRFromErrorCode(errorCode));
+ return new IOException(Interop.Kernel32.GetMessage(errorCode), MakeHRFromErrorCode(errorCode));
case Interop.Errors.ERROR_SHARING_VIOLATION:
if (path.Length == 0)
@@ -84,7 +90,7 @@ namespace System.IO
return new OperationCanceledException();
default:
- return new IOException(GetMessage(errorCode), MakeHRFromErrorCode(errorCode));
+ return new IOException(Interop.Kernel32.GetMessage(errorCode), MakeHRFromErrorCode(errorCode));
}
}
@@ -97,13 +103,5 @@ namespace System.IO
return unchecked(((int)0x80070000) | errorCode);
}
-
- /// <summary>
- /// Returns a string message for the specified Win32 error code.
- /// </summary>
- internal static string GetMessage(int errorCode)
- {
- return Interop.Kernel32.GetMessage(errorCode);
- }
}
}
diff --git a/src/mscorlib/shared/System/IndexOutOfRangeException.cs b/src/mscorlib/shared/System/IndexOutOfRangeException.cs
index d5b24b35d5..bec63d73d6 100644
--- a/src/mscorlib/shared/System/IndexOutOfRangeException.cs
+++ b/src/mscorlib/shared/System/IndexOutOfRangeException.cs
@@ -20,19 +20,19 @@ namespace System
public IndexOutOfRangeException()
: base(SR.Arg_IndexOutOfRangeException)
{
- HResult = __HResults.COR_E_INDEXOUTOFRANGE;
+ HResult = HResults.COR_E_INDEXOUTOFRANGE;
}
public IndexOutOfRangeException(String message)
: base(message)
{
- HResult = __HResults.COR_E_INDEXOUTOFRANGE;
+ HResult = HResults.COR_E_INDEXOUTOFRANGE;
}
public IndexOutOfRangeException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_INDEXOUTOFRANGE;
+ HResult = HResults.COR_E_INDEXOUTOFRANGE;
}
}
}
diff --git a/src/mscorlib/shared/System/InsufficientExecutionStackException.cs b/src/mscorlib/shared/System/InsufficientExecutionStackException.cs
index 41df3ae970..a14cb67150 100644
--- a/src/mscorlib/shared/System/InsufficientExecutionStackException.cs
+++ b/src/mscorlib/shared/System/InsufficientExecutionStackException.cs
@@ -11,19 +11,19 @@ namespace System
public InsufficientExecutionStackException()
: base(SR.Arg_InsufficientExecutionStackException)
{
- HResult = __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK;
+ HResult = HResults.COR_E_INSUFFICIENTEXECUTIONSTACK;
}
public InsufficientExecutionStackException(String message)
: base(message)
{
- HResult = __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK;
+ HResult = HResults.COR_E_INSUFFICIENTEXECUTIONSTACK;
}
public InsufficientExecutionStackException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK;
+ HResult = HResults.COR_E_INSUFFICIENTEXECUTIONSTACK;
}
}
}
diff --git a/src/mscorlib/src/System/Int16.cs b/src/mscorlib/shared/System/Int16.cs
index 82e5dd5a38..6aaf4280d3 100644
--- a/src/mscorlib/src/System/Int16.cs
+++ b/src/mscorlib/shared/System/Int16.cs
@@ -12,19 +12,18 @@
**
===========================================================*/
-
-using System;
+using System.Diagnostics.Contracts;
using System.Globalization;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
+using System.Runtime.Versioning;
namespace System
{
[Serializable]
- [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
- [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
- public struct Int16 : IComparable, IFormattable, IConvertible
- , IComparable<Int16>, IEquatable<Int16>
+ [StructLayout(LayoutKind.Sequential)]
+ [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ public struct Int16 : IComparable, IConvertible, IFormattable, IComparable<Int16>, IEquatable<Int16>
{
private short m_value; // Do not rename (binary serialization)
@@ -66,7 +65,7 @@ namespace System
return m_value == ((Int16)obj).m_value;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public bool Equals(Int16 obj)
{
return m_value == obj;
@@ -117,27 +116,37 @@ namespace System
public static short Parse(String s)
{
- return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
public static short Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
- return Parse(s, style, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
public static short Parse(String s, IFormatProvider provider)
{
- return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
public static short Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
+ }
+
+ public static short Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
- private static short Parse(String s, NumberStyles style, NumberFormatInfo info)
+ private static short Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info)
{
int i = 0;
try
@@ -166,16 +175,35 @@ namespace System
public static bool TryParse(String s, out Int16 result)
{
- return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return TryParse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int16 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return TryParse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
+ }
+
+ public static bool TryParse(ReadOnlySpan<char> s, out Int16 result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
- private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out Int16 result)
+ private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out Int16 result)
{
result = 0;
int i;
diff --git a/src/mscorlib/src/System/Int32.cs b/src/mscorlib/shared/System/Int32.cs
index 503552117d..f5e832a274 100644
--- a/src/mscorlib/src/System/Int32.cs
+++ b/src/mscorlib/shared/System/Int32.cs
@@ -12,19 +12,18 @@
**
===========================================================*/
-using System;
+using System.Diagnostics.Contracts;
using System.Globalization;
-using System.Runtime;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
+using System.Runtime.Versioning;
namespace System
{
[Serializable]
- [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
- [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
- public struct Int32 : IComparable, IFormattable, IConvertible
- , IComparable<Int32>, IEquatable<Int32>
+ [StructLayout(LayoutKind.Sequential)]
+ [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ public struct Int32 : IComparable, IConvertible, IFormattable, IComparable<Int32>, IEquatable<Int32>
{
private int m_value; // Do not rename (binary serialization)
@@ -33,8 +32,11 @@ namespace System
// 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.
+ // Returns :
+ // 0 if the values are equal
+ // Negative number if _value is less than value
+ // Positive number if _value is more than value
+ // null is considered to be less than any instance, hence returns positive number
// If object is not of type Int32, this method throws an ArgumentException.
//
public int CompareTo(Object value)
@@ -45,8 +47,8 @@ namespace System
}
if (value is Int32)
{
- // Need to use compare because subtraction will wrap
- // to positive for very large neg numbers, etc.
+ // NOTE: Cannot use return (_value - value) as this causes a wrap
+ // around in cases where _value - value > MaxValue.
int i = (int)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
@@ -57,8 +59,8 @@ namespace System
public int CompareTo(int value)
{
- // Need to use compare because subtraction will wrap
- // to positive for very large neg numbers, etc.
+ // NOTE: Cannot use return (_value - value) as this causes a wrap
+ // around in cases where _value - value > MaxValue.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
@@ -73,7 +75,7 @@ namespace System
return m_value == ((Int32)obj).m_value;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public bool Equals(Int32 obj)
{
return m_value == obj;
@@ -116,14 +118,16 @@ namespace System
[Pure]
public static int Parse(String s)
{
- return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseInt32(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[Pure]
public static int Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
- return Number.ParseInt32(s, style, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseInt32(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
// Parses an integer from a String in the given style. If
@@ -133,7 +137,8 @@ namespace System
[Pure]
public static int Parse(String s, IFormatProvider provider)
{
- return Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseInt32(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
// Parses an integer from a String in the given style. If
@@ -144,6 +149,13 @@ namespace System
public static int Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseInt32(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
+ }
+
+ public static int Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
@@ -153,7 +165,13 @@ namespace System
[Pure]
public static bool TryParse(String s, out Int32 result)
{
- return Number.TryParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return Number.TryParseInt32(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
// Parses an integer from a String in the given style. Returns false rather
@@ -163,6 +181,19 @@ namespace System
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out Int32 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return Number.TryParseInt32(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
+ }
+
+ public static bool TryParse(ReadOnlySpan<char> s, out int result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseInt32(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
diff --git a/src/mscorlib/src/System/Int64.cs b/src/mscorlib/shared/System/Int64.cs
index 015387233c..785fa39fa5 100644
--- a/src/mscorlib/src/System/Int64.cs
+++ b/src/mscorlib/shared/System/Int64.cs
@@ -12,18 +12,18 @@
**
===========================================================*/
-using System;
+using System.Diagnostics.Contracts;
using System.Globalization;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
+using System.Runtime.Versioning;
namespace System
{
[Serializable]
- [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
- [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
- public struct Int64 : IComparable, IFormattable, IConvertible
- , IComparable<Int64>, IEquatable<Int64>
+ [StructLayout(LayoutKind.Sequential)]
+ [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ public struct Int64 : IComparable, IConvertible, IFormattable, IComparable<Int64>, IEquatable<Int64>
{
private long m_value; // Do not rename (binary serialization)
@@ -72,7 +72,7 @@ namespace System
return m_value == ((Int64)obj).m_value;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public bool Equals(Int64 obj)
{
return m_value == obj;
@@ -110,18 +110,21 @@ namespace System
public static long Parse(String s)
{
- return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseInt64(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
public static long Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
- return Number.ParseInt64(s, style, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseInt64(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
public static long Parse(String s, IFormatProvider provider)
{
- return Number.ParseInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseInt64(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
@@ -132,17 +135,43 @@ namespace System
public static long Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseInt64(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
+ }
+
+ public static long Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseInt64(s, style, NumberFormatInfo.GetInstance(provider));
}
public static Boolean TryParse(String s, out Int64 result)
{
- return Number.TryParseInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return Number.TryParseInt64(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Int64 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return Number.TryParseInt64(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
+ }
+
+ public static bool TryParse(ReadOnlySpan<char> s, out long result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseInt64(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
diff --git a/src/mscorlib/shared/System/InvalidCastException.cs b/src/mscorlib/shared/System/InvalidCastException.cs
index cf359ac0b5..00b393c60e 100644
--- a/src/mscorlib/shared/System/InvalidCastException.cs
+++ b/src/mscorlib/shared/System/InvalidCastException.cs
@@ -17,19 +17,19 @@ namespace System
public InvalidCastException()
: base(SR.Arg_InvalidCastException)
{
- HResult = __HResults.COR_E_INVALIDCAST;
+ HResult = HResults.COR_E_INVALIDCAST;
}
public InvalidCastException(String message)
: base(message)
{
- HResult = __HResults.COR_E_INVALIDCAST;
+ HResult = HResults.COR_E_INVALIDCAST;
}
public InvalidCastException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_INVALIDCAST;
+ HResult = HResults.COR_E_INVALIDCAST;
}
public InvalidCastException(String message, int errorCode)
diff --git a/src/mscorlib/shared/System/InvalidOperationException.cs b/src/mscorlib/shared/System/InvalidOperationException.cs
index ad743e05ff..74a4ffd74a 100644
--- a/src/mscorlib/shared/System/InvalidOperationException.cs
+++ b/src/mscorlib/shared/System/InvalidOperationException.cs
@@ -21,19 +21,19 @@ namespace System
public InvalidOperationException()
: base(SR.Arg_InvalidOperationException)
{
- HResult = __HResults.COR_E_INVALIDOPERATION;
+ HResult = HResults.COR_E_INVALIDOPERATION;
}
public InvalidOperationException(String message)
: base(message)
{
- HResult = __HResults.COR_E_INVALIDOPERATION;
+ HResult = HResults.COR_E_INVALIDOPERATION;
}
public InvalidOperationException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_INVALIDOPERATION;
+ HResult = HResults.COR_E_INVALIDOPERATION;
}
protected InvalidOperationException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/InvalidProgramException.cs b/src/mscorlib/shared/System/InvalidProgramException.cs
index 47e7325836..e3521574ea 100644
--- a/src/mscorlib/shared/System/InvalidProgramException.cs
+++ b/src/mscorlib/shared/System/InvalidProgramException.cs
@@ -20,19 +20,19 @@ namespace System
public InvalidProgramException()
: base(SR.InvalidProgram_Default)
{
- HResult = __HResults.COR_E_INVALIDPROGRAM;
+ HResult = HResults.COR_E_INVALIDPROGRAM;
}
public InvalidProgramException(String message)
: base(message)
{
- HResult = __HResults.COR_E_INVALIDPROGRAM;
+ HResult = HResults.COR_E_INVALIDPROGRAM;
}
public InvalidProgramException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_INVALIDPROGRAM;
+ HResult = HResults.COR_E_INVALIDPROGRAM;
}
}
}
diff --git a/src/mscorlib/shared/System/Lazy.cs b/src/mscorlib/shared/System/Lazy.cs
index 5d68714c7e..2ef3cd2e5f 100644
--- a/src/mscorlib/shared/System/Lazy.cs
+++ b/src/mscorlib/shared/System/Lazy.cs
@@ -261,7 +261,7 @@ namespace System
/// Initializes a new instance of the <see cref="T:System.Threading.Lazy{T}"/>
/// class that uses <typeparamref name="T"/>'s default constructor and a specified thread-safety mode.
/// </summary>
- /// <param name="mode">The lazy thread-safety mode mode</param>
+ /// <param name="mode">The lazy thread-safety mode</param>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="mode"/> mode contains an invalid valuee</exception>
public Lazy(LazyThreadSafetyMode mode) :
this(null, mode, useDefaultConstructor:true)
diff --git a/src/mscorlib/shared/System/MemberAccessException.cs b/src/mscorlib/shared/System/MemberAccessException.cs
index abca952f19..bb26d9e3c4 100644
--- a/src/mscorlib/shared/System/MemberAccessException.cs
+++ b/src/mscorlib/shared/System/MemberAccessException.cs
@@ -23,7 +23,7 @@ namespace System
public MemberAccessException()
: base(SR.Arg_AccessException)
{
- HResult = __HResults.COR_E_MEMBERACCESS;
+ HResult = HResults.COR_E_MEMBERACCESS;
}
// Creates a new MemberAccessException with its message string set to
@@ -33,13 +33,13 @@ namespace System
public MemberAccessException(String message)
: base(message)
{
- HResult = __HResults.COR_E_MEMBERACCESS;
+ HResult = HResults.COR_E_MEMBERACCESS;
}
public MemberAccessException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_MEMBERACCESS;
+ HResult = HResults.COR_E_MEMBERACCESS;
}
protected MemberAccessException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/Memory.cs b/src/mscorlib/shared/System/Memory.cs
new file mode 100644
index 0000000000..270f88e4bc
--- /dev/null
+++ b/src/mscorlib/shared/System/Memory.cs
@@ -0,0 +1,284 @@
+// 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.Buffers;
+using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
+using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
+using System.Diagnostics;
+using System.Runtime;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace System
+{
+ public struct Memory<T>
+ {
+ // The highest order bit of _index is used to discern whether _arrayOrOwnedMemory is an array or an owned memory
+ // if (_index >> 31) == 1, object _arrayOrOwnedMemory is an OwnedMemory<T>
+ // else, object _arrayOrOwnedMemory is a T[]
+ private readonly object _arrayOrOwnedMemory;
+ private readonly int _index;
+ private readonly int _length;
+
+ private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF;
+
+ /// <summary>
+ /// Creates a new memory over the entirety of the target array.
+ /// </summary>
+ /// <param name="array">The target array.</param>
+ /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
+ /// reference (Nothing in Visual Basic).</exception>
+ /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Memory(T[] array)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ if (default(T) == null && array.GetType() != typeof(T[]))
+ ThrowHelper.ThrowArrayTypeMismatchException();
+
+ _arrayOrOwnedMemory = array;
+ _index = 0;
+ _length = array.Length;
+ }
+
+ /// <summary>
+ /// Creates a new memory over the portion of the target array beginning
+ /// at 'start' index and ending at 'end' index (exclusive).
+ /// </summary>
+ /// <param name="array">The target array.</param>
+ /// <param name="start">The index at which to begin the memory.</param>
+ /// <param name="length">The number of items in the memory.</param>
+ /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
+ /// reference (Nothing in Visual Basic).</exception>
+ /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length).
+ /// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Memory(T[] array, int start, int length)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ if (default(T) == null && array.GetType() != typeof(T[]))
+ ThrowHelper.ThrowArrayTypeMismatchException();
+ if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ _arrayOrOwnedMemory = array;
+ _index = start;
+ _length = length;
+ }
+
+ // Constructor for internal use only.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal Memory(OwnedMemory<T> owner, int index, int length)
+ {
+ if (owner == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ownedMemory);
+ if (index < 0 || length < 0)
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ _arrayOrOwnedMemory = owner;
+ _index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask
+ _length = length;
+ }
+
+ /// <summary>
+ /// Defines an implicit conversion of an array to a <see cref="Memory{T}"/>
+ /// </summary>
+ public static implicit operator Memory<T>(T[] array) => new Memory<T>(array);
+
+ /// <summary>
+ /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/>
+ /// </summary>
+ public static implicit operator Memory<T>(ArraySegment<T> arraySegment) => new Memory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
+
+ /// <summary>
+ /// Defines an implicit conversion of a <see cref="Memory{T}"/> to a <see cref="ReadOnlyMemory{T}"/>
+ /// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static implicit operator ReadOnlyMemory<T>(Memory<T> memory)
+ {
+ if (memory._index < 0)
+ return new ReadOnlyMemory<T>((OwnedMemory<T>)memory._arrayOrOwnedMemory, memory._index & RemoveOwnedFlagBitMask, memory._length);
+ return new ReadOnlyMemory<T>((T[])memory._arrayOrOwnedMemory, memory._index, memory._length);
+ }
+
+ /// <summary>
+ /// Returns an empty <see cref="Memory{T}"/>
+ /// </summary>
+ public static Memory<T> Empty { get; } = Array.Empty<T>();
+
+ /// <summary>
+ /// The number of items in the memory.
+ /// </summary>
+ public int Length => _length;
+
+ /// <summary>
+ /// Returns true if Length is 0.
+ /// </summary>
+ public bool IsEmpty => _length == 0;
+
+ /// <summary>
+ /// Forms a slice out of the given memory, beginning at 'start'.
+ /// </summary>
+ /// <param name="start">The index at which to begin this slice.</param>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length).
+ /// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Memory<T> Slice(int start)
+ {
+ if ((uint)start > (uint)_length)
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ if (_index < 0)
+ return new Memory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, _length - start);
+ return new Memory<T>((T[])_arrayOrOwnedMemory, _index + start, _length - start);
+ }
+
+ /// <summary>
+ /// Forms a slice out of the given memory, beginning at 'start', of given length
+ /// </summary>
+ /// <param name="start">The index at which to begin this slice.</param>
+ /// <param name="length">The desired length for the slice (exclusive).</param>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length).
+ /// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public Memory<T> Slice(int start, int length)
+ {
+ if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ if (_index < 0)
+ return new Memory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, length);
+ return new Memory<T>((T[])_arrayOrOwnedMemory, _index + start, length);
+ }
+
+ /// <summary>
+ /// Returns a span from the memory.
+ /// </summary>
+ public Span<T> Span
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get
+ {
+ if (_index < 0)
+ return ((OwnedMemory<T>)_arrayOrOwnedMemory).AsSpan().Slice(_index & RemoveOwnedFlagBitMask, _length);
+ return new Span<T>((T[])_arrayOrOwnedMemory, _index, _length);
+ }
+ }
+
+ public unsafe MemoryHandle Retain(bool pin = false)
+ {
+ MemoryHandle memoryHandle;
+ if (pin)
+ {
+ if (_index < 0)
+ {
+ memoryHandle = ((OwnedMemory<T>)_arrayOrOwnedMemory).Pin();
+ }
+ else
+ {
+ var array = (T[])_arrayOrOwnedMemory;
+ var handle = GCHandle.Alloc(array, GCHandleType.Pinned);
+ void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index);
+ memoryHandle = new MemoryHandle(null, pointer, handle);
+ }
+ }
+ else
+ {
+ if (_index < 0)
+ {
+ ((OwnedMemory<T>)_arrayOrOwnedMemory).Retain();
+ memoryHandle = new MemoryHandle((OwnedMemory<T>)_arrayOrOwnedMemory);
+ }
+ else
+ {
+ memoryHandle = new MemoryHandle(null);
+ }
+ }
+ return memoryHandle;
+ }
+
+ /// <summary>
+ /// Get an array segment from the underlying memory.
+ /// If unable to get the array segment, return false with a default array segment.
+ /// </summary>
+ public bool TryGetArray(out ArraySegment<T> arraySegment)
+ {
+ if (_index < 0)
+ {
+ if (((OwnedMemory<T>)_arrayOrOwnedMemory).TryGetArray(out var segment))
+ {
+ arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & RemoveOwnedFlagBitMask), _length);
+ return true;
+ }
+ }
+ else
+ {
+ arraySegment = new ArraySegment<T>((T[])_arrayOrOwnedMemory, _index, _length);
+ return true;
+ }
+
+ arraySegment = default(ArraySegment<T>);
+ return false;
+ }
+
+ /// <summary>
+ /// Copies the contents from the memory into a new array. This heap
+ /// allocates, so should generally be avoided, however it is sometimes
+ /// necessary to bridge the gap with APIs written in terms of arrays.
+ /// </summary>
+ public T[] ToArray() => Span.ToArray();
+
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj)
+ {
+ if (obj is ReadOnlyMemory<T>)
+ {
+ return ((ReadOnlyMemory<T>)obj).Equals(this);
+ }
+ else if (obj is Memory<T> memory)
+ {
+ return Equals(memory);
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// Returns true if the memory points to the same array and has the same length. Note that
+ /// this does *not* check to see if the *contents* are equal.
+ /// </summary>
+ public bool Equals(Memory<T> other)
+ {
+ return
+ _arrayOrOwnedMemory == other._arrayOrOwnedMemory &&
+ _index == other._index &&
+ _length == other._length;
+ }
+
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override int GetHashCode()
+ {
+ return CombineHashCodes(_arrayOrOwnedMemory.GetHashCode(), (_index & RemoveOwnedFlagBitMask).GetHashCode(), _length.GetHashCode());
+ }
+
+ private static int CombineHashCodes(int left, int right)
+ {
+ return ((left << 5) + left) ^ right;
+ }
+
+ private static int CombineHashCodes(int h1, int h2, int h3)
+ {
+ return CombineHashCodes(CombineHashCodes(h1, h2), h3);
+ }
+
+ }
+} \ No newline at end of file
diff --git a/src/mscorlib/shared/System/MethodAccessException.cs b/src/mscorlib/shared/System/MethodAccessException.cs
index 2c9c998c15..12691386c5 100644
--- a/src/mscorlib/shared/System/MethodAccessException.cs
+++ b/src/mscorlib/shared/System/MethodAccessException.cs
@@ -18,19 +18,19 @@ namespace System
public MethodAccessException()
: base(SR.Arg_MethodAccessException)
{
- HResult = __HResults.COR_E_METHODACCESS;
+ HResult = HResults.COR_E_METHODACCESS;
}
public MethodAccessException(String message)
: base(message)
{
- HResult = __HResults.COR_E_METHODACCESS;
+ HResult = HResults.COR_E_METHODACCESS;
}
public MethodAccessException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_METHODACCESS;
+ HResult = HResults.COR_E_METHODACCESS;
}
protected MethodAccessException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/MissingMethodException.cs b/src/mscorlib/shared/System/MissingMethodException.cs
index 967f434302..4f5e8b6562 100644
--- a/src/mscorlib/shared/System/MissingMethodException.cs
+++ b/src/mscorlib/shared/System/MissingMethodException.cs
@@ -20,19 +20,19 @@ namespace System
public MissingMethodException()
: base(SR.Arg_MissingMethodException)
{
- HResult = __HResults.COR_E_MISSINGMETHOD;
+ HResult = HResults.COR_E_MISSINGMETHOD;
}
public MissingMethodException(string message)
: base(message)
{
- HResult = __HResults.COR_E_MISSINGMETHOD;
+ HResult = HResults.COR_E_MISSINGMETHOD;
}
public MissingMethodException(string message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_MISSINGMETHOD;
+ HResult = HResults.COR_E_MISSINGMETHOD;
}
public MissingMethodException(string className, string methodName)
diff --git a/src/mscorlib/shared/System/MulticastNotSupportedException.cs b/src/mscorlib/shared/System/MulticastNotSupportedException.cs
index 493671e227..56a3ec9c00 100644
--- a/src/mscorlib/shared/System/MulticastNotSupportedException.cs
+++ b/src/mscorlib/shared/System/MulticastNotSupportedException.cs
@@ -16,19 +16,19 @@ namespace System
public MulticastNotSupportedException()
: base(SR.Arg_MulticastNotSupportedException)
{
- HResult = __HResults.COR_E_MULTICASTNOTSUPPORTED;
+ HResult = HResults.COR_E_MULTICASTNOTSUPPORTED;
}
public MulticastNotSupportedException(String message)
: base(message)
{
- HResult = __HResults.COR_E_MULTICASTNOTSUPPORTED;
+ HResult = HResults.COR_E_MULTICASTNOTSUPPORTED;
}
public MulticastNotSupportedException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_MULTICASTNOTSUPPORTED;
+ HResult = HResults.COR_E_MULTICASTNOTSUPPORTED;
}
}
}
diff --git a/src/mscorlib/shared/System/NonSerializedAttribute.cs b/src/mscorlib/shared/System/NonSerializedAttribute.cs
new file mode 100644
index 0000000000..cabd5a2aa2
--- /dev/null
+++ b/src/mscorlib/shared/System/NonSerializedAttribute.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.
+
+namespace System
+{
+ [AttributeUsage(AttributeTargets.Field, Inherited = false)]
+ public sealed class NonSerializedAttribute : Attribute
+ {
+ public NonSerializedAttribute()
+ {
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/NotFiniteNumberException.cs b/src/mscorlib/shared/System/NotFiniteNumberException.cs
index 99882b9eb2..ca47a21e5c 100644
--- a/src/mscorlib/shared/System/NotFiniteNumberException.cs
+++ b/src/mscorlib/shared/System/NotFiniteNumberException.cs
@@ -14,41 +14,41 @@ namespace System
: base(SR.Arg_NotFiniteNumberException)
{
_offendingNumber = 0;
- HResult = __HResults.COR_E_NOTFINITENUMBER;
+ HResult = HResults.COR_E_NOTFINITENUMBER;
}
public NotFiniteNumberException(double offendingNumber)
: base()
{
_offendingNumber = offendingNumber;
- HResult = __HResults.COR_E_NOTFINITENUMBER;
+ HResult = HResults.COR_E_NOTFINITENUMBER;
}
public NotFiniteNumberException(String message)
: base(message)
{
_offendingNumber = 0;
- HResult = __HResults.COR_E_NOTFINITENUMBER;
+ HResult = HResults.COR_E_NOTFINITENUMBER;
}
public NotFiniteNumberException(String message, double offendingNumber)
: base(message)
{
_offendingNumber = offendingNumber;
- HResult = __HResults.COR_E_NOTFINITENUMBER;
+ HResult = HResults.COR_E_NOTFINITENUMBER;
}
public NotFiniteNumberException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_NOTFINITENUMBER;
+ HResult = HResults.COR_E_NOTFINITENUMBER;
}
public NotFiniteNumberException(String message, double offendingNumber, Exception innerException)
: base(message, innerException)
{
_offendingNumber = offendingNumber;
- HResult = __HResults.COR_E_NOTFINITENUMBER;
+ HResult = HResults.COR_E_NOTFINITENUMBER;
}
protected NotFiniteNumberException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/NotImplementedException.cs b/src/mscorlib/shared/System/NotImplementedException.cs
index ae62527fac..98976c19db 100644
--- a/src/mscorlib/shared/System/NotImplementedException.cs
+++ b/src/mscorlib/shared/System/NotImplementedException.cs
@@ -21,17 +21,17 @@ namespace System
public NotImplementedException()
: base(SR.Arg_NotImplementedException)
{
- HResult = __HResults.E_NOTIMPL;
+ HResult = HResults.E_NOTIMPL;
}
public NotImplementedException(String message)
: base(message)
{
- HResult = __HResults.E_NOTIMPL;
+ HResult = HResults.E_NOTIMPL;
}
public NotImplementedException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.E_NOTIMPL;
+ HResult = HResults.E_NOTIMPL;
}
protected NotImplementedException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/NotSupportedException.cs b/src/mscorlib/shared/System/NotSupportedException.cs
index 8532e5ad2f..dc43261fbd 100644
--- a/src/mscorlib/shared/System/NotSupportedException.cs
+++ b/src/mscorlib/shared/System/NotSupportedException.cs
@@ -20,19 +20,19 @@ namespace System
public NotSupportedException()
: base(SR.Arg_NotSupportedException)
{
- HResult = __HResults.COR_E_NOTSUPPORTED;
+ HResult = HResults.COR_E_NOTSUPPORTED;
}
public NotSupportedException(String message)
: base(message)
{
- HResult = __HResults.COR_E_NOTSUPPORTED;
+ HResult = HResults.COR_E_NOTSUPPORTED;
}
public NotSupportedException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_NOTSUPPORTED;
+ HResult = HResults.COR_E_NOTSUPPORTED;
}
protected NotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/NullReferenceException.cs b/src/mscorlib/shared/System/NullReferenceException.cs
index f689345654..eb6d709dbf 100644
--- a/src/mscorlib/shared/System/NullReferenceException.cs
+++ b/src/mscorlib/shared/System/NullReferenceException.cs
@@ -20,19 +20,19 @@ namespace System
public NullReferenceException()
: base(SR.Arg_NullReferenceException)
{
- HResult = __HResults.COR_E_NULLREFERENCE;
+ HResult = HResults.COR_E_NULLREFERENCE;
}
public NullReferenceException(String message)
: base(message)
{
- HResult = __HResults.COR_E_NULLREFERENCE;
+ HResult = HResults.COR_E_NULLREFERENCE;
}
public NullReferenceException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_NULLREFERENCE;
+ HResult = HResults.COR_E_NULLREFERENCE;
}
protected NullReferenceException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/ObjectDisposedException.cs b/src/mscorlib/shared/System/ObjectDisposedException.cs
index 6e8e6b2d74..3d7ba5df15 100644
--- a/src/mscorlib/shared/System/ObjectDisposedException.cs
+++ b/src/mscorlib/shared/System/ObjectDisposedException.cs
@@ -28,14 +28,14 @@ namespace System
public ObjectDisposedException(String objectName, String message) : base(message)
{
- HResult = __HResults.COR_E_OBJECTDISPOSED;
+ HResult = HResults.COR_E_OBJECTDISPOSED;
_objectName = objectName;
}
public ObjectDisposedException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_OBJECTDISPOSED;
+ HResult = HResults.COR_E_OBJECTDISPOSED;
}
protected ObjectDisposedException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/OperationCanceledException.cs b/src/mscorlib/shared/System/OperationCanceledException.cs
index 2c7654854f..44a0427c58 100644
--- a/src/mscorlib/shared/System/OperationCanceledException.cs
+++ b/src/mscorlib/shared/System/OperationCanceledException.cs
@@ -31,19 +31,19 @@ namespace System
public OperationCanceledException()
: base(SR.OperationCanceled)
{
- HResult = __HResults.COR_E_OPERATIONCANCELED;
+ HResult = HResults.COR_E_OPERATIONCANCELED;
}
public OperationCanceledException(String message)
: base(message)
{
- HResult = __HResults.COR_E_OPERATIONCANCELED;
+ HResult = HResults.COR_E_OPERATIONCANCELED;
}
public OperationCanceledException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_OPERATIONCANCELED;
+ HResult = HResults.COR_E_OPERATIONCANCELED;
}
diff --git a/src/mscorlib/shared/System/OverflowException.cs b/src/mscorlib/shared/System/OverflowException.cs
index 4052e41a18..bf6676ca2c 100644
--- a/src/mscorlib/shared/System/OverflowException.cs
+++ b/src/mscorlib/shared/System/OverflowException.cs
@@ -20,19 +20,19 @@ namespace System
public OverflowException()
: base(SR.Arg_OverflowException)
{
- HResult = __HResults.COR_E_OVERFLOW;
+ HResult = HResults.COR_E_OVERFLOW;
}
public OverflowException(String message)
: base(message)
{
- HResult = __HResults.COR_E_OVERFLOW;
+ HResult = HResults.COR_E_OVERFLOW;
}
public OverflowException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_OVERFLOW;
+ HResult = HResults.COR_E_OVERFLOW;
}
protected OverflowException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/PlatformNotSupportedException.cs b/src/mscorlib/shared/System/PlatformNotSupportedException.cs
index f679ac9454..4403c1da06 100644
--- a/src/mscorlib/shared/System/PlatformNotSupportedException.cs
+++ b/src/mscorlib/shared/System/PlatformNotSupportedException.cs
@@ -20,19 +20,19 @@ namespace System
public PlatformNotSupportedException()
: base(SR.Arg_PlatformNotSupported)
{
- HResult = __HResults.COR_E_PLATFORMNOTSUPPORTED;
+ HResult = HResults.COR_E_PLATFORMNOTSUPPORTED;
}
public PlatformNotSupportedException(String message)
: base(message)
{
- HResult = __HResults.COR_E_PLATFORMNOTSUPPORTED;
+ HResult = HResults.COR_E_PLATFORMNOTSUPPORTED;
}
public PlatformNotSupportedException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_PLATFORMNOTSUPPORTED;
+ HResult = HResults.COR_E_PLATFORMNOTSUPPORTED;
}
protected PlatformNotSupportedException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/Random.cs b/src/mscorlib/shared/System/Random.cs
index 4affed8a1a..20f035e2e8 100644
--- a/src/mscorlib/shared/System/Random.cs
+++ b/src/mscorlib/shared/System/Random.cs
@@ -2,20 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-/*============================================================
-**
-**
-** Purpose: A random number generator.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime;
-using System.Runtime.CompilerServices;
-using System.Globalization;
-using System.Diagnostics.Contracts;
-
namespace System
{
public class Random
@@ -23,11 +9,10 @@ namespace System
//
// Private Constants
//
- private const int MBIG = Int32.MaxValue;
+ private const int MBIG = int.MaxValue;
private const int MSEED = 161803398;
private const int MZ = 0;
-
//
// Member Variables
//
@@ -64,7 +49,7 @@ namespace System
int mj, mk;
//Initialize our Seed array.
- int subtraction = (Seed == Int32.MinValue) ? Int32.MaxValue : Math.Abs(Seed);
+ int subtraction = (Seed == int.MinValue) ? int.MaxValue : Math.Abs(Seed);
mj = MSEED - subtraction;
_seedArray[55] = mj;
mk = 1;
@@ -195,8 +180,8 @@ namespace System
result = -result;
}
double d = result;
- d += (Int32.MaxValue - 1); // get a number in range [0 .. 2 * Int32MaxValue - 1)
- d /= 2 * (uint)Int32.MaxValue - 1;
+ d += (int.MaxValue - 1); // get a number in range [0 .. 2 * Int32MaxValue - 1)
+ d /= 2 * (uint)int.MaxValue - 1;
return d;
}
@@ -213,10 +198,9 @@ namespace System
{
throw new ArgumentOutOfRangeException(nameof(minValue), SR.Format(SR.Argument_MinMaxValue, nameof(minValue), nameof(maxValue)));
}
- Contract.EndContractBlock();
long range = (long)maxValue - minValue;
- if (range <= (long)Int32.MaxValue)
+ if (range <= int.MaxValue)
{
return ((int)(Sample() * range) + minValue);
}
@@ -238,7 +222,6 @@ namespace System
{
throw new ArgumentOutOfRangeException(nameof(maxValue), SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(maxValue)));
}
- Contract.EndContractBlock();
return (int)(Sample() * maxValue);
}
@@ -263,10 +246,17 @@ namespace System
public virtual void NextBytes(byte[] buffer)
{
if (buffer == null) throw new ArgumentNullException(nameof(buffer));
- Contract.EndContractBlock();
for (int i = 0; i < buffer.Length; i++)
{
- buffer[i] = (byte)(InternalSample() % (Byte.MaxValue + 1));
+ buffer[i] = (byte)InternalSample();
+ }
+ }
+
+ public virtual void NextBytes(Span<byte> buffer)
+ {
+ for (int i = 0; i < buffer.Length; i++)
+ {
+ buffer[i] = (byte)Next();
}
}
}
diff --git a/src/mscorlib/shared/System/RankException.cs b/src/mscorlib/shared/System/RankException.cs
index 15759ea75d..f2c5d06548 100644
--- a/src/mscorlib/shared/System/RankException.cs
+++ b/src/mscorlib/shared/System/RankException.cs
@@ -21,19 +21,19 @@ namespace System
public RankException()
: base(SR.Arg_RankException)
{
- HResult = __HResults.COR_E_RANK;
+ HResult = HResults.COR_E_RANK;
}
public RankException(String message)
: base(message)
{
- HResult = __HResults.COR_E_RANK;
+ HResult = HResults.COR_E_RANK;
}
public RankException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_RANK;
+ HResult = HResults.COR_E_RANK;
}
protected RankException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/ReadOnlyMemory.cs b/src/mscorlib/shared/System/ReadOnlyMemory.cs
new file mode 100644
index 0000000000..8153d02fa3
--- /dev/null
+++ b/src/mscorlib/shared/System/ReadOnlyMemory.cs
@@ -0,0 +1,270 @@
+// 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.Buffers;
+using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
+using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
+using System.Diagnostics;
+using System.Runtime;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace System
+{
+ public struct ReadOnlyMemory<T>
+ {
+ // The highest order bit of _index is used to discern whether _arrayOrOwnedMemory is an array or an owned memory
+ // if (_index >> 31) == 1, object _arrayOrOwnedMemory is an OwnedMemory<T>
+ // else, object _arrayOrOwnedMemory is a T[]
+ private readonly object _arrayOrOwnedMemory;
+ private readonly int _index;
+ private readonly int _length;
+
+ private const int RemoveOwnedFlagBitMask = 0x7FFFFFFF;
+
+ /// <summary>
+ /// Creates a new memory over the entirety of the target array.
+ /// </summary>
+ /// <param name="array">The target array.</param>
+ /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
+ /// reference (Nothing in Visual Basic).</exception>
+ /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ReadOnlyMemory(T[] array)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+
+ _arrayOrOwnedMemory = array;
+ _index = 0;
+ _length = array.Length;
+ }
+
+ /// <summary>
+ /// Creates a new memory over the portion of the target array beginning
+ /// at 'start' index and ending at 'end' index (exclusive).
+ /// </summary>
+ /// <param name="array">The target array.</param>
+ /// <param name="start">The index at which to begin the memory.</param>
+ /// <param name="length">The number of items in the memory.</param>
+ /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
+ /// reference (Nothing in Visual Basic).</exception>
+ /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> or end index is not in the range (&lt;0 or &gt;=Length).
+ /// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ReadOnlyMemory(T[] array, int start, int length)
+ {
+ if (array == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
+ if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ _arrayOrOwnedMemory = array;
+ _index = start;
+ _length = length;
+ }
+
+ // Constructor for internal use only.
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ internal ReadOnlyMemory(OwnedMemory<T> owner, int index, int length)
+ {
+ if (owner == null)
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.ownedMemory);
+ if (index < 0 || length < 0)
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ _arrayOrOwnedMemory = owner;
+ _index = index | (1 << 31); // Before using _index, check if _index < 0, then 'and' it with RemoveOwnedFlagBitMask
+ _length = length;
+ }
+
+ /// <summary>
+ /// Defines an implicit conversion of an array to a <see cref="Memory{T}"/>
+ /// </summary>
+ public static implicit operator ReadOnlyMemory<T>(T[] array) => new ReadOnlyMemory<T>(array);
+
+ /// <summary>
+ /// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="Memory{T}"/>
+ /// </summary>
+ public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> arraySegment) => new ReadOnlyMemory<T>(arraySegment.Array, arraySegment.Offset, arraySegment.Count);
+
+ /// <summary>
+ /// Returns an empty <see cref="Memory{T}"/>
+ /// </summary>
+ public static ReadOnlyMemory<T> Empty { get; } = Array.Empty<T>();
+
+ /// <summary>
+ /// The number of items in the memory.
+ /// </summary>
+ public int Length => _length;
+
+ /// <summary>
+ /// Returns true if Length is 0.
+ /// </summary>
+ public bool IsEmpty => _length == 0;
+
+ /// <summary>
+ /// Forms a slice out of the given memory, beginning at 'start'.
+ /// </summary>
+ /// <param name="start">The index at which to begin this slice.</param>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;=Length).
+ /// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ReadOnlyMemory<T> Slice(int start)
+ {
+ if ((uint)start > (uint)_length)
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ if (_index < 0)
+ return new ReadOnlyMemory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, _length - start);
+ return new ReadOnlyMemory<T>((T[])_arrayOrOwnedMemory, _index + start, _length - start);
+ }
+
+ /// <summary>
+ /// Forms a slice out of the given memory, beginning at 'start', of given length
+ /// </summary>
+ /// <param name="start">The index at which to begin this slice.</param>
+ /// <param name="length">The desired length for the slice (exclusive).</param>
+ /// <exception cref="System.ArgumentOutOfRangeException">
+ /// Thrown when the specified <paramref name="start"/> or end index is not in range (&lt;0 or &gt;=Length).
+ /// </exception>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public ReadOnlyMemory<T> Slice(int start, int length)
+ {
+ if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
+ ThrowHelper.ThrowArgumentOutOfRangeException();
+
+ if (_index < 0)
+ return new ReadOnlyMemory<T>((OwnedMemory<T>)_arrayOrOwnedMemory, (_index & RemoveOwnedFlagBitMask) + start, length);
+ return new ReadOnlyMemory<T>((T[])_arrayOrOwnedMemory, _index + start, length);
+ }
+
+ /// <summary>
+ /// Returns a span from the memory.
+ /// </summary>
+ public ReadOnlySpan<T> Span
+ {
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ get
+ {
+ if (_index < 0)
+ return ((OwnedMemory<T>)_arrayOrOwnedMemory).AsSpan().Slice(_index & RemoveOwnedFlagBitMask, _length);
+ return new ReadOnlySpan<T>((T[])_arrayOrOwnedMemory, _index, _length);
+ }
+ }
+
+ public unsafe MemoryHandle Retain(bool pin = false)
+ {
+ MemoryHandle memoryHandle;
+ if (pin)
+ {
+ if (_index < 0)
+ {
+ memoryHandle = ((OwnedMemory<T>)_arrayOrOwnedMemory).Pin();
+ }
+ else
+ {
+ var array = (T[])_arrayOrOwnedMemory;
+ var handle = GCHandle.Alloc(array, GCHandleType.Pinned);
+ void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref array.GetRawSzArrayData()), _index);
+ memoryHandle = new MemoryHandle(null, pointer, handle);
+ }
+ }
+ else
+ {
+ if (_index < 0)
+ {
+ ((OwnedMemory<T>)_arrayOrOwnedMemory).Retain();
+ memoryHandle = new MemoryHandle((OwnedMemory<T>)_arrayOrOwnedMemory);
+ }
+ else
+ {
+ memoryHandle = new MemoryHandle(null);
+ }
+ }
+ return memoryHandle;
+ }
+
+ /// <summary>
+ /// Get an array segment from the underlying memory.
+ /// If unable to get the array segment, return false with a default array segment.
+ /// </summary>
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public bool DangerousTryGetArray(out ArraySegment<T> arraySegment)
+ {
+ if (_index < 0)
+ {
+ if (((OwnedMemory<T>)_arrayOrOwnedMemory).TryGetArray(out var segment))
+ {
+ arraySegment = new ArraySegment<T>(segment.Array, segment.Offset + (_index & RemoveOwnedFlagBitMask), _length);
+ return true;
+ }
+ }
+ else
+ {
+ arraySegment = new ArraySegment<T>((T[])_arrayOrOwnedMemory, _index, _length);
+ return true;
+ }
+
+ arraySegment = default(ArraySegment<T>);
+ return false;
+ }
+
+ /// <summary>
+ /// Copies the contents from the memory into a new array. This heap
+ /// allocates, so should generally be avoided, however it is sometimes
+ /// necessary to bridge the gap with APIs written in terms of arrays.
+ /// </summary>
+ public T[] ToArray() => Span.ToArray();
+
+ [EditorBrowsable(EditorBrowsableState.Never)]
+ public override bool Equals(object obj)
+ {
+ if (obj is ReadOnlyMemory<T> readOnlyMemory)
+ {
+ return Equals(readOnlyMemory);
+ }
+ else if (obj is Memory<T> memory)
+ {
+ return Equals(memory);
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// Returns true if the memory points to the same array and has the same length. Note that
+ /// this does *not* check to see if the *contents* are equal.
+ /// </summary>
+ public bool Equals(ReadOnlyMemory<T> other)
+ {
+ return
+ _arrayOrOwnedMemory == other._arrayOrOwnedMemory &&
+ _index == other._index &&
+ _length == other._length;
+ }
+
+ [EditorBrowsable( EditorBrowsableState.Never)]
+ public override int GetHashCode()
+ {
+ return CombineHashCodes(_arrayOrOwnedMemory.GetHashCode(), (_index & RemoveOwnedFlagBitMask).GetHashCode(), _length.GetHashCode());
+ }
+
+ private static int CombineHashCodes(int left, int right)
+ {
+ return ((left << 5) + left) ^ right;
+ }
+
+ private static int CombineHashCodes(int h1, int h2, int h3)
+ {
+ return CombineHashCodes(CombineHashCodes(h1, h2), h3);
+ }
+
+ }
+} \ No newline at end of file
diff --git a/src/mscorlib/shared/System/ReadOnlySpan.cs b/src/mscorlib/shared/System/ReadOnlySpan.cs
index ae49f59269..bcf1697e88 100644
--- a/src/mscorlib/shared/System/ReadOnlySpan.cs
+++ b/src/mscorlib/shared/System/ReadOnlySpan.cs
@@ -2,10 +2,10 @@
// 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.Diagnostics;
using System.Runtime.CompilerServices;
-using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
-using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
+using System.Runtime.Versioning;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
@@ -15,7 +15,9 @@ namespace System
/// ReadOnlySpan represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
+ [IsReadOnly]
[IsByRefLike]
+ [NonVersionable]
public struct ReadOnlySpan<T>
{
/// <summary>A byref or a native ptr.</summary>
@@ -44,29 +46,6 @@ namespace System
/// <summary>
/// Creates a new read-only span over the portion of the target array beginning
- /// at 'start' index and covering the remainder of the array.
- /// </summary>
- /// <param name="array">The target array.</param>
- /// <param name="start">The index at which to begin the read-only span.</param>
- /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
- /// reference (Nothing in Visual Basic).</exception>
- /// <exception cref="System.ArgumentOutOfRangeException">
- /// Thrown when the specified <paramref name="start"/> is not in the range (&lt;0 or &gt;=Length).
- /// </exception>
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public ReadOnlySpan(T[] array, int start)
- {
- if (array == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- if ((uint)start > (uint)array.Length)
- ThrowHelper.ThrowArgumentOutOfRangeException();
-
- _pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start));
- _length = array.Length - start;
- }
-
- /// <summary>
- /// Creates a new read-only span over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
@@ -126,6 +105,7 @@ namespace System
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
public static ReadOnlySpan<T> DangerousCreate(object obj, ref T objectData, int length) => new ReadOnlySpan<T>(ref objectData, length);
// Constructor for internal use only.
@@ -143,6 +123,7 @@ namespace System
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
public ref T DangerousGetPinnableReference()
{
return ref _pointer.Value;
@@ -151,12 +132,26 @@ namespace System
/// <summary>
/// The number of items in the read-only span.
/// </summary>
- public int Length => _length;
+ public int Length
+ {
+ [NonVersionable]
+ get
+ {
+ return _length;
+ }
+ }
/// <summary>
/// Returns true if Length is 0.
/// </summary>
- public bool IsEmpty => _length == 0;
+ public bool IsEmpty
+ {
+ [NonVersionable]
+ get
+ {
+ return _length == 0;
+ }
+ }
/// <summary>
/// Returns the specified element of the read-only span.
@@ -179,6 +174,7 @@ namespace System
[Intrinsic]
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [NonVersionable]
get
{
if ((uint)index >= (uint)_length)
diff --git a/src/mscorlib/shared/System/Reflection/AmbiguousMatchException.cs b/src/mscorlib/shared/System/Reflection/AmbiguousMatchException.cs
index a0075bbc0b..c4aeca704d 100644
--- a/src/mscorlib/shared/System/Reflection/AmbiguousMatchException.cs
+++ b/src/mscorlib/shared/System/Reflection/AmbiguousMatchException.cs
@@ -11,19 +11,19 @@ namespace System.Reflection
public AmbiguousMatchException()
: base(SR.RFLCT_Ambiguous)
{
- HResult = __HResults.COR_E_AMBIGUOUSMATCH;
+ HResult = HResults.COR_E_AMBIGUOUSMATCH;
}
public AmbiguousMatchException(string message)
: base(message)
{
- HResult = __HResults.COR_E_AMBIGUOUSMATCH;
+ HResult = HResults.COR_E_AMBIGUOUSMATCH;
}
public AmbiguousMatchException(string message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_AMBIGUOUSMATCH;
+ HResult = HResults.COR_E_AMBIGUOUSMATCH;
}
}
}
diff --git a/src/mscorlib/shared/System/Reflection/BindingFlags.cs b/src/mscorlib/shared/System/Reflection/BindingFlags.cs
index 26c875d0f9..7ba83e20da 100644
--- a/src/mscorlib/shared/System/Reflection/BindingFlags.cs
+++ b/src/mscorlib/shared/System/Reflection/BindingFlags.cs
@@ -46,5 +46,6 @@ namespace System.Reflection
// These are a couple of misc attributes used
IgnoreReturn = 0x01000000, // This is used in COM Interop
+ DoNotWrapExceptions = 0x02000000, // Disables wrapping exceptions in TargetInvocationException
}
}
diff --git a/src/mscorlib/shared/System/Reflection/CustomAttributeFormatException.cs b/src/mscorlib/shared/System/Reflection/CustomAttributeFormatException.cs
index 13766ae8d0..ae67158a53 100644
--- a/src/mscorlib/shared/System/Reflection/CustomAttributeFormatException.cs
+++ b/src/mscorlib/shared/System/Reflection/CustomAttributeFormatException.cs
@@ -21,7 +21,7 @@ namespace System.Reflection
public CustomAttributeFormatException(string message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_CUSTOMATTRIBUTEFORMAT;
+ HResult = HResults.COR_E_CUSTOMATTRIBUTEFORMAT;
}
protected CustomAttributeFormatException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/Reflection/IReflect.cs b/src/mscorlib/shared/System/Reflection/IReflect.cs
index 51141ae47c..a7e84b6168 100644
--- a/src/mscorlib/shared/System/Reflection/IReflect.cs
+++ b/src/mscorlib/shared/System/Reflection/IReflect.cs
@@ -47,7 +47,7 @@ namespace System.Reflection
MemberInfo[] GetMembers(BindingFlags bindingAttr);
// Description of the Binding Process.
- // We must invoke a method that is accessable and for which the provided
+ // We must invoke a method that is accessible and for which the provided
// parameters have the most specific match. A method may be called if
// 1. The number of parameters in the method declaration equals the number of
// arguments provided to the invocation
@@ -59,7 +59,7 @@ namespace System.Reflection
// of methods is filtered by the name, number of arguments and a set of search modifiers
// defined in the Binder.
//
- // After the method is selected, it will be invoked. Accessability is checked
+ // After the method is selected, it will be invoked. Accessibility is checked
// at that point. The search may be control which set of methods are searched based
// upon the accessibility attribute associated with the method.
//
diff --git a/src/mscorlib/shared/System/Reflection/InvalidFilterCriteriaException.cs b/src/mscorlib/shared/System/Reflection/InvalidFilterCriteriaException.cs
index 07880a768d..85a447707c 100644
--- a/src/mscorlib/shared/System/Reflection/InvalidFilterCriteriaException.cs
+++ b/src/mscorlib/shared/System/Reflection/InvalidFilterCriteriaException.cs
@@ -21,7 +21,7 @@ namespace System.Reflection
public InvalidFilterCriteriaException(string message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_INVALIDFILTERCRITERIA;
+ HResult = HResults.COR_E_INVALIDFILTERCRITERIA;
}
protected InvalidFilterCriteriaException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/Reflection/MethodInfo.Internal.cs b/src/mscorlib/shared/System/Reflection/MethodInfo.Internal.cs
new file mode 100644
index 0000000000..a36ef900da
--- /dev/null
+++ b/src/mscorlib/shared/System/Reflection/MethodInfo.Internal.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.
+
+namespace System.Reflection
+{
+ public abstract partial class MethodInfo : MethodBase
+ {
+#if CORECLR
+ internal
+#else
+ // Not an api but needs to be public so that Reflection.Core can access it.
+ public
+#endif
+ virtual int GenericParameterCount => GetGenericArguments().Length;
+ }
+}
diff --git a/src/mscorlib/shared/System/Reflection/MethodInfo.cs b/src/mscorlib/shared/System/Reflection/MethodInfo.cs
index 3f60149e87..95c62ba7f0 100644
--- a/src/mscorlib/shared/System/Reflection/MethodInfo.cs
+++ b/src/mscorlib/shared/System/Reflection/MethodInfo.cs
@@ -4,7 +4,7 @@
namespace System.Reflection
{
- public abstract class MethodInfo : MethodBase
+ public abstract partial class MethodInfo : MethodBase
{
protected MethodInfo() { }
diff --git a/src/mscorlib/shared/System/Reflection/Pointer.cs b/src/mscorlib/shared/System/Reflection/Pointer.cs
index 55376c66c0..e1a9990cf0 100644
--- a/src/mscorlib/shared/System/Reflection/Pointer.cs
+++ b/src/mscorlib/shared/System/Reflection/Pointer.cs
@@ -46,6 +46,6 @@ namespace System.Reflection
}
internal Type GetPointerType() => _ptrType;
- internal object GetPointerValue() => (IntPtr)_ptr;
+ internal IntPtr GetPointerValue() => (IntPtr)_ptr;
}
}
diff --git a/src/mscorlib/shared/System/Reflection/ReflectionTypeLoadException.cs b/src/mscorlib/shared/System/Reflection/ReflectionTypeLoadException.cs
index ca0c6ab0db..0e86d34056 100644
--- a/src/mscorlib/shared/System/Reflection/ReflectionTypeLoadException.cs
+++ b/src/mscorlib/shared/System/Reflection/ReflectionTypeLoadException.cs
@@ -13,7 +13,7 @@ namespace System.Reflection
{
Types = classes;
LoaderExceptions = exceptions;
- HResult = __HResults.COR_E_REFLECTIONTYPELOAD;
+ HResult = HResults.COR_E_REFLECTIONTYPELOAD;
}
public ReflectionTypeLoadException(Type[] classes, Exception[] exceptions, string message)
@@ -21,7 +21,7 @@ namespace System.Reflection
{
Types = classes;
LoaderExceptions = exceptions;
- HResult = __HResults.COR_E_REFLECTIONTYPELOAD;
+ HResult = HResults.COR_E_REFLECTIONTYPELOAD;
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/Reflection/SignatureArrayType.cs b/src/mscorlib/shared/System/Reflection/SignatureArrayType.cs
new file mode 100644
index 0000000000..52011b8a9d
--- /dev/null
+++ b/src/mscorlib/shared/System/Reflection/SignatureArrayType.cs
@@ -0,0 +1,46 @@
+// 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;
+
+namespace System.Reflection
+{
+ internal sealed class SignatureArrayType : SignatureHasElementType
+ {
+ internal SignatureArrayType(SignatureType elementType, int rank, bool isMultiDim)
+ : base(elementType)
+ {
+ Debug.Assert(rank > 0);
+ Debug.Assert(rank == 1 || isMultiDim);
+
+ _rank = rank;
+ _isMultiDim = isMultiDim;
+ }
+
+ protected sealed override bool IsArrayImpl() => true;
+ protected sealed override bool IsByRefImpl() => false;
+ protected sealed override bool IsPointerImpl() => false;
+
+ public sealed override bool IsSZArray => !_isMultiDim;
+ public sealed override bool IsVariableBoundArray => _isMultiDim;
+
+ public sealed override int GetArrayRank() => _rank;
+
+ protected sealed override string Suffix
+ {
+ get
+ {
+ if (!_isMultiDim)
+ return "[]";
+ else if (_rank == 1)
+ return "[*]";
+ else
+ return "[" + new string(',', _rank - 1) + "]";
+ }
+ }
+
+ private readonly int _rank;
+ private readonly bool _isMultiDim;
+ }
+}
diff --git a/src/mscorlib/shared/System/Reflection/SignatureByRefType.cs b/src/mscorlib/shared/System/Reflection/SignatureByRefType.cs
new file mode 100644
index 0000000000..eb5f6de42e
--- /dev/null
+++ b/src/mscorlib/shared/System/Reflection/SignatureByRefType.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;
+
+namespace System.Reflection
+{
+ internal sealed class SignatureByRefType : SignatureHasElementType
+ {
+ internal SignatureByRefType(SignatureType elementType)
+ : base(elementType)
+ {
+ }
+
+ protected sealed override bool IsArrayImpl() => false;
+ protected sealed override bool IsByRefImpl() => true;
+ protected sealed override bool IsPointerImpl() => false;
+
+ public sealed override bool IsSZArray => false;
+ public sealed override bool IsVariableBoundArray => false;
+
+ public sealed override int GetArrayRank() => throw new ArgumentException(SR.Argument_HasToBeArrayClass);
+
+ protected sealed override string Suffix => "&";
+ }
+}
diff --git a/src/mscorlib/shared/System/Reflection/SignatureConstructedGenericType.cs b/src/mscorlib/shared/System/Reflection/SignatureConstructedGenericType.cs
new file mode 100644
index 0000000000..afcdfda352
--- /dev/null
+++ b/src/mscorlib/shared/System/Reflection/SignatureConstructedGenericType.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.Text;
+using System.Diagnostics;
+
+namespace System.Reflection
+{
+ internal sealed class SignatureConstructedGenericType : SignatureType
+ {
+ internal SignatureConstructedGenericType(Type genericTypeDefinition, Type[] genericTypeArguments)
+ {
+ Debug.Assert(genericTypeDefinition != null && genericTypeArguments != null);
+ _genericTypeDefinition = genericTypeDefinition;
+ _genericTypeArguments = (Type[])(genericTypeArguments.Clone());
+ }
+
+ public sealed override bool IsTypeDefinition => false;
+ public sealed override bool IsGenericTypeDefinition => false;
+ protected sealed override bool HasElementTypeImpl() => false;
+ protected sealed override bool IsArrayImpl() => false;
+ protected sealed override bool IsByRefImpl() => false;
+ public sealed override bool IsByRefLike => _genericTypeDefinition.IsByRefLike;
+ protected sealed override bool IsPointerImpl() => false;
+ public sealed override bool IsSZArray => false;
+ public sealed override bool IsVariableBoundArray => false;
+ public sealed override bool IsConstructedGenericType => true;
+ public sealed override bool IsGenericParameter => false;
+ public sealed override bool IsGenericMethodParameter => false;
+ public sealed override bool ContainsGenericParameters
+ {
+ get
+ {
+ for (int i = 0; i < _genericTypeArguments.Length; i++)
+ {
+ if (_genericTypeArguments[i].ContainsGenericParameters)
+ return true;
+ }
+ return false;
+ }
+ }
+
+ internal sealed override SignatureType ElementType => null;
+ public sealed override int GetArrayRank() => throw new ArgumentException(SR.Argument_HasToBeArrayClass);
+ public sealed override Type GetGenericTypeDefinition() => _genericTypeDefinition;
+ public sealed override Type[] GetGenericArguments() => GenericTypeArguments;
+ public sealed override Type[] GenericTypeArguments => (Type[])(_genericTypeArguments.Clone());
+ public sealed override int GenericParameterPosition => throw new InvalidOperationException(SR.Arg_NotGenericParameter);
+
+ public sealed override string Name => _genericTypeDefinition.Name;
+ public sealed override string Namespace => _genericTypeDefinition.Namespace;
+
+ public sealed override string ToString()
+ {
+ StringBuilder sb = new StringBuilder();
+ sb.Append(_genericTypeDefinition.ToString());
+ sb.Append('[');
+ for (int i = 0; i < _genericTypeArguments.Length; i++)
+ {
+ if (i != 0)
+ sb.Append(',');
+ sb.Append(_genericTypeArguments[i].ToString());
+ }
+ sb.Append(']');
+ return sb.ToString();
+ }
+
+ private readonly Type _genericTypeDefinition;
+ private readonly Type[] _genericTypeArguments;
+ }
+}
diff --git a/src/mscorlib/shared/System/Reflection/SignatureGenericMethodParameterType.cs b/src/mscorlib/shared/System/Reflection/SignatureGenericMethodParameterType.cs
new file mode 100644
index 0000000000..ae73272ab7
--- /dev/null
+++ b/src/mscorlib/shared/System/Reflection/SignatureGenericMethodParameterType.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.
+
+namespace System.Reflection
+{
+ internal sealed class SignatureGenericMethodParameterType : SignatureGenericParameterType
+ {
+ internal SignatureGenericMethodParameterType(int position)
+ : base(position)
+ {
+ }
+
+ public sealed override bool IsGenericMethodParameter => true;
+
+ public sealed override string Name => "!!" + GenericParameterPosition;
+ }
+}
diff --git a/src/mscorlib/shared/System/Reflection/SignatureGenericParameterType.cs b/src/mscorlib/shared/System/Reflection/SignatureGenericParameterType.cs
new file mode 100644
index 0000000000..fee7bce353
--- /dev/null
+++ b/src/mscorlib/shared/System/Reflection/SignatureGenericParameterType.cs
@@ -0,0 +1,46 @@
+// 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;
+
+namespace System.Reflection
+{
+ internal abstract class SignatureGenericParameterType : SignatureType
+ {
+ protected SignatureGenericParameterType(int position)
+ {
+ Debug.Assert(position >= 0);
+ _position = position;
+ }
+
+ public sealed override bool IsTypeDefinition => false;
+ public sealed override bool IsGenericTypeDefinition => false;
+ protected sealed override bool HasElementTypeImpl() => false;
+ protected sealed override bool IsArrayImpl() => false;
+ protected sealed override bool IsByRefImpl() => false;
+ public sealed override bool IsByRefLike => false;
+ protected sealed override bool IsPointerImpl() => false;
+ public sealed override bool IsSZArray => false;
+ public sealed override bool IsVariableBoundArray => false;
+ public sealed override bool IsConstructedGenericType => false;
+ public sealed override bool IsGenericParameter => true;
+ public abstract override bool IsGenericMethodParameter { get; }
+ public sealed override bool ContainsGenericParameters => true;
+
+ internal sealed override SignatureType ElementType => null;
+ public sealed override int GetArrayRank() => throw new ArgumentException(SR.Argument_HasToBeArrayClass);
+ public sealed override Type GetGenericTypeDefinition() => throw new InvalidOperationException(SR.InvalidOperation_NotGenericType);
+ public sealed override Type[] GetGenericArguments() => Array.Empty<Type>();
+ public sealed override Type[] GenericTypeArguments => Array.Empty<Type>();
+ public sealed override int GenericParameterPosition => _position;
+
+ public abstract override string Name { get; }
+ public sealed override string Namespace => null;
+
+ public sealed override string ToString() => Name;
+
+ private readonly int _position;
+ }
+}
diff --git a/src/mscorlib/shared/System/Reflection/SignatureHasElementType.cs b/src/mscorlib/shared/System/Reflection/SignatureHasElementType.cs
new file mode 100644
index 0000000000..e1aa6c3584
--- /dev/null
+++ b/src/mscorlib/shared/System/Reflection/SignatureHasElementType.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.
+
+using System;
+using System.Diagnostics;
+
+namespace System.Reflection
+{
+ internal abstract class SignatureHasElementType : SignatureType
+ {
+ protected SignatureHasElementType(SignatureType elementType)
+ {
+ Debug.Assert(elementType != null);
+ _elementType = elementType;
+ }
+
+ public sealed override bool IsTypeDefinition => false;
+ public sealed override bool IsGenericTypeDefinition => false;
+ protected sealed override bool HasElementTypeImpl() => true;
+ protected abstract override bool IsArrayImpl();
+ protected abstract override bool IsByRefImpl();
+ public sealed override bool IsByRefLike => false;
+ protected abstract override bool IsPointerImpl();
+ public abstract override bool IsSZArray { get; }
+ public abstract override bool IsVariableBoundArray { get; }
+ public sealed override bool IsConstructedGenericType => false;
+ public sealed override bool IsGenericParameter => false;
+ public sealed override bool IsGenericMethodParameter => false;
+ public sealed override bool ContainsGenericParameters => _elementType.ContainsGenericParameters;
+
+ internal sealed override SignatureType ElementType => _elementType;
+ public abstract override int GetArrayRank();
+ public sealed override Type GetGenericTypeDefinition() => throw new InvalidOperationException(SR.InvalidOperation_NotGenericType);
+ public sealed override Type[] GetGenericArguments() => Array.Empty<Type>();
+ public sealed override Type[] GenericTypeArguments => Array.Empty<Type>();
+ public sealed override int GenericParameterPosition => throw new InvalidOperationException(SR.Arg_NotGenericParameter);
+
+ public sealed override string Name => _elementType.Name + Suffix;
+ public sealed override string Namespace => _elementType.Namespace;
+
+ public sealed override string ToString() => _elementType.ToString() + Suffix;
+
+ protected abstract string Suffix { get; }
+
+ private readonly SignatureType _elementType;
+ }
+}
diff --git a/src/mscorlib/shared/System/Reflection/SignaturePointerType.cs b/src/mscorlib/shared/System/Reflection/SignaturePointerType.cs
new file mode 100644
index 0000000000..a75a208165
--- /dev/null
+++ b/src/mscorlib/shared/System/Reflection/SignaturePointerType.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;
+
+namespace System.Reflection
+{
+ internal sealed class SignaturePointerType : SignatureHasElementType
+ {
+ internal SignaturePointerType(SignatureType elementType)
+ : base(elementType)
+ {
+ }
+
+ protected sealed override bool IsArrayImpl() => false;
+ protected sealed override bool IsByRefImpl() => false;
+ protected sealed override bool IsPointerImpl() => true;
+
+ public sealed override bool IsSZArray => false;
+ public sealed override bool IsVariableBoundArray => false;
+
+ public sealed override int GetArrayRank() => throw new ArgumentException(SR.Argument_HasToBeArrayClass);
+
+ protected sealed override string Suffix => "*";
+ }
+}
diff --git a/src/mscorlib/shared/System/Reflection/SignatureType.cs b/src/mscorlib/shared/System/Reflection/SignatureType.cs
new file mode 100644
index 0000000000..c3dfc49174
--- /dev/null
+++ b/src/mscorlib/shared/System/Reflection/SignatureType.cs
@@ -0,0 +1,139 @@
+// 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.Globalization;
+using System.Collections.Generic;
+using System.Runtime.InteropServices;
+
+namespace System.Reflection
+{
+ //
+ // Signature Types are highly restricted Type objects that can be passed in the Type[] parameter to Type.GetMethod(). Their primary
+ // use is to pass types representing generic parameters defined by the method, or types composed from them. Passing in the normal
+ // generic parameter Type obtained from MethodInfo.GetGenericArguments() is usually impractical (if you had the method, you wouldn't
+ // be looking for it!)
+ //
+ internal abstract class SignatureType : Type
+ {
+ public sealed override bool IsSignatureType => true;
+
+ // Type flavor predicates
+ public abstract override bool IsTypeDefinition { get; }
+ protected abstract override bool HasElementTypeImpl();
+ protected abstract override bool IsArrayImpl();
+ public abstract override bool IsSZArray { get; }
+ public abstract override bool IsVariableBoundArray { get; }
+ protected abstract override bool IsByRefImpl();
+ public abstract override bool IsByRefLike { get; }
+ protected abstract override bool IsPointerImpl();
+ public sealed override bool IsGenericType => IsGenericTypeDefinition || IsConstructedGenericType;
+ public abstract override bool IsGenericTypeDefinition { get; }
+ public abstract override bool IsConstructedGenericType { get; }
+ public abstract override bool IsGenericParameter { get; }
+ public abstract bool IsGenericMethodParameter { get; }
+ public abstract override bool ContainsGenericParameters { get; }
+ public sealed override MemberTypes MemberType => MemberTypes.TypeInfo;
+
+ // Compositors
+ public sealed override Type MakeArrayType() => new SignatureArrayType(this, rank: 1, isMultiDim: false);
+ public sealed override Type MakeArrayType(int rank)
+ {
+ if (rank <= 0)
+ throw new IndexOutOfRangeException();
+ return new SignatureArrayType(this, rank: rank, isMultiDim: true);
+ }
+ public sealed override Type MakeByRefType() => new SignatureByRefType(this);
+ public sealed override Type MakePointerType() => new SignaturePointerType(this);
+ public sealed override Type MakeGenericType(params Type[] typeArguments) => throw new NotSupportedException(SR.NotSupported_SignatureType); // There is no SignatureType for type definition types so it would never be legal to call this.
+
+ // Dissectors
+ public sealed override Type GetElementType() => ElementType;
+ public abstract override int GetArrayRank();
+ public abstract override Type GetGenericTypeDefinition();
+ public abstract override Type[] GenericTypeArguments { get; }
+ public abstract override Type[] GetGenericArguments();
+ public abstract override int GenericParameterPosition { get; }
+ internal abstract SignatureType ElementType { get; }
+
+ // Identity
+#if DEBUG
+ public sealed override bool Equals(object o) => base.Equals(o);
+ public sealed override bool Equals(Type o) => base.Equals(o);
+ public sealed override int GetHashCode() => base.GetHashCode();
+#endif
+ public sealed override Type UnderlyingSystemType => this; // Equals(Type) depends on this.
+
+ // Naming and diagnostics
+ public abstract override string Name { get; }
+ public abstract override string Namespace { get; }
+ public sealed override string FullName => null;
+ public sealed override string AssemblyQualifiedName => null;
+ public abstract override string ToString();
+
+ // Not supported on Signature Types
+ public sealed override Assembly Assembly => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override Module Module => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override Type ReflectedType => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override Type BaseType => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override Type[] GetInterfaces() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override bool IsAssignableFrom(Type c) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override int MetadataToken => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override Type DeclaringType => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override MethodBase DeclaringMethod => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override Type[] GetGenericParameterConstraints() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override GenericParameterAttributes GenericParameterAttributes => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override bool IsEnumDefined(object value) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override string GetEnumName(object value) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override string[] GetEnumNames() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override Type GetEnumUnderlyingType() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override Array GetEnumValues() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override Guid GUID => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ protected sealed override TypeCode GetTypeCodeImpl() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ protected sealed override TypeAttributes GetAttributeFlagsImpl() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override EventInfo GetEvent(string name, BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override EventInfo[] GetEvents(BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override FieldInfo GetField(string name, BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override FieldInfo[] GetFields(BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override MemberInfo[] GetMembers(BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override MethodInfo[] GetMethods(BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override Type GetNestedType(string name, BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override Type[] GetNestedTypes(BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override PropertyInfo[] GetProperties(BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ protected sealed override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ protected sealed override MethodInfo GetMethodImpl(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ protected sealed override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override MemberInfo[] GetMember(string name, BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override MemberInfo[] GetDefaultMembers() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override EventInfo[] GetEvents() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override object[] GetCustomAttributes(bool inherit) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override object[] GetCustomAttributes(Type attributeType, bool inherit) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override bool IsDefined(Type attributeType, bool inherit) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override IList<CustomAttributeData> GetCustomAttributesData() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override Type GetInterface(string name, bool ignoreCase) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ protected sealed override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ protected sealed override bool IsCOMObjectImpl() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ protected sealed override bool IsPrimitiveImpl() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override IEnumerable<CustomAttributeData> CustomAttributes => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override Type[] FindInterfaces(TypeFilter filter, object filterCriteria) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override InterfaceMapping GetInterfaceMap(Type interfaceType) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ protected sealed override bool IsContextfulImpl() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override bool IsEnum => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override bool IsEquivalentTo(Type other) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override bool IsInstanceOfType(object o) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ protected sealed override bool IsMarshalByRefImpl() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override bool IsSecurityCritical => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override bool IsSecuritySafeCritical => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override bool IsSecurityTransparent => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override bool IsSerializable => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override bool IsSubclassOf(Type c) => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ protected sealed override bool IsValueTypeImpl() => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override StructLayoutAttribute StructLayoutAttribute => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ public sealed override RuntimeTypeHandle TypeHandle => throw new NotSupportedException(SR.NotSupported_SignatureType);
+ }
+}
diff --git a/src/mscorlib/shared/System/Reflection/SignatureTypeExtensions.cs b/src/mscorlib/shared/System/Reflection/SignatureTypeExtensions.cs
new file mode 100644
index 0000000000..b30da50073
--- /dev/null
+++ b/src/mscorlib/shared/System/Reflection/SignatureTypeExtensions.cs
@@ -0,0 +1,227 @@
+// 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.Reflection;
+using System.Diagnostics;
+
+namespace System.Reflection
+{
+#if CORECLR
+ internal
+#else
+ public // Needs to be public so that Reflection.Core can see it.
+#endif
+ static class SignatureTypeExtensions
+ {
+ /// <summary>
+ /// This is semantically identical to
+ ///
+ /// parameter.ParameterType == pattern.TryResolveAgainstGenericMethod(parameter.Member)
+ ///
+ /// but without the allocation overhead of TryResolve.
+ /// </summary>
+ public static bool MatchesParameterTypeExactly(this Type pattern, ParameterInfo parameter)
+ {
+ if (pattern is SignatureType signatureType)
+ return signatureType.MatchesExactly(parameter.ParameterType);
+ else
+ return pattern == (object)(parameter.ParameterType);
+ }
+
+ /// <summary>
+ /// This is semantically identical to
+ ///
+ /// actual == pattern.TryResolveAgainstGenericMethod(parameterMember)
+ ///
+ /// but without the allocation overhead of TryResolve.
+ /// </summary>
+ internal static bool MatchesExactly(this SignatureType pattern, Type actual)
+ {
+ if (pattern.IsSZArray)
+ {
+ return actual.IsSZArray && pattern.ElementType.MatchesExactly(actual.GetElementType());
+ }
+ else if (pattern.IsVariableBoundArray)
+ {
+ return actual.IsVariableBoundArray && pattern.GetArrayRank() == actual.GetArrayRank() && pattern.ElementType.MatchesExactly(actual.GetElementType());
+ }
+ else if (pattern.IsByRef)
+ {
+ return actual.IsByRef && pattern.ElementType.MatchesExactly(actual.GetElementType());
+ }
+ else if (pattern.IsPointer)
+ {
+ return actual.IsPointer && pattern.ElementType.MatchesExactly(actual.GetElementType());
+ }
+ else if (pattern.IsConstructedGenericType)
+ {
+ if (!actual.IsConstructedGenericType)
+ return false;
+ if (!(pattern.GetGenericTypeDefinition() == actual.GetGenericTypeDefinition()))
+ return false;
+ Type[] patternGenericTypeArguments = pattern.GenericTypeArguments;
+ Type[] actualGenericTypeArguments = actual.GenericTypeArguments;
+ int count = patternGenericTypeArguments.Length;
+ if (count != actualGenericTypeArguments.Length)
+ return false;
+ for (int i = 0; i < count; i++)
+ {
+ Type patternGenericTypeArgument = patternGenericTypeArguments[i];
+ if (patternGenericTypeArgument is SignatureType signatureType)
+ {
+ if (!signatureType.MatchesExactly(actualGenericTypeArguments[i]))
+ return false;
+ }
+ else
+ {
+ if (patternGenericTypeArgument != actualGenericTypeArguments[i])
+ return false;
+ }
+ }
+ return true;
+ }
+ else if (pattern.IsGenericMethodParameter)
+ {
+ if (!(actual.IsGenericParameter && actual.DeclaringMethod != null))
+ return false;
+ if (pattern.GenericParameterPosition != actual.GenericParameterPosition)
+ return false;
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /// <summary>
+ /// Translates a SignatureType into its equivalent resolved Type by recursively substituting all generic parameter references
+ /// with its corresponding generic parameter definition. This is slow so MatchesExactly or MatchesParameterTypeExactly should be
+ /// substituted instead whenever possible. This is only used by the DefaultBinder when its fast-path checks have been exhausted and
+ /// it needs to call non-trivial methods like IsAssignableFrom which SignatureTypes will never support.
+ ///
+ /// Because this method is used to eliminate method candidates in a GetMethod() lookup, it is entirely possible that the Type
+ /// might not be creatable due to conflicting generic constraints. Since this merely implies that this candidate is not
+ /// the method we're looking for, we return null rather than let the TypeLoadException bubble up. The DefaultBinder will catch
+ /// the null and continue its search for a better candidate.
+ /// </summary>
+ internal static Type TryResolveAgainstGenericMethod(this SignatureType signatureType, MethodInfo genericMethod)
+ {
+ return signatureType.TryResolve(genericMethod.GetGenericArguments());
+ }
+
+ private static Type TryResolve(this SignatureType signatureType, Type[] genericMethodParameters)
+ {
+ if (signatureType.IsSZArray)
+ {
+ return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakeArrayType();
+ }
+ else if (signatureType.IsVariableBoundArray)
+ {
+ return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakeArrayType(signatureType.GetArrayRank());
+ }
+ else if (signatureType.IsByRef)
+ {
+ return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakeByRefType();
+ }
+ else if (signatureType.IsPointer)
+ {
+ return signatureType.ElementType.TryResolve(genericMethodParameters)?.TryMakePointerType();
+ }
+ else if (signatureType.IsConstructedGenericType)
+ {
+ Type[] genericTypeArguments = signatureType.GenericTypeArguments;
+ int count = genericTypeArguments.Length;
+ Type[] newGenericTypeArguments = new Type[count];
+ for (int i = 0; i < count; i++)
+ {
+ Type genericTypeArgument = genericTypeArguments[i];
+ if (genericTypeArgument is SignatureType signatureGenericTypeArgument)
+ {
+ newGenericTypeArguments[i] = signatureGenericTypeArgument.TryResolve(genericMethodParameters);
+ if (newGenericTypeArguments[i] == null)
+ return null;
+ }
+ else
+ {
+ newGenericTypeArguments[i] = genericTypeArgument;
+ }
+ }
+ return signatureType.GetGenericTypeDefinition().TryMakeGenericType(newGenericTypeArguments);
+ }
+ else if (signatureType.IsGenericMethodParameter)
+ {
+ int position = signatureType.GenericParameterPosition;
+ if (position >= genericMethodParameters.Length)
+ return null;
+ return genericMethodParameters[position];
+ }
+ else
+ {
+ return null;
+ }
+ }
+
+ private static Type TryMakeArrayType(this Type type)
+ {
+ try
+ {
+ return type.MakeArrayType();
+ }
+ catch
+ {
+ return null;
+ }
+ }
+
+ private static Type TryMakeArrayType(this Type type, int rank)
+ {
+ try
+ {
+ return type.MakeArrayType(rank);
+ }
+ catch
+ {
+ return null;
+ }
+ }
+
+ private static Type TryMakeByRefType(this Type type)
+ {
+ try
+ {
+ return type.MakeByRefType();
+ }
+ catch
+ {
+ return null;
+ }
+ }
+
+ private static Type TryMakePointerType(this Type type)
+ {
+ try
+ {
+ return type.MakePointerType();
+ }
+ catch
+ {
+ return null;
+ }
+ }
+
+ private static Type TryMakeGenericType(this Type type, Type[] instantiation)
+ {
+ try
+ {
+ return type.MakeGenericType(instantiation);
+ }
+ catch
+ {
+ return null;
+ }
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Reflection/TargetException.cs b/src/mscorlib/shared/System/Reflection/TargetException.cs
index 6e43f56fa4..2309daace1 100644
--- a/src/mscorlib/shared/System/Reflection/TargetException.cs
+++ b/src/mscorlib/shared/System/Reflection/TargetException.cs
@@ -21,7 +21,7 @@ namespace System.Reflection
public TargetException(string message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_TARGET;
+ HResult = HResults.COR_E_TARGET;
}
protected TargetException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/Reflection/TargetInvocationException.cs b/src/mscorlib/shared/System/Reflection/TargetInvocationException.cs
index 8d0bfef40d..7c4f60a03e 100644
--- a/src/mscorlib/shared/System/Reflection/TargetInvocationException.cs
+++ b/src/mscorlib/shared/System/Reflection/TargetInvocationException.cs
@@ -11,13 +11,13 @@ namespace System.Reflection
public TargetInvocationException(Exception inner)
: base(SR.Arg_TargetInvocationException, inner)
{
- HResult = __HResults.COR_E_TARGETINVOCATION;
+ HResult = HResults.COR_E_TARGETINVOCATION;
}
public TargetInvocationException(string message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_TARGETINVOCATION;
+ HResult = HResults.COR_E_TARGETINVOCATION;
}
}
}
diff --git a/src/mscorlib/shared/System/Reflection/TargetParameterCountException.cs b/src/mscorlib/shared/System/Reflection/TargetParameterCountException.cs
index e200cdb94f..f31758b7ba 100644
--- a/src/mscorlib/shared/System/Reflection/TargetParameterCountException.cs
+++ b/src/mscorlib/shared/System/Reflection/TargetParameterCountException.cs
@@ -11,19 +11,19 @@ namespace System.Reflection
public TargetParameterCountException()
: base(SR.Arg_TargetParameterCountException)
{
- HResult = __HResults.COR_E_TARGETPARAMCOUNT;
+ HResult = HResults.COR_E_TARGETPARAMCOUNT;
}
public TargetParameterCountException(string message)
: base(message)
{
- HResult = __HResults.COR_E_TARGETPARAMCOUNT;
+ HResult = HResults.COR_E_TARGETPARAMCOUNT;
}
public TargetParameterCountException(string message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_TARGETPARAMCOUNT;
+ HResult = HResults.COR_E_TARGETPARAMCOUNT;
}
}
}
diff --git a/src/mscorlib/shared/System/Reflection/TypeDelegator.cs b/src/mscorlib/shared/System/Reflection/TypeDelegator.cs
index bcbff05d62..1dba278893 100644
--- a/src/mscorlib/shared/System/Reflection/TypeDelegator.cs
+++ b/src/mscorlib/shared/System/Reflection/TypeDelegator.cs
@@ -108,6 +108,7 @@ namespace System.Reflection
protected override bool IsPointerImpl() => typeImpl.IsPointer;
protected override bool IsValueTypeImpl() => typeImpl.IsValueType;
protected override bool IsCOMObjectImpl() => typeImpl.IsCOMObject;
+ public override bool IsByRefLike => typeImpl.IsByRefLike;
public override bool IsConstructedGenericType => typeImpl.IsConstructedGenericType;
public override Type GetElementType() => typeImpl.GetElementType();
protected override bool HasElementTypeImpl() => typeImpl.HasElementType;
diff --git a/src/mscorlib/shared/System/Resources/MissingManifestResourceException.cs b/src/mscorlib/shared/System/Resources/MissingManifestResourceException.cs
index ec814393d0..e11d15d200 100644
--- a/src/mscorlib/shared/System/Resources/MissingManifestResourceException.cs
+++ b/src/mscorlib/shared/System/Resources/MissingManifestResourceException.cs
@@ -12,19 +12,19 @@ namespace System.Resources
public MissingManifestResourceException()
: base(SR.Arg_MissingManifestResourceException)
{
- HResult = System.__HResults.COR_E_MISSINGMANIFESTRESOURCE;
+ HResult = System.HResults.COR_E_MISSINGMANIFESTRESOURCE;
}
public MissingManifestResourceException(string message)
: base(message)
{
- HResult = System.__HResults.COR_E_MISSINGMANIFESTRESOURCE;
+ HResult = System.HResults.COR_E_MISSINGMANIFESTRESOURCE;
}
public MissingManifestResourceException(string message, Exception inner)
: base(message, inner)
{
- HResult = System.__HResults.COR_E_MISSINGMANIFESTRESOURCE;
+ HResult = System.HResults.COR_E_MISSINGMANIFESTRESOURCE;
}
protected MissingManifestResourceException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/Resources/MissingSatelliteAssemblyException.cs b/src/mscorlib/shared/System/Resources/MissingSatelliteAssemblyException.cs
index d2ddc992ac..615aed6a8c 100644
--- a/src/mscorlib/shared/System/Resources/MissingSatelliteAssemblyException.cs
+++ b/src/mscorlib/shared/System/Resources/MissingSatelliteAssemblyException.cs
@@ -27,26 +27,26 @@ namespace System.Resources
public MissingSatelliteAssemblyException()
: base(SR.MissingSatelliteAssembly_Default)
{
- HResult = System.__HResults.COR_E_MISSINGSATELLITEASSEMBLY;
+ HResult = System.HResults.COR_E_MISSINGSATELLITEASSEMBLY;
}
public MissingSatelliteAssemblyException(string message)
: base(message)
{
- HResult = System.__HResults.COR_E_MISSINGSATELLITEASSEMBLY;
+ HResult = System.HResults.COR_E_MISSINGSATELLITEASSEMBLY;
}
public MissingSatelliteAssemblyException(string message, String cultureName)
: base(message)
{
- HResult = System.__HResults.COR_E_MISSINGSATELLITEASSEMBLY;
+ HResult = System.HResults.COR_E_MISSINGSATELLITEASSEMBLY;
_cultureName = cultureName;
}
public MissingSatelliteAssemblyException(string message, Exception inner)
: base(message, inner)
{
- HResult = System.__HResults.COR_E_MISSINGSATELLITEASSEMBLY;
+ HResult = System.HResults.COR_E_MISSINGSATELLITEASSEMBLY;
}
protected MissingSatelliteAssemblyException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/AsyncMethodBuilderAttribute.cs
new file mode 100644
index 0000000000..688a3a01ba
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/AsyncMethodBuilderAttribute.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.
+
+namespace System.Runtime.CompilerServices
+{
+ /// <summary>
+ /// Indicates the type of the async method builder that should be used by a language compiler to
+ /// build the attributed type when used as the return type of an async method.
+ /// </summary>
+ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Delegate | AttributeTargets.Enum, Inherited = false, AllowMultiple = false)]
+ public sealed class AsyncMethodBuilderAttribute : Attribute
+ {
+ /// <summary>Initializes the <see cref="AsyncMethodBuilderAttribute"/>.</summary>
+ /// <param name="builderType">The <see cref="Type"/> of the associated builder.</param>
+ public AsyncMethodBuilderAttribute(Type builderType) => BuilderType = builderType;
+
+ /// <summary>Gets the <see cref="Type"/> of the associated builder.</summary>
+ public Type BuilderType { get; }
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs
new file mode 100644
index 0000000000..813d9e5cd7
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/AsyncValueTaskMethodBuilder.cs
@@ -0,0 +1,111 @@
+// 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.Security;
+using System.Threading.Tasks;
+
+namespace System.Runtime.CompilerServices
+{
+ /// <summary>Represents a builder for asynchronous methods that returns a <see cref="ValueTask{TResult}"/>.</summary>
+ /// <typeparam name="TResult">The type of the result.</typeparam>
+ [StructLayout(LayoutKind.Auto)]
+ public struct AsyncValueTaskMethodBuilder<TResult>
+ {
+ /// <summary>The <see cref="AsyncTaskMethodBuilder{TResult}"/> to which most operations are delegated.</summary>
+ private AsyncTaskMethodBuilder<TResult> _methodBuilder; // mutable struct; do not make it readonly
+ /// <summary>The result for this builder, if it's completed before any awaits occur.</summary>
+ private TResult _result;
+ /// <summary>true if <see cref="_result"/> contains the synchronous result for the async method; otherwise, false.</summary>
+ private bool _haveResult;
+ /// <summary>true if the builder should be used for setting/getting the result; otherwise, false.</summary>
+ private bool _useBuilder;
+
+ /// <summary>Creates an instance of the <see cref="AsyncValueTaskMethodBuilder{TResult}"/> struct.</summary>
+ /// <returns>The initialized instance.</returns>
+ public static AsyncValueTaskMethodBuilder<TResult> Create() =>
+#if CORECLR
+ // _methodBuilder should be initialized to AsyncTaskMethodBuilder<TResult>.Create(), but on coreclr
+ // that Create() is a nop, so we can just return the default here.
+ default(AsyncValueTaskMethodBuilder<TResult>);
+#else
+ // corert's AsyncTaskMethodBuilder<TResult>.Create() currently does additional debugger-related
+ // work, so we need to delegate to it.
+ new AsyncValueTaskMethodBuilder<TResult>() { _methodBuilder = AsyncTaskMethodBuilder<TResult>.Create() };
+#endif
+
+ /// <summary>Begins running the builder with the associated state machine.</summary>
+ /// <typeparam name="TStateMachine">The type of the state machine.</typeparam>
+ /// <param name="stateMachine">The state machine instance, passed by reference.</param>
+ public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine =>
+ _methodBuilder.Start(ref stateMachine); // will provide the right ExecutionContext semantics
+
+ /// <summary>Associates the builder with the specified state machine.</summary>
+ /// <param name="stateMachine">The state machine instance to associate with the builder.</param>
+ public void SetStateMachine(IAsyncStateMachine stateMachine) => _methodBuilder.SetStateMachine(stateMachine);
+
+ /// <summary>Marks the task as successfully completed.</summary>
+ /// <param name="result">The result to use to complete the task.</param>
+ public void SetResult(TResult result)
+ {
+ if (_useBuilder)
+ {
+ _methodBuilder.SetResult(result);
+ }
+ else
+ {
+ _result = result;
+ _haveResult = true;
+ }
+ }
+
+ /// <summary>Marks the task as failed and binds the specified exception to the task.</summary>
+ /// <param name="exception">The exception to bind to the task.</param>
+ public void SetException(Exception exception) => _methodBuilder.SetException(exception);
+
+ /// <summary>Gets the task for this builder.</summary>
+ public ValueTask<TResult> Task
+ {
+ get
+ {
+ if (_haveResult)
+ {
+ return new ValueTask<TResult>(_result);
+ }
+ else
+ {
+ _useBuilder = true;
+ return new ValueTask<TResult>(_methodBuilder.Task);
+ }
+ }
+ }
+
+ /// <summary>Schedules the state machine to proceed to the next action when the specified awaiter completes.</summary>
+ /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam>
+ /// <typeparam name="TStateMachine">The type of the state machine.</typeparam>
+ /// <param name="awaiter">the awaiter</param>
+ /// <param name="stateMachine">The state machine.</param>
+ public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
+ where TAwaiter : INotifyCompletion
+ where TStateMachine : IAsyncStateMachine
+ {
+ _useBuilder = true;
+ _methodBuilder.AwaitOnCompleted(ref awaiter, ref stateMachine);
+ }
+
+ /// <summary>Schedules the state machine to proceed to the next action when the specified awaiter completes.</summary>
+ /// <typeparam name="TAwaiter">The type of the awaiter.</typeparam>
+ /// <typeparam name="TStateMachine">The type of the state machine.</typeparam>
+ /// <param name="awaiter">the awaiter</param>
+ /// <param name="stateMachine">The state machine.</param>
+ [SecuritySafeCritical]
+ public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine)
+ where TAwaiter : ICriticalNotifyCompletion
+ where TStateMachine : IAsyncStateMachine
+ {
+ _useBuilder = true;
+ _methodBuilder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs
new file mode 100644
index 0000000000..4ec931c4af
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/ConfiguredValueTaskAwaitable.cs
@@ -0,0 +1,71 @@
+// 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.Threading.Tasks;
+
+namespace System.Runtime.CompilerServices
+{
+ /// <summary>Provides an awaitable type that enables configured awaits on a <see cref="ValueTask{TResult}"/>.</summary>
+ /// <typeparam name="TResult">The type of the result produced.</typeparam>
+ [StructLayout(LayoutKind.Auto)]
+ public struct ConfiguredValueTaskAwaitable<TResult>
+ {
+ /// <summary>The wrapped <see cref="ValueTask{TResult}"/>.</summary>
+ private readonly ValueTask<TResult> _value;
+ /// <summary>true to attempt to marshal the continuation back to the original context captured; otherwise, false.</summary>
+ private readonly bool _continueOnCapturedContext;
+
+ /// <summary>Initializes the awaitable.</summary>
+ /// <param name="value">The wrapped <see cref="ValueTask{TResult}"/>.</param>
+ /// <param name="continueOnCapturedContext">
+ /// true to attempt to marshal the continuation back to the original synchronization context captured; otherwise, false.
+ /// </param>
+ internal ConfiguredValueTaskAwaitable(ValueTask<TResult> value, bool continueOnCapturedContext)
+ {
+ _value = value;
+ _continueOnCapturedContext = continueOnCapturedContext;
+ }
+
+ /// <summary>Returns an awaiter for this <see cref="ConfiguredValueTaskAwaitable{TResult}"/> instance.</summary>
+ public ConfiguredValueTaskAwaiter GetAwaiter() =>
+ new ConfiguredValueTaskAwaiter(_value, _continueOnCapturedContext);
+
+ /// <summary>Provides an awaiter for a <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary>
+ [StructLayout(LayoutKind.Auto)]
+ public struct ConfiguredValueTaskAwaiter : ICriticalNotifyCompletion
+ {
+ /// <summary>The value being awaited.</summary>
+ private ValueTask<TResult> _value; // Methods are called on this; avoid making it readonly so as to avoid unnecessary copies
+ /// <summary>The value to pass to ConfigureAwait.</summary>
+ private readonly bool _continueOnCapturedContext;
+
+ /// <summary>Initializes the awaiter.</summary>
+ /// <param name="value">The value to be awaited.</param>
+ /// <param name="continueOnCapturedContext">The value to pass to ConfigureAwait.</param>
+ internal ConfiguredValueTaskAwaiter(ValueTask<TResult> value, bool continueOnCapturedContext)
+ {
+ _value = value;
+ _continueOnCapturedContext = continueOnCapturedContext;
+ }
+
+ /// <summary>Gets whether the <see cref="ConfiguredValueTaskAwaitable{TResult}"/> has completed.</summary>
+ public bool IsCompleted => _value.IsCompleted;
+
+ /// <summary>Gets the result of the ValueTask.</summary>
+ public TResult GetResult() =>
+ _value._task == null ?
+ _value._result :
+ _value._task.GetAwaiter().GetResult();
+
+ /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary>
+ public void OnCompleted(Action continuation) =>
+ _value.AsTask().ConfigureAwait(_continueOnCapturedContext).GetAwaiter().OnCompleted(continuation);
+
+ /// <summary>Schedules the continuation action for the <see cref="ConfiguredValueTaskAwaitable{TResult}"/>.</summary>
+ public void UnsafeOnCompleted(Action continuation) =>
+ _value.AsTask().ConfigureAwait(_continueOnCapturedContext).GetAwaiter().UnsafeOnCompleted(continuation);
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.cs
new file mode 100644
index 0000000000..f75693eb40
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/CustomConstantAttribute.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.Runtime.CompilerServices
+{
+ [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
+ public abstract class CustomConstantAttribute : Attribute
+ {
+ public abstract Object Value { get; }
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs
new file mode 100644
index 0000000000..813e6803bf
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/DateTimeConstantAttribute.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.
+
+namespace System.Runtime.CompilerServices
+{
+ [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
+ public sealed class DateTimeConstantAttribute : CustomConstantAttribute
+ {
+ private DateTime _date;
+
+ public DateTimeConstantAttribute(long ticks)
+ {
+ _date = new DateTime(ticks);
+ }
+
+ public override Object Value => _date;
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
new file mode 100644
index 0000000000..19db84eb43
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/DecimalConstantAttribute.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.
+
+// Note: If you add a new ctor overloads you need to update ParameterInfo.RawDefaultValue
+
+namespace System.Runtime.CompilerServices
+{
+ [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
+ public sealed class DecimalConstantAttribute : Attribute
+ {
+ private Decimal _dec;
+
+ [CLSCompliant(false)]
+ public DecimalConstantAttribute(
+ byte scale,
+ byte sign,
+ uint hi,
+ uint mid,
+ uint low
+ )
+ {
+ _dec = new Decimal((int)low, (int)mid, (int)hi, (sign != 0), scale);
+ }
+
+ public DecimalConstantAttribute(
+ byte scale,
+ byte sign,
+ int hi,
+ int mid,
+ int low
+ )
+ {
+ _dec = new Decimal(low, mid, hi, (sign != 0), scale);
+ }
+
+ public Decimal Value => _dec;
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/IntrinsicAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/IntrinsicAttribute.cs
new file mode 100644
index 0000000000..dd01bacc49
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/IntrinsicAttribute.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.Runtime.CompilerServices
+{
+ // Calls to methods or references to fields marked with this attribute may be replaced at
+ // some call sites with jit intrinsic expansions.
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Field, Inherited = false)]
+ internal sealed class IntrinsicAttribute : Attribute
+ {
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/MethodImplAttribute.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/MethodImplAttribute.cs
new file mode 100644
index 0000000000..8e8f93c268
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/MethodImplAttribute.cs
@@ -0,0 +1,29 @@
+// 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.Runtime.CompilerServices
+{
+ // Custom attribute to specify additional method properties.
+ [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
+ sealed public class MethodImplAttribute : Attribute
+ {
+ public MethodCodeType MethodCodeType;
+
+ public MethodImplAttribute(MethodImplOptions methodImplOptions)
+ {
+ Value = methodImplOptions;
+ }
+
+ public MethodImplAttribute(short value)
+ {
+ Value = (MethodImplOptions)value;
+ }
+
+ public MethodImplAttribute()
+ {
+ }
+
+ public MethodImplOptions Value { get; }
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/RuntimeWrappedException.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/RuntimeWrappedException.cs
new file mode 100644
index 0000000000..e4af9be678
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/RuntimeWrappedException.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.Runtime.CompilerServices
+{
+ /// <summary>
+ /// Exception used to wrap all non-CLS compliant exceptions.
+ /// </summary>
+ public sealed class RuntimeWrappedException : Exception
+ {
+ private Object _wrappedException; // EE expects this name
+
+ // Not an api but has to be public as System.Linq.Expression invokes this through Reflection when an expression
+ // throws an object that doesn't derive from Exception.
+ public RuntimeWrappedException(Object thrownObject)
+ : base(SR.RuntimeWrappedException)
+ {
+ HResult = HResults.COR_E_RUNTIMEWRAPPED;
+ _wrappedException = thrownObject;
+ }
+
+ public override void GetObjectData(SerializationInfo info, StreamingContext context)
+ {
+ base.GetObjectData(info, context);
+ }
+
+ public Object WrappedException => _wrappedException;
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/CompilerServices/ValueTaskAwaiter.cs b/src/mscorlib/shared/System/Runtime/CompilerServices/ValueTaskAwaiter.cs
new file mode 100644
index 0000000000..c419482521
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/CompilerServices/ValueTaskAwaiter.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.Runtime.InteropServices;
+using System.Threading.Tasks;
+
+namespace System.Runtime.CompilerServices
+{
+ /// <summary>Provides an awaiter for a <see cref="ValueTask{TResult}"/>.</summary>
+ public struct ValueTaskAwaiter<TResult> : ICriticalNotifyCompletion
+ {
+ /// <summary>The value being awaited.</summary>
+ private ValueTask<TResult> _value; // Methods are called on this; avoid making it readonly so as to avoid unnecessary copies
+
+ /// <summary>Initializes the awaiter.</summary>
+ /// <param name="value">The value to be awaited.</param>
+ internal ValueTaskAwaiter(ValueTask<TResult> value) => _value = value;
+
+ /// <summary>Gets whether the <see cref="ValueTask{TResult}"/> has completed.</summary>
+ public bool IsCompleted => _value.IsCompleted;
+
+ /// <summary>Gets the result of the ValueTask.</summary>
+ public TResult GetResult() =>
+ _value._task == null ?
+ _value._result :
+ _value._task.GetAwaiter().GetResult();
+
+ /// <summary>Schedules the continuation action for this ValueTask.</summary>
+ public void OnCompleted(Action continuation) =>
+ _value.AsTask().ConfigureAwait(continueOnCapturedContext: true).GetAwaiter().OnCompleted(continuation);
+
+ /// <summary>Schedules the continuation action for this ValueTask.</summary>
+ public void UnsafeOnCompleted(Action continuation) =>
+ _value.AsTask().ConfigureAwait(continueOnCapturedContext: true).GetAwaiter().UnsafeOnCompleted(continuation);
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs b/src/mscorlib/shared/System/Runtime/ExceptionServices/HandleProcessCorruptedStateExceptionsAttribute.cs
index 00067748f2..cc1bc81e5a 100644
--- a/src/mscorlib/src/System/Runtime/ExceptionServices/CorruptingExceptionCommon.cs
+++ b/src/mscorlib/shared/System/Runtime/ExceptionServices/HandleProcessCorruptedStateExceptionsAttribute.cs
@@ -2,20 +2,6 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-/*=============================================================================
-**
-**
-**
-** Purpose: Contains common usage support entities for Corrupting Exceptions
-**
-** Created: 06/20/2008
-**
-**
-**
-=============================================================================*/
-
-using System;
-
namespace System.Runtime.ExceptionServices
{
// This attribute can be applied to methods to indicate that ProcessCorruptedState
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/BestFitMappingAttribute.cs b/src/mscorlib/shared/System/Runtime/InteropServices/BestFitMappingAttribute.cs
new file mode 100644
index 0000000000..4ebee1538c
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/BestFitMappingAttribute.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.
+
+namespace System.Runtime.InteropServices
+{
+ [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
+ public sealed class BestFitMappingAttribute : Attribute
+ {
+ public BestFitMappingAttribute(bool BestFitMapping)
+ {
+ this.BestFitMapping = BestFitMapping;
+ }
+
+ public bool BestFitMapping { get; }
+
+ public bool ThrowOnUnmappableChar;
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/DefaultCharSetAttribute.cs b/src/mscorlib/shared/System/Runtime/InteropServices/DefaultCharSetAttribute.cs
new file mode 100644
index 0000000000..7a486f7017
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/DefaultCharSetAttribute.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.
+
+namespace System.Runtime.InteropServices
+{
+ [AttributeUsage(AttributeTargets.Module, Inherited = false)]
+ public sealed class DefaultCharSetAttribute : Attribute
+ {
+ public DefaultCharSetAttribute(CharSet charSet)
+ {
+ CharSet = charSet;
+ }
+
+ public CharSet CharSet { get; }
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/DefaultDllImportSearchPathsAttribute.cs b/src/mscorlib/shared/System/Runtime/InteropServices/DefaultDllImportSearchPathsAttribute.cs
new file mode 100644
index 0000000000..1ff27fbbd5
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/DefaultDllImportSearchPathsAttribute.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.
+
+namespace System.Runtime.InteropServices
+{
+ [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Method, AllowMultiple = false)]
+ public sealed class DefaultDllImportSearchPathsAttribute : Attribute
+ {
+ public DefaultDllImportSearchPathsAttribute(DllImportSearchPath paths)
+ {
+ Paths = paths;
+ }
+
+ public DllImportSearchPath Paths { get; }
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/DllImportAttribute.cs b/src/mscorlib/shared/System/Runtime/InteropServices/DllImportAttribute.cs
new file mode 100644
index 0000000000..97f870d49c
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/DllImportAttribute.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.
+
+namespace System.Runtime.InteropServices
+{
+ [AttributeUsage(AttributeTargets.Method, Inherited = false)]
+ public sealed class DllImportAttribute : Attribute
+ {
+ public DllImportAttribute(string dllName)
+ {
+ Value = dllName;
+ }
+
+ public string Value { get; }
+
+ public string EntryPoint;
+ public CharSet CharSet;
+ public bool SetLastError;
+ public bool ExactSpelling;
+ public CallingConvention CallingConvention;
+ public bool BestFitMapping;
+ public bool PreserveSig;
+ public bool ThrowOnUnmappableChar;
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/DllImportSearchPath.cs b/src/mscorlib/shared/System/Runtime/InteropServices/DllImportSearchPath.cs
new file mode 100644
index 0000000000..8dbdb40be9
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/DllImportSearchPath.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.
+
+namespace System.Runtime.InteropServices
+{
+ [Flags]
+ public enum DllImportSearchPath
+ {
+ UseDllDirectoryForDependencies = 0x100,
+ ApplicationDirectory = 0x200,
+ UserDirectories = 0x400,
+ System32 = 0x800,
+ SafeDirectories = 0x1000,
+ AssemblyDirectory = 0x2,
+ LegacyBehavior = 0x0
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/ExternalException.cs b/src/mscorlib/shared/System/Runtime/InteropServices/ExternalException.cs
index 81b9a46928..0861d19362 100644
--- a/src/mscorlib/shared/System/Runtime/InteropServices/ExternalException.cs
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/ExternalException.cs
@@ -26,19 +26,19 @@ namespace System.Runtime.InteropServices
public ExternalException()
: base(SR.Arg_ExternalException)
{
- HResult = __HResults.E_FAIL;
+ HResult = HResults.E_FAIL;
}
public ExternalException(string message)
: base(message)
{
- HResult = __HResults.E_FAIL;
+ HResult = HResults.E_FAIL;
}
public ExternalException(string message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.E_FAIL;
+ HResult = HResults.E_FAIL;
}
public ExternalException(string message, int errorCode)
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/FieldOffsetAttribute.cs b/src/mscorlib/shared/System/Runtime/InteropServices/FieldOffsetAttribute.cs
new file mode 100644
index 0000000000..27e1097749
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/FieldOffsetAttribute.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.
+
+namespace System.Runtime.InteropServices
+{
+ [AttributeUsage(AttributeTargets.Field, Inherited = false)]
+ public sealed class FieldOffsetAttribute : Attribute
+ {
+ public FieldOffsetAttribute(int offset)
+ {
+ Value = offset;
+ }
+
+ public int Value { get; }
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/InAttribute.cs b/src/mscorlib/shared/System/Runtime/InteropServices/InAttribute.cs
new file mode 100644
index 0000000000..39f5a958bc
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/InAttribute.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.
+
+namespace System.Runtime.InteropServices
+{
+ [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
+ public sealed class InAttribute : Attribute
+ {
+ public InAttribute()
+ {
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/MarshalAsAttribute.cs b/src/mscorlib/shared/System/Runtime/InteropServices/MarshalAsAttribute.cs
new file mode 100644
index 0000000000..4a64050ed1
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/MarshalAsAttribute.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.
+
+namespace System.Runtime.InteropServices
+{
+ [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.ReturnValue, Inherited = false)]
+ public sealed class MarshalAsAttribute : Attribute
+ {
+ public MarshalAsAttribute(UnmanagedType unmanagedType)
+ {
+ Value = unmanagedType;
+ }
+ public MarshalAsAttribute(short unmanagedType)
+ {
+ Value = (UnmanagedType)unmanagedType;
+ }
+
+ public UnmanagedType Value { get; }
+
+ // Fields used with SubType = SafeArray.
+ public VarEnum SafeArraySubType;
+ public Type SafeArrayUserDefinedSubType;
+
+ // Field used with iid_is attribute (interface pointers).
+ public int IidParameterIndex;
+
+ // Fields used with SubType = ByValArray and LPArray.
+ // Array size = parameter(PI) * PM + C
+ public UnmanagedType ArraySubType;
+ public short SizeParamIndex; // param index PI
+ public int SizeConst; // constant C
+
+ // Fields used with SubType = CustomMarshaler
+ public string MarshalType; // Name of marshaler class
+ public Type MarshalTypeRef; // Type of marshaler class
+ public string MarshalCookie; // cookie to pass to marshaler
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/OptionalAttribute.cs b/src/mscorlib/shared/System/Runtime/InteropServices/OptionalAttribute.cs
new file mode 100644
index 0000000000..5ac75d7b3e
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/OptionalAttribute.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.
+
+namespace System.Runtime.InteropServices
+{
+ [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
+ public sealed class OptionalAttribute : Attribute
+ {
+ public OptionalAttribute()
+ {
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/OutAttribute.cs b/src/mscorlib/shared/System/Runtime/InteropServices/OutAttribute.cs
new file mode 100644
index 0000000000..338ceac91e
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/OutAttribute.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.
+
+namespace System.Runtime.InteropServices
+{
+ [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
+ public sealed class OutAttribute : Attribute
+ {
+ public OutAttribute()
+ {
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/PreserveSigAttribute.cs b/src/mscorlib/shared/System/Runtime/InteropServices/PreserveSigAttribute.cs
new file mode 100644
index 0000000000..464e1abcbe
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/PreserveSigAttribute.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.
+
+namespace System.Runtime.InteropServices
+{
+ [AttributeUsage(AttributeTargets.Method, Inherited = false)]
+ public sealed class PreserveSigAttribute : Attribute
+ {
+ public PreserveSigAttribute()
+ {
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/StructLayoutAttribute.cs b/src/mscorlib/shared/System/Runtime/InteropServices/StructLayoutAttribute.cs
new file mode 100644
index 0000000000..c4cce9956e
--- /dev/null
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/StructLayoutAttribute.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.
+
+namespace System.Runtime.InteropServices
+{
+ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
+ public sealed class StructLayoutAttribute : Attribute
+ {
+ public StructLayoutAttribute(LayoutKind layoutKind)
+ {
+ Value = layoutKind;
+ }
+
+ public StructLayoutAttribute(short layoutKind)
+ {
+ Value = (LayoutKind)layoutKind;
+ }
+
+ public LayoutKind Value { get; }
+
+ public int Pack;
+ public int Size;
+ public CharSet CharSet;
+ }
+}
diff --git a/src/mscorlib/shared/System/Runtime/InteropServices/UnmanagedFunctionPointerAttribute.cs b/src/mscorlib/shared/System/Runtime/InteropServices/UnmanagedFunctionPointerAttribute.cs
index 2d69c95afe..c4f96903ee 100644
--- a/src/mscorlib/shared/System/Runtime/InteropServices/UnmanagedFunctionPointerAttribute.cs
+++ b/src/mscorlib/shared/System/Runtime/InteropServices/UnmanagedFunctionPointerAttribute.cs
@@ -7,11 +7,6 @@ namespace System.Runtime.InteropServices
[AttributeUsage(AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
public sealed class UnmanagedFunctionPointerAttribute : Attribute
{
- public bool BestFitMapping;
- public bool SetLastError;
- public bool ThrowOnUnmappableChar;
- public CharSet CharSet;
-
public UnmanagedFunctionPointerAttribute()
{
CallingConvention = CallingConvention.Winapi;
@@ -23,5 +18,10 @@ namespace System.Runtime.InteropServices
}
public CallingConvention CallingConvention { get; }
+
+ public bool BestFitMapping;
+ public bool SetLastError;
+ public bool ThrowOnUnmappableChar;
+ public CharSet CharSet;
}
}
diff --git a/src/mscorlib/shared/System/Runtime/Serialization/SerializationException.cs b/src/mscorlib/shared/System/Runtime/Serialization/SerializationException.cs
index bfe3313659..3e0af092c0 100644
--- a/src/mscorlib/shared/System/Runtime/Serialization/SerializationException.cs
+++ b/src/mscorlib/shared/System/Runtime/Serialization/SerializationException.cs
@@ -15,19 +15,19 @@ namespace System.Runtime.Serialization
public SerializationException()
: base(s_nullMessage)
{
- HResult = __HResults.COR_E_SERIALIZATION;
+ HResult = HResults.COR_E_SERIALIZATION;
}
public SerializationException(String message)
: base(message)
{
- HResult = __HResults.COR_E_SERIALIZATION;
+ HResult = HResults.COR_E_SERIALIZATION;
}
public SerializationException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_SERIALIZATION;
+ HResult = HResults.COR_E_SERIALIZATION;
}
protected SerializationException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/src/System/SByte.cs b/src/mscorlib/shared/System/SByte.cs
index 8a0ab3e129..c984767336 100644
--- a/src/mscorlib/src/System/SByte.cs
+++ b/src/mscorlib/shared/System/SByte.cs
@@ -2,28 +2,18 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-/*============================================================
-**
-**
-**
-** Purpose:
-**
-**
-===========================================================*/
-
+using System.Diagnostics.Contracts;
using System.Globalization;
-using System;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
+using System.Runtime.Versioning;
namespace System
{
- // A place holder class for signed bytes.
[Serializable]
- [CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
- [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
- public struct SByte : IComparable, IFormattable, IConvertible
- , IComparable<SByte>, IEquatable<SByte>
+ [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)]
+ [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ public struct SByte : IComparable, IConvertible, IFormattable, IComparable<SByte>, IEquatable<SByte>
{
private sbyte m_value; // Do not rename (binary serialization)
@@ -68,7 +58,7 @@ namespace System
return m_value == ((SByte)obj).m_value;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public bool Equals(SByte obj)
{
return m_value == obj;
@@ -121,20 +111,23 @@ namespace System
[CLSCompliant(false)]
public static sbyte Parse(String s)
{
- return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static sbyte Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
- return Parse(s, style, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static sbyte Parse(String s, IFormatProvider provider)
{
- return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
// Parses a signed byte from a String in the given style. If
@@ -145,11 +138,25 @@ namespace System
public static sbyte Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
+ }
+
+ [CLSCompliant(false)]
+ public static sbyte Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
private static sbyte Parse(String s, NumberStyles style, NumberFormatInfo info)
{
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), style, info);
+ }
+
+ private static sbyte Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info)
+ {
int i = 0;
try
{
@@ -176,17 +183,37 @@ namespace System
[CLSCompliant(false)]
public static bool TryParse(String s, out SByte result)
{
- return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return TryParse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out SByte result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return TryParse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
+ }
+
+ [CLSCompliant(false)]
+ public static bool TryParse(ReadOnlySpan<char> s, out sbyte result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
- private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out SByte result)
+ private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out SByte result)
{
result = 0;
int i;
diff --git a/src/mscorlib/shared/System/Security/SecurityException.cs b/src/mscorlib/shared/System/Security/SecurityException.cs
index 538f475343..2866a4780c 100644
--- a/src/mscorlib/shared/System/Security/SecurityException.cs
+++ b/src/mscorlib/shared/System/Security/SecurityException.cs
@@ -12,32 +12,32 @@ namespace System.Security
public SecurityException()
: base(SR.Arg_SecurityException)
{
- HResult = __HResults.COR_E_SECURITY;
+ HResult = HResults.COR_E_SECURITY;
}
public SecurityException(string message)
: base(message)
{
- HResult = __HResults.COR_E_SECURITY;
+ HResult = HResults.COR_E_SECURITY;
}
public SecurityException(string message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_SECURITY;
+ HResult = HResults.COR_E_SECURITY;
}
public SecurityException(string message, Type type)
: base(message)
{
- HResult = __HResults.COR_E_SECURITY;
+ HResult = HResults.COR_E_SECURITY;
PermissionType = type;
}
public SecurityException(string message, Type type, string state)
: base(message)
{
- HResult = __HResults.COR_E_SECURITY;
+ HResult = HResults.COR_E_SECURITY;
PermissionType = type;
PermissionState = state;
}
diff --git a/src/mscorlib/shared/System/Security/VerificationException.cs b/src/mscorlib/shared/System/Security/VerificationException.cs
index ea5a75906e..bd095f3df4 100644
--- a/src/mscorlib/shared/System/Security/VerificationException.cs
+++ b/src/mscorlib/shared/System/Security/VerificationException.cs
@@ -11,19 +11,19 @@ namespace System.Security
public VerificationException()
: base(SR.Verification_Exception)
{
- HResult = __HResults.COR_E_VERIFICATION;
+ HResult = HResults.COR_E_VERIFICATION;
}
public VerificationException(string message)
: base(message)
{
- HResult = __HResults.COR_E_VERIFICATION;
+ HResult = HResults.COR_E_VERIFICATION;
}
public VerificationException(string message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_VERIFICATION;
+ HResult = HResults.COR_E_VERIFICATION;
}
protected VerificationException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/SerializableAttribute.cs b/src/mscorlib/shared/System/SerializableAttribute.cs
new file mode 100644
index 0000000000..c256931373
--- /dev/null
+++ b/src/mscorlib/shared/System/SerializableAttribute.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
+{
+ [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)]
+ public sealed class SerializableAttribute : Attribute
+ {
+ public SerializableAttribute() { }
+ }
+}
diff --git a/src/mscorlib/src/System/Single.cs b/src/mscorlib/shared/System/Single.cs
index 2bdc2a9696..0be8cfbc37 100644
--- a/src/mscorlib/src/System/Single.cs
+++ b/src/mscorlib/shared/System/Single.cs
@@ -11,20 +11,18 @@
**
===========================================================*/
+using System.Diagnostics.Contracts;
using System.Globalization;
-using System;
-using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
-using System.Runtime.ConstrainedExecution;
-using System.Diagnostics.Contracts;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
namespace System
{
[Serializable]
- [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
- [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
- public struct Single : IComparable, IFormattable, IConvertible
- , IComparable<Single>, IEquatable<Single>
+ [StructLayout(LayoutKind.Sequential)]
+ [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ public struct Single : IComparable, IConvertible, IFormattable, IComparable<Single>, IEquatable<Single>
{
private float m_value; // Do not rename (binary serialization)
@@ -38,11 +36,12 @@ namespace System
public const float NegativeInfinity = (float)-1.0 / (float)0.0;
public const float NaN = (float)0.0 / (float)0.0;
- internal static float NegativeZero = BitConverter.Int32BitsToSingle(unchecked((int)0x80000000));
+ // We use this explicit definition to avoid the confusion between 0.0 and -0.0.
+ internal const float NegativeZero = (float)-0.0;
/// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsFinite(float f)
{
@@ -52,7 +51,7 @@ namespace System
/// <summary>Determines whether the specified value is infinite.</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsInfinity(float f)
{
@@ -62,7 +61,7 @@ namespace System
/// <summary>Determines whether the specified value is NaN.</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNaN(float f)
{
@@ -72,7 +71,7 @@ namespace System
/// <summary>Determines whether the specified value is negative.</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNegative(float f)
{
@@ -82,7 +81,7 @@ namespace System
/// <summary>Determines whether the specified value is negative infinity.</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsNegativeInfinity(float f)
{
@@ -91,7 +90,7 @@ namespace System
/// <summary>Determines whether the specified value is normal.</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public unsafe static bool IsNormal(float f)
{
@@ -102,7 +101,7 @@ namespace System
/// <summary>Determines whether the specified value is positive infinity.</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe static bool IsPositiveInfinity(float f)
{
@@ -111,7 +110,7 @@ namespace System
/// <summary>Determines whether the specified value is subnormal.</summary>
[Pure]
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
// This is probably not worth inlining, it has branches and should be rarely called
public unsafe static bool IsSubnormal(float f)
{
@@ -162,37 +161,37 @@ namespace System
return 1;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public static bool operator ==(Single left, Single right)
{
return left == right;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public static bool operator !=(Single left, Single right)
{
return left != right;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public static bool operator <(Single left, Single right)
{
return left < right;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public static bool operator >(Single left, Single right)
{
return left > right;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public static bool operator <=(Single left, Single right)
{
return left <= right;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public static bool operator >=(Single left, Single right)
{
return left >= right;
@@ -269,67 +268,88 @@ namespace System
//
public static float Parse(String s)
{
- return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseSingle(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
}
public static float Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
- return Parse(s, style, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseSingle(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
public static float Parse(String s, IFormatProvider provider)
{
- return Parse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseSingle(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
}
public static float Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
- return Parse(s, style, NumberFormatInfo.GetInstance(provider));
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseSingle(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
}
- private static float Parse(String s, NumberStyles style, NumberFormatInfo info)
+ public static float Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
- return Number.ParseSingle(s, style, info);
+ NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
+ return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider));
}
public static Boolean TryParse(String s, out Single result)
{
- return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return TryParse(s.AsReadOnlySpan(), NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
}
public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Single result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
- return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
- }
- private static Boolean TryParse(String s, NumberStyles style, NumberFormatInfo info, out Single result)
- {
if (s == null)
{
result = 0;
return false;
}
+
+ return TryParse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
+ }
+
+ public static Boolean TryParse(ReadOnlySpan<char> s, out Single result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
+ return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
+ }
+
+ private static Boolean TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out Single result)
+ {
bool success = Number.TryParseSingle(s, style, info, out result);
if (!success)
{
- String sTrim = s.Trim();
- if (sTrim.Equals(info.PositiveInfinitySymbol))
+ ReadOnlySpan<char> sTrim = s.Trim();
+ if (StringSpanHelpers.Equals(sTrim, info.PositiveInfinitySymbol))
{
result = PositiveInfinity;
}
- else if (sTrim.Equals(info.NegativeInfinitySymbol))
+ else if (StringSpanHelpers.Equals(sTrim, info.NegativeInfinitySymbol))
{
result = NegativeInfinity;
}
- else if (sTrim.Equals(info.NaNSymbol))
+ else if (StringSpanHelpers.Equals(sTrim, info.NaNSymbol))
{
result = NaN;
}
else
+ {
return false; // We really failed
+ }
}
return true;
}
diff --git a/src/mscorlib/shared/System/Span.NonGeneric.cs b/src/mscorlib/shared/System/Span.NonGeneric.cs
index 62b6faa8ec..0e8bfaa994 100644
--- a/src/mscorlib/shared/System/Span.NonGeneric.cs
+++ b/src/mscorlib/shared/System/Span.NonGeneric.cs
@@ -118,7 +118,7 @@ namespace System
/// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is a null
/// reference (Nothing in Visual Basic).</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- public static ReadOnlySpan<char> AsSpan(this string text)
+ public static ReadOnlySpan<char> AsReadOnlySpan(this string text)
{
if (text == null)
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
diff --git a/src/mscorlib/shared/System/Span.cs b/src/mscorlib/shared/System/Span.cs
index 88612eb28b..de6787d09d 100644
--- a/src/mscorlib/shared/System/Span.cs
+++ b/src/mscorlib/shared/System/Span.cs
@@ -2,11 +2,10 @@
// 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.Diagnostics;
-using System.Runtime;
using System.Runtime.CompilerServices;
-using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
-using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
+using System.Runtime.Versioning;
#pragma warning disable 0809 //warning CS0809: Obsolete member 'Span<T>.Equals(object)' overrides non-obsolete member 'object.Equals(object)'
@@ -22,7 +21,9 @@ namespace System
/// Span represents a contiguous region of arbitrary memory. Unlike arrays, it can point to either managed
/// or native memory, or to memory allocated on the stack. It is type- and memory-safe.
/// </summary>
+ [IsReadOnly]
[IsByRefLike]
+ [NonVersionable]
public struct Span<T>
{
/// <summary>A byref or a native ptr.</summary>
@@ -54,32 +55,6 @@ namespace System
/// <summary>
/// Creates a new span over the portion of the target array beginning
- /// at 'start' index and covering the remainder of the array.
- /// </summary>
- /// <param name="array">The target array.</param>
- /// <param name="start">The index at which to begin the span.</param>
- /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="array"/> is a null
- /// reference (Nothing in Visual Basic).</exception>
- /// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
- /// <exception cref="System.ArgumentOutOfRangeException">
- /// Thrown when the specified <paramref name="start"/> is not in the range (&lt;0 or &gt;=Length).
- /// </exception>
- [MethodImpl(MethodImplOptions.AggressiveInlining)]
- public Span(T[] array, int start)
- {
- if (array == null)
- ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
- if (default(T) == null && array.GetType() != typeof(T[]))
- ThrowHelper.ThrowArrayTypeMismatchException();
- if ((uint)start > (uint)array.Length)
- ThrowHelper.ThrowArgumentOutOfRangeException();
-
- _pointer = new ByReference<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start));
- _length = array.Length - start;
- }
-
- /// <summary>
- /// Creates a new span over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
@@ -142,6 +117,7 @@ namespace System
/// <param name="objectData">A reference to data within that object.</param>
/// <param name="length">The number of <typeparamref name="T"/> elements the memory contains.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
public static Span<T> DangerousCreate(object obj, ref T objectData, int length) => new Span<T>(ref objectData, length);
// Constructor for internal use only.
@@ -158,6 +134,8 @@ namespace System
/// Returns a reference to the 0th element of the Span. If the Span is empty, returns a reference to the location where the 0th element
/// would have been stored. Such a reference can be used for pinning but must never be dereferenced.
/// </summary>
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [EditorBrowsable(EditorBrowsableState.Never)]
public ref T DangerousGetPinnableReference()
{
return ref _pointer.Value;
@@ -166,12 +144,26 @@ namespace System
/// <summary>
/// The number of items in the span.
/// </summary>
- public int Length => _length;
+ public int Length
+ {
+ [NonVersionable]
+ get
+ {
+ return _length;
+ }
+ }
/// <summary>
/// Returns true if Length is 0.
/// </summary>
- public bool IsEmpty => _length == 0;
+ public bool IsEmpty
+ {
+ [NonVersionable]
+ get
+ {
+ return _length == 0;
+ }
+ }
/// <summary>
/// Returns a reference to specified element of the Span.
@@ -194,6 +186,7 @@ namespace System
[Intrinsic]
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
+ [NonVersionable]
get
{
if ((uint)index >= (uint)_length)
diff --git a/src/mscorlib/shared/System/StackOverflowException.cs b/src/mscorlib/shared/System/StackOverflowException.cs
index fb0e88246c..8b21eb769a 100644
--- a/src/mscorlib/shared/System/StackOverflowException.cs
+++ b/src/mscorlib/shared/System/StackOverflowException.cs
@@ -20,19 +20,19 @@ namespace System
public StackOverflowException()
: base(SR.Arg_StackOverflowException)
{
- HResult = __HResults.COR_E_STACKOVERFLOW;
+ HResult = HResults.COR_E_STACKOVERFLOW;
}
public StackOverflowException(String message)
: base(message)
{
- HResult = __HResults.COR_E_STACKOVERFLOW;
+ HResult = HResults.COR_E_STACKOVERFLOW;
}
public StackOverflowException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_STACKOVERFLOW;
+ HResult = HResults.COR_E_STACKOVERFLOW;
}
}
}
diff --git a/src/mscorlib/shared/System/StringSpanHelpers.cs b/src/mscorlib/shared/System/StringSpanHelpers.cs
new file mode 100644
index 0000000000..bdfd965641
--- /dev/null
+++ b/src/mscorlib/shared/System/StringSpanHelpers.cs
@@ -0,0 +1,93 @@
+// 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.Globalization;
+
+namespace System
+{
+ /// <summary>Helpers for string-like operations on spans of chars.</summary>
+ internal static class StringSpanHelpers
+ {
+ // TODO https://github.com/dotnet/corefx/issues/21395: Provide public, efficient implementations
+
+ public static bool Equals(this ReadOnlySpan<char> left, ReadOnlySpan<char> right, StringComparison comparisonType) =>
+ comparisonType == StringComparison.Ordinal ? Equals(left, right) :
+ comparisonType == StringComparison.OrdinalIgnoreCase ? EqualsOrdinalIgnoreCase(left, right) :
+ throw new ArgumentOutOfRangeException(nameof(comparisonType));
+
+ public static bool Equals(this ReadOnlySpan<char> left, string right) =>
+ Equals(left, right.AsReadOnlySpan());
+
+ public static bool Equals(this ReadOnlySpan<char> left, ReadOnlySpan<char> right)
+ {
+ if (left.Length != right.Length)
+ {
+ return false;
+ }
+
+ for (int i = 0; i < left.Length; i++)
+ {
+ if (left[i] != right[i])
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ private static bool EqualsOrdinalIgnoreCase(this ReadOnlySpan<char> left, ReadOnlySpan<char> right)
+ {
+ if (left.Length != right.Length)
+ {
+ return false;
+ }
+
+ for (int i = 0; i < left.Length; i++)
+ {
+ char x = left[i], y = right[i];
+ if (x != y &&
+ TextInfo.ToUpperAsciiInvariant(x) != TextInfo.ToUpperAsciiInvariant(y))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public static ReadOnlySpan<char> Trim(this ReadOnlySpan<char> source)
+ {
+ int startIndex = 0, endIndex = source.Length - 1;
+
+ while (startIndex <= endIndex && char.IsWhiteSpace(source[startIndex]))
+ {
+ startIndex++;
+ }
+
+ while (endIndex >= startIndex && char.IsWhiteSpace(source[endIndex]))
+ {
+ endIndex--;
+ }
+
+ return source.Slice(startIndex, endIndex - startIndex + 1);
+ }
+
+ public static int IndexOf(this ReadOnlySpan<char> source, char value) =>
+ IndexOf(source, value, 0);
+
+ public static int IndexOf(this ReadOnlySpan<char> source, char value, int startIndex)
+ {
+ for (int i = startIndex; i < source.Length; i++)
+ {
+ if (source[i] == value)
+ {
+ return i;
+ }
+ }
+
+ return -1;
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/SystemException.cs b/src/mscorlib/shared/System/SystemException.cs
index d5bcde7efc..64a4b9ca31 100644
--- a/src/mscorlib/shared/System/SystemException.cs
+++ b/src/mscorlib/shared/System/SystemException.cs
@@ -11,19 +11,19 @@ namespace System
public SystemException()
: base(SR.Arg_SystemException)
{
- HResult = __HResults.COR_E_SYSTEM;
+ HResult = HResults.COR_E_SYSTEM;
}
public SystemException(String message)
: base(message)
{
- HResult = __HResults.COR_E_SYSTEM;
+ HResult = HResults.COR_E_SYSTEM;
}
public SystemException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_SYSTEM;
+ HResult = HResults.COR_E_SYSTEM;
}
protected SystemException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/Text/Decoder.cs b/src/mscorlib/shared/System/Text/Decoder.cs
index f109f3db49..82d33d518c 100644
--- a/src/mscorlib/shared/System/Text/Decoder.cs
+++ b/src/mscorlib/shared/System/Text/Decoder.cs
@@ -134,6 +134,14 @@ namespace System.Text
return GetCharCount(arrbyte, 0, count);
}
+ public virtual unsafe int GetCharCount(ReadOnlySpan<byte> bytes, bool flush)
+ {
+ fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference())
+ {
+ return GetCharCount(bytesPtr, bytes.Length, flush);
+ }
+ }
+
// Decodes a range of bytes in a byte array into a range of characters
// in a character array. The method decodes byteCount bytes from
// bytes starting at index byteIndex, storing the resulting
@@ -220,6 +228,15 @@ namespace System.Text
return charCount;
}
+ public virtual unsafe int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool flush)
+ {
+ fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference())
+ fixed (char* charsPtr = &chars.DangerousGetPinnableReference())
+ {
+ return GetChars(bytesPtr, bytes.Length, charsPtr, chars.Length, flush);
+ }
+ }
+
// This method is used when the output buffer might not be large enough.
// It will decode until it runs out of bytes, and then it will return
// true if it the entire input was converted. In either case it
@@ -326,5 +343,14 @@ namespace System.Text
// Oops, we didn't have anything, we'll have to throw an overflow
throw new ArgumentException(SR.Argument_ConversionOverflow);
}
+
+ public virtual unsafe void Convert(ReadOnlySpan<byte> bytes, Span<char> chars, bool flush, out int bytesUsed, out int charsUsed, out bool completed)
+ {
+ fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference())
+ fixed (char* charsPtr = &chars.DangerousGetPinnableReference())
+ {
+ Convert(bytesPtr, bytes.Length, charsPtr, chars.Length, flush, out bytesUsed, out charsUsed, out completed);
+ }
+ }
}
}
diff --git a/src/mscorlib/shared/System/Text/DecoderExceptionFallback.cs b/src/mscorlib/shared/System/Text/DecoderExceptionFallback.cs
index b465aa68ef..26d604a919 100644
--- a/src/mscorlib/shared/System/Text/DecoderExceptionFallback.cs
+++ b/src/mscorlib/shared/System/Text/DecoderExceptionFallback.cs
@@ -106,19 +106,19 @@ namespace System.Text
public DecoderFallbackException()
: base(SR.Arg_ArgumentException)
{
- HResult = __HResults.COR_E_ARGUMENT;
+ HResult = HResults.COR_E_ARGUMENT;
}
public DecoderFallbackException(String message)
: base(message)
{
- HResult = __HResults.COR_E_ARGUMENT;
+ HResult = HResults.COR_E_ARGUMENT;
}
public DecoderFallbackException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_ARGUMENT;
+ HResult = HResults.COR_E_ARGUMENT;
}
public DecoderFallbackException(String message, byte[] bytesUnknown, int index)
diff --git a/src/mscorlib/shared/System/Text/Encoder.cs b/src/mscorlib/shared/System/Text/Encoder.cs
index b0602f3cce..79a633f1ff 100644
--- a/src/mscorlib/shared/System/Text/Encoder.cs
+++ b/src/mscorlib/shared/System/Text/Encoder.cs
@@ -132,6 +132,14 @@ namespace System.Text
return GetByteCount(arrChar, 0, count, flush);
}
+ public virtual unsafe int GetByteCount(ReadOnlySpan<char> chars, bool flush)
+ {
+ fixed (char* charsPtr = &chars.DangerousGetPinnableReference())
+ {
+ return GetByteCount(charsPtr, chars.Length, flush);
+ }
+ }
+
// Encodes a range of characters in a character array into a range of bytes
// in a byte array. The method encodes charCount characters from
// chars starting at index charIndex, storing the resulting
@@ -214,6 +222,15 @@ namespace System.Text
return byteCount;
}
+ public virtual unsafe int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes, bool flush)
+ {
+ fixed (char* charsPtr = &chars.DangerousGetPinnableReference())
+ fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference())
+ {
+ return GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length, flush);
+ }
+ }
+
// This method is used to avoid running out of output buffer space.
// It will encode until it runs out of chars, and then it will return
// true if it the entire input was converted. In either case it
@@ -320,6 +337,15 @@ namespace System.Text
// Oops, we didn't have anything, we'll have to throw an overflow
throw new ArgumentException(SR.Argument_ConversionOverflow);
}
+
+ public virtual unsafe void Convert(ReadOnlySpan<char> chars, Span<byte> bytes, bool flush, out int charsUsed, out int bytesUsed, out bool completed)
+ {
+ fixed (char* charsPtr = &chars.DangerousGetPinnableReference())
+ fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference())
+ {
+ Convert(charsPtr, chars.Length, bytesPtr, bytes.Length, flush, out charsUsed, out bytesUsed, out completed);
+ }
+ }
}
}
diff --git a/src/mscorlib/shared/System/Text/EncoderExceptionFallback.cs b/src/mscorlib/shared/System/Text/EncoderExceptionFallback.cs
index 98eff25b94..71426e5f31 100644
--- a/src/mscorlib/shared/System/Text/EncoderExceptionFallback.cs
+++ b/src/mscorlib/shared/System/Text/EncoderExceptionFallback.cs
@@ -108,19 +108,19 @@ namespace System.Text
public EncoderFallbackException()
: base(SR.Arg_ArgumentException)
{
- HResult = __HResults.COR_E_ARGUMENT;
+ HResult = HResults.COR_E_ARGUMENT;
}
public EncoderFallbackException(String message)
: base(message)
{
- HResult = __HResults.COR_E_ARGUMENT;
+ HResult = HResults.COR_E_ARGUMENT;
}
public EncoderFallbackException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_ARGUMENT;
+ HResult = HResults.COR_E_ARGUMENT;
}
internal EncoderFallbackException(
diff --git a/src/mscorlib/shared/System/Text/Encoding.cs b/src/mscorlib/shared/System/Text/Encoding.cs
index 4f23d2a4a7..bf8cb03db2 100644
--- a/src/mscorlib/shared/System/Text/Encoding.cs
+++ b/src/mscorlib/shared/System/Text/Encoding.cs
@@ -382,6 +382,8 @@ namespace System.Text
return Array.Empty<byte>();
}
+ public virtual ReadOnlySpan<byte> Preamble => GetPreamble();
+
private void GetDataItem()
{
if (_dataItem == null)
@@ -733,6 +735,14 @@ namespace System.Text
return GetByteCount(arrChar, 0, count);
}
+ public virtual unsafe int GetByteCount(ReadOnlySpan<char> chars)
+ {
+ fixed (char* charsPtr = &chars.DangerousGetPinnableReference())
+ {
+ return GetByteCount(charsPtr, chars.Length);
+ }
+ }
+
// For NLS Encodings, workhorse takes an encoder (may be null)
// Always validate parameters before calling internal version, which will only assert.
internal virtual unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder)
@@ -916,6 +926,15 @@ namespace System.Text
return byteCount;
}
+ public virtual unsafe int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes)
+ {
+ fixed (char* charsPtr = &chars.DangerousGetPinnableReference())
+ fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference())
+ {
+ return GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length);
+ }
+ }
+
// Returns the number of characters produced by decoding the given byte
// array.
//
@@ -962,6 +981,14 @@ namespace System.Text
return GetCharCount(arrbyte, 0, count);
}
+ public virtual unsafe int GetCharCount(ReadOnlySpan<byte> bytes)
+ {
+ fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference())
+ {
+ return GetCharCount(bytesPtr, bytes.Length);
+ }
+ }
+
// This is our internal workhorse
// Always validate parameters before calling internal version, which will only assert.
internal virtual unsafe int GetCharCount(byte* bytes, int count, DecoderNLS decoder)
@@ -1070,6 +1097,14 @@ namespace System.Text
return charCount;
}
+ public virtual unsafe int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars)
+ {
+ fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference())
+ fixed (char* charsPtr = &chars.DangerousGetPinnableReference())
+ {
+ return GetChars(bytesPtr, bytes.Length, charsPtr, chars.Length);
+ }
+ }
// This is our internal workhorse
// Always validate parameters before calling internal version, which will only assert.
@@ -1093,6 +1128,15 @@ namespace System.Text
return String.CreateStringFromEncoding(bytes, byteCount, this);
}
+ public unsafe string GetString(ReadOnlySpan<byte> bytes)
+ {
+ fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference())
+ {
+ return GetString(bytesPtr, bytes.Length);
+ }
+ }
+
+
// Returns the code page identifier of this encoding. The returned value is
// an integer between 0 and 65535 if the encoding has a code page
// identifier, or -1 if the encoding does not represent a code page.
diff --git a/src/mscorlib/shared/System/Text/Normalization.cs b/src/mscorlib/shared/System/Text/Normalization.cs
index dc8bc2af71..976756251a 100644
--- a/src/mscorlib/shared/System/Text/Normalization.cs
+++ b/src/mscorlib/shared/System/Text/Normalization.cs
@@ -4,7 +4,6 @@
namespace System.Text
{
- // This is the enumeration for Normalization Forms
public enum NormalizationForm
{
FormC = 1,
@@ -12,18 +11,4 @@ namespace System.Text
FormKC = 5,
FormKD = 6
}
-
- internal enum ExtendedNormalizationForms
- {
- FormC = 1,
- FormD = 2,
- FormKC = 5,
- FormKD = 6,
- FormIdna = 0xd,
- FormCDisallowUnassigned = 0x101,
- FormDDisallowUnassigned = 0x102,
- FormKCDisallowUnassigned = 0x105,
- FormKDDisallowUnassigned = 0x106,
- FormIdnaDisallowUnassigned = 0x10d
- }
}
diff --git a/src/mscorlib/shared/System/Text/StringBuilder.cs b/src/mscorlib/shared/System/Text/StringBuilder.cs
index 34533a92ca..a73e6757d4 100644
--- a/src/mscorlib/shared/System/Text/StringBuilder.cs
+++ b/src/mscorlib/shared/System/Text/StringBuilder.cs
@@ -822,11 +822,6 @@ namespace System.Text
throw new ArgumentNullException(nameof(destination));
}
- if (count < 0)
- {
- throw new ArgumentOutOfRangeException(nameof(count), SR.Arg_NegativeArgCount);
- }
-
if (destinationIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.Format(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(destinationIndex)));
@@ -836,6 +831,17 @@ namespace System.Text
{
throw new ArgumentException(SR.ArgumentOutOfRange_OffsetOut);
}
+ Contract.EndContractBlock();
+
+ CopyTo(sourceIndex, new Span<char>(destination).Slice(destinationIndex), count);
+ }
+
+ public void CopyTo(int sourceIndex, Span<char> destination, int count)
+ {
+ if (count < 0)
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), SR.Arg_NegativeArgCount);
+ }
if ((uint)sourceIndex > (uint)Length)
{
@@ -852,7 +858,7 @@ namespace System.Text
StringBuilder chunk = this;
int sourceEndIndex = sourceIndex + count;
- int curDestIndex = destinationIndex + count;
+ int curDestIndex = count;
while (count > 0)
{
int chunkEndIndex = sourceEndIndex - chunk.m_ChunkOffset;
@@ -1033,6 +1039,21 @@ namespace System.Text
return this;
}
+ public StringBuilder Append(ReadOnlySpan<char> value)
+ {
+ if (value.Length > 0)
+ {
+ unsafe
+ {
+ fixed (char* valueChars = &value.DangerousGetPinnableReference())
+ {
+ Append(valueChars, value.Length);
+ }
+ }
+ }
+ return this;
+ }
+
#region AppendJoin
public unsafe StringBuilder AppendJoin(string separator, params object[] values)
@@ -1263,6 +1284,27 @@ namespace System.Text
public StringBuilder Insert(int index, Object value) => (value == null) ? this : Insert(index, value.ToString(), 1);
+ public StringBuilder Insert(int index, ReadOnlySpan<char> value)
+ {
+ Contract.Ensures(Contract.Result<StringBuilder>() != null);
+ Contract.EndContractBlock();
+
+ if ((uint)index > (uint)Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_Index);
+ }
+
+ if (value.Length > 0)
+ {
+ unsafe
+ {
+ fixed (char* sourcePtr = &value.DangerousGetPinnableReference())
+ Insert(index, sourcePtr, value.Length);
+ }
+ }
+ return this;
+ }
+
public StringBuilder AppendFormat(String format, Object arg0) => AppendFormatHelper(null, format, new ParamsArray(arg0));
public StringBuilder AppendFormat(String format, Object arg0, Object arg1) => AppendFormatHelper(null, format, new ParamsArray(arg0, arg1));
@@ -1884,7 +1926,7 @@ namespace System.Text
Debug.Assert(gapEnd <= sourceChunk.m_ChunkLength, "gap too big");
if (delta != 0) // can skip the sliding of gaps if source an target string are the same size.
{
- // Copy the gap data between the current replacement and the the next replacement
+ // Copy the gap data between the current replacement and the next replacement
fixed (char* sourcePtr = &sourceChunk.m_ChunkChars[gapStart])
ReplaceInPlaceAtChunk(ref targetChunk, ref targetIndexInChunk, sourcePtr, gapEnd - gapStart);
}
@@ -1944,7 +1986,7 @@ namespace System.Text
/// </summary>
/// <param name="chunk">
/// The chunk in which to start replacing characters.
- /// Receieves the chunk in which character replacement ends.
+ /// Receives the chunk in which character replacement ends.
/// </param>
/// <param name="indexInChunk">
/// The index in <paramref name="chunk"/> to start replacing characters at.
@@ -2001,22 +2043,23 @@ namespace System.Text
}
}
- private static void ThreadSafeCopy(char[] source, int sourceIndex, char[] destination, int destinationIndex, int count)
+ private static unsafe void ThreadSafeCopy(char[] source, int sourceIndex, Span<char> destination, int destinationIndex, int count)
{
if (count > 0)
{
- if ((uint)sourceIndex <= (uint)source.Length && (sourceIndex + count) <= source.Length)
+ if ((uint)sourceIndex > (uint)source.Length || count > source.Length - sourceIndex)
{
- unsafe
- {
- fixed (char* sourcePtr = &source[sourceIndex])
- ThreadSafeCopy(sourcePtr, destination, destinationIndex, count);
- }
+ throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index);
}
- else
+
+ if ((uint)destinationIndex > (uint)destination.Length || count > destination.Length - destinationIndex)
{
- throw new ArgumentOutOfRangeException(nameof(sourceIndex), SR.ArgumentOutOfRange_Index);
+ throw new ArgumentOutOfRangeException(nameof(destinationIndex), SR.ArgumentOutOfRange_Index);
}
+
+ fixed (char* sourcePtr = &source[sourceIndex])
+ fixed (char* destinationPtr = &destination.DangerousGetPinnableReference())
+ string.wstrcpy(destinationPtr + destinationIndex, sourcePtr, count);
}
}
diff --git a/src/mscorlib/shared/System/Text/UTF32Encoding.cs b/src/mscorlib/shared/System/Text/UTF32Encoding.cs
index 10161d193e..260518e21c 100644
--- a/src/mscorlib/shared/System/Text/UTF32Encoding.cs
+++ b/src/mscorlib/shared/System/Text/UTF32Encoding.cs
@@ -39,6 +39,9 @@ namespace System.Text
internal static readonly UTF32Encoding s_default = new UTF32Encoding(bigEndian: false, byteOrderMark: true);
internal static readonly UTF32Encoding s_bigEndianDefault = new UTF32Encoding(bigEndian: true, byteOrderMark: true);
+ private static readonly byte[] s_bigEndianPreamble = new byte[4] { 0x00, 0x00, 0xFE, 0xFF };
+ private static readonly byte[] s_littleEndianPreamble = new byte[4] { 0xFF, 0xFE, 0x00, 0x00 };
+
private bool _emitUTF32ByteOrderMark = false;
private bool _isThrowException = false;
private bool _bigEndian = false;
@@ -1177,6 +1180,10 @@ namespace System.Text
return Array.Empty<byte>();
}
+ public override ReadOnlySpan<byte> Preamble =>
+ GetType() != typeof(UTF32Encoding) ? GetPreamble() : // in case a derived UTF32Encoding overrode GetPreamble
+ _emitUTF32ByteOrderMark ? (_bigEndian ? s_bigEndianPreamble : s_littleEndianPreamble) :
+ Array.Empty<byte>();
public override bool Equals(Object value)
{
diff --git a/src/mscorlib/shared/System/Text/UTF8Encoding.cs b/src/mscorlib/shared/System/Text/UTF8Encoding.cs
index 02b18935e4..974bf75650 100644
--- a/src/mscorlib/shared/System/Text/UTF8Encoding.cs
+++ b/src/mscorlib/shared/System/Text/UTF8Encoding.cs
@@ -54,15 +54,19 @@ namespace System.Text
internal sealed class UTF8EncodingSealed : UTF8Encoding
{
public UTF8EncodingSealed(bool encoderShouldEmitUTF8Identifier) : base(encoderShouldEmitUTF8Identifier) { }
+
+ public override ReadOnlySpan<byte> Preamble => _emitUTF8Identifier ? s_preamble : Array.Empty<byte>();
}
// Used by Encoding.UTF8 for lazy initialization
// The initialization code will not be run until a static member of the class is referenced
internal static readonly UTF8EncodingSealed s_default = new UTF8EncodingSealed(encoderShouldEmitUTF8Identifier: true);
+ internal static readonly byte[] s_preamble = new byte[3] { 0xEF, 0xBB, 0xBF };
+
// Yes, the idea of emitting U+FEFF as a UTF-8 identifier has made it into
// the standard.
- private bool _emitUTF8Identifier = false;
+ internal readonly bool _emitUTF8Identifier = false;
private bool _isThrowException = false;
@@ -2497,6 +2501,10 @@ namespace System.Text
return Array.Empty<byte>();
}
+ public override ReadOnlySpan<byte> Preamble =>
+ GetType() != typeof(UTF8Encoding) ? GetPreamble() : // in case a derived UTF8Encoding overrode GetPreamble
+ _emitUTF8Identifier ? s_preamble :
+ Array.Empty<byte>();
public override bool Equals(Object value)
{
diff --git a/src/mscorlib/shared/System/Text/UnicodeEncoding.cs b/src/mscorlib/shared/System/Text/UnicodeEncoding.cs
index 8e44317ce2..78355299c1 100644
--- a/src/mscorlib/shared/System/Text/UnicodeEncoding.cs
+++ b/src/mscorlib/shared/System/Text/UnicodeEncoding.cs
@@ -20,6 +20,9 @@ namespace System.Text
internal static readonly UnicodeEncoding s_bigEndianDefault = new UnicodeEncoding(bigEndian: true, byteOrderMark: true);
internal static readonly UnicodeEncoding s_littleEndianDefault = new UnicodeEncoding(bigEndian: false, byteOrderMark: true);
+ private static readonly byte[] s_bigEndianPreamble = new byte[2] { 0xfe, 0xff };
+ private static readonly byte[] s_littleEndianPreamble = new byte[2] { 0xff, 0xfe };
+
internal bool isThrowException = false;
internal bool bigEndian = false;
@@ -1898,6 +1901,10 @@ namespace System.Text
return Array.Empty<Byte>();
}
+ public override ReadOnlySpan<byte> Preamble =>
+ GetType() != typeof(UnicodeEncoding) ? GetPreamble() : // in case a derived UnicodeEncoding overrode GetPreamble
+ byteOrderMark ? (bigEndian ? s_bigEndianPreamble : s_littleEndianPreamble) :
+ Array.Empty<byte>();
public override int GetMaxByteCount(int charCount)
{
diff --git a/src/mscorlib/shared/System/Threading/AbandonedMutexException.cs b/src/mscorlib/shared/System/Threading/AbandonedMutexException.cs
index 15bc5a7341..c43148d22a 100644
--- a/src/mscorlib/shared/System/Threading/AbandonedMutexException.cs
+++ b/src/mscorlib/shared/System/Threading/AbandonedMutexException.cs
@@ -22,39 +22,39 @@ namespace System.Threading
public AbandonedMutexException()
: base(SR.Threading_AbandonedMutexException)
{
- HResult = __HResults.COR_E_ABANDONEDMUTEX;
+ HResult = HResults.COR_E_ABANDONEDMUTEX;
}
public AbandonedMutexException(String message)
: base(message)
{
- HResult = __HResults.COR_E_ABANDONEDMUTEX;
+ HResult = HResults.COR_E_ABANDONEDMUTEX;
}
public AbandonedMutexException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_ABANDONEDMUTEX;
+ HResult = HResults.COR_E_ABANDONEDMUTEX;
}
public AbandonedMutexException(int location, WaitHandle handle)
: base(SR.Threading_AbandonedMutexException)
{
- HResult = __HResults.COR_E_ABANDONEDMUTEX;
+ HResult = HResults.COR_E_ABANDONEDMUTEX;
SetupException(location, handle);
}
public AbandonedMutexException(String message, int location, WaitHandle handle)
: base(message)
{
- HResult = __HResults.COR_E_ABANDONEDMUTEX;
+ HResult = HResults.COR_E_ABANDONEDMUTEX;
SetupException(location, handle);
}
public AbandonedMutexException(String message, Exception inner, int location, WaitHandle handle)
: base(message, inner)
{
- HResult = __HResults.COR_E_ABANDONEDMUTEX;
+ HResult = HResults.COR_E_ABANDONEDMUTEX;
SetupException(location, handle);
}
diff --git a/src/mscorlib/shared/System/Threading/DeferredDisposableLifetime.cs b/src/mscorlib/shared/System/Threading/DeferredDisposableLifetime.cs
index 89380fee60..e2b1eb983b 100644
--- a/src/mscorlib/shared/System/Threading/DeferredDisposableLifetime.cs
+++ b/src/mscorlib/shared/System/Threading/DeferredDisposableLifetime.cs
@@ -18,7 +18,7 @@ namespace System.Threading
/// Indicates whether the object has been disposed.
/// </param>
/// <remarks>
- /// If the refount reaches zero before the object is disposed, this method will be called with
+ /// If the refcount reaches zero before the object is disposed, this method will be called with
/// <paramref name="disposed"/> set to false. If the object is then disposed, this method will be
/// called again, with <paramref name="disposed"/> set to true. If the refcount reaches zero
/// after the object has already been disposed, this will be called a single time, with
diff --git a/src/mscorlib/shared/System/Threading/LazyInitializer.cs b/src/mscorlib/shared/System/Threading/LazyInitializer.cs
index b03d1db302..f422ab9172 100644
--- a/src/mscorlib/shared/System/Threading/LazyInitializer.cs
+++ b/src/mscorlib/shared/System/Threading/LazyInitializer.cs
@@ -25,7 +25,7 @@ namespace System.Threading
/// Initializes a target reference type with the type's default constructor if the target has not
/// already been initialized.
/// </summary>
- /// <typeparam name="T">The refence type of the reference to be initialized.</typeparam>
+ /// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
/// <param name="target">A reference of type <typeparamref name="T"/> to initialize if it has not
/// already been initialized.</param>
/// <returns>The initialized reference of type <typeparamref name="T"/>.</returns>
diff --git a/src/mscorlib/shared/System/Threading/ReaderWriterLockSlim.cs b/src/mscorlib/shared/System/Threading/ReaderWriterLockSlim.cs
index 98517ad85f..1b2147e6e1 100644
--- a/src/mscorlib/shared/System/Threading/ReaderWriterLockSlim.cs
+++ b/src/mscorlib/shared/System/Threading/ReaderWriterLockSlim.cs
@@ -4,7 +4,6 @@
using Internal.Runtime.Augments;
using System.Diagnostics; // for TraceInformation
-using System.Threading;
using System.Runtime.CompilerServices;
namespace System.Threading
@@ -54,8 +53,10 @@ namespace System.Threading
/// </summary>
public class ReaderWriterLockSlim : IDisposable
{
+ private static readonly int ProcessorCount = Environment.ProcessorCount;
+
//Specifying if locked can be reacquired recursively.
- private bool _fIsReentrant;
+ private readonly bool _fIsReentrant;
// Lock specification for myLock: This lock protects exactly the local fields associated with this
// instance of ReaderWriterLockSlim. It does NOT protect the memory associated with
@@ -74,8 +75,7 @@ namespace System.Threading
private uint _numWriteUpgradeWaiters; // maximum number of threads that can be doing a WaitOne on the upgradeEvent (at most 1).
private uint _numUpgradeWaiters;
- //Variable used for quick check when there are no waiters.
- private bool _fNoWaiters;
+ private WaiterStates _waiterStates;
private int _upgradeLockOwnerId;
private int _writeLockOwnerId;
@@ -146,10 +146,37 @@ namespace System.Threading
_fIsReentrant = true;
}
InitializeThreadCounts();
- _fNoWaiters = true;
+ _waiterStates = WaiterStates.NoWaiters;
_lockID = Interlocked.Increment(ref s_nextLockID);
}
+ private bool HasNoWaiters
+ {
+ get
+ {
+#if DEBUG
+ Debug.Assert(MyLockHeld);
+#endif
+
+ return (_waiterStates & WaiterStates.NoWaiters) != WaiterStates.None;
+ }
+ set
+ {
+#if DEBUG
+ Debug.Assert(MyLockHeld);
+#endif
+
+ if (value)
+ {
+ _waiterStates |= WaiterStates.NoWaiters;
+ }
+ else
+ {
+ _waiterStates &= ~WaiterStates.NoWaiters;
+ }
+ }
+ }
+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static bool IsRWEntryEmpty(ReaderWriterCount rwc)
{
@@ -352,8 +379,7 @@ namespace System.Threading
}
bool retVal = true;
-
- int spincount = 0;
+ int spinCount = 0;
for (; ;)
{
@@ -368,13 +394,17 @@ namespace System.Threading
break;
}
- if (spincount < MaxSpinCount)
+ if (timeout.IsExpired)
{
ExitMyLock();
- if (timeout.IsExpired)
- return false;
- spincount++;
- SpinWait(spincount);
+ return false;
+ }
+
+ if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyRead())
+ {
+ ExitMyLock();
+ spinCount++;
+ SpinWait(spinCount);
EnterMyLock();
//The per-thread structure may have been recycled as the lock is acquired (due to message pumping), load again.
if (IsRwHashEntryChanged(lrwc))
@@ -391,7 +421,13 @@ namespace System.Threading
continue; // since we left the lock, start over.
}
- retVal = WaitOnEvent(_readEvent, ref _numReadWaiters, timeout, isWriteWaiter: false);
+ retVal =
+ WaitOnEvent(
+ _readEvent,
+ ref _numReadWaiters,
+ timeout,
+ isWriteWaiter: false,
+ waiterSignaledState: WaiterStates.None);
if (!retVal)
{
return false;
@@ -480,8 +516,8 @@ namespace System.Threading
}
}
- int spincount = 0;
bool retVal = true;
+ int spinCount = 0;
for (; ;)
{
@@ -528,13 +564,17 @@ namespace System.Threading
}
}
- if (spincount < MaxSpinCount)
+ if (timeout.IsExpired)
{
ExitMyLock();
- if (timeout.IsExpired)
- return false;
- spincount++;
- SpinWait(spincount);
+ return false;
+ }
+
+ if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyWrite(upgradingToWrite))
+ {
+ ExitMyLock();
+ spinCount++;
+ SpinWait(spinCount);
EnterMyLock();
continue;
}
@@ -549,7 +589,13 @@ namespace System.Threading
Debug.Assert(_numWriteUpgradeWaiters == 0, "There can be at most one thread with the upgrade lock held.");
- retVal = WaitOnEvent(_waitUpgradeEvent, ref _numWriteUpgradeWaiters, timeout, isWriteWaiter: true);
+ retVal =
+ WaitOnEvent(
+ _waitUpgradeEvent,
+ ref _numWriteUpgradeWaiters,
+ timeout,
+ isWriteWaiter: true,
+ waiterSignaledState: WaiterStates.None);
//The lock is not held in case of failure.
if (!retVal)
@@ -564,7 +610,13 @@ namespace System.Threading
continue; // since we left the lock, start over.
}
- retVal = WaitOnEvent(_writeEvent, ref _numWriteWaiters, timeout, isWriteWaiter: true);
+ retVal =
+ WaitOnEvent(
+ _writeEvent,
+ ref _numWriteWaiters,
+ timeout,
+ isWriteWaiter: true,
+ waiterSignaledState: WaiterStates.WriteWaiterSignaled);
//The lock is not held in case of failure.
if (!retVal)
return false;
@@ -671,8 +723,7 @@ namespace System.Threading
}
bool retVal = true;
-
- int spincount = 0;
+ int spinCount = 0;
for (; ;)
{
@@ -686,13 +737,17 @@ namespace System.Threading
break;
}
- if (spincount < MaxSpinCount)
+ if (timeout.IsExpired)
{
ExitMyLock();
- if (timeout.IsExpired)
- return false;
- spincount++;
- SpinWait(spincount);
+ return false;
+ }
+
+ if (spinCount < MaxSpinCount && ShouldSpinForEnterAnyRead())
+ {
+ ExitMyLock();
+ spinCount++;
+ SpinWait(spinCount);
EnterMyLock();
continue;
}
@@ -705,7 +760,13 @@ namespace System.Threading
}
//Only one thread with the upgrade lock held can proceed.
- retVal = WaitOnEvent(_upgradeEvent, ref _numUpgradeWaiters, timeout, isWriteWaiter: false);
+ retVal =
+ WaitOnEvent(
+ _upgradeEvent,
+ ref _numUpgradeWaiters,
+ timeout,
+ isWriteWaiter: false,
+ waiterSignaledState: WaiterStates.UpgradeableReadWaiterSignaled);
if (!retVal)
return false;
}
@@ -890,14 +951,20 @@ namespace System.Threading
EventWaitHandle waitEvent,
ref uint numWaiters,
TimeoutTracker timeout,
- bool isWriteWaiter)
+ bool isWriteWaiter,
+ WaiterStates waiterSignaledState)
{
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
+ Debug.Assert(
+ waiterSignaledState == WaiterStates.None ||
+ waiterSignaledState == WaiterStates.WriteWaiterSignaled ||
+ waiterSignaledState == WaiterStates.UpgradeableReadWaiterSignaled);
+
waitEvent.Reset();
numWaiters++;
- _fNoWaiters = false;
+ HasNoWaiters = false;
//Setting these bits will prevent new readers from getting in.
if (_numWriteWaiters == 1)
@@ -917,8 +984,19 @@ namespace System.Threading
EnterMyLock();
--numWaiters;
+ if (waitSuccessful && waiterSignaledState != WaiterStates.None)
+ {
+ // Indicate that a signaled waiter of this type has woken. Since non-read waiters are signaled to wake one
+ // at a time, we avoid waking up more than one waiter of that type upon successive enter/exit loops until
+ // the signaled thread actually wakes up. For example, if there are multiple write waiters and one thread is
+ // repeatedly entering and exiting a write lock, every exit would otherwise signal a different write waiter
+ // to wake up unnecessarily when only one woken waiter may actually succeed in entering the write lock.
+ Debug.Assert((_waiterStates & waiterSignaledState) != WaiterStates.None);
+ _waiterStates &= ~waiterSignaledState;
+ }
+
if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0)
- _fNoWaiters = true;
+ HasNoWaiters = true;
if (_numWriteWaiters == 0)
ClearWritersWaiting();
@@ -948,7 +1026,7 @@ namespace System.Threading
#if DEBUG
Debug.Assert(MyLockHeld);
#endif
- if (_fNoWaiters)
+ if (HasNoWaiters)
{
ExitMyLock();
return;
@@ -984,8 +1062,20 @@ namespace System.Threading
}
else if (readercount == 0 && _numWriteWaiters > 0)
{
+ // Check if a waiter of the same type has already been signaled but hasn't woken yet. If so, avoid signaling
+ // and waking another waiter unnecessarily.
+ WaiterStates signaled = _waiterStates & WaiterStates.WriteWaiterSignaled;
+ if (signaled == WaiterStates.None)
+ {
+ _waiterStates |= WaiterStates.WriteWaiterSignaled;
+ }
+
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
- _writeEvent.Set(); // release one writer.
+
+ if (signaled == WaiterStates.None)
+ {
+ _writeEvent.Set(); // release one writer.
+ }
}
else
{
@@ -999,7 +1089,7 @@ namespace System.Threading
Debug.Assert(MyLockHeld);
#endif
- if (_numWriteWaiters != 0 || _numWriteUpgradeWaiters != 0 || _fNoWaiters)
+ if (_numWriteWaiters != 0 || _numWriteUpgradeWaiters != 0 || HasNoWaiters)
{
ExitMyLock();
return;
@@ -1009,6 +1099,19 @@ namespace System.Threading
bool setReadEvent = _numReadWaiters != 0;
bool setUpgradeEvent = _numUpgradeWaiters != 0 && _upgradeLockOwnerId == -1;
+ if (setUpgradeEvent)
+ {
+ // Check if a waiter of the same type has already been signaled but hasn't woken yet. If so, avoid signaling
+ // and waking another waiter unnecessarily.
+ if ((_waiterStates & WaiterStates.UpgradeableReadWaiterSignaled) == WaiterStates.None)
+ {
+ _waiterStates |= WaiterStates.UpgradeableReadWaiterSignaled;
+ }
+ else
+ {
+ setUpgradeEvent = false;
+ }
+ }
ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock)
@@ -1059,33 +1162,62 @@ namespace System.Threading
return _owners & READER_MASK;
}
+ private bool ShouldSpinForEnterAnyRead()
+ {
+ // If there is a write waiter or write upgrade waiter, the waiter would block a reader from acquiring the RW lock
+ // because the waiter takes precedence. In that case, the reader is not likely to make progress by spinning.
+ // Although another thread holding a write lock would prevent this thread from acquiring a read lock, it is by
+ // itself not a good enough reason to skip spinning.
+ return HasNoWaiters || (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0);
+ }
+
+ private bool ShouldSpinForEnterAnyWrite(bool isUpgradeToWrite)
+ {
+ // If there is a write upgrade waiter, the waiter would block a writer from acquiring the RW lock because the waiter
+ // holds a read lock. In that case, the writer is not likely to make progress by spinning. Regarding upgrading to a
+ // write lock, there is no type of waiter that would block the upgrade from happening. Although another thread
+ // holding a read or write lock would prevent this thread from acquiring the write lock, it is by itself not a good
+ // enough reason to skip spinning.
+ return isUpgradeToWrite || _numWriteUpgradeWaiters == 0;
+ }
+
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ private bool TryEnterMyLock()
+ {
+ return Interlocked.CompareExchange(ref _myLock, 1, 0) == 0;
+ }
+
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnterMyLock()
{
- if (Interlocked.CompareExchange(ref _myLock, 1, 0) != 0)
+ if (!TryEnterMyLock())
+ {
EnterMyLockSpin();
+ }
}
private void EnterMyLockSpin()
{
- int pc = Environment.ProcessorCount;
- for (int i = 0; ; i++)
+ int processorCount = ProcessorCount;
+ for (int spinIndex = 0; ; spinIndex++)
{
- if (i < LockSpinCount && pc > 1)
+ if (spinIndex < LockSpinCount && processorCount > 1)
{
- RuntimeThread.SpinWait(LockSpinCycles * (i + 1)); // Wait a few dozen instructions to let another processor release lock.
+ RuntimeThread.SpinWait(LockSpinCycles * (spinIndex + 1)); // Wait a few dozen instructions to let another processor release lock.
}
- else if (i < (LockSpinCount + LockSleep0Count))
+ else if (spinIndex < (LockSpinCount + LockSleep0Count))
{
- RuntimeThread.Sleep(0); // Give up my quantum.
+ RuntimeThread.Sleep(0); // Give up my quantum.
}
else
{
- RuntimeThread.Sleep(1); // Give up my quantum.
+ RuntimeThread.Sleep(1); // Give up my quantum.
}
- if (_myLock == 0 && Interlocked.CompareExchange(ref _myLock, 1, 0) == 0)
+ if (_myLock == 0 && TryEnterMyLock())
+ {
return;
+ }
}
}
@@ -1099,12 +1231,12 @@ namespace System.Threading
private bool MyLockHeld { get { return _myLock != 0; } }
#endif
- private static void SpinWait(int SpinCount)
+ private static void SpinWait(int spinCount)
{
//Exponential back-off
- if ((SpinCount < 5) && (Environment.ProcessorCount > 1))
+ if ((spinCount < 5) && (ProcessorCount > 1))
{
- RuntimeThread.SpinWait(LockSpinCycles * SpinCount);
+ RuntimeThread.SpinWait(LockSpinCycles * spinCount);
}
else
{
@@ -1307,5 +1439,19 @@ namespace System.Threading
return (int)_numWriteWaiters;
}
}
+
+ [Flags]
+ private enum WaiterStates : byte
+ {
+ None = 0x0,
+
+ // Used for quick check when there are no waiters
+ NoWaiters = 0x1,
+
+ // Used to avoid signaling more than one waiter to wake up when only one can make progress, see WaitOnEvent
+ WriteWaiterSignaled = 0x2,
+ UpgradeableReadWaiterSignaled = 0x4
+ // Write upgrade waiters are excluded because there can only be one at any given time
+ }
}
}
diff --git a/src/mscorlib/shared/System/Threading/SpinWait.cs b/src/mscorlib/shared/System/Threading/SpinWait.cs
index d25d54f26f..414ad1852f 100644
--- a/src/mscorlib/shared/System/Threading/SpinWait.cs
+++ b/src/mscorlib/shared/System/Threading/SpinWait.cs
@@ -69,9 +69,26 @@ namespace System.Threading
// numbers may seem fairly arbitrary, but were derived with at least some
// thought in the design document. I fully expect they will need to change
// over time as we gain more experience with performance.
- internal const int YIELD_THRESHOLD = 10; // When to switch over to a true yield.
- internal const int SLEEP_0_EVERY_HOW_MANY_TIMES = 5; // After how many yields should we Sleep(0)?
- internal const int SLEEP_1_EVERY_HOW_MANY_TIMES = 20; // After how many yields should we Sleep(1)?
+ internal const int YieldThreshold = 10; // When to switch over to a true yield.
+ private const int Sleep0EveryHowManyYields = 5; // After how many yields should we Sleep(0)?
+ internal const int DefaultSleep1Threshold = 20; // After how many yields should we Sleep(1) frequently?
+
+ /// <summary>
+ /// A suggested number of spin iterations before doing a proper wait, such as waiting on an event that becomes signaled
+ /// when the resource becomes available.
+ /// </summary>
+ /// <remarks>
+ /// These numbers were arrived at by experimenting with different numbers in various cases that currently use it. It's
+ /// only a suggested value and typically works well when the proper wait is something like an event.
+ ///
+ /// Spinning less can lead to early waiting and more context switching, spinning more can decrease latency but may use
+ /// up some CPU time unnecessarily. Depends on the situation too, for instance SemaphoreSlim uses more iterations
+ /// because the waiting there is currently a lot more expensive (involves more spinning, taking a lock, etc.). It also
+ /// depends on the likelihood of the spin being successful and how long the wait would be but those are not accounted
+ /// for here.
+ /// </remarks>
+ internal static readonly int SpinCountforSpinBeforeWait = PlatformHelper.IsSingleProcessor ? 1 : 35;
+ internal const int Sleep1ThresholdForSpinBeforeWait = 40; // should be greater than SpinCountforSpinBeforeWait
// The number of times we've spun already.
private int _count;
@@ -81,7 +98,12 @@ namespace System.Threading
/// </summary>
public int Count
{
- get { return _count; }
+ get => _count;
+ internal set
+ {
+ Debug.Assert(value >= 0);
+ _count = value;
+ }
}
/// <summary>
@@ -94,10 +116,7 @@ namespace System.Threading
/// On a single-CPU machine, <see cref="SpinOnce"/> always yields the processor. On machines with
/// multiple CPUs, <see cref="SpinOnce"/> may yield after an unspecified number of calls.
/// </remarks>
- public bool NextSpinWillYield
- {
- get { return _count > YIELD_THRESHOLD || PlatformHelper.IsSingleProcessor; }
- }
+ public bool NextSpinWillYield => _count >= YieldThreshold || PlatformHelper.IsSingleProcessor;
/// <summary>
/// Performs a single spin.
@@ -108,7 +127,27 @@ namespace System.Threading
/// </remarks>
public void SpinOnce()
{
- if (NextSpinWillYield)
+ SpinOnce(DefaultSleep1Threshold);
+ }
+
+ internal void SpinOnce(int sleep1Threshold)
+ {
+ Debug.Assert(sleep1Threshold >= YieldThreshold || PlatformHelper.IsSingleProcessor); // so that NextSpinWillYield behaves as requested
+
+ // (_count - YieldThreshold) % 2 == 0: The purpose of this check is to interleave Thread.Yield/Sleep(0) with
+ // Thread.SpinWait. Otherwise, the following issues occur:
+ // - When there are no threads to switch to, Yield and Sleep(0) become no-op and it turns the spin loop into a
+ // busy-spin that may quickly reach the max spin count and cause the thread to enter a wait state, or may
+ // just busy-spin for longer than desired before a Sleep(1). Completing the spin loop too early can cause
+ // excessive context switcing if a wait follows, and entering the Sleep(1) stage too early can cause
+ // excessive delays.
+ // - If there are multiple threads doing Yield and Sleep(0) (typically from the same spin loop due to
+ // contention), they may switch between one another, delaying work that can make progress.
+ if ((
+ _count >= YieldThreshold &&
+ (_count >= sleep1Threshold || (_count - YieldThreshold) % 2 == 0)
+ ) ||
+ PlatformHelper.IsSingleProcessor)
{
//
// We must yield.
@@ -125,19 +164,21 @@ namespace System.Threading
// configured to use the (default) coarse-grained system timer.
//
- int yieldsSoFar = (_count >= YIELD_THRESHOLD ? _count - YIELD_THRESHOLD : _count);
-
- if ((yieldsSoFar % SLEEP_1_EVERY_HOW_MANY_TIMES) == (SLEEP_1_EVERY_HOW_MANY_TIMES - 1))
+ if (_count >= sleep1Threshold)
{
RuntimeThread.Sleep(1);
}
- else if ((yieldsSoFar % SLEEP_0_EVERY_HOW_MANY_TIMES) == (SLEEP_0_EVERY_HOW_MANY_TIMES - 1))
- {
- RuntimeThread.Sleep(0);
- }
else
{
- RuntimeThread.Yield();
+ int yieldsSoFar = _count >= YieldThreshold ? (_count - YieldThreshold) / 2 : _count;
+ if ((yieldsSoFar % Sleep0EveryHowManyYields) == (Sleep0EveryHowManyYields - 1))
+ {
+ RuntimeThread.Sleep(0);
+ }
+ else
+ {
+ RuntimeThread.Yield();
+ }
}
}
else
@@ -153,11 +194,24 @@ namespace System.Threading
// number of spins we are willing to tolerate to reduce delay to the caller,
// since we expect most callers will eventually block anyway.
//
- RuntimeThread.SpinWait(4 << _count);
+ // Also, cap the maximum spin count to a value such that many thousands of CPU cycles would not be wasted doing
+ // the equivalent of YieldProcessor(), as that that point SwitchToThread/Sleep(0) are more likely to be able to
+ // allow other useful work to run. Long YieldProcessor() loops can help to reduce contention, but Sleep(1) is
+ // usually better for that.
+ //
+ // RuntimeThread.OptimalMaxSpinWaitsPerSpinIteration:
+ // - See Thread::InitializeYieldProcessorNormalized(), which describes and calculates this value.
+ //
+ int n = RuntimeThread.OptimalMaxSpinWaitsPerSpinIteration;
+ if (_count <= 30 && (1 << _count) < n)
+ {
+ n = 1 << _count;
+ }
+ RuntimeThread.SpinWait(n);
}
// Finally, increment our spin counter.
- _count = (_count == int.MaxValue ? YIELD_THRESHOLD : _count + 1);
+ _count = (_count == int.MaxValue ? YieldThreshold : _count + 1);
}
/// <summary>
@@ -299,9 +353,7 @@ namespace System.Threading
/// <summary>
/// Gets whether the current machine has only a single processor.
/// </summary>
- internal static bool IsSingleProcessor
- {
- get { return ProcessorCount == 1; }
- }
+ /// <remarks>This typically does not change on a machine, so it's checked only once.</remarks>
+ internal static readonly bool IsSingleProcessor = ProcessorCount == 1;
}
}
diff --git a/src/mscorlib/shared/System/Threading/SynchronizationLockException.cs b/src/mscorlib/shared/System/Threading/SynchronizationLockException.cs
index c64fc9ced8..5ab186ec9a 100644
--- a/src/mscorlib/shared/System/Threading/SynchronizationLockException.cs
+++ b/src/mscorlib/shared/System/Threading/SynchronizationLockException.cs
@@ -21,19 +21,19 @@ namespace System.Threading
public SynchronizationLockException()
: base(SR.Arg_SynchronizationLockException)
{
- HResult = __HResults.COR_E_SYNCHRONIZATIONLOCK;
+ HResult = HResults.COR_E_SYNCHRONIZATIONLOCK;
}
public SynchronizationLockException(String message)
: base(message)
{
- HResult = __HResults.COR_E_SYNCHRONIZATIONLOCK;
+ HResult = HResults.COR_E_SYNCHRONIZATIONLOCK;
}
public SynchronizationLockException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_SYNCHRONIZATIONLOCK;
+ HResult = HResults.COR_E_SYNCHRONIZATIONLOCK;
}
protected SynchronizationLockException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/Threading/Tasks/ValueTask.cs b/src/mscorlib/shared/System/Threading/Tasks/ValueTask.cs
new file mode 100644
index 0000000000..384e4a8ab3
--- /dev/null
+++ b/src/mscorlib/shared/System/Threading/Tasks/ValueTask.cs
@@ -0,0 +1,169 @@
+// 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.Collections.Generic;
+using System.ComponentModel;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+namespace System.Threading.Tasks
+{
+ /// <summary>
+ /// Provides a value type that wraps a <see cref="Task{TResult}"/> and a <typeparamref name="TResult"/>,
+ /// only one of which is used.
+ /// </summary>
+ /// <typeparam name="TResult">The type of the result.</typeparam>
+ /// <remarks>
+ /// <para>
+ /// Methods may return an instance of this value type when it's likely that the result of their
+ /// operations will be available synchronously and when the method is expected to be invoked so
+ /// frequently that the cost of allocating a new <see cref="Task{TResult}"/> for each call will
+ /// be prohibitive.
+ /// </para>
+ /// <para>
+ /// There are tradeoffs to using a <see cref="ValueTask{TResult}"/> instead of a <see cref="Task{TResult}"/>.
+ /// For example, while a <see cref="ValueTask{TResult}"/> can help avoid an allocation in the case where the
+ /// successful result is available synchronously, it also contains two fields whereas a <see cref="Task{TResult}"/>
+ /// as a reference type is a single field. This means that a method call ends up returning two fields worth of
+ /// data instead of one, which is more data to copy. It also means that if a method that returns one of these
+ /// is awaited within an async method, the state machine for that async method will be larger due to needing
+ /// to store the struct that's two fields instead of a single reference.
+ /// </para>
+ /// <para>
+ /// Further, for uses other than consuming the result of an asynchronous operation via await,
+ /// <see cref="ValueTask{TResult}"/> can lead to a more convoluted programming model, which can in turn actually
+ /// lead to more allocations. For example, consider a method that could return either a <see cref="Task{TResult}"/>
+ /// with a cached task as a common result or a <see cref="ValueTask{TResult}"/>. If the consumer of the result
+ /// wants to use it as a <see cref="Task{TResult}"/>, such as to use with in methods like Task.WhenAll and Task.WhenAny,
+ /// the <see cref="ValueTask{TResult}"/> would first need to be converted into a <see cref="Task{TResult}"/> using
+ /// <see cref="ValueTask{TResult}.AsTask"/>, which leads to an allocation that would have been avoided if a cached
+ /// <see cref="Task{TResult}"/> had been used in the first place.
+ /// </para>
+ /// <para>
+ /// As such, the default choice for any asynchronous method should be to return a <see cref="Task"/> or
+ /// <see cref="Task{TResult}"/>. Only if performance analysis proves it worthwhile should a <see cref="ValueTask{TResult}"/>
+ /// be used instead of <see cref="Task{TResult}"/>. There is no non-generic version of <see cref="ValueTask{TResult}"/>
+ /// as the Task.CompletedTask property may be used to hand back a successfully completed singleton in the case where
+ /// a <see cref="Task"/>-returning method completes synchronously and successfully.
+ /// </para>
+ /// </remarks>
+ [AsyncMethodBuilder(typeof(AsyncValueTaskMethodBuilder<>))]
+ [StructLayout(LayoutKind.Auto)]
+ public struct ValueTask<TResult> : IEquatable<ValueTask<TResult>>
+ {
+ /// <summary>The task to be used if the operation completed asynchronously or if it completed synchronously but non-successfully.</summary>
+ internal readonly Task<TResult> _task;
+ /// <summary>The result to be used if the operation completed successfully synchronously.</summary>
+ internal readonly TResult _result;
+
+ /// <summary>Initialize the <see cref="ValueTask{TResult}"/> with the result of the successful operation.</summary>
+ /// <param name="result">The result.</param>
+ public ValueTask(TResult result)
+ {
+ _task = null;
+ _result = result;
+ }
+
+ /// <summary>
+ /// Initialize the <see cref="ValueTask{TResult}"/> with a <see cref="Task{TResult}"/> that represents the operation.
+ /// </summary>
+ /// <param name="task">The task.</param>
+ public ValueTask(Task<TResult> task)
+ {
+ if (task == null)
+ {
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.task);
+ }
+
+ _task = task;
+ _result = default(TResult);
+ }
+
+ /// <summary>Returns the hash code for this instance.</summary>
+ public override int GetHashCode() =>
+ _task != null ? _task.GetHashCode() :
+ _result != null ? _result.GetHashCode() :
+ 0;
+
+ /// <summary>Returns a value indicating whether this value is equal to a specified <see cref="object"/>.</summary>
+ public override bool Equals(object obj) =>
+ obj is ValueTask<TResult> &&
+ Equals((ValueTask<TResult>)obj);
+
+ /// <summary>Returns a value indicating whether this value is equal to a specified <see cref="ValueTask{TResult}"/> value.</summary>
+ public bool Equals(ValueTask<TResult> other) =>
+ _task != null || other._task != null ?
+ _task == other._task :
+ EqualityComparer<TResult>.Default.Equals(_result, other._result);
+
+ /// <summary>Returns a value indicating whether two <see cref="ValueTask{TResult}"/> values are equal.</summary>
+ public static bool operator==(ValueTask<TResult> left, ValueTask<TResult> right) =>
+ left.Equals(right);
+
+ /// <summary>Returns a value indicating whether two <see cref="ValueTask{TResult}"/> values are not equal.</summary>
+ public static bool operator!=(ValueTask<TResult> left, ValueTask<TResult> right) =>
+ !left.Equals(right);
+
+ /// <summary>
+ /// Gets a <see cref="Task{TResult}"/> object to represent this ValueTask. It will
+ /// either return the wrapped task object if one exists, or it'll manufacture a new
+ /// task object to represent the result.
+ /// </summary>
+ public Task<TResult> AsTask() =>
+ // Return the task if we were constructed from one, otherwise manufacture one. We don't
+ // cache the generated task into _task as it would end up changing both equality comparison
+ // and the hash code we generate in GetHashCode.
+ _task ?? AsyncTaskMethodBuilder<TResult>.GetTaskForResult(_result);
+
+ /// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a completed operation.</summary>
+ public bool IsCompleted => _task == null || _task.IsCompleted;
+
+ /// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a successfully completed operation.</summary>
+ public bool IsCompletedSuccessfully => _task == null || _task.IsCompletedSuccessfully;
+
+ /// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a failed operation.</summary>
+ public bool IsFaulted => _task != null && _task.IsFaulted;
+
+ /// <summary>Gets whether the <see cref="ValueTask{TResult}"/> represents a canceled operation.</summary>
+ public bool IsCanceled => _task != null && _task.IsCanceled;
+
+ /// <summary>Gets the result.</summary>
+ public TResult Result => _task == null ? _result : _task.GetAwaiter().GetResult();
+
+ /// <summary>Gets an awaiter for this value.</summary>
+ public ValueTaskAwaiter<TResult> GetAwaiter() => new ValueTaskAwaiter<TResult>(this);
+
+ /// <summary>Configures an awaiter for this value.</summary>
+ /// <param name="continueOnCapturedContext">
+ /// true to attempt to marshal the continuation back to the captured context; otherwise, false.
+ /// </param>
+ public ConfiguredValueTaskAwaitable<TResult> ConfigureAwait(bool continueOnCapturedContext) =>
+ new ConfiguredValueTaskAwaitable<TResult>(this, continueOnCapturedContext);
+
+ /// <summary>Gets a string-representation of this <see cref="ValueTask{TResult}"/>.</summary>
+ public override string ToString()
+ {
+ if (_task != null)
+ {
+ return _task.IsCompletedSuccessfully && _task.Result != null ?
+ _task.Result.ToString() :
+ string.Empty;
+ }
+ else
+ {
+ return _result != null ?
+ _result.ToString() :
+ string.Empty;
+ }
+ }
+
+ // TODO https://github.com/dotnet/corefx/issues/22171:
+ // Remove CreateAsyncMethodBuilder once the C# compiler relies on the AsyncBuilder attribute.
+
+ /// <summary>Creates a method builder for use with an async method.</summary>
+ /// <returns>The created builder.</returns>
+ [EditorBrowsable(EditorBrowsableState.Never)] // intended only for compiler consumption
+ public static AsyncValueTaskMethodBuilder<TResult> CreateAsyncMethodBuilder() => AsyncValueTaskMethodBuilder<TResult>.Create();
+ }
+}
diff --git a/src/mscorlib/shared/System/Threading/ThreadAbortException.cs b/src/mscorlib/shared/System/Threading/ThreadAbortException.cs
index ebbc29a702..01fdf1317b 100644
--- a/src/mscorlib/shared/System/Threading/ThreadAbortException.cs
+++ b/src/mscorlib/shared/System/Threading/ThreadAbortException.cs
@@ -22,7 +22,7 @@ namespace System.Threading
{
internal ThreadAbortException()
{
- HResult = __HResults.COR_E_THREADABORTED;
+ HResult = HResults.COR_E_THREADABORTED;
}
public object ExceptionState => null;
diff --git a/src/mscorlib/shared/System/Threading/ThreadStartException.cs b/src/mscorlib/shared/System/Threading/ThreadStartException.cs
index 7a87943ed1..35930d1d2d 100644
--- a/src/mscorlib/shared/System/Threading/ThreadStartException.cs
+++ b/src/mscorlib/shared/System/Threading/ThreadStartException.cs
@@ -11,13 +11,13 @@ namespace System.Threading
internal ThreadStartException()
: base(SR.Arg_ThreadStartException)
{
- HResult = __HResults.COR_E_THREADSTART;
+ HResult = HResults.COR_E_THREADSTART;
}
internal ThreadStartException(Exception reason)
: base(SR.Arg_ThreadStartException, reason)
{
- HResult = __HResults.COR_E_THREADSTART;
+ HResult = HResults.COR_E_THREADSTART;
}
}
}
diff --git a/src/mscorlib/shared/System/Threading/ThreadStateException.cs b/src/mscorlib/shared/System/Threading/ThreadStateException.cs
index 9477cb1ae4..d8f97a4f3b 100644
--- a/src/mscorlib/shared/System/Threading/ThreadStateException.cs
+++ b/src/mscorlib/shared/System/Threading/ThreadStateException.cs
@@ -21,19 +21,19 @@ namespace System.Threading
public ThreadStateException()
: base(SR.Arg_ThreadStateException)
{
- HResult = __HResults.COR_E_THREADSTATE;
+ HResult = HResults.COR_E_THREADSTATE;
}
public ThreadStateException(String message)
: base(message)
{
- HResult = __HResults.COR_E_THREADSTATE;
+ HResult = HResults.COR_E_THREADSTATE;
}
public ThreadStateException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_THREADSTATE;
+ HResult = HResults.COR_E_THREADSTATE;
}
protected ThreadStateException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/Threading/TimeoutHelper.cs b/src/mscorlib/shared/System/Threading/TimeoutHelper.cs
index c66c9add92..c96a4d00d6 100644
--- a/src/mscorlib/shared/System/Threading/TimeoutHelper.cs
+++ b/src/mscorlib/shared/System/Threading/TimeoutHelper.cs
@@ -13,7 +13,7 @@ namespace System.Threading
internal static class TimeoutHelper
{
/// <summary>
- /// Returns the Environment.TickCount as a start time in milliseconds as a uint, TickCount tools over from postive to negative every ~ 25 days
+ /// Returns the Environment.TickCount as a start time in milliseconds as a uint, TickCount tools over from positive to negative every ~ 25 days
/// then ~25 days to back to positive again, uint is sued to ignore the sign and double the range to 50 days
/// </summary>
/// <returns></returns>
@@ -26,7 +26,7 @@ namespace System.Threading
/// Helper function to measure and update the elapsed time
/// </summary>
/// <param name="startTime"> The first time (in milliseconds) observed when the wait started</param>
- /// <param name="originalWaitMillisecondsTimeout">The orginal wait timeoutout in milliseconds</param>
+ /// <param name="originalWaitMillisecondsTimeout">The original wait timeout in milliseconds</param>
/// <returns>The new wait time in milliseconds, -1 if the time expired</returns>
public static int UpdateTimeOut(uint startTime, int originalWaitMillisecondsTimeout)
{
diff --git a/src/mscorlib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs b/src/mscorlib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs
index 770e70d7ab..47e127191d 100644
--- a/src/mscorlib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs
+++ b/src/mscorlib/shared/System/Threading/WaitHandleCannotBeOpenedException.cs
@@ -10,17 +10,17 @@ namespace System.Threading
{
public WaitHandleCannotBeOpenedException() : base(SR.Threading_WaitHandleCannotBeOpenedException)
{
- HResult = __HResults.COR_E_WAITHANDLECANNOTBEOPENED;
+ HResult = HResults.COR_E_WAITHANDLECANNOTBEOPENED;
}
public WaitHandleCannotBeOpenedException(String message) : base(message)
{
- HResult = __HResults.COR_E_WAITHANDLECANNOTBEOPENED;
+ HResult = HResults.COR_E_WAITHANDLECANNOTBEOPENED;
}
public WaitHandleCannotBeOpenedException(String message, Exception innerException) : base(message, innerException)
{
- HResult = __HResults.COR_E_WAITHANDLECANNOTBEOPENED;
+ HResult = HResults.COR_E_WAITHANDLECANNOTBEOPENED;
}
protected WaitHandleCannotBeOpenedException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/TimeSpan.cs b/src/mscorlib/shared/System/TimeSpan.cs
index 39be059362..263a0a5824 100644
--- a/src/mscorlib/shared/System/TimeSpan.cs
+++ b/src/mscorlib/shared/System/TimeSpan.cs
@@ -316,55 +316,119 @@ namespace System
}
public static TimeSpan Parse(String s)
{
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input);
/* Constructs a TimeSpan from a string. Leading and trailing white space characters are allowed. */
- return TimeSpanParse.Parse(s, null);
+ return TimeSpanParse.Parse(s.AsReadOnlySpan(), null);
}
public static TimeSpan Parse(String input, IFormatProvider formatProvider)
{
+ if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input);
+ return TimeSpanParse.Parse(input.AsReadOnlySpan(), formatProvider);
+ }
+ public static TimeSpan Parse(ReadOnlySpan<char> input, IFormatProvider formatProvider = null)
+ {
return TimeSpanParse.Parse(input, formatProvider);
}
public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider)
{
- return TimeSpanParse.ParseExact(input, format, formatProvider, TimeSpanStyles.None);
+ if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input);
+ return TimeSpanParse.ParseExact(input.AsReadOnlySpan(), format, formatProvider, TimeSpanStyles.None);
}
public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider)
{
- return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None);
+ if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input);
+ return TimeSpanParse.ParseExactMultiple(input.AsReadOnlySpan(), formats, formatProvider, TimeSpanStyles.None);
}
public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles)
{
ValidateStyles(styles, nameof(styles));
+ if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input);
+ return TimeSpanParse.ParseExact(input.AsReadOnlySpan(), format, formatProvider, styles);
+ }
+ public static TimeSpan ParseExact(ReadOnlySpan<char> input, string format, IFormatProvider formatProvider, TimeSpanStyles styles = TimeSpanStyles.None)
+ {
+ ValidateStyles(styles, nameof(styles));
return TimeSpanParse.ParseExact(input, format, formatProvider, styles);
}
public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles)
{
ValidateStyles(styles, nameof(styles));
+ if (input == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.input);
+ return TimeSpanParse.ParseExactMultiple(input.AsReadOnlySpan(), formats, formatProvider, styles);
+ }
+ public static TimeSpan ParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, TimeSpanStyles styles = TimeSpanStyles.None)
+ {
+ ValidateStyles(styles, nameof(styles));
return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles);
}
public static Boolean TryParse(String s, out TimeSpan result)
{
- return TimeSpanParse.TryParse(s, null, out result);
+ if (s == null)
+ {
+ result = default(TimeSpan);
+ return false;
+ }
+ return TimeSpanParse.TryParse(s.AsReadOnlySpan(), null, out result);
}
public static Boolean TryParse(String input, IFormatProvider formatProvider, out TimeSpan result)
{
+ if (input == null)
+ {
+ result = default(TimeSpan);
+ return false;
+ }
+ return TimeSpanParse.TryParse(input.AsReadOnlySpan(), formatProvider, out result);
+ }
+ public static bool TryParse(ReadOnlySpan<char> input, out TimeSpan result, IFormatProvider formatProvider = null)
+ {
return TimeSpanParse.TryParse(input, formatProvider, out result);
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, out TimeSpan result)
{
- return TimeSpanParse.TryParseExact(input, format, formatProvider, TimeSpanStyles.None, out result);
+ if (input == null)
+ {
+ result = default(TimeSpan);
+ return false;
+ }
+ return TimeSpanParse.TryParseExact(input.AsReadOnlySpan(), format, formatProvider, TimeSpanStyles.None, out result);
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, out TimeSpan result)
{
- return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result);
+ if (input == null)
+ {
+ result = default(TimeSpan);
+ return false;
+ }
+ return TimeSpanParse.TryParseExactMultiple(input.AsReadOnlySpan(), formats, formatProvider, TimeSpanStyles.None, out result);
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result)
{
ValidateStyles(styles, nameof(styles));
+ if (input == null)
+ {
+ result = default(TimeSpan);
+ return false;
+ }
+ return TimeSpanParse.TryParseExact(input.AsReadOnlySpan(), format, formatProvider, styles, out result);
+ }
+ public static bool TryParseExact(ReadOnlySpan<char> input, string format, IFormatProvider formatProvider, out TimeSpan result, TimeSpanStyles styles = TimeSpanStyles.None)
+ {
+ ValidateStyles(styles, nameof(styles));
return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result);
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result)
{
ValidateStyles(styles, nameof(styles));
+ if (input == null)
+ {
+ result = default(TimeSpan);
+ return false;
+ }
+ return TimeSpanParse.TryParseExactMultiple(input.AsReadOnlySpan(), formats, formatProvider, styles, out result);
+ }
+ public static bool TryParseExact(ReadOnlySpan<char> input, string[] formats, IFormatProvider formatProvider, out TimeSpan result, TimeSpanStyles styles = TimeSpanStyles.None)
+ {
+ ValidateStyles(styles, nameof(styles));
return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result);
}
public override String ToString()
@@ -379,6 +443,10 @@ namespace System
{
return TimeSpanFormat.Format(this, format, formatProvider);
}
+ public bool TryFormat(Span<char> destination, out int charsWritten, string format = null, IFormatProvider formatProvider = null)
+ {
+ return TimeSpanFormat.TryFormat(this, destination, out charsWritten, format, formatProvider);
+ }
#endregion
public static TimeSpan operator -(TimeSpan t)
diff --git a/src/mscorlib/shared/System/TimeoutException.cs b/src/mscorlib/shared/System/TimeoutException.cs
index 4ba95bc47b..b50ae2f902 100644
--- a/src/mscorlib/shared/System/TimeoutException.cs
+++ b/src/mscorlib/shared/System/TimeoutException.cs
@@ -20,19 +20,19 @@ namespace System
public TimeoutException()
: base(SR.Arg_TimeoutException)
{
- HResult = __HResults.COR_E_TIMEOUT;
+ HResult = HResults.COR_E_TIMEOUT;
}
public TimeoutException(String message)
: base(message)
{
- HResult = __HResults.COR_E_TIMEOUT;
+ HResult = HResults.COR_E_TIMEOUT;
}
public TimeoutException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_TIMEOUT;
+ HResult = HResults.COR_E_TIMEOUT;
}
protected TimeoutException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/Type.cs b/src/mscorlib/shared/System/Type.cs
index 2ba58918a0..ab3d55bc66 100644
--- a/src/mscorlib/shared/System/Type.cs
+++ b/src/mscorlib/shared/System/Type.cs
@@ -47,6 +47,8 @@ namespace System
public virtual bool IsSZArray { get { throw NotImplemented.ByDesign; } }
public virtual bool IsVariableBoundArray => IsArray && !IsSZArray;
+ public virtual bool IsByRefLike => throw new NotSupportedException(SR.NotSupported_SubclassOverride);
+
public bool HasElementType => HasElementTypeImpl();
protected abstract bool HasElementTypeImpl();
public abstract Type GetElementType();
@@ -106,6 +108,8 @@ namespace System
public bool IsValueType => IsValueTypeImpl();
protected virtual bool IsValueTypeImpl() => IsSubclassOf(typeof(ValueType));
+ public virtual bool IsSignatureType => false;
+
public virtual bool IsSecurityCritical { get { throw NotImplemented.ByDesign; } }
public virtual bool IsSecuritySafeCritical { get { throw NotImplemented.ByDesign; } }
public virtual bool IsSecurityTransparent { get { throw NotImplemented.ByDesign; } }
@@ -177,6 +181,27 @@ namespace System
protected abstract MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers);
+ public MethodInfo GetMethod(string name, int genericParameterCount, Type[] types) => GetMethod(name, genericParameterCount, types, null);
+ public MethodInfo GetMethod(string name, int genericParameterCount, Type[] types, ParameterModifier[] modifiers) => GetMethod(name, genericParameterCount, Type.DefaultLookup, null, types, modifiers);
+ public MethodInfo GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers) => GetMethod(name, genericParameterCount, bindingAttr, binder, CallingConventions.Any, types, modifiers);
+ public MethodInfo GetMethod(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers)
+ {
+ if (name == null)
+ throw new ArgumentNullException(nameof(name));
+ if (genericParameterCount < 0)
+ throw new ArgumentException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(genericParameterCount));
+ if (types == null)
+ throw new ArgumentNullException(nameof(types));
+ for (int i = 0; i < types.Length; i++)
+ {
+ if (types[i] == null)
+ throw new ArgumentNullException(nameof(types));
+ }
+ return GetMethodImpl(name, genericParameterCount, bindingAttr, binder, callConvention, types, modifiers);
+ }
+
+ protected virtual MethodInfo GetMethodImpl(string name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) => throw new NotSupportedException();
+
public MethodInfo[] GetMethods() => GetMethods(Type.DefaultLookup);
public abstract MethodInfo[] GetMethods(BindingFlags bindingAttr);
@@ -317,6 +342,13 @@ namespace System
public virtual Type MakeGenericType(params Type[] typeArguments) { throw new NotSupportedException(SR.NotSupported_SubclassOverride); }
public virtual Type MakePointerType() { throw new NotSupportedException(); }
+ public static Type MakeGenericMethodParameter(int position)
+ {
+ if (position < 0)
+ throw new ArgumentException(SR.ArgumentOutOfRange_MustBeNonNegNum, nameof(position));
+ return new SignatureGenericMethodParameterType(position);
+ }
+
public override string ToString() => "Type: " + Name; // Why do we add the "Type: " prefix?
public override bool Equals(object o) => o == null ? false : Equals(o as Type);
diff --git a/src/mscorlib/shared/System/TypeAccessException.cs b/src/mscorlib/shared/System/TypeAccessException.cs
index 302dcb1ac1..ff081582b6 100644
--- a/src/mscorlib/shared/System/TypeAccessException.cs
+++ b/src/mscorlib/shared/System/TypeAccessException.cs
@@ -13,19 +13,19 @@ namespace System
public TypeAccessException()
: base(SR.Arg_TypeAccessException)
{
- HResult = __HResults.COR_E_TYPEACCESS;
+ HResult = HResults.COR_E_TYPEACCESS;
}
public TypeAccessException(string message)
: base(message)
{
- HResult = __HResults.COR_E_TYPEACCESS;
+ HResult = HResults.COR_E_TYPEACCESS;
}
public TypeAccessException(string message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_TYPEACCESS;
+ HResult = HResults.COR_E_TYPEACCESS;
}
protected TypeAccessException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/TypeInitializationException.cs b/src/mscorlib/shared/System/TypeInitializationException.cs
index 8d0b8a9f79..03a1bad3a7 100644
--- a/src/mscorlib/shared/System/TypeInitializationException.cs
+++ b/src/mscorlib/shared/System/TypeInitializationException.cs
@@ -28,7 +28,7 @@ namespace System
private TypeInitializationException()
: base(SR.TypeInitialization_Default)
{
- HResult = __HResults.COR_E_TYPEINITIALIZATION;
+ HResult = HResults.COR_E_TYPEINITIALIZATION;
}
@@ -41,14 +41,14 @@ namespace System
// for Interop only, though it's not particularly useful.
internal TypeInitializationException(String message) : base(message)
{
- HResult = __HResults.COR_E_TYPEINITIALIZATION;
+ HResult = HResults.COR_E_TYPEINITIALIZATION;
}
internal TypeInitializationException(String fullTypeName, String message, Exception innerException)
: base(message, innerException)
{
_typeName = fullTypeName;
- HResult = __HResults.COR_E_TYPEINITIALIZATION;
+ HResult = HResults.COR_E_TYPEINITIALIZATION;
}
public override void GetObjectData(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/shared/System/TypeUnloadedException.cs b/src/mscorlib/shared/System/TypeUnloadedException.cs
index c7ed71c9cb..97039bb8f1 100644
--- a/src/mscorlib/shared/System/TypeUnloadedException.cs
+++ b/src/mscorlib/shared/System/TypeUnloadedException.cs
@@ -11,19 +11,19 @@ namespace System
public TypeUnloadedException()
: base(SR.Arg_TypeUnloadedException)
{
- HResult = __HResults.COR_E_TYPEUNLOADED;
+ HResult = HResults.COR_E_TYPEUNLOADED;
}
public TypeUnloadedException(string message)
: base(message)
{
- HResult = __HResults.COR_E_TYPEUNLOADED;
+ HResult = HResults.COR_E_TYPEUNLOADED;
}
public TypeUnloadedException(string message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_TYPEUNLOADED;
+ HResult = HResults.COR_E_TYPEUNLOADED;
}
protected TypeUnloadedException(SerializationInfo info, StreamingContext context)
diff --git a/src/mscorlib/src/System/UInt16.cs b/src/mscorlib/shared/System/UInt16.cs
index 746ed7ba49..4cd290bc45 100644
--- a/src/mscorlib/src/System/UInt16.cs
+++ b/src/mscorlib/shared/System/UInt16.cs
@@ -11,19 +11,19 @@
**
===========================================================*/
+using System.Diagnostics.Contracts;
using System.Globalization;
-using System;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
+using System.Runtime.Versioning;
namespace System
{
- // Wrapper for unsigned 16 bit integers.
[Serializable]
- [CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
- [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
- public struct UInt16 : IComparable, IFormattable, IConvertible
- , IComparable<UInt16>, IEquatable<UInt16>
+ [CLSCompliant(false)]
+ [StructLayout(LayoutKind.Sequential)]
+ [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ public struct UInt16 : IComparable, IConvertible, IFormattable, IComparable<UInt16>, IEquatable<UInt16>
{
private ushort m_value; // Do not rename (binary serialization)
@@ -64,7 +64,7 @@ namespace System
return m_value == ((UInt16)obj).m_value;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public bool Equals(UInt16 obj)
{
return m_value == obj;
@@ -105,31 +105,42 @@ namespace System
[CLSCompliant(false)]
public static ushort Parse(String s)
{
- return Parse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static ushort Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
- return Parse(s, style, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static ushort Parse(String s, IFormatProvider provider)
{
- return Parse(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static ushort Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Parse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
+ }
+
+ [CLSCompliant(false)]
+ public static ushort Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return Parse(s, style, NumberFormatInfo.GetInstance(provider));
}
- private static ushort Parse(String s, NumberStyles style, NumberFormatInfo info)
+ private static ushort Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info)
{
uint i = 0;
try
@@ -148,17 +159,37 @@ namespace System
[CLSCompliant(false)]
public static bool TryParse(String s, out UInt16 result)
{
- return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return TryParse(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt16 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return TryParse(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
+ }
+
+ [CLSCompliant(false)]
+ public static bool TryParse(ReadOnlySpan<char> s, out ushort result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
- private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out UInt16 result)
+ private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out UInt16 result)
{
result = 0;
UInt32 i;
diff --git a/src/mscorlib/src/System/UInt32.cs b/src/mscorlib/shared/System/UInt32.cs
index f696816b98..49835613b2 100644
--- a/src/mscorlib/src/System/UInt32.cs
+++ b/src/mscorlib/shared/System/UInt32.cs
@@ -12,20 +12,19 @@
**
===========================================================*/
+using System.Diagnostics.Contracts;
using System.Globalization;
-using System;
-using System.Runtime;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
+using System.Runtime.Versioning;
namespace System
{
- // * Wrapper for unsigned 32 bit integers.
[Serializable]
- [CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
- [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
- public struct UInt32 : IComparable, IFormattable, IConvertible
- , IComparable<UInt32>, IEquatable<UInt32>
+ [CLSCompliant(false)]
+ [StructLayout(LayoutKind.Sequential)]
+ [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ public struct UInt32 : IComparable, IConvertible, IFormattable, IComparable<UInt32>, IEquatable<UInt32>
{
private uint m_value; // Do not rename (binary serialization)
@@ -75,7 +74,7 @@ namespace System
return m_value == ((UInt32)obj).m_value;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public bool Equals(UInt32 obj)
{
return m_value == obj;
@@ -115,40 +114,71 @@ namespace System
[CLSCompliant(false)]
public static uint Parse(String s)
{
- return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseUInt32(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static uint Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
- return Number.ParseUInt32(s, style, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseUInt32(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static uint Parse(String s, IFormatProvider provider)
{
- return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseUInt32(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static uint Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseUInt32(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
+ }
+
+ [CLSCompliant(false)]
+ public static uint Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static bool TryParse(String s, out UInt32 result)
{
- return Number.TryParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return Number.TryParseUInt32(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt32 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return Number.TryParseUInt32(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
+ }
+
+ [CLSCompliant(false)]
+ public static bool TryParse(ReadOnlySpan<char> s, out UInt32 result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
diff --git a/src/mscorlib/src/System/UInt64.cs b/src/mscorlib/shared/System/UInt64.cs
index 03cdcc5f40..424d48b8b1 100644
--- a/src/mscorlib/src/System/UInt64.cs
+++ b/src/mscorlib/shared/System/UInt64.cs
@@ -11,19 +11,19 @@
**
===========================================================*/
+using System.Diagnostics.Contracts;
using System.Globalization;
-using System;
+using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-using System.Diagnostics.Contracts;
+using System.Runtime.Versioning;
namespace System
{
- // Wrapper for unsigned 64 bit integers.
[Serializable]
- [CLSCompliant(false), System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
- [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
- public struct UInt64 : IComparable, IFormattable, IConvertible
- , IComparable<UInt64>, IEquatable<UInt64>
+ [CLSCompliant(false)]
+ [StructLayout(LayoutKind.Sequential)]
+ [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
+ public struct UInt64 : IComparable, IConvertible, IFormattable, IComparable<UInt64>, IEquatable<UInt64>
{
private ulong m_value; // Do not rename (binary serialization)
@@ -72,7 +72,7 @@ namespace System
return m_value == ((UInt64)obj).m_value;
}
- [System.Runtime.Versioning.NonVersionable]
+ [NonVersionable]
public bool Equals(UInt64 obj)
{
return m_value == obj;
@@ -111,39 +111,70 @@ namespace System
[CLSCompliant(false)]
public static ulong Parse(String s)
{
- return Number.ParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseUInt64(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static ulong Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
- return Number.ParseUInt64(s, style, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseUInt64(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static ulong Parse(string s, IFormatProvider provider)
{
- return Number.ParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseUInt64(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static ulong Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseUInt64(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
+ }
+
+ [CLSCompliant(false)]
+ public static ulong Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt64(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static Boolean TryParse(String s, out UInt64 result)
{
- return Number.TryParseUInt64(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return Number.TryParseUInt64(s.AsReadOnlySpan(), NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result);
}
[CLSCompliant(false)]
public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt64 result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
+
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return Number.TryParseUInt64(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
+ }
+
+ [CLSCompliant(false)]
+ public static Boolean TryParse(ReadOnlySpan<char> s, out UInt64 result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseUInt64(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
diff --git a/src/mscorlib/shared/System/UnauthorizedAccessException.cs b/src/mscorlib/shared/System/UnauthorizedAccessException.cs
index 667d576292..679a1a762d 100644
--- a/src/mscorlib/shared/System/UnauthorizedAccessException.cs
+++ b/src/mscorlib/shared/System/UnauthorizedAccessException.cs
@@ -24,19 +24,19 @@ namespace System
public UnauthorizedAccessException()
: base(SR.Arg_UnauthorizedAccessException)
{
- HResult = __HResults.COR_E_UNAUTHORIZEDACCESS;
+ HResult = HResults.COR_E_UNAUTHORIZEDACCESS;
}
public UnauthorizedAccessException(String message)
: base(message)
{
- HResult = __HResults.COR_E_UNAUTHORIZEDACCESS;
+ HResult = HResults.COR_E_UNAUTHORIZEDACCESS;
}
public UnauthorizedAccessException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_UNAUTHORIZEDACCESS;
+ HResult = HResults.COR_E_UNAUTHORIZEDACCESS;
}
protected UnauthorizedAccessException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/shared/System/UnitySerializationHolder.cs b/src/mscorlib/shared/System/UnitySerializationHolder.cs
new file mode 100644
index 0000000000..bbfebff8a6
--- /dev/null
+++ b/src/mscorlib/shared/System/UnitySerializationHolder.cs
@@ -0,0 +1,66 @@
+// 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
+{
+ /// <summary>
+ /// Holds Null class for which we guarantee that there is only ever one instance of.
+ /// This only exists for compatibility with .NET Framework.
+ /// </summary>
+ [Serializable]
+#if CORECLR
+ internal
+#else
+ public // On CoreRT this must be public.
+#endif
+ sealed class UnitySerializationHolder : ISerializable, IObjectReference
+ {
+ internal const int NullUnity = 0x0002;
+ private readonly int _unityType;
+ private readonly string _data;
+
+ /// <summary>
+ /// A helper method that returns the SerializationInfo that a class utilizing
+ /// UnitySerializationHelper should return from a call to GetObjectData. It contains
+ /// the unityType (defined above) and any optional data (used only for the reflection types).
+ /// </summary>
+ internal static void GetUnitySerializationInfo(SerializationInfo info, int unityType)
+ {
+ info.SetType(typeof(UnitySerializationHolder));
+ info.AddValue("Data", null, typeof(string));
+ info.AddValue("UnityType", unityType);
+ info.AddValue("AssemblyName", string.Empty);
+ }
+
+ public UnitySerializationHolder(SerializationInfo info, StreamingContext context)
+ {
+ if (info == null)
+ {
+ throw new ArgumentNullException(nameof(info));
+ }
+
+ // We are ignoring any other serialization input as we are only concerned about DBNull.
+ // We also store data and use it for erorr logging.
+ _unityType = info.GetInt32("UnityType");
+ _data = info.GetString("Data");
+ }
+
+ public void GetObjectData(SerializationInfo info, StreamingContext context) =>
+ throw new NotSupportedException(SR.NotSupported_UnitySerHolder);
+
+ public object GetRealObject(StreamingContext context)
+ {
+ // We are only support deserializing DBNull and throwing for everything else.
+ if (_unityType != NullUnity)
+ {
+ throw new ArgumentException(SR.Format(SR.Argument_InvalidUnity, _data ?? "UnityType"));
+ }
+
+ // We are always returning the same DBNull instance.
+ return DBNull.Value;
+ }
+ }
+}
diff --git a/src/mscorlib/shared/System/Version.cs b/src/mscorlib/shared/System/Version.cs
index a2140ab137..9c66d9b904 100644
--- a/src/mscorlib/shared/System/Version.cs
+++ b/src/mscorlib/shared/System/Version.cs
@@ -197,82 +197,118 @@ namespace System
return accumulator;
}
- public override String ToString()
+ public override string ToString() =>
+ ToString(DefaultFormatFieldCount);
+
+ public string ToString(int fieldCount) =>
+ fieldCount == 0 ? string.Empty :
+ fieldCount == 1 ? _Major.ToString() :
+ StringBuilderCache.GetStringAndRelease(ToCachedStringBuilder(fieldCount));
+
+ public bool TryFormat(Span<char> destination, out int charsWritten) =>
+ TryFormat(destination, DefaultFormatFieldCount, out charsWritten);
+
+ public bool TryFormat(Span<char> destination, int fieldCount, out int charsWritten)
{
- if (_Build == -1) return (ToString(2));
- if (_Revision == -1) return (ToString(3));
- return (ToString(4));
+ if (fieldCount == 0)
+ {
+ charsWritten = 0;
+ return true;
+ }
+
+ // TODO https://github.com/dotnet/corefx/issues/22403: fieldCount==1 can just use int.TryFormat
+
+ StringBuilder sb = ToCachedStringBuilder(fieldCount);
+ if (sb.Length <= destination.Length)
+ {
+ sb.CopyTo(0, destination, sb.Length);
+ StringBuilderCache.Release(sb);
+ charsWritten = sb.Length;
+ return true;
+ }
+
+ StringBuilderCache.Release(sb);
+ charsWritten = 0;
+ return false;
}
- public String ToString(int fieldCount)
+ private int DefaultFormatFieldCount =>
+ _Build == -1 ? 2 :
+ _Revision == -1 ? 3 :
+ 4;
+
+ private StringBuilder ToCachedStringBuilder(int fieldCount)
{
- StringBuilder sb;
- switch (fieldCount)
+ if (fieldCount == 1)
{
- case 0:
- return (String.Empty);
- case 1:
- return (_Major.ToString());
- case 2:
- sb = StringBuilderCache.Acquire();
- AppendPositiveNumber(_Major, sb);
- sb.Append('.');
- AppendPositiveNumber(_Minor, sb);
- return StringBuilderCache.GetStringAndRelease(sb);
- default:
- if (_Build == -1)
- throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "2"), nameof(fieldCount));
+ StringBuilder sb = StringBuilderCache.Acquire();
+ AppendNonNegativeNumber(_Major, sb);
+ return sb;
+ }
+ else if (fieldCount == 2)
+ {
+ StringBuilder sb = StringBuilderCache.Acquire();
+ AppendNonNegativeNumber(_Major, sb);
+ sb.Append('.');
+ AppendNonNegativeNumber(_Minor, sb);
+ return sb;
+ }
+ else
+ {
+ if (_Build == -1)
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "2"), nameof(fieldCount));
+ }
- if (fieldCount == 3)
- {
- sb = StringBuilderCache.Acquire();
- AppendPositiveNumber(_Major, sb);
- sb.Append('.');
- AppendPositiveNumber(_Minor, sb);
- sb.Append('.');
- AppendPositiveNumber(_Build, sb);
- return StringBuilderCache.GetStringAndRelease(sb);
- }
+ if (fieldCount == 3)
+ {
+ StringBuilder sb = StringBuilderCache.Acquire();
+ AppendNonNegativeNumber(_Major, sb);
+ sb.Append('.');
+ AppendNonNegativeNumber(_Minor, sb);
+ sb.Append('.');
+ AppendNonNegativeNumber(_Build, sb);
+ return sb;
+ }
- if (_Revision == -1)
- throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "3"), nameof(fieldCount));
+ if (_Revision == -1)
+ {
+ throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "3"), nameof(fieldCount));
+ }
- if (fieldCount == 4)
- {
- sb = StringBuilderCache.Acquire();
- AppendPositiveNumber(_Major, sb);
- sb.Append('.');
- AppendPositiveNumber(_Minor, sb);
- sb.Append('.');
- AppendPositiveNumber(_Build, sb);
- sb.Append('.');
- AppendPositiveNumber(_Revision, sb);
- return StringBuilderCache.GetStringAndRelease(sb);
- }
+ if (fieldCount == 4)
+ {
+ StringBuilder sb = StringBuilderCache.Acquire();
+ AppendNonNegativeNumber(_Major, sb);
+ sb.Append('.');
+ AppendNonNegativeNumber(_Minor, sb);
+ sb.Append('.');
+ AppendNonNegativeNumber(_Build, sb);
+ sb.Append('.');
+ AppendNonNegativeNumber(_Revision, sb);
+ return sb;
+ }
- throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "4"), nameof(fieldCount));
+ throw new ArgumentException(SR.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, "0", "4"), nameof(fieldCount));
}
}
+ // TODO https://github.com/dotnet/corefx/issues/22616:
+ // Use StringBuilder.Append(int) once it's been updated to use spans internally.
//
- // AppendPositiveNumber is an optimization to append a number to a StringBuilder object without
+ // AppendNonNegativeNumber is an optimization to append a number to a StringBuilder object without
// doing any boxing and not even creating intermediate string.
// Note: as we always have positive numbers then it is safe to convert the number to string
// regardless of the current culture as we'll not have any punctuation marks in the number
- //
- private const int ZERO_CHAR_VALUE = (int)'0';
- private static void AppendPositiveNumber(int num, StringBuilder sb)
+ private static void AppendNonNegativeNumber(int num, StringBuilder sb)
{
Debug.Assert(num >= 0, "AppendPositiveNumber expect positive numbers");
int index = sb.Length;
- int reminder;
-
do
{
- reminder = num % 10;
- num = num / 10;
- sb.Insert(index, (char)(ZERO_CHAR_VALUE + reminder));
+ num = Math.DivRem(num, 10, out int remainder);
+ sb.Insert(index, (char)('0' + remainder));
} while (num > 0);
}
@@ -282,104 +318,108 @@ namespace System
{
throw new ArgumentNullException(nameof(input));
}
- Contract.EndContractBlock();
- VersionResult r = new VersionResult();
- r.Init(nameof(input), true);
- if (!TryParseVersion(input, ref r))
- {
- throw r.GetVersionParseException();
- }
- return r.m_parsedVersion;
+ return ParseVersion(input.AsReadOnlySpan(), throwOnFailure: true);
}
- public static bool TryParse(string input, out Version result)
- {
- VersionResult r = new VersionResult();
- r.Init(nameof(input), false);
- bool b = TryParseVersion(input, ref r);
- result = r.m_parsedVersion;
- return b;
- }
+ public static Version Parse(ReadOnlySpan<char> input) =>
+ ParseVersion(input, throwOnFailure: true);
- private static bool TryParseVersion(string version, ref VersionResult result)
+ public static bool TryParse(string input, out Version result)
{
- int major, minor, build, revision;
-
- if ((Object)version == null)
+ if (input == null)
{
- result.SetFailure(ParseFailureKind.ArgumentNullException);
+ result = null;
return false;
}
- String[] parsedComponents = version.Split('.');
- int parsedComponentsLength = parsedComponents.Length;
- if ((parsedComponentsLength < 2) || (parsedComponentsLength > 4))
+ return (result = ParseVersion(input.AsReadOnlySpan(), throwOnFailure: false)) != null;
+ }
+
+ public static bool TryParse(ReadOnlySpan<char> input, out Version result) =>
+ (result = ParseVersion(input, throwOnFailure: false)) != null;
+
+ private static Version ParseVersion(ReadOnlySpan<char> input, bool throwOnFailure)
+ {
+ // Find the separator between major and minor. It must exist.
+ int majorEnd = input.IndexOf('.');
+ if (majorEnd < 0)
{
- result.SetFailure(ParseFailureKind.ArgumentException);
- return false;
+ if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input));
+ return null;
}
- if (!TryParseComponent(parsedComponents[0], nameof(version), ref result, out major))
+ // Find the ends of the optional minor and build portions.
+ // We musn't have any separators after build.
+ int buildEnd = -1;
+ int minorEnd = input.IndexOf('.', majorEnd + 1);
+ if (minorEnd != -1)
{
- return false;
+ buildEnd = input.IndexOf('.', minorEnd + 1);
+ if (buildEnd != -1)
+ {
+ if (input.IndexOf('.', buildEnd + 1) != -1)
+ {
+ if (throwOnFailure) throw new ArgumentException(SR.Arg_VersionString, nameof(input));
+ return null;
+ }
+ }
}
- if (!TryParseComponent(parsedComponents[1], nameof(version), ref result, out minor))
+ int major, minor, build, revision;
+
+ // Parse the major version
+ if (!TryParseComponent(input.Slice(0, majorEnd), nameof(input), throwOnFailure, out major))
{
- return false;
+ return null;
}
- parsedComponentsLength -= 2;
-
- if (parsedComponentsLength > 0)
+ if (minorEnd != -1)
{
- if (!TryParseComponent(parsedComponents[2], "build", ref result, out build))
+ // If there's more than a major and minor, parse the minor, too.
+ if (!TryParseComponent(input.Slice(majorEnd + 1, minorEnd - majorEnd - 1), nameof(input), throwOnFailure, out minor))
{
- return false;
+ return null;
}
- parsedComponentsLength--;
-
- if (parsedComponentsLength > 0)
+ if (buildEnd != -1)
{
- if (!TryParseComponent(parsedComponents[3], "revision", ref result, out revision))
- {
- return false;
- }
- else
- {
- result.m_parsedVersion = new Version(major, minor, build, revision);
- }
+ // major.minor.build.revision
+ return
+ TryParseComponent(input.Slice(minorEnd + 1, buildEnd - minorEnd - 1), nameof(build), throwOnFailure, out build) &&
+ TryParseComponent(input.Slice(buildEnd + 1), nameof(revision), throwOnFailure, out revision) ?
+ new Version(major, minor, build, revision) :
+ null;
}
else
{
- result.m_parsedVersion = new Version(major, minor, build);
+ // major.minor.build
+ return TryParseComponent(input.Slice(minorEnd + 1), nameof(build), throwOnFailure, out build) ?
+ new Version(major, minor, build) :
+ null;
}
}
else
{
- result.m_parsedVersion = new Version(major, minor);
+ // major.minor
+ return TryParseComponent(input.Slice(majorEnd + 1), nameof(input), throwOnFailure, out minor) ?
+ new Version(major, minor) :
+ null;
}
-
- return true;
}
- private static bool TryParseComponent(string component, string componentName, ref VersionResult result, out int parsedComponent)
+ private static bool TryParseComponent(ReadOnlySpan<char> component, string componentName, bool throwOnFailure, out int parsedComponent)
{
- if (!Int32.TryParse(component, NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedComponent))
+ if (throwOnFailure)
{
- result.SetFailure(ParseFailureKind.FormatException, component);
- return false;
- }
-
- if (parsedComponent < 0)
- {
- result.SetFailure(ParseFailureKind.ArgumentOutOfRangeException, componentName);
- return false;
+ if ((parsedComponent = int.Parse(component, NumberStyles.Integer, CultureInfo.InvariantCulture)) < 0)
+ {
+ throw new ArgumentOutOfRangeException(componentName, SR.ArgumentOutOfRange_Version);
+ }
+ return true;
}
- return true;
+ return int.TryParse(component, out parsedComponent, NumberStyles.Integer, CultureInfo.InvariantCulture) && parsedComponent >= 0;
}
public static bool operator ==(Version v1, Version v2)
@@ -422,75 +462,5 @@ namespace System
{
return (v2 <= v1);
}
-
- internal enum ParseFailureKind
- {
- ArgumentNullException,
- ArgumentException,
- ArgumentOutOfRangeException,
- FormatException
- }
-
- internal struct VersionResult
- {
- internal Version m_parsedVersion;
- internal ParseFailureKind m_failure;
- internal string m_exceptionArgument;
- internal string m_argumentName;
- internal bool m_canThrow;
-
- internal void Init(string argumentName, bool canThrow)
- {
- m_canThrow = canThrow;
- m_argumentName = argumentName;
- }
-
- internal void SetFailure(ParseFailureKind failure)
- {
- SetFailure(failure, String.Empty);
- }
-
- internal void SetFailure(ParseFailureKind failure, string argument)
- {
- m_failure = failure;
- m_exceptionArgument = argument;
- if (m_canThrow)
- {
- throw GetVersionParseException();
- }
- }
-
- internal Exception GetVersionParseException()
- {
- switch (m_failure)
- {
- case ParseFailureKind.ArgumentNullException:
- return new ArgumentNullException(m_argumentName);
- case ParseFailureKind.ArgumentException:
- return new ArgumentException(SR.Arg_VersionString);
- case ParseFailureKind.ArgumentOutOfRangeException:
- return new ArgumentOutOfRangeException(m_exceptionArgument, SR.ArgumentOutOfRange_Version);
- case ParseFailureKind.FormatException:
- // Regenerate the FormatException as would be thrown by Int32.Parse()
- try
- {
- Int32.Parse(m_exceptionArgument, CultureInfo.InvariantCulture);
- }
- catch (FormatException e)
- {
- return e;
- }
- catch (OverflowException e)
- {
- return e;
- }
- Debug.Assert(false, "Int32.Parse() did not throw exception but TryParse failed: " + m_exceptionArgument);
- return new FormatException(SR.Format_InvalidString);
- default:
- Debug.Assert(false, "Unmatched case in Version.GetVersionParseException() for value: " + m_failure);
- return new ArgumentException(SR.Arg_VersionString);
- }
- }
- }
}
}
diff --git a/src/mscorlib/src/Internal/Padding.cs b/src/mscorlib/src/Internal/Padding.cs
new file mode 100644
index 0000000000..d25acdc9c7
--- /dev/null
+++ b/src/mscorlib/src/Internal/Padding.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;
+
+namespace Internal
+{
+
+ /// <summary>A class for common padding constants and eventually routines.</summary>
+ internal static class PaddingHelpers
+ {
+ /// <summary>A size greater than or equal to the size of the most common CPU cache lines.</summary>
+#if ARM64
+ internal const int CACHE_LINE_SIZE = 128;
+#else
+ internal const int CACHE_LINE_SIZE = 64;
+#endif
+ }
+
+ /// <summary>Padding structure used to minimize false sharing</summary>
+ [StructLayout(LayoutKind.Explicit, Size = PaddingHelpers.CACHE_LINE_SIZE - sizeof(int))]
+ internal struct PaddingFor32
+ {
+ }
+}
+
diff --git a/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs b/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs
index 605f974da0..4c67ea3fd6 100644
--- a/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs
+++ b/src/mscorlib/src/Internal/Runtime/Augments/RuntimeThread.cs
@@ -15,6 +15,8 @@ namespace Internal.Runtime.Augments
{
public class RuntimeThread : CriticalFinalizerObject
{
+ private static int s_optimalMaxSpinWaitsPerSpinIteration;
+
internal RuntimeThread() { }
public static RuntimeThread Create(ThreadStart start) => new Thread(start);
@@ -186,6 +188,33 @@ namespace Internal.Runtime.Augments
private extern bool JoinInternal(int millisecondsTimeout);
public static void Sleep(int millisecondsTimeout) => Thread.Sleep(millisecondsTimeout);
+
+ [DllImport(JitHelpers.QCall)]
+ [SuppressUnmanagedCodeSecurity]
+ private static extern int GetOptimalMaxSpinWaitsPerSpinIterationInternal();
+
+ /// <summary>
+ /// Max value to be passed into <see cref="SpinWait(int)"/> for optimal delaying. This value is normalized to be
+ /// appropriate for the processor.
+ /// </summary>
+ internal static int OptimalMaxSpinWaitsPerSpinIteration
+ {
+ get
+ {
+ if (s_optimalMaxSpinWaitsPerSpinIteration != 0)
+ {
+ return s_optimalMaxSpinWaitsPerSpinIteration;
+ }
+
+ // This is done lazily because the first call to the function below in the process triggers a measurement that
+ // takes a nontrivial amount of time. See Thread::InitializeYieldProcessorNormalized(), which describes and
+ // calculates this value.
+ s_optimalMaxSpinWaitsPerSpinIteration = GetOptimalMaxSpinWaitsPerSpinIterationInternal();
+ Debug.Assert(s_optimalMaxSpinWaitsPerSpinIteration > 0);
+ return s_optimalMaxSpinWaitsPerSpinIteration;
+ }
+ }
+
public static void SpinWait(int iterations) => Thread.SpinWait(iterations);
public static bool Yield() => Thread.Yield();
diff --git a/src/mscorlib/src/Interop/Unix/Interop.Libraries.cs b/src/mscorlib/src/Interop/Unix/Interop.Libraries.cs
new file mode 100644
index 0000000000..31df8c75de
--- /dev/null
+++ b/src/mscorlib/src/Interop/Unix/Interop.Libraries.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.
+
+internal static partial class Interop
+{
+ internal static partial class Libraries
+ {
+ internal const string Kernel32 = "libcoreclr";
+ internal const string User32 = "libcoreclr";
+ internal const string Ole32 = "libcoreclr";
+ internal const string OleAut32 = "libcoreclr";
+ }
+}
diff --git a/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs b/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
index 521ea65e10..0a2057ca53 100644
--- a/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
+++ b/src/mscorlib/src/Microsoft/Win32/RegistryKey.cs
@@ -119,27 +119,6 @@ namespace Microsoft.Win32
private volatile RegistryView regView = RegistryView.Default;
/**
- * RegistryInternalCheck values. Useful only for CheckPermission
- */
- private enum RegistryInternalCheck
- {
- CheckSubKeyWritePermission = 0,
- CheckSubKeyReadPermission = 1,
- CheckSubKeyCreatePermission = 2,
- CheckSubTreeReadPermission = 3,
- CheckSubTreeWritePermission = 4,
- CheckSubTreeReadWritePermission = 5,
- CheckValueWritePermission = 6,
- CheckValueCreatePermission = 7,
- CheckValueReadPermission = 8,
- CheckKeyReadPermission = 9,
- CheckSubTreePermission = 10,
- CheckOpenSubKeyWithWritablePermission = 11,
- CheckOpenSubKeyPermission = 12
- };
-
-
- /**
* Creates a RegistryKey.
*
* This key is bound to hkey, if writable is <b>false</b> then no write operations
@@ -318,29 +297,6 @@ namespace Microsoft.Win32
return null;
}
- // This required no security checks. This is to get around the Deleting SubKeys which only require
- // write permission. They call OpenSubKey which required read. Now instead call this function w/o security checks
- internal RegistryKey InternalOpenSubKey(String name, bool writable)
- {
- ValidateKeyName(name);
- EnsureNotDisposed();
-
- SafeRegistryHandle result = null;
- int ret = Win32Native.RegOpenKeyEx(hkey,
- name,
- 0,
- GetRegistryKeyAccess(writable) | (int)regView,
- out result);
-
- if (ret == 0 && !result.IsInvalid)
- {
- RegistryKey key = new RegistryKey(result, writable, false, remoteKey, false, regView);
- key.keyName = keyName + "\\" + name;
- return key;
- }
- return null;
- }
-
/**
* Returns a subkey with read only permissions.
*
@@ -502,9 +458,7 @@ namespace Microsoft.Win32
* Note that <var>name</var> can be null or "", at which point the
* unnamed or default value of this Registry key is returned, if any.
* The default values for RegistryKeys are OS-dependent. NT doesn't
- * have them by default, but they can exist and be of any type. On
- * Win95, the default value is always an empty key of type REG_SZ.
- * Win98 supports default values of any type, but defaults to REG_SZ.
+ * have them by default, but they can exist and be of any type.
*
* @param name Name of value to retrieve.
* @param defaultValue Value to return if <i>name</i> doesn't exist.
@@ -1036,7 +990,7 @@ namespace Microsoft.Win32
throw new IOException(SR.Arg_RegKeyNotFound, errorCode);
default:
- throw new IOException(Win32Native.GetMessage(errorCode), errorCode);
+ throw new IOException(Interop.Kernel32.GetMessage(errorCode), errorCode);
}
}
@@ -1102,14 +1056,6 @@ namespace Microsoft.Win32
}
}
- private bool ContainsRegistryValue(string name)
- {
- int type = 0;
- int datasize = 0;
- int retval = Win32Native.RegQueryValueEx(hkey, name, null, ref type, (byte[])null, ref datasize);
- return retval == 0;
- }
-
private void EnsureNotDisposed()
{
if (hkey == null)
diff --git a/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs b/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs
index 1b835d5dd1..f36bc18140 100644
--- a/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs
+++ b/src/mscorlib/src/Microsoft/Win32/UnsafeNativeMethods.cs
@@ -4,25 +4,20 @@
namespace Microsoft.Win32
{
- using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
- using System.Runtime.CompilerServices;
- using System.Runtime.ConstrainedExecution;
+ using System.Diagnostics.Tracing;
using System.Runtime.InteropServices;
- using System.Runtime.Serialization;
- using System.Runtime.Versioning;
using System.Security;
using System.Text;
- using System.Diagnostics.Tracing;
[SuppressUnmanagedCodeSecurityAttribute()]
internal static class UnsafeNativeMethods
{
- [DllImport(Win32Native.KERNEL32, EntryPoint = "GetTimeZoneInformation", SetLastError = true, ExactSpelling = true)]
+ [DllImport(Interop.Libraries.Kernel32, EntryPoint = "GetTimeZoneInformation", SetLastError = true, ExactSpelling = true)]
internal static extern int GetTimeZoneInformation(out Win32Native.TimeZoneInformation lpTimeZoneInformation);
- [DllImport(Win32Native.KERNEL32, EntryPoint = "GetDynamicTimeZoneInformation", SetLastError = true, ExactSpelling = true)]
+ [DllImport(Interop.Libraries.Kernel32, EntryPoint = "GetDynamicTimeZoneInformation", SetLastError = true, ExactSpelling = true)]
internal static extern int GetDynamicTimeZoneInformation(out Win32Native.DynamicTimeZoneInformation lpDynamicTimeZoneInformation);
//
@@ -36,7 +31,7 @@ namespace Microsoft.Win32
// PULONGLONG pululEnumerator
// );
//
- [DllImport(Win32Native.KERNEL32, EntryPoint = "GetFileMUIPath", SetLastError = true, ExactSpelling = true)]
+ [DllImport(Interop.Libraries.Kernel32, EntryPoint = "GetFileMUIPath", SetLastError = true, ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetFileMUIPath(
int flags,
@@ -50,18 +45,6 @@ namespace Microsoft.Win32
ref int fileMuiPathLength,
ref Int64 enumerator);
-
- [DllImport(Win32Native.USER32, EntryPoint = "LoadStringW", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
- internal static extern int LoadString(SafeLibraryHandle handle, int id, [Out] StringBuilder buffer, int bufferLength);
-
- [DllImport(Win32Native.KERNEL32, CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)]
- internal static extern SafeLibraryHandle LoadLibraryEx(string libFilename, IntPtr reserved, int flags);
-
- [DllImport(Win32Native.KERNEL32, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
- [return: MarshalAs(UnmanagedType.Bool)]
- internal static extern bool FreeLibrary(IntPtr hModule);
-
-
[SuppressUnmanagedCodeSecurityAttribute()]
internal static unsafe class ManifestEtw
{
@@ -247,6 +230,7 @@ namespace Microsoft.Win32
int OutBufferSize,
ref int ReturnLength);
}
+
#if FEATURE_COMINTEROP
[DllImport("combase.dll", PreserveSig = true)]
internal static extern int RoGetActivationFactory(
@@ -254,6 +238,5 @@ namespace Microsoft.Win32
[In] ref Guid iid,
[Out, MarshalAs(UnmanagedType.IInspectable)] out Object factory);
#endif
-
}
}
diff --git a/src/mscorlib/src/Microsoft/Win32/Win32Native.cs b/src/mscorlib/src/Microsoft/Win32/Win32Native.cs
index e4d8b9af24..eaa9cedfc6 100644
--- a/src/mscorlib/src/Microsoft/Win32/Win32Native.cs
+++ b/src/mscorlib/src/Microsoft/Win32/Win32Native.cs
@@ -18,13 +18,13 @@
* For handles, you should use a SafeHandle subclass specific to your handle
* type. For files, we have the following set of interesting definitions:
*
- * [DllImport(KERNEL32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
+ * [DllImport(Interop.Libraries.Kernel32, SetLastError=true, CharSet=CharSet.Auto, BestFitMapping=false)]
* private static extern SafeFileHandle CreateFile(...);
*
- * [DllImport(KERNEL32, SetLastError=true)]
+ * [DllImport(Interop.Libraries.Kernel32, SetLastError=true)]
* unsafe internal static extern int ReadFile(SafeFileHandle handle, ...);
*
- * [DllImport(KERNEL32, SetLastError=true)]
+ * [DllImport(Interop.Libraries.Kernel32, SetLastError=true)]
* internal static extern bool CloseHandle(IntPtr handle);
*
* P/Invoke will create the SafeFileHandle instance for you and assign the
@@ -59,7 +59,7 @@
* [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
* internal struct OSVERSIONINFO { ... }
*
- * [DllImport(KERNEL32, CharSet=CharSet.Auto)]
+ * [DllImport(Interop.Libraries.Kernel32, CharSet=CharSet.Auto)]
* internal static extern bool GetVersionEx(ref OSVERSIONINFO lposvi);
*
* OR:
@@ -67,7 +67,7 @@
* [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Auto)]
* internal class OSVERSIONINFO { ... }
*
- * [DllImport(KERNEL32, CharSet=CharSet.Auto)]
+ * [DllImport(Interop.Libraries.Kernel32, CharSet=CharSet.Auto)]
* internal static extern bool GetVersionEx([In, Out] OSVERSIONINFO lposvi);
*
* Note that classes require being marked as [In, Out] while value types must
@@ -152,9 +152,6 @@ namespace Microsoft.Win32
internal const int REG_RESOURCE_REQUIREMENTS_LIST = 10;
internal const int REG_QWORD = 11; // 64-bit number
- internal const int HWND_BROADCAST = 0xffff;
- internal const int WM_SETTINGCHANGE = 0x001A;
-
// TimeZone
internal const int TIME_ZONE_ID_INVALID = -1;
internal const int TIME_ZONE_ID_UNKNOWN = 0;
@@ -170,9 +167,6 @@ namespace Microsoft.Win32
internal const int MUI_LANG_NEUTRAL_PE_FILE = 0x100;
internal const int MUI_NON_LANG_NEUTRAL_FILE = 0x200;
- internal const int LOAD_LIBRARY_AS_DATAFILE = 0x00000002;
- internal const int LOAD_STRING_MAX_LENGTH = 500;
-
[StructLayout(LayoutKind.Sequential)]
internal struct SystemTime
{
@@ -356,24 +350,6 @@ namespace Microsoft.Win32
internal const int LPTR = (LMEM_FIXED | LMEM_ZEROINIT);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
- internal class OSVERSIONINFO
- {
- internal OSVERSIONINFO()
- {
- OSVersionInfoSize = (int)Marshal.SizeOf(this);
- }
-
- // The OSVersionInfoSize field must be set to Marshal.SizeOf(this)
- internal int OSVersionInfoSize = 0;
- internal int MajorVersion = 0;
- internal int MinorVersion = 0;
- internal int BuildNumber = 0;
- internal int PlatformId = 0;
- [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
- internal String CSDVersion = null;
- }
-
- [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal class OSVERSIONINFOEX
{
public OSVERSIONINFOEX()
@@ -460,17 +436,6 @@ namespace Microsoft.Win32
internal uint Type;
}
-#if !FEATURE_PAL
- internal const String KERNEL32 = "kernel32.dll";
- internal const String USER32 = "user32.dll";
- internal const String OLE32 = "ole32.dll";
- internal const String OLEAUT32 = "oleaut32.dll";
-#else //FEATURE_PAL
- internal const String KERNEL32 = "libcoreclr";
- internal const String USER32 = "libcoreclr";
- internal const String OLE32 = "libcoreclr";
- internal const String OLEAUT32 = "libcoreclr";
-#endif //FEATURE_PAL
internal const String ADVAPI32 = "advapi32.dll";
internal const String SHELL32 = "shell32.dll";
internal const String SHIM = "mscoree.dll";
@@ -478,34 +443,10 @@ namespace Microsoft.Win32
internal const String SECUR32 = "secur32.dll";
internal const String MSCORWKS = "coreclr.dll";
- [DllImport(KERNEL32, CharSet = CharSet.Auto, BestFitMapping = true)]
- internal static extern int FormatMessage(int dwFlags, IntPtr lpSource,
- int dwMessageId, int dwLanguageId, [Out]StringBuilder lpBuffer,
- int nSize, IntPtr va_list_arguments);
-
- // Gets an error message for a Win32 error code.
- internal static String GetMessage(int errorCode)
- {
- StringBuilder sb = StringBuilderCache.Acquire(512);
- int result = Win32Native.FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS |
- FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ARGUMENT_ARRAY,
- IntPtr.Zero, errorCode, 0, sb, sb.Capacity, IntPtr.Zero);
- if (result != 0)
- {
- // result is the # of characters copied to the StringBuilder.
- return StringBuilderCache.GetStringAndRelease(sb);
- }
- else
- {
- StringBuilderCache.Release(sb);
- return SR.Format(SR.UnknownError_Num, errorCode);
- }
- }
-
- [DllImport(KERNEL32, EntryPoint = "LocalAlloc")]
+ [DllImport(Interop.Libraries.Kernel32, EntryPoint = "LocalAlloc")]
internal static extern IntPtr LocalAlloc_NoSafeHandle(int uFlags, UIntPtr sizetdwBytes);
- [DllImport(KERNEL32, SetLastError = true)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
internal static extern IntPtr LocalFree(IntPtr handle);
internal static bool GlobalMemoryStatusEx(ref MEMORYSTATUSEX buffer)
@@ -514,99 +455,83 @@ namespace Microsoft.Win32
return GlobalMemoryStatusExNative(ref buffer);
}
- [DllImport(KERNEL32, SetLastError = true, EntryPoint = "GlobalMemoryStatusEx")]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true, EntryPoint = "GlobalMemoryStatusEx")]
private static extern bool GlobalMemoryStatusExNative([In, Out] ref MEMORYSTATUSEX buffer);
- [DllImport(KERNEL32, SetLastError = true)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
unsafe internal static extern UIntPtr VirtualQuery(void* address, ref MEMORY_BASIC_INFORMATION buffer, UIntPtr sizeOfBuffer);
// VirtualAlloc should generally be avoided, but is needed in
// the MemoryFailPoint implementation (within a CER) to increase the
// size of the page file, ignoring any host memory allocators.
- [DllImport(KERNEL32, SetLastError = true)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
unsafe internal static extern void* VirtualAlloc(void* address, UIntPtr numBytes, int commitOrReserve, int pageProtectionMode);
- [DllImport(KERNEL32, SetLastError = true)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
unsafe internal static extern bool VirtualFree(void* address, UIntPtr numBytes, int pageFreeMode);
- [DllImport(KERNEL32, CharSet = CharSet.Ansi, ExactSpelling = true, EntryPoint = "lstrlenA")]
+ [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Ansi, ExactSpelling = true, EntryPoint = "lstrlenA")]
internal static extern int lstrlenA(IntPtr ptr);
- [DllImport(KERNEL32, CharSet = CharSet.Unicode, ExactSpelling = true, EntryPoint = "lstrlenW")]
+ [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Unicode, ExactSpelling = true, EntryPoint = "lstrlenW")]
internal static extern int lstrlenW(IntPtr ptr);
- [DllImport(Win32Native.OLEAUT32, CharSet = CharSet.Unicode)]
+ [DllImport(Interop.Libraries.OleAut32, CharSet = CharSet.Unicode)]
internal static extern IntPtr SysAllocStringLen(String src, int len); // BSTR
- [DllImport(Win32Native.OLEAUT32)]
+ [DllImport(Interop.Libraries.OleAut32)]
internal static extern uint SysStringLen(IntPtr bstr);
- [DllImport(Win32Native.OLEAUT32)]
+ [DllImport(Interop.Libraries.OleAut32)]
internal static extern void SysFreeString(IntPtr bstr);
#if FEATURE_COMINTEROP
- [DllImport(Win32Native.OLEAUT32)]
+ [DllImport(Interop.Libraries.OleAut32)]
internal static extern IntPtr SysAllocStringByteLen(byte[] str, uint len); // BSTR
- [DllImport(Win32Native.OLEAUT32)]
+ [DllImport(Interop.Libraries.OleAut32)]
internal static extern uint SysStringByteLen(IntPtr bstr);
#endif
- [DllImport(KERNEL32, SetLastError = true)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
internal static extern bool SetEvent(SafeWaitHandle handle);
- [DllImport(KERNEL32, SetLastError = true)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
internal static extern bool ResetEvent(SafeWaitHandle handle);
- [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle CreateEventEx(SECURITY_ATTRIBUTES lpSecurityAttributes, string name, uint flags, uint desiredAccess);
- [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle OpenEvent(uint desiredAccess, bool inheritHandle, string name);
- [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle CreateMutexEx(SECURITY_ATTRIBUTES lpSecurityAttributes, string name, uint flags, uint desiredAccess);
- [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle OpenMutex(uint desiredAccess, bool inheritHandle, string name);
- [DllImport(KERNEL32, SetLastError = true)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
internal static extern bool ReleaseMutex(SafeWaitHandle handle);
- [DllImport(KERNEL32, SetLastError = true)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
internal static extern bool CloseHandle(IntPtr handle);
- [DllImport(KERNEL32, SetLastError = true)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
internal static unsafe extern int WriteFile(SafeFileHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero);
- [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle CreateSemaphoreEx(SECURITY_ATTRIBUTES lpSecurityAttributes, int initialCount, int maximumCount, string name, uint flags, uint desiredAccess);
- [DllImport(KERNEL32, SetLastError = true)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ReleaseSemaphore(SafeWaitHandle handle, int releaseCount, out int previousCount);
- [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeWaitHandle OpenSemaphore(uint desiredAccess, bool inheritHandle, string name);
- // Will be in winnls.h
- internal const int FIND_STARTSWITH = 0x00100000; // see if value is at the beginning of source
- internal const int FIND_ENDSWITH = 0x00200000; // see if value is at the end of source
- internal const int FIND_FROMSTART = 0x00400000; // look for value in source, starting at the beginning
- internal const int FIND_FROMEND = 0x00800000; // look for value in source, starting at the end
-
- [StructLayout(LayoutKind.Sequential)]
- internal struct NlsVersionInfoEx
- {
- internal int dwNLSVersionInfoSize;
- internal int dwNLSVersion;
- internal int dwDefinedVersion;
- internal int dwEffectiveId;
- internal Guid guidCustomVersion;
- }
-
- [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
+ [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
internal static extern int GetSystemDirectory([Out]StringBuilder sb, int length);
internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); // WinBase.h
@@ -616,17 +541,9 @@ namespace Microsoft.Win32
internal const int STD_OUTPUT_HANDLE = -11;
internal const int STD_ERROR_HANDLE = -12;
- [DllImport(KERNEL32, SetLastError = true)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
internal static extern IntPtr GetStdHandle(int nStdHandle); // param is NOT a handle, but it returns one!
- // From wincon.h
- internal const int CTRL_C_EVENT = 0;
- internal const int CTRL_BREAK_EVENT = 1;
- internal const int CTRL_CLOSE_EVENT = 2;
- internal const int CTRL_LOGOFF_EVENT = 5;
- internal const int CTRL_SHUTDOWN_EVENT = 6;
- internal const short KEY_EVENT = 1;
-
// From WinBase.h
internal const int FILE_TYPE_DISK = 0x0001;
internal const int FILE_TYPE_CHAR = 0x0002;
@@ -719,14 +636,6 @@ namespace Microsoft.Win32
// From WinStatus.h
internal const int STATUS_ACCOUNT_RESTRICTION = unchecked((int)0xC000006E);
- // Use this to translate error codes like the above into HRESULTs like
- // 0x80070006 for ERROR_INVALID_HANDLE
- internal static int MakeHRFromErrorCode(int errorCode)
- {
- BCLDebug.Assert((0xFFFF0000 & errorCode) == 0, "This is an HRESULT, not an error code!");
- return unchecked(((int)0x80070000) | errorCode);
- }
-
// Win32 Structs in N/Direct style
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
[BestFitMapping(false)]
@@ -756,51 +665,49 @@ namespace Microsoft.Win32
internal String cAlternateFileName = null;
}
- [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern SafeFindHandle FindFirstFile(String fileName, [In, Out] Win32Native.WIN32_FIND_DATA data);
- [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern bool FindNextFile(
SafeFindHandle hndFindFile,
[In, Out, MarshalAs(UnmanagedType.LPStruct)]
WIN32_FIND_DATA lpFindFileData);
- [DllImport(KERNEL32)]
+ [DllImport(Interop.Libraries.Kernel32)]
internal static extern bool FindClose(IntPtr handle);
- [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern bool GetFileAttributesEx(String name, int fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation);
- internal const int LCID_SUPPORTED = 0x00000002; // supported locale ids
-
- [DllImport(KERNEL32)]
+ [DllImport(Interop.Libraries.Kernel32)]
internal static extern unsafe int WideCharToMultiByte(uint cp, uint flags, char* pwzSource, int cchSource, byte* pbDestBuffer, int cbDestBuffer, IntPtr null1, IntPtr null2);
- [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
+ [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
internal static extern bool SetEnvironmentVariable(string lpName, string lpValue);
- [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
+ [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
internal static extern int GetEnvironmentVariable(string lpName, [Out]StringBuilder lpValue, int size);
- [DllImport(KERNEL32, CharSet = CharSet.Unicode)]
+ [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Unicode)]
internal static unsafe extern char* GetEnvironmentStrings();
- [DllImport(KERNEL32, CharSet = CharSet.Unicode)]
+ [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Unicode)]
internal static unsafe extern bool FreeEnvironmentStrings(char* pStrings);
- [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true)]
+ [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Auto, SetLastError = true)]
internal static extern uint GetCurrentProcessId();
- [DllImport(OLE32)]
+ [DllImport(Interop.Libraries.Ole32)]
internal extern static int CoCreateGuid(out Guid guid);
- [DllImport(OLE32)]
+ [DllImport(Interop.Libraries.Ole32)]
internal static extern IntPtr CoTaskMemAlloc(UIntPtr cb);
- [DllImport(OLE32)]
+ [DllImport(Interop.Libraries.Ole32)]
internal static extern void CoTaskMemFree(IntPtr ptr);
- [DllImport(OLE32)]
+ [DllImport(Interop.Libraries.Ole32)]
internal static extern IntPtr CoTaskMemRealloc(IntPtr pv, UIntPtr cb);
#if FEATURE_WIN32_REGISTRY
@@ -825,14 +732,6 @@ namespace Microsoft.Win32
int ulOptions, int samDesired, out SafeRegistryHandle hkResult);
[DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
- internal static extern int RegQueryInfoKey(SafeRegistryHandle hKey, [Out]StringBuilder lpClass,
- int[] lpcbClass, IntPtr lpReserved_MustBeZero, ref int lpcSubKeys,
- int[] lpcbMaxSubKeyLen, int[] lpcbMaxClassLen,
- ref int lpcValues, int[] lpcbMaxValueNameLen,
- int[] lpcbMaxValueLen, int[] lpcbSecurityDescriptor,
- int[] lpftLastWriteTime);
-
- [DllImport(ADVAPI32, CharSet = CharSet.Auto, BestFitMapping = false)]
internal static extern int RegQueryValueEx(SafeRegistryHandle hKey, String lpValueName,
int[] lpReserved, ref int lpType, [Out] byte[] lpData,
ref int lpcbData);
@@ -869,74 +768,13 @@ namespace Microsoft.Win32
int Reserved, RegistryValueKind dwType, String lpData, int cbData);
#endif // FEATURE_WIN32_REGISTRY
- [DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
+ [DllImport(Interop.Libraries.Kernel32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
internal static extern int ExpandEnvironmentStrings(String lpSrc, [Out]StringBuilder lpDst, int nSize);
- [DllImport(KERNEL32)]
+ [DllImport(Interop.Libraries.Kernel32)]
internal static extern IntPtr LocalReAlloc(IntPtr handle, IntPtr sizetcbBytes, int uFlags);
- internal const int SHGFP_TYPE_CURRENT = 0; // the current (user) folder path setting
- internal const int UOI_FLAGS = 1;
- internal const int WSF_VISIBLE = 1;
-
- // .NET Framework 4.0 and newer - all versions of windows ||| \public\sdk\inc\shlobj.h
- internal const int CSIDL_FLAG_CREATE = 0x8000; // force folder creation in SHGetFolderPath
- internal const int CSIDL_FLAG_DONT_VERIFY = 0x4000; // return an unverified folder path
- internal const int CSIDL_ADMINTOOLS = 0x0030; // <user name>\Start Menu\Programs\Administrative Tools
- internal const int CSIDL_CDBURN_AREA = 0x003b; // USERPROFILE\Local Settings\Application Data\Microsoft\CD Burning
- internal const int CSIDL_COMMON_ADMINTOOLS = 0x002f; // All Users\Start Menu\Programs\Administrative Tools
- internal const int CSIDL_COMMON_DOCUMENTS = 0x002e; // All Users\Documents
- internal const int CSIDL_COMMON_MUSIC = 0x0035; // All Users\My Music
- internal const int CSIDL_COMMON_OEM_LINKS = 0x003a; // Links to All Users OEM specific apps
- internal const int CSIDL_COMMON_PICTURES = 0x0036; // All Users\My Pictures
- internal const int CSIDL_COMMON_STARTMENU = 0x0016; // All Users\Start Menu
- internal const int CSIDL_COMMON_PROGRAMS = 0X0017; // All Users\Start Menu\Programs
- internal const int CSIDL_COMMON_STARTUP = 0x0018; // All Users\Startup
- internal const int CSIDL_COMMON_DESKTOPDIRECTORY = 0x0019; // All Users\Desktop
- internal const int CSIDL_COMMON_TEMPLATES = 0x002d; // All Users\Templates
- internal const int CSIDL_COMMON_VIDEO = 0x0037; // All Users\My Video
- internal const int CSIDL_FONTS = 0x0014; // windows\fonts
- internal const int CSIDL_MYVIDEO = 0x000e; // "My Videos" folder
- internal const int CSIDL_NETHOOD = 0x0013; // %APPDATA%\Microsoft\Windows\Network Shortcuts
- internal const int CSIDL_PRINTHOOD = 0x001b; // %APPDATA%\Microsoft\Windows\Printer Shortcuts
- internal const int CSIDL_PROFILE = 0x0028; // %USERPROFILE% (%SystemDrive%\Users\%USERNAME%)
- internal const int CSIDL_PROGRAM_FILES_COMMONX86 = 0x002c; // x86 Program Files\Common on RISC
- internal const int CSIDL_PROGRAM_FILESX86 = 0x002a; // x86 C:\Program Files on RISC
- internal const int CSIDL_RESOURCES = 0x0038; // %windir%\Resources
- internal const int CSIDL_RESOURCES_LOCALIZED = 0x0039; // %windir%\resources\0409 (code page)
- internal const int CSIDL_SYSTEMX86 = 0x0029; // %windir%\system32
- internal const int CSIDL_WINDOWS = 0x0024; // GetWindowsDirectory()
-
- // .NET Framework 3.5 and earlier - all versions of windows
- internal const int CSIDL_APPDATA = 0x001a;
- internal const int CSIDL_COMMON_APPDATA = 0x0023;
- internal const int CSIDL_LOCAL_APPDATA = 0x001c;
- internal const int CSIDL_COOKIES = 0x0021;
- internal const int CSIDL_FAVORITES = 0x0006;
- internal const int CSIDL_HISTORY = 0x0022;
- internal const int CSIDL_INTERNET_CACHE = 0x0020;
- internal const int CSIDL_PROGRAMS = 0x0002;
- internal const int CSIDL_RECENT = 0x0008;
- internal const int CSIDL_SENDTO = 0x0009;
- internal const int CSIDL_STARTMENU = 0x000b;
- internal const int CSIDL_STARTUP = 0x0007;
- internal const int CSIDL_SYSTEM = 0x0025;
- internal const int CSIDL_TEMPLATES = 0x0015;
- internal const int CSIDL_DESKTOPDIRECTORY = 0x0010;
- internal const int CSIDL_PERSONAL = 0x0005;
- internal const int CSIDL_PROGRAM_FILES = 0x0026;
- internal const int CSIDL_PROGRAM_FILES_COMMON = 0x002b;
- internal const int CSIDL_DESKTOP = 0x0000;
- internal const int CSIDL_DRIVES = 0x0011;
- internal const int CSIDL_MYMUSIC = 0x000d;
- internal const int CSIDL_MYPICTURES = 0x0027;
-
- internal const int NameSamCompatible = 2;
-
- [DllImport(USER32, SetLastError = true, BestFitMapping = false)]
- internal static extern IntPtr SendMessageTimeout(IntPtr hWnd, int Msg, IntPtr wParam, String lParam, uint fuFlags, uint uTimeout, IntPtr lpdwResult);
-
- [DllImport(KERNEL32, SetLastError = true)]
+ [DllImport(Interop.Libraries.Kernel32, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal extern static bool QueryUnbiasedInterruptTime(out ulong UnbiasedTime);
diff --git a/src/mscorlib/src/System/Activator.cs b/src/mscorlib/src/System/Activator.cs
index 50c517339b..be938aa43d 100644
--- a/src/mscorlib/src/System/Activator.cs
+++ b/src/mscorlib/src/System/Activator.cs
@@ -51,7 +51,6 @@ namespace System
return CreateInstance(type, bindingAttr, binder, args, culture, null);
}
- [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public Object CreateInstance(Type type,
BindingFlags bindingAttr,
Binder binder,
@@ -80,8 +79,7 @@ namespace System
if (rt == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(type));
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return rt.CreateInstanceImpl(bindingAttr, binder, args, culture, activationAttributes, ref stackMark);
+ return rt.CreateInstanceImpl(bindingAttr, binder, args, culture, activationAttributes);
}
static public Object CreateInstance(Type type, params Object[] args)
@@ -111,9 +109,13 @@ namespace System
return Activator.CreateInstance(type, false);
}
- [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public Object CreateInstance(Type type, bool nonPublic)
{
+ return CreateInstance(type, nonPublic, wrapExceptions: true);
+ }
+
+ static internal Object CreateInstance(Type type, bool nonPublic, bool wrapExceptions)
+ {
if ((object)type == null)
throw new ArgumentNullException(nameof(type));
Contract.EndContractBlock();
@@ -123,11 +125,9 @@ namespace System
if (rt == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(type));
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
- return rt.CreateInstanceDefaultCtor(!nonPublic, false, true, ref stackMark);
+ return rt.CreateInstanceDefaultCtor(!nonPublic, false, true, wrapExceptions);
}
- [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
static public T CreateInstance<T>()
{
RuntimeType rt = typeof(T) as RuntimeType;
@@ -137,10 +137,8 @@ namespace System
if (rt.HasElementType)
throw new MissingMethodException(SR.Arg_NoDefCTor);
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-
// Skip the CreateInstanceCheckThis call to avoid perf cost and to maintain compatibility with V2 (throwing the same exceptions).
- return (T)rt.CreateInstanceDefaultCtor(true /*publicOnly*/, true /*skipCheckThis*/, true /*fillCache*/, ref stackMark);
+ return (T)rt.CreateInstanceDefaultCtor(true /*publicOnly*/, true /*skipCheckThis*/, true /*fillCache*/, true /*wrapExceptions*/);
}
}
}
diff --git a/src/mscorlib/src/System/AppContext/AppContextDefaultValues.cs b/src/mscorlib/src/System/AppContext/AppContextDefaultValues.cs
index 9f00e8148c..320a14109b 100644
--- a/src/mscorlib/src/System/AppContext/AppContextDefaultValues.cs
+++ b/src/mscorlib/src/System/AppContext/AppContextDefaultValues.cs
@@ -114,7 +114,7 @@ namespace System
{
value = value.Substring(1);
}
- Version realVersion = new Version(value);
+ Version realVersion = Version.Parse(value);
// The version class will represent some unset values as -1 internally (instead of 0).
version = realVersion.Major * 10000;
if (realVersion.Minor > 0)
diff --git a/src/mscorlib/src/System/AppDomain.cs b/src/mscorlib/src/System/AppDomain.cs
index 553b83feee..1c009ed605 100644
--- a/src/mscorlib/src/System/AppDomain.cs
+++ b/src/mscorlib/src/System/AppDomain.cs
@@ -226,7 +226,7 @@ namespace System
/// <summary>
/// Initialize the compatibility flags to non-NULL values.
- /// This method is also called from the VM when the default domain dosen't have a domain manager.
+ /// This method is also called from the VM when the default domain doesn't have a domain manager.
/// </summary>
private void InitializeCompatibilityFlags()
{
@@ -398,7 +398,7 @@ namespace System
}
[Obsolete("AppDomain.GetCurrentThreadId has been deprecated because it does not provide a stable Id when managed threads are running on fibers (aka lightweight threads). To get a stable identifier for a managed thread, use the ManagedThreadId property on Thread. http://go.microsoft.com/fwlink/?linkid=14202", false)]
- [DllImport(Microsoft.Win32.Win32Native.KERNEL32)]
+ [DllImport(Interop.Libraries.Kernel32)]
public static extern int GetCurrentThreadId();
private AppDomain()
@@ -874,7 +874,7 @@ namespace System
/// <summary>
/// Handle used to marshal an AppDomain to the VM (eg QCall). When marshaled via a QCall, the target
- /// method in the VM will recieve a QCall::AppDomainHandle parameter.
+ /// method in the VM will receive a QCall::AppDomainHandle parameter.
/// </summary>
internal struct AppDomainHandle
{
diff --git a/src/mscorlib/src/System/AppDomainSetup.cs b/src/mscorlib/src/System/AppDomainSetup.cs
index 7d20b57017..d0fdf4e725 100644
--- a/src/mscorlib/src/System/AppDomainSetup.cs
+++ b/src/mscorlib/src/System/AppDomainSetup.cs
@@ -14,7 +14,6 @@ namespace System
{
using System.Text;
using System.Runtime.InteropServices;
- using System.Runtime.Serialization;
using System.Security;
using Path = System.IO.Path;
using System.Diagnostics;
@@ -62,20 +61,8 @@ namespace System
// A collection of strings used to indicate which breaking changes shouldn't be applied
// to an AppDomain. We only use the keys, the values are ignored.
- [OptionalField(VersionAdded = 4)]
private Dictionary<string, object> _CompatFlags;
- [OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5
- private String _TargetFrameworkName;
-
- [OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5
- private bool _CheckedForTargetFrameworkName;
-
-#if FEATURE_RANDOMIZED_STRING_HASHING
- [OptionalField(VersionAdded = 5)] // This was added in .NET FX v4.5
- private bool _UseRandomizedStringHashing;
-#endif
-
internal AppDomainSetup(AppDomainSetup copy, bool copyDomainBoundData)
{
string[] mine = Value;
@@ -101,13 +88,6 @@ namespace System
{
SetCompatibilitySwitches(copy._CompatFlags.Keys);
}
-
- _TargetFrameworkName = copy._TargetFrameworkName;
-
-#if FEATURE_RANDOMIZED_STRING_HASHING
- _UseRandomizedStringHashing = copy._UseRandomizedStringHashing;
-#endif
-
}
}
@@ -168,20 +148,11 @@ namespace System
public void SetCompatibilitySwitches(IEnumerable<String> switches)
{
-#if FEATURE_RANDOMIZED_STRING_HASHING
- _UseRandomizedStringHashing = false;
-#endif
if (switches != null)
{
_CompatFlags = new Dictionary<string, object>();
foreach (String str in switches)
{
-#if FEATURE_RANDOMIZED_STRING_HASHING
- if (StringComparer.OrdinalIgnoreCase.Equals("UseRandomizedStringHashAlgorithm", str))
- {
- _UseRandomizedStringHashing = true;
- }
-#endif
_CompatFlags.Add(str, null);
}
}
@@ -196,11 +167,7 @@ namespace System
{
get
{
- return _TargetFrameworkName;
- }
- set
- {
- _TargetFrameworkName = value;
+ return null;
}
}
diff --git a/src/mscorlib/src/System/AppDomainUnloadedException.cs b/src/mscorlib/src/System/AppDomainUnloadedException.cs
index a5e74e2b23..b673d8c998 100644
--- a/src/mscorlib/src/System/AppDomainUnloadedException.cs
+++ b/src/mscorlib/src/System/AppDomainUnloadedException.cs
@@ -21,7 +21,7 @@ namespace System
public AppDomainUnloadedException()
: base(SR.Arg_AppDomainUnloadedException)
{
- HResult = __HResults.COR_E_APPDOMAINUNLOADED;
+ HResult = HResults.COR_E_APPDOMAINUNLOADED;
}
//
diff --git a/src/mscorlib/src/System/Array.cs b/src/mscorlib/src/System/Array.cs
index 62a4ecf16e..01c1ac0234 100644
--- a/src/mscorlib/src/System/Array.cs
+++ b/src/mscorlib/src/System/Array.cs
@@ -2418,13 +2418,14 @@ namespace System
private sealed class SZArrayEnumerator : IEnumerator, ICloneable
{
- private Array _array;
+ private readonly Array _array;
private int _index;
- private int _endIndex; // cache array length, since it's a little slow.
+ private int _endIndex; // Cache Array.Length, since it's a little slow.
internal SZArrayEnumerator(Array array)
{
Debug.Assert(array.Rank == 1 && array.GetLowerBound(0) == 0, "SZArrayEnumerator only works on single dimension arrays w/ a lower bound of zero.");
+
_array = array;
_index = -1;
_endIndex = array.Length;
@@ -2612,8 +2613,7 @@ namespace System
//! Warning: "this" is an array, not an SZArrayHelper. See comments above
//! or you may introduce a security hole!
T[] _this = JitHelpers.UnsafeCast<T[]>(this);
- int length = _this.Length;
- return length == 0 ? SZGenericArrayEnumerator<T>.Empty : new SZGenericArrayEnumerator<T>(_this, length);
+ return _this.Length == 0 ? SZGenericArrayEnumerator<T>.Empty : new SZGenericArrayEnumerator<T>(_this);
}
// -----------------------------------------------------------
@@ -2724,54 +2724,53 @@ namespace System
//
private sealed class SZGenericArrayEnumerator<T> : IEnumerator<T>
{
- private T[] _array;
+ private readonly T[] _array;
private int _index;
- private int _endIndex; // cache array length, since it's a little slow.
- // Passing -1 for endIndex so that MoveNext always returns false without mutating _index
- internal static readonly SZGenericArrayEnumerator<T> Empty = new SZGenericArrayEnumerator<T>(null, -1);
+ // Array.Empty is intentionally omitted here, since we don't want to pay for generic instantiations that
+ // wouldn't have otherwise been used.
+ internal static readonly SZGenericArrayEnumerator<T> Empty = new SZGenericArrayEnumerator<T>(new T[0]);
- internal SZGenericArrayEnumerator(T[] array, int endIndex)
+ internal SZGenericArrayEnumerator(T[] array)
{
- // We allow passing null array in case of empty enumerator.
- Debug.Assert(array != null || endIndex == -1, "endIndex should be -1 in the case of a null array (for the empty enumerator).");
+ Debug.Assert(array != null);
+
_array = array;
_index = -1;
- _endIndex = endIndex;
}
public bool MoveNext()
{
- if (_index < _endIndex)
+ int index = _index + 1;
+ bool result = index < _array.Length;
+
+ if (result)
{
- _index++;
- return (_index < _endIndex);
+ _index = index;
}
- return false;
- }
+ return result;
+ }
+
public T Current
{
get
{
- if (_index < 0) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumNotStarted();
- if (_index >= _endIndex) ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumEnded();
- return _array[_index];
- }
- }
+ int index = _index;
+ T[] array = _array;
- object IEnumerator.Current
- {
- get
- {
- return Current;
+ if ((uint)index >= (uint)array.Length)
+ {
+ ThrowHelper.ThrowInvalidOperationException_EnumCurrent(index);
+ }
+
+ return array[index];
}
}
+
+ object IEnumerator.Current => Current;
- void IEnumerator.Reset()
- {
- _index = -1;
- }
+ void IEnumerator.Reset() => _index = -1;
public void Dispose()
{
diff --git a/src/mscorlib/src/System/Buffer.cs b/src/mscorlib/src/System/Buffer.cs
index 92b938df8c..71859ec587 100644
--- a/src/mscorlib/src/System/Buffer.cs
+++ b/src/mscorlib/src/System/Buffer.cs
@@ -2,7 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-#if AMD64 || (BIT32 && !ARM)
+#if AMD64 || ARM64 || (BIT32 && !ARM)
#define HAS_CUSTOM_BLOCKS
#endif
@@ -262,6 +262,17 @@ namespace System
{
#if AMD64 || (BIT32 && !ARM)
const nuint CopyThreshold = 2048;
+#elif ARM64
+#if PLATFORM_WINDOWS
+ // TODO-ARM64-WINDOWS-OPT determine optimal value for Windows
+ // https://github.com/dotnet/coreclr/issues/13843
+ const nuint CopyThreshold = 2048;
+#else // PLATFORM_WINDOWS
+ // Managed code is currently faster than glibc unoptimized memmove
+ // TODO-ARM64-UNIX-OPT revisit when glibc optimized memmove is in Linux distros
+ // https://github.com/dotnet/coreclr/issues/13844
+ const nuint CopyThreshold = UInt64.MaxValue;
+#endif // PLATFORM_WINDOWS
#else
const nuint CopyThreshold = 512;
#endif // AMD64 || (BIT32 && !ARM)
@@ -369,7 +380,6 @@ namespace System
{
goto PInvoke;
}
-
// Copy 64-bytes at a time until the remainder is less than 64.
// If remainder is greater than 16 bytes, then jump to MCPY00. Otherwise, unconditionally copy the last 16 bytes and return.
Debug.Assert(len > 64 && len <= CopyThreshold);
diff --git a/src/mscorlib/src/System/ByReference.cs b/src/mscorlib/src/System/ByReference.cs
index 833dab0d55..8079605bfb 100644
--- a/src/mscorlib/src/System/ByReference.cs
+++ b/src/mscorlib/src/System/ByReference.cs
@@ -3,12 +3,14 @@
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
+using System.Runtime.Versioning;
namespace System
{
// ByReference<T> is meant to be used to represent "ref T" fields. It is working
// around lack of first class support for byref fields in C# and IL. The JIT and
// type loader has special handling for it that turns it into a thin wrapper around ref T.
+ [NonVersionable]
internal struct ByReference<T>
{
private IntPtr _value;
diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs
index 436808c439..4111c5964e 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentDictionary.cs
@@ -2,9 +2,9 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-//
/*============================================================
**
+** Class: ConcurrentDictionary
**
**
** Purpose: A scalable dictionary for concurrent access
@@ -12,18 +12,13 @@
**
===========================================================*/
-using System;
-using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
-using System.Diagnostics.Contracts;
-using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
-using System.Text;
+using System.Reflection;
+using System.Runtime.CompilerServices;
using System.Threading;
-using System.Security;
namespace System.Collections.Concurrent
{
@@ -46,91 +41,78 @@ namespace System.Collections.Concurrent
/// Wrapping the three tables in a single object allows us to atomically
/// replace all tables at once.
/// </summary>
- private class Tables
+ private sealed class Tables
{
- internal readonly Node[] m_buckets; // A singly-linked list for each bucket.
- internal readonly object[] m_locks; // A set of locks, each guarding a section of the table.
- internal volatile int[] m_countPerLock; // The number of elements guarded by each lock.
- internal readonly IEqualityComparer<TKey> m_comparer; // Key equality comparer
+ internal readonly Node[] _buckets; // A singly-linked list for each bucket.
+ internal readonly object[] _locks; // A set of locks, each guarding a section of the table.
+ internal volatile int[] _countPerLock; // The number of elements guarded by each lock.
- internal Tables(Node[] buckets, object[] locks, int[] countPerLock, IEqualityComparer<TKey> comparer)
+ internal Tables(Node[] buckets, object[] locks, int[] countPerLock)
{
- m_buckets = buckets;
- m_locks = locks;
- m_countPerLock = countPerLock;
- m_comparer = comparer;
+ _buckets = buckets;
+ _locks = locks;
+ _countPerLock = countPerLock;
}
}
- private volatile Tables m_tables; // Internal tables of the dictionary
- // NOTE: this is only used for compat reasons to serialize the comparer.
- // This should not be accessed from anywhere else outside of the serialization methods.
- internal IEqualityComparer<TKey> m_comparer;
- private readonly bool m_growLockArray; // Whether to dynamically increase the size of the striped lock
-
- // How many times we resized becaused of collisions.
- // This is used to make sure we don't resize the dictionary because of multi-threaded Add() calls
- // that generate collisions. Whenever a GrowTable() should be the only place that changes this
- private int m_keyRehashCount;
-
- private int m_budget; // The maximum number of elements per lock before a resize operation is triggered
-
- // The default concurrency level is DEFAULT_CONCURRENCY_MULTIPLIER * #CPUs. The higher the
- // DEFAULT_CONCURRENCY_MULTIPLIER, the more concurrent writes can take place without interference
- // and blocking, but also the more expensive operations that require all locks become (e.g. table
- // resizing, ToArray, Count, etc). According to brief benchmarks that we ran, 4 seems like a good
- // compromise.
- private const int DEFAULT_CONCURRENCY_MULTIPLIER = 4;
+ private volatile Tables _tables; // Internal tables of the dictionary
+ private IEqualityComparer<TKey> _comparer; // Key equality comparer
+ private readonly bool _growLockArray; // Whether to dynamically increase the size of the striped lock
+ private int _budget; // The maximum number of elements per lock before a resize operation is triggered
// The default capacity, i.e. the initial # of buckets. When choosing this value, we are making
// a trade-off between the size of a very small dictionary, and the number of resizes when
// constructing a large dictionary. Also, the capacity should not be divisible by a small prime.
- private const int DEFAULT_CAPACITY = 31;
+ private const int DefaultCapacity = 31;
// The maximum size of the striped lock that will not be exceeded when locks are automatically
// added as the dictionary grows. However, the user is allowed to exceed this limit by passing
- // a concurrency level larger than MAX_LOCK_NUMBER into the constructor.
- private const int MAX_LOCK_NUMBER = 1024;
+ // a concurrency level larger than MaxLockNumber into the constructor.
+ private const int MaxLockNumber = 1024;
// Whether TValue is a type that can be written atomically (i.e., with no danger of torn reads)
private static readonly bool s_isValueWriteAtomic = IsValueWriteAtomic();
-
/// <summary>
/// Determines whether type TValue can be written atomically
/// </summary>
private static bool IsValueWriteAtomic()
{
- Type valueType = typeof(TValue);
- if (valueType.IsEnum)
- {
- valueType = Enum.GetUnderlyingType(valueType);
- }
-
//
// Section 12.6.6 of ECMA CLI explains which types can be read and written atomically without
// the risk of tearing.
//
// See http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-335.pdf
//
- bool isAtomic =
- (valueType.IsClass)
- || valueType == typeof(Boolean)
- || valueType == typeof(Char)
- || valueType == typeof(Byte)
- || valueType == typeof(SByte)
- || valueType == typeof(Int16)
- || valueType == typeof(UInt16)
- || valueType == typeof(Int32)
- || valueType == typeof(UInt32)
- || valueType == typeof(Single);
-
- if (!isAtomic && IntPtr.Size == 8)
+ Type valueType = typeof(TValue);
+ if (!valueType.IsValueType)
+ {
+ return true;
+ }
+ if (valueType.IsEnum)
{
- isAtomic |= valueType == typeof(Double) || valueType == typeof(Int64);
+ valueType = Enum.GetUnderlyingType(valueType);
}
- return isAtomic;
+ switch (Type.GetTypeCode(valueType))
+ {
+ case TypeCode.Boolean:
+ case TypeCode.Byte:
+ case TypeCode.Char:
+ case TypeCode.Int16:
+ case TypeCode.Int32:
+ case TypeCode.SByte:
+ case TypeCode.Single:
+ case TypeCode.UInt16:
+ case TypeCode.UInt32:
+ return true;
+ case TypeCode.Int64:
+ case TypeCode.Double:
+ case TypeCode.UInt64:
+ return IntPtr.Size == 8;
+ default:
+ return false;
+ }
}
/// <summary>
@@ -139,7 +121,7 @@ namespace System.Collections.Concurrent
/// class that is empty, has the default concurrency level, has the default initial capacity, and
/// uses the default comparer for the key type.
/// </summary>
- public ConcurrentDictionary() : this(DefaultConcurrencyLevel, DEFAULT_CAPACITY, true, EqualityComparer<TKey>.Default) { }
+ public ConcurrentDictionary() : this(DefaultConcurrencyLevel, DefaultCapacity, true, null) { }
internal ConcurrentDictionary(int concurrencyLevel, int capacity, bool growLockArray, IEqualityComparer<TKey> comparer)
{
@@ -151,7 +133,6 @@ namespace System.Collections.Concurrent
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ConcurrentDictionary_CapacityMustNotBeNegative);
}
- if (comparer == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.comparer);
// The capacity should be at least as large as the concurrency level. Otherwise, we would have locks that don't guard
// any buckets.
@@ -168,13 +149,13 @@ namespace System.Collections.Concurrent
int[] countPerLock = new int[locks.Length];
Node[] buckets = new Node[capacity];
- m_tables = new Tables(buckets, locks, countPerLock, comparer);
+ _tables = new Tables(buckets, locks, countPerLock);
- m_growLockArray = growLockArray;
- m_budget = buckets.Length / locks.Length;
+ _comparer = comparer ?? EqualityComparer<TKey>.Default;
+ _growLockArray = growLockArray;
+ _budget = buckets.Length / locks.Length;
}
-
/// <summary>
/// Attempts to add the specified key and value to the <see cref="ConcurrentDictionary{TKey,
/// TValue}"/>.
@@ -191,9 +172,9 @@ namespace System.Collections.Concurrent
/// contains too many elements.</exception>
public bool TryAdd(TKey key, TValue value)
{
- if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ if (key == null) ThrowKeyNullException();
TValue dummy;
- return TryAddInternal(key, value, false, true, out dummy);
+ return TryAddInternal(key, _comparer.GetHashCode(key), value, false, true, out dummy);
}
/// <summary>
@@ -208,14 +189,14 @@ namespace System.Collections.Concurrent
/// (Nothing in Visual Basic).</exception>
public bool ContainsKey(TKey key)
{
- if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ if (key == null) ThrowKeyNullException();
TValue throwAwayValue;
return TryGetValue(key, out throwAwayValue);
}
/// <summary>
- /// Attempts to remove and return the the value with the specified key from the
+ /// Attempts to remove and return the value with the specified key from the
/// <see cref="ConcurrentDictionary{TKey, TValue}"/>.
/// </summary>
/// <param name="key">The key of the element to remove and return.</param>
@@ -228,7 +209,7 @@ namespace System.Collections.Concurrent
/// (Nothing in Visual Basic).</exception>
public bool TryRemove(TKey key, out TValue value)
{
- if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ if (key == null) ThrowKeyNullException();
return TryRemoveInternal(key, out value, false, default(TValue));
}
@@ -246,34 +227,33 @@ namespace System.Collections.Concurrent
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
private bool TryRemoveInternal(TKey key, out TValue value, bool matchValue, TValue oldValue)
{
+ int hashcode = _comparer.GetHashCode(key);
while (true)
{
- Tables tables = m_tables;
-
- IEqualityComparer<TKey> comparer = tables.m_comparer;
+ Tables tables = _tables;
int bucketNo, lockNo;
- GetBucketAndLockNo(comparer.GetHashCode(key), out bucketNo, out lockNo, tables.m_buckets.Length, tables.m_locks.Length);
+ GetBucketAndLockNo(hashcode, out bucketNo, out lockNo, tables._buckets.Length, tables._locks.Length);
- lock (tables.m_locks[lockNo])
+ lock (tables._locks[lockNo])
{
// If the table just got resized, we may not be holding the right lock, and must retry.
- // This should be a rare occurence.
- if (tables != m_tables)
+ // This should be a rare occurrence.
+ if (tables != _tables)
{
continue;
}
Node prev = null;
- for (Node curr = tables.m_buckets[bucketNo]; curr != null; curr = curr.m_next)
+ for (Node curr = tables._buckets[bucketNo]; curr != null; curr = curr._next)
{
- Assert((prev == null && curr == tables.m_buckets[bucketNo]) || prev.m_next == curr);
+ Debug.Assert((prev == null && curr == tables._buckets[bucketNo]) || prev._next == curr);
- if (comparer.Equals(curr.m_key, key))
+ if (hashcode == curr._hashcode && _comparer.Equals(curr._key, key))
{
if (matchValue)
{
- bool valuesMatch = EqualityComparer<TValue>.Default.Equals(oldValue, curr.m_value);
+ bool valuesMatch = EqualityComparer<TValue>.Default.Equals(oldValue, curr._value);
if (!valuesMatch)
{
value = default(TValue);
@@ -283,15 +263,15 @@ namespace System.Collections.Concurrent
if (prev == null)
{
- Volatile.Write<Node>(ref tables.m_buckets[bucketNo], curr.m_next);
+ Volatile.Write<Node>(ref tables._buckets[bucketNo], curr._next);
}
else
{
- prev.m_next = curr.m_next;
+ prev._next = curr._next;
}
- value = curr.m_value;
- tables.m_countPerLock[lockNo]--;
+ value = curr._value;
+ tables._countPerLock[lockNo]--;
return true;
}
prev = curr;
@@ -319,27 +299,32 @@ namespace System.Collections.Concurrent
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
public bool TryGetValue(TKey key, out TValue value)
{
- if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ if (key == null) ThrowKeyNullException();
+ return TryGetValueInternal(key, _comparer.GetHashCode(key), out value);
+ }
- int bucketNo, lockNoUnused;
+ private bool TryGetValueInternal(TKey key, int hashcode, out TValue value)
+ {
+ Debug.Assert(_comparer.GetHashCode(key) == hashcode);
+
+ // We must capture the _buckets field in a local variable. It is set to a new table on each table resize.
+ Tables tables = _tables;
- // We must capture the m_buckets field in a local variable. It is set to a new table on each table resize.
- Tables tables = m_tables;
- IEqualityComparer<TKey> comparer = tables.m_comparer;
- GetBucketAndLockNo(comparer.GetHashCode(key), out bucketNo, out lockNoUnused, tables.m_buckets.Length, tables.m_locks.Length);
+ int bucketNo = GetBucket(hashcode, tables._buckets.Length);
// We can get away w/out a lock here.
- // The Volatile.Read ensures that the load of the fields of 'n' doesn't move before the load from buckets[i].
- Node n = Volatile.Read<Node>(ref tables.m_buckets[bucketNo]);
+ // The Volatile.Read ensures that we have a copy of the reference to tables._buckets[bucketNo].
+ // This protects us from reading fields ('_hashcode', '_key', '_value' and '_next') of different instances.
+ Node n = Volatile.Read<Node>(ref tables._buckets[bucketNo]);
while (n != null)
{
- if (comparer.Equals(n.m_key, key))
+ if (hashcode == n._hashcode && _comparer.Equals(n._key, key))
{
- value = n.m_value;
+ value = n._value;
return true;
}
- n = n.m_next;
+ n = n._next;
}
value = default(TValue);
@@ -356,9 +341,9 @@ namespace System.Collections.Concurrent
{
AcquireAllLocks(ref locksAcquired);
- Tables newTables = new Tables(new Node[DEFAULT_CAPACITY], m_tables.m_locks, new int[m_tables.m_countPerLock.Length], m_tables.m_comparer);
- m_tables = newTables;
- m_budget = Math.Max(1, newTables.m_buckets.Length / newTables.m_locks.Length);
+ Tables newTables = new Tables(new Node[DefaultCapacity], _tables._locks, new int[_tables._countPerLock.Length]);
+ _tables = newTables;
+ _budget = Math.Max(1, newTables._buckets.Length / newTables._locks.Length);
}
finally
{
@@ -400,9 +385,9 @@ namespace System.Collections.Concurrent
int count = 0;
- for (int i = 0; i < m_tables.m_locks.Length && count >= 0; i++)
+ for (int i = 0; i < _tables._locks.Length && count >= 0; i++)
{
- count += m_tables.m_countPerLock[i];
+ count += _tables._countPerLock[i];
}
if (array.Length - count < index || count < 0) //"count" itself or "count + index" can overflow
@@ -434,14 +419,18 @@ namespace System.Collections.Concurrent
int count = 0;
checked
{
- for (int i = 0; i < m_tables.m_locks.Length; i++)
+ for (int i = 0; i < _tables._locks.Length; i++)
{
- count += m_tables.m_countPerLock[i];
+ count += _tables._countPerLock[i];
}
}
- KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[count];
+ if (count == 0)
+ {
+ return Array.Empty<KeyValuePair<TKey, TValue>>();
+ }
+ KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[count];
CopyToPairs(array, 0);
return array;
}
@@ -454,16 +443,16 @@ namespace System.Collections.Concurrent
/// <summary>
/// Copy dictionary contents to an array - shared implementation between ToArray and CopyTo.
///
- /// Important: the caller must hold all locks in m_locks before calling CopyToPairs.
+ /// Important: the caller must hold all locks in _locks before calling CopyToPairs.
/// </summary>
private void CopyToPairs(KeyValuePair<TKey, TValue>[] array, int index)
{
- Node[] buckets = m_tables.m_buckets;
+ Node[] buckets = _tables._buckets;
for (int i = 0; i < buckets.Length; i++)
{
- for (Node current = buckets[i]; current != null; current = current.m_next)
+ for (Node current = buckets[i]; current != null; current = current._next)
{
- array[index] = new KeyValuePair<TKey, TValue>(current.m_key, current.m_value);
+ array[index] = new KeyValuePair<TKey, TValue>(current._key, current._value);
index++; //this should never flow, CopyToPairs is only called when there's no overflow risk
}
}
@@ -472,16 +461,16 @@ namespace System.Collections.Concurrent
/// <summary>
/// Copy dictionary contents to an array - shared implementation between ToArray and CopyTo.
///
- /// Important: the caller must hold all locks in m_locks before calling CopyToEntries.
+ /// Important: the caller must hold all locks in _locks before calling CopyToEntries.
/// </summary>
private void CopyToEntries(DictionaryEntry[] array, int index)
{
- Node[] buckets = m_tables.m_buckets;
+ Node[] buckets = _tables._buckets;
for (int i = 0; i < buckets.Length; i++)
{
- for (Node current = buckets[i]; current != null; current = current.m_next)
+ for (Node current = buckets[i]; current != null; current = current._next)
{
- array[index] = new DictionaryEntry(current.m_key, current.m_value);
+ array[index] = new DictionaryEntry(current._key, current._value);
index++; //this should never flow, CopyToEntries is only called when there's no overflow risk
}
}
@@ -490,16 +479,16 @@ namespace System.Collections.Concurrent
/// <summary>
/// Copy dictionary contents to an array - shared implementation between ToArray and CopyTo.
///
- /// Important: the caller must hold all locks in m_locks before calling CopyToObjects.
+ /// Important: the caller must hold all locks in _locks before calling CopyToObjects.
/// </summary>
private void CopyToObjects(object[] array, int index)
{
- Node[] buckets = m_tables.m_buckets;
+ Node[] buckets = _tables._buckets;
for (int i = 0; i < buckets.Length; i++)
{
- for (Node current = buckets[i]; current != null; current = current.m_next)
+ for (Node current = buckets[i]; current != null; current = current._next)
{
- array[index] = new KeyValuePair<TKey, TValue>(current.m_key, current.m_value);
+ array[index] = new KeyValuePair<TKey, TValue>(current._key, current._value);
index++; //this should never flow, CopyToObjects is only called when there's no overflow risk
}
}
@@ -516,17 +505,18 @@ namespace System.Collections.Concurrent
/// </remarks>
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
- Node[] buckets = m_tables.m_buckets;
+ Node[] buckets = _tables._buckets;
for (int i = 0; i < buckets.Length; i++)
{
- // The Volatile.Read ensures that the load of the fields of 'current' doesn't move before the load from buckets[i].
+ // The Volatile.Read ensures that we have a copy of the reference to buckets[i].
+ // This protects us from reading fields ('_key', '_value' and '_next') of different instances.
Node current = Volatile.Read<Node>(ref buckets[i]);
while (current != null)
{
- yield return new KeyValuePair<TKey, TValue>(current.m_key, current.m_value);
- current = current.m_next;
+ yield return new KeyValuePair<TKey, TValue>(current._key, current._value);
+ current = current._next;
}
}
}
@@ -537,39 +527,37 @@ namespace System.Collections.Concurrent
/// If key doesn't exist, we always add value and return true;
/// </summary>
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
- private bool TryAddInternal(TKey key, TValue value, bool updateIfExists, bool acquireLock, out TValue resultingValue)
+ private bool TryAddInternal(TKey key, int hashcode, TValue value, bool updateIfExists, bool acquireLock, out TValue resultingValue)
{
+ Debug.Assert(_comparer.GetHashCode(key) == hashcode);
+
while (true)
{
int bucketNo, lockNo;
- int hashcode;
- Tables tables = m_tables;
- IEqualityComparer<TKey> comparer = tables.m_comparer;
- hashcode = comparer.GetHashCode(key);
- GetBucketAndLockNo(hashcode, out bucketNo, out lockNo, tables.m_buckets.Length, tables.m_locks.Length);
+ Tables tables = _tables;
+ GetBucketAndLockNo(hashcode, out bucketNo, out lockNo, tables._buckets.Length, tables._locks.Length);
bool resizeDesired = false;
bool lockTaken = false;
-
try
{
if (acquireLock)
- Monitor.Enter(tables.m_locks[lockNo], ref lockTaken);
+ Monitor.Enter(tables._locks[lockNo], ref lockTaken);
// If the table just got resized, we may not be holding the right lock, and must retry.
- // This should be a rare occurence.
- if (tables != m_tables)
+ // This should be a rare occurrence.
+ if (tables != _tables)
{
continue;
}
// Try to find this key in the bucket
Node prev = null;
- for (Node node = tables.m_buckets[bucketNo]; node != null; node = node.m_next)
+ for (Node node = tables._buckets[bucketNo]; node != null; node = node._next)
{
- Assert((prev == null && node == tables.m_buckets[bucketNo]) || prev.m_next == node);
- if (comparer.Equals(node.m_key, key))
+ Debug.Assert((prev == null && node == tables._buckets[bucketNo]) || prev._next == node);
+ if (hashcode == node._hashcode && _comparer.Equals(node._key, key))
{
// The key was found in the dictionary. If updates are allowed, update the value for that key.
// We need to create a new node for the update, in order to support TValue types that cannot
@@ -578,25 +566,25 @@ namespace System.Collections.Concurrent
{
if (s_isValueWriteAtomic)
{
- node.m_value = value;
+ node._value = value;
}
else
{
- Node newNode = new Node(node.m_key, value, hashcode, node.m_next);
+ Node newNode = new Node(node._key, value, hashcode, node._next);
if (prev == null)
{
- tables.m_buckets[bucketNo] = newNode;
+ Volatile.Write(ref tables._buckets[bucketNo], newNode);
}
else
{
- prev.m_next = newNode;
+ prev._next = newNode;
}
}
resultingValue = value;
}
else
{
- resultingValue = node.m_value;
+ resultingValue = node._value;
}
return false;
}
@@ -604,10 +592,10 @@ namespace System.Collections.Concurrent
}
// The key was not found in the bucket. Insert the key-value pair.
- Volatile.Write<Node>(ref tables.m_buckets[bucketNo], new Node(key, value, hashcode, tables.m_buckets[bucketNo]));
+ Volatile.Write<Node>(ref tables._buckets[bucketNo], new Node(key, value, hashcode, tables._buckets[bucketNo]));
checked
{
- tables.m_countPerLock[lockNo]++;
+ tables._countPerLock[lockNo]++;
}
//
@@ -615,7 +603,7 @@ namespace System.Collections.Concurrent
// It is also possible that GrowTable will increase the budget but won't resize the bucket table.
// That happens if the bucket table is found to be poorly utilized due to a bad hash function.
//
- if (tables.m_countPerLock[lockNo] > m_budget)
+ if (tables._countPerLock[lockNo] > _budget)
{
resizeDesired = true;
}
@@ -623,7 +611,7 @@ namespace System.Collections.Concurrent
finally
{
if (lockTaken)
- Monitor.Exit(tables.m_locks[lockNo]);
+ Monitor.Exit(tables._locks[lockNo]);
}
//
@@ -636,11 +624,7 @@ namespace System.Collections.Concurrent
//
if (resizeDesired)
{
-#if FEATURE_RANDOMIZED_STRING_HASHING
- GrowTable(tables, tables.m_comparer, false, m_keyRehashCount);
-#else
- GrowTable(tables, tables.m_comparer, false, m_keyRehashCount);
-#endif
+ GrowTable(tables);
}
resultingValue = value;
@@ -654,7 +638,7 @@ namespace System.Collections.Concurrent
/// <param name="key">The key of the value to get or set.</param>
/// <value>The value associated with the specified key. If the specified key is not found, a get
/// operation throws a
- /// <see cref="T:Sytem.Collections.Generic.KeyNotFoundException"/>, and a set operation creates a new
+ /// <see cref="T:System.Collections.Generic.KeyNotFoundException"/>, and a set operation creates a new
/// element with the specified key.</value>
/// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null reference
/// (Nothing in Visual Basic).</exception>
@@ -668,25 +652,41 @@ namespace System.Collections.Concurrent
TValue value;
if (!TryGetValue(key, out value))
{
- ThrowHelper.ThrowKeyNotFoundException();
+ ThrowKeyNotFoundException();
}
return value;
}
set
{
- if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ if (key == null) ThrowKeyNullException();
TValue dummy;
- TryAddInternal(key, value, true, true, out dummy);
+ TryAddInternal(key, _comparer.GetHashCode(key), value, true, true, out dummy);
}
}
+ // These exception throwing sites have been extracted into their own NoInlining methods
+ // as these are uncommonly needed and when inlined are observed to prevent the inlining
+ // of important methods like TryGetValue and ContainsKey.
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void ThrowKeyNotFoundException()
+ {
+ throw new KeyNotFoundException();
+ }
+
+ [MethodImpl(MethodImplOptions.NoInlining)]
+ private static void ThrowKeyNullException()
+ {
+ throw new ArgumentNullException("key");
+ }
+
/// <summary>
/// Gets the number of key/value pairs contained in the <see
/// cref="ConcurrentDictionary{TKey,TValue}"/>.
/// </summary>
/// <exception cref="T:System.OverflowException">The dictionary contains too many
/// elements.</exception>
- /// <value>The number of key/value paris contained in the <see
+ /// <value>The number of key/value pairs contained in the <see
/// cref="ConcurrentDictionary{TKey,TValue}"/>.</value>
/// <remarks>Count has snapshot semantics and represents the number of items in the <see
/// cref="ConcurrentDictionary{TKey,TValue}"/>
@@ -696,31 +696,46 @@ namespace System.Collections.Concurrent
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "ConcurrencyCop just doesn't know about these locks")]
get
{
- int count = 0;
-
int acquiredLocks = 0;
try
{
// Acquire all locks
AcquireAllLocks(ref acquiredLocks);
- // Compute the count, we allow overflow
- for (int i = 0; i < m_tables.m_countPerLock.Length; i++)
- {
- count += m_tables.m_countPerLock[i];
- }
+ return GetCountInternal();
}
finally
{
// Release locks that have been acquired earlier
ReleaseLocks(0, acquiredLocks);
}
-
- return count;
}
}
+ /// <summary>
+ /// Gets the number of key/value pairs contained in the <see
+ /// cref="ConcurrentDictionary{TKey,TValue}"/>. Should only be used after all locks
+ /// have been acquired.
+ /// </summary>
+ /// <exception cref="T:System.OverflowException">The dictionary contains too many
+ /// elements.</exception>
+ /// <value>The number of key/value pairs contained in the <see
+ /// cref="ConcurrentDictionary{TKey,TValue}"/>.</value>
+ /// <remarks>Count has snapshot semantics and represents the number of items in the <see
+ /// cref="ConcurrentDictionary{TKey,TValue}"/>
+ /// at the moment when Count was accessed.</remarks>
+ private int GetCountInternal()
+ {
+ int count = 0;
+
+ // Compute the count, we allow overflow
+ for (int i = 0; i < _tables._countPerLock.Length; i++)
+ {
+ count += _tables._countPerLock[i];
+ }
+ return count;
+ }
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentDictionary{TKey,TValue}"/> is empty.
@@ -738,9 +753,9 @@ namespace System.Collections.Concurrent
// Acquire all locks
AcquireAllLocks(ref acquiredLocks);
- for (int i = 0; i < m_tables.m_countPerLock.Length; i++)
+ for (int i = 0; i < _tables._countPerLock.Length; i++)
{
- if (m_tables.m_countPerLock[i] != 0)
+ if (_tables._countPerLock[i] != 0)
{
return false;
}
@@ -775,7 +790,7 @@ namespace System.Collections.Concurrent
{
if (!TryAdd(key, value))
{
- ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_KeyAlreadyExisted);
+ ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_KeyAlreadyExisted, ExceptionArgument.key);
}
}
@@ -908,7 +923,8 @@ namespace System.Collections.Concurrent
/// name="keyValuePair"/> is a null reference (Nothing in Visual Basic).</exception>
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
- if (keyValuePair.Key == null) ThrowHelper.ThrowArgumentNullException(ExceptionResource.ConcurrentDictionary_ItemKeyIsNull);
+ if (keyValuePair.Key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.keyValuePair, ExceptionResource.ConcurrentDictionary_ItemKeyIsNull);
+
TValue throwAwayValue;
return TryRemoveInternal(keyValuePair.Key, out throwAwayValue, true, keyValuePair.Value);
}
@@ -954,17 +970,18 @@ namespace System.Collections.Concurrent
/// </exception>
void IDictionary.Add(object key, object value)
{
- if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
- if (!(key is TKey)) ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_TypeOfKeyIncorrect);
+ if (key == null) ThrowKeyNullException();
+ if (!(key is TKey)) ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_TypeOfKeyIncorrect, ExceptionArgument.key);
- TValue typedValue = default(TValue);
+ TValue typedValue;
try
{
typedValue = (TValue)value;
}
catch (InvalidCastException)
{
- ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_TypeOfValueIncorrect);
+ ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_TypeOfValueIncorrect, ExceptionArgument.value);
+ return;
}
((IDictionary<TKey, TValue>)this).Add((TKey)key, typedValue);
@@ -982,9 +999,9 @@ namespace System.Collections.Concurrent
/// (Nothing in Visual Basic).</exception>
bool IDictionary.Contains(object key)
{
- if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ if (key == null) ThrowKeyNullException();
- return (key is TKey) && ((ConcurrentDictionary<TKey, TValue>)this).ContainsKey((TKey)key);
+ return (key is TKey) && this.ContainsKey((TKey)key);
}
/// <summary>Provides an <see cref="T:System.Collections.Generics.IDictionaryEnumerator"/> for the
@@ -1042,12 +1059,12 @@ namespace System.Collections.Concurrent
/// (Nothing in Visual Basic).</exception>
void IDictionary.Remove(object key)
{
- if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ if (key == null) ThrowKeyNullException();
TValue throwAwayValue;
if (key is TKey)
{
- this.TryRemove((TKey)key, out throwAwayValue);
+ TryRemove((TKey)key, out throwAwayValue);
}
}
@@ -1084,10 +1101,10 @@ namespace System.Collections.Concurrent
{
get
{
- if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ if (key == null) ThrowKeyNullException();
TValue value;
- if (key is TKey && this.TryGetValue((TKey)key, out value))
+ if (key is TKey && TryGetValue((TKey)key, out value))
{
return value;
}
@@ -1096,10 +1113,10 @@ namespace System.Collections.Concurrent
}
set
{
- if (key == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
+ if (key == null) ThrowKeyNullException();
- if (!(key is TKey)) ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_TypeOfKeyIncorrect);
- if (!(value is TValue)) ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_TypeOfValueIncorrect);
+ if (!(key is TKey)) ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_TypeOfKeyIncorrect, ExceptionArgument.key);
+ if (!(value is TValue)) ThrowHelper.ThrowArgumentException(ExceptionResource.ConcurrentDictionary_TypeOfValueIncorrect, ExceptionArgument.value);
((ConcurrentDictionary<TKey, TValue>)this)[(TKey)key] = (TValue)value;
}
@@ -1137,13 +1154,13 @@ namespace System.Collections.Concurrent
try
{
AcquireAllLocks(ref locksAcquired);
- Tables tables = m_tables;
+ Tables tables = _tables;
int count = 0;
- for (int i = 0; i < tables.m_locks.Length && count >= 0; i++)
+ for (int i = 0; i < tables._locks.Length && count >= 0; i++)
{
- count += tables.m_countPerLock[i];
+ count += tables._countPerLock[i];
}
if (array.Length - count < index || count < 0) //"count" itself or "count + index" can overflow
@@ -1217,62 +1234,49 @@ namespace System.Collections.Concurrent
/// <summary>
/// Replaces the bucket table with a larger one. To prevent multiple threads from resizing the
- /// table as a result of a race condition, the Tables instance that holds the table of buckets deemed too
+ /// table as a result of races, the Tables instance that holds the table of buckets deemed too
/// small is passed in as an argument to GrowTable(). GrowTable() obtains a lock, and then checks
- /// the Tables instance has been replaced in the meantime or not.
- /// The <paramref name="rehashCount"/> will be used to ensure that we don't do two subsequent resizes
- /// because of a collision
+ /// the Tables instance has been replaced in the meantime or not.
/// </summary>
- private void GrowTable(Tables tables, IEqualityComparer<TKey> newComparer, bool regenerateHashKeys, int rehashCount)
+ private void GrowTable(Tables tables)
{
+ const int MaxArrayLength = 0X7FEFFFFF;
int locksAcquired = 0;
try
{
- // The thread that first obtains m_locks[0] will be the one doing the resize operation
+ // The thread that first obtains _locks[0] will be the one doing the resize operation
AcquireLocks(0, 1, ref locksAcquired);
- if (regenerateHashKeys && rehashCount == m_keyRehashCount)
+ // Make sure nobody resized the table while we were waiting for lock 0:
+ if (tables != _tables)
{
- // This method is called with regenerateHashKeys==true when we detected
- // more than HashHelpers.HashCollisionThreshold collisions when adding a new element.
- // In that case we are in the process of switching to another (randomized) comparer
- // and we have to re-hash all the keys in the table.
- // We are only going to do this if we did not just rehash the entire table while waiting for the lock
- tables = m_tables;
+ // We assume that since the table reference is different, it was already resized (or the budget
+ // was adjusted). If we ever decide to do table shrinking, or replace the table for other reasons,
+ // we will have to revisit this logic.
+ return;
}
- else
+
+ // Compute the (approx.) total size. Use an Int64 accumulation variable to avoid an overflow.
+ long approxCount = 0;
+ for (int i = 0; i < tables._countPerLock.Length; i++)
{
- // If we don't require a regeneration of hash keys we want to make sure we don't do work when
- // we don't have to
- if (tables != m_tables)
- {
- // We assume that since the table reference is different, it was already resized (or the budget
- // was adjusted). If we ever decide to do table shrinking, or replace the table for other reasons,
- // we will have to revisit this logic.
- return;
- }
+ approxCount += tables._countPerLock[i];
+ }
- // Compute the (approx.) total size. Use an Int64 accumulation variable to avoid an overflow.
- long approxCount = 0;
- for (int i = 0; i < tables.m_countPerLock.Length; i++)
+ //
+ // If the bucket array is too empty, double the budget instead of resizing the table
+ //
+ if (approxCount < tables._buckets.Length / 4)
+ {
+ _budget = 2 * _budget;
+ if (_budget < 0)
{
- approxCount += tables.m_countPerLock[i];
+ _budget = int.MaxValue;
}
+ return;
+ }
- //
- // If the bucket array is too empty, double the budget instead of resizing the table
- //
- if (approxCount < tables.m_buckets.Length / 4)
- {
- m_budget = 2 * m_budget;
- if (m_budget < 0)
- {
- m_budget = int.MaxValue;
- }
- return;
- }
- }
// Compute the new table size. We find the smallest integer larger than twice the previous table size, and not divisible by
// 2,3,5 or 7. We can consider a different table-sizing policy in the future.
int newLength = 0;
@@ -1282,7 +1286,7 @@ namespace System.Collections.Concurrent
checked
{
// Double the size of the buckets table and add one, so that we have an odd integer.
- newLength = tables.m_buckets.Length * 2 + 1;
+ newLength = tables._buckets.Length * 2 + 1;
// Now, we only need to check odd integers, and find the first that is not divisible
// by 3, 5 or 7.
@@ -1291,9 +1295,9 @@ namespace System.Collections.Concurrent
newLength += 2;
}
- Assert(newLength % 2 != 0);
+ Debug.Assert(newLength % 2 != 0);
- if (newLength > Array.MaxArrayLength)
+ if (newLength > MaxArrayLength)
{
maximizeTableSize = true;
}
@@ -1306,28 +1310,27 @@ namespace System.Collections.Concurrent
if (maximizeTableSize)
{
- newLength = Array.MaxArrayLength;
+ newLength = MaxArrayLength;
// We want to make sure that GrowTable will not be called again, since table is at the maximum size.
// To achieve that, we set the budget to int.MaxValue.
//
// (There is one special case that would allow GrowTable() to be called in the future:
// calling Clear() on the ConcurrentDictionary will shrink the table and lower the budget.)
- m_budget = int.MaxValue;
+ _budget = int.MaxValue;
}
// Now acquire all other locks for the table
- AcquireLocks(1, tables.m_locks.Length, ref locksAcquired);
+ AcquireLocks(1, tables._locks.Length, ref locksAcquired);
- object[] newLocks = tables.m_locks;
+ object[] newLocks = tables._locks;
// Add more locks
- if (m_growLockArray && tables.m_locks.Length < MAX_LOCK_NUMBER)
+ if (_growLockArray && tables._locks.Length < MaxLockNumber)
{
- newLocks = new object[tables.m_locks.Length * 2];
- Array.Copy(tables.m_locks, newLocks, tables.m_locks.Length);
-
- for (int i = tables.m_locks.Length; i < newLocks.Length; i++)
+ newLocks = new object[tables._locks.Length * 2];
+ Array.Copy(tables._locks, 0, newLocks, 0, tables._locks.Length);
+ for (int i = tables._locks.Length; i < newLocks.Length; i++)
{
newLocks[i] = new object();
}
@@ -1337,24 +1340,16 @@ namespace System.Collections.Concurrent
int[] newCountPerLock = new int[newLocks.Length];
// Copy all data into a new table, creating new nodes for all elements
- for (int i = 0; i < tables.m_buckets.Length; i++)
+ for (int i = 0; i < tables._buckets.Length; i++)
{
- Node current = tables.m_buckets[i];
+ Node current = tables._buckets[i];
while (current != null)
{
- Node next = current.m_next;
+ Node next = current._next;
int newBucketNo, newLockNo;
- int nodeHashCode = current.m_hashcode;
-
- if (regenerateHashKeys)
- {
- // Recompute the hash from the key
- nodeHashCode = newComparer.GetHashCode(current.m_key);
- }
-
- GetBucketAndLockNo(nodeHashCode, out newBucketNo, out newLockNo, newBuckets.Length, newLocks.Length);
+ GetBucketAndLockNo(current._hashcode, out newBucketNo, out newLockNo, newBuckets.Length, newLocks.Length);
- newBuckets[newBucketNo] = new Node(current.m_key, current.m_value, nodeHashCode, newBuckets[newBucketNo]);
+ newBuckets[newBucketNo] = new Node(current._key, current._value, current._hashcode, newBuckets[newBucketNo]);
checked
{
@@ -1365,22 +1360,11 @@ namespace System.Collections.Concurrent
}
}
- // If this resize regenerated the hashkeys, increment the count
- if (regenerateHashKeys)
- {
- // We use unchecked here because we don't want to throw an exception if
- // an overflow happens
- unchecked
- {
- m_keyRehashCount++;
- }
- }
-
// Adjust the budget
- m_budget = Math.Max(1, newBuckets.Length / newLocks.Length);
+ _budget = Math.Max(1, newBuckets.Length / newLocks.Length);
// Replace tables with the new versions
- m_tables = new Tables(newBuckets, newLocks, newCountPerLock, newComparer);
+ _tables = new Tables(newBuckets, newLocks, newCountPerLock);
}
finally
{
@@ -1390,16 +1374,25 @@ namespace System.Collections.Concurrent
}
/// <summary>
+ /// Computes the bucket for a particular key.
+ /// </summary>
+ private static int GetBucket(int hashcode, int bucketCount)
+ {
+ int bucketNo = (hashcode & 0x7fffffff) % bucketCount;
+ Debug.Assert(bucketNo >= 0 && bucketNo < bucketCount);
+ return bucketNo;
+ }
+
+ /// <summary>
/// Computes the bucket and lock number for a particular key.
/// </summary>
- private void GetBucketAndLockNo(
- int hashcode, out int bucketNo, out int lockNo, int bucketCount, int lockCount)
+ private static void GetBucketAndLockNo(int hashcode, out int bucketNo, out int lockNo, int bucketCount, int lockCount)
{
bucketNo = (hashcode & 0x7fffffff) % bucketCount;
lockNo = bucketNo % lockCount;
- Assert(bucketNo >= 0 && bucketNo < bucketCount);
- Assert(lockNo >= 0 && lockNo < lockCount);
+ Debug.Assert(bucketNo >= 0 && bucketNo < bucketCount);
+ Debug.Assert(lockNo >= 0 && lockNo < lockCount);
}
/// <summary>
@@ -1407,7 +1400,7 @@ namespace System.Collections.Concurrent
/// </summary>
private static int DefaultConcurrencyLevel
{
- get { return DEFAULT_CONCURRENCY_MULTIPLIER * PlatformHelper.ProcessorCount; }
+ get { return PlatformHelper.ProcessorCount; }
}
/// <summary>
@@ -1420,10 +1413,10 @@ namespace System.Collections.Concurrent
// First, acquire lock 0
AcquireLocks(0, 1, ref locksAcquired);
- // Now that we have lock 0, the m_locks array will not change (i.e., grow),
- // and so we can safely read m_locks.Length.
- AcquireLocks(1, m_tables.m_locks.Length, ref locksAcquired);
- Assert(locksAcquired == m_tables.m_locks.Length);
+ // Now that we have lock 0, the _locks array will not change (i.e., grow),
+ // and so we can safely read _locks.Length.
+ AcquireLocks(1, _tables._locks.Length, ref locksAcquired);
+ Debug.Assert(locksAcquired == _tables._locks.Length);
}
/// <summary>
@@ -1433,8 +1426,8 @@ namespace System.Collections.Concurrent
/// </summary>
private void AcquireLocks(int fromInclusive, int toExclusive, ref int locksAcquired)
{
- Assert(fromInclusive <= toExclusive);
- object[] locks = m_tables.m_locks;
+ Debug.Assert(fromInclusive <= toExclusive);
+ object[] locks = _tables._locks;
for (int i = fromInclusive; i < toExclusive; i++)
{
@@ -1459,11 +1452,11 @@ namespace System.Collections.Concurrent
[SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "Reviewed for thread safety")]
private void ReleaseLocks(int fromInclusive, int toExclusive)
{
- Assert(fromInclusive <= toExclusive);
+ Debug.Assert(fromInclusive <= toExclusive);
for (int i = fromInclusive; i < toExclusive; i++)
{
- Monitor.Exit(m_tables.m_locks[i]);
+ Monitor.Exit(_tables._locks[i]);
}
}
@@ -1477,15 +1470,18 @@ namespace System.Collections.Concurrent
try
{
AcquireAllLocks(ref locksAcquired);
- List<TKey> keys = new List<TKey>();
- for (int i = 0; i < m_tables.m_buckets.Length; i++)
+ int count = GetCountInternal();
+ if (count < 0) ThrowHelper.ThrowOutOfMemoryException();
+
+ List<TKey> keys = new List<TKey>(count);
+ for (int i = 0; i < _tables._buckets.Length; i++)
{
- Node current = m_tables.m_buckets[i];
+ Node current = _tables._buckets[i];
while (current != null)
{
- keys.Add(current.m_key);
- current = current.m_next;
+ keys.Add(current._key);
+ current = current._next;
}
}
@@ -1507,15 +1503,18 @@ namespace System.Collections.Concurrent
try
{
AcquireAllLocks(ref locksAcquired);
- List<TValue> values = new List<TValue>();
- for (int i = 0; i < m_tables.m_buckets.Length; i++)
+ int count = GetCountInternal();
+ if (count < 0) ThrowHelper.ThrowOutOfMemoryException();
+
+ List<TValue> values = new List<TValue>(count);
+ for (int i = 0; i < _tables._buckets.Length; i++)
{
- Node current = m_tables.m_buckets[i];
+ Node current = _tables._buckets[i];
while (current != null)
{
- values.Add(current.m_value);
- current = current.m_next;
+ values.Add(current._value);
+ current = current._next;
}
}
@@ -1528,30 +1527,21 @@ namespace System.Collections.Concurrent
}
/// <summary>
- /// A helper method for asserts.
- /// </summary>
- [Conditional("DEBUG")]
- private void Assert(bool condition)
- {
- Debug.Assert(condition);
- }
-
- /// <summary>
/// A node in a singly-linked list representing a particular hash table bucket.
/// </summary>
- private class Node
+ private sealed class Node
{
- internal TKey m_key;
- internal TValue m_value;
- internal volatile Node m_next;
- internal int m_hashcode;
+ internal readonly TKey _key;
+ internal TValue _value;
+ internal volatile Node _next;
+ internal readonly int _hashcode;
internal Node(TKey key, TValue value, int hashcode, Node next)
{
- m_key = key;
- m_value = value;
- m_next = next;
- m_hashcode = hashcode;
+ _key = key;
+ _value = value;
+ _next = next;
+ _hashcode = hashcode;
}
}
@@ -1559,43 +1549,43 @@ namespace System.Collections.Concurrent
/// A private class to represent enumeration over the dictionary that implements the
/// IDictionaryEnumerator interface.
/// </summary>
- private class DictionaryEnumerator : IDictionaryEnumerator
+ private sealed class DictionaryEnumerator : IDictionaryEnumerator
{
- private IEnumerator<KeyValuePair<TKey, TValue>> m_enumerator; // Enumerator over the dictionary.
+ IEnumerator<KeyValuePair<TKey, TValue>> _enumerator; // Enumerator over the dictionary.
internal DictionaryEnumerator(ConcurrentDictionary<TKey, TValue> dictionary)
{
- m_enumerator = dictionary.GetEnumerator();
+ _enumerator = dictionary.GetEnumerator();
}
public DictionaryEntry Entry
{
- get { return new DictionaryEntry(m_enumerator.Current.Key, m_enumerator.Current.Value); }
+ get { return new DictionaryEntry(_enumerator.Current.Key, _enumerator.Current.Value); }
}
public object Key
{
- get { return m_enumerator.Current.Key; }
+ get { return _enumerator.Current.Key; }
}
public object Value
{
- get { return m_enumerator.Current.Value; }
+ get { return _enumerator.Current.Value; }
}
public object Current
{
- get { return this.Entry; }
+ get { return Entry; }
}
public bool MoveNext()
{
- return m_enumerator.MoveNext();
+ return _enumerator.MoveNext();
}
public void Reset()
{
- m_enumerator.Reset();
+ _enumerator.Reset();
}
}
}
diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
index 632f0eecef..304bcd6b79 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentQueue.cs
@@ -5,7 +5,6 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
-using System.Runtime.Serialization;
using System.Threading;
namespace System.Collections.Concurrent
@@ -53,16 +52,11 @@ namespace System.Collections.Concurrent
/// Lock used to protect cross-segment operations, including any updates to <see cref="_tail"/> or <see cref="_head"/>
/// and any operations that need to get a consistent view of them.
/// </summary>
- [NonSerialized]
private object _crossSegmentLock;
/// <summary>The current tail segment.</summary>
- [NonSerialized]
private volatile Segment _tail;
/// <summary>The current head segment.</summary>
- [NonSerialized]
private volatile Segment _head;
- /// <summary>Field used to temporarily store the contents of the queue for serialization.</summary>
- private T[] _serializationArray;
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class.
@@ -73,29 +67,6 @@ namespace System.Collections.Concurrent
_tail = _head = new Segment(InitialSegmentLength);
}
- /// <summary>Set the data array to be serialized.</summary>
- [OnSerializing]
- private void OnSerializing(StreamingContext context)
- {
- _serializationArray = ToArray();
- }
-
- /// <summary>Clear the data array that was serialized.</summary>
- [OnSerialized]
- private void OnSerialized(StreamingContext context)
- {
- _serializationArray = null;
- }
-
- /// <summary>Construct the queue from the deserialized <see cref="_serializationArray"/>.</summary>
- [OnDeserialized]
- private void OnDeserialized(StreamingContext context)
- {
- Debug.Assert(_serializationArray != null);
- InitializeFromCollection(_serializationArray);
- _serializationArray = null;
- }
-
/// <summary>
/// Initializes the contents of the queue from an existing collection.
/// </summary>
@@ -139,7 +110,7 @@ namespace System.Collections.Concurrent
{
if (collection == null)
{
- throw new ArgumentNullException(nameof(collection));
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
InitializeFromCollection(collection);
@@ -182,7 +153,7 @@ namespace System.Collections.Concurrent
// Validate arguments.
if (array == null)
{
- throw new ArgumentNullException(nameof(array));
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
// Otherwise, fall back to the slower path that first copies the contents
@@ -204,7 +175,7 @@ namespace System.Collections.Concurrent
/// cref="ICollection"/>. This property is not supported.
/// </summary>
/// <exception cref="NotSupportedException">The SyncRoot property is not supported.</exception>
- object ICollection.SyncRoot { get { throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported); } }
+ object ICollection.SyncRoot { get { ThrowHelper.ThrowNotSupportedException(ExceptionResource.ConcurrentCollection_SyncRoot_NotSupported); return default(object); } }
/// <summary>Returns an enumerator that iterates through a collection.</summary>
/// <returns>An <see cref="IEnumerator"/> that can be used to iterate through the collection.</returns>
@@ -426,11 +397,11 @@ namespace System.Collections.Concurrent
{
if (array == null)
{
- throw new ArgumentNullException(nameof(array));
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0)
{
- throw new ArgumentOutOfRangeException(nameof(index));
+ ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
// Snap for enumeration
@@ -442,7 +413,7 @@ namespace System.Collections.Concurrent
long count = GetCount(head, headHead, tail, tailTail);
if (index > array.Length - count)
{
- throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
+ ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
// Copy the items to the target array
@@ -737,7 +708,7 @@ namespace System.Collections.Concurrent
/// <summary>Attempts to retrieve the value for the first element in the queue.</summary>
/// <param name="result">The value of the first element, if found.</param>
- /// <param name="resultUsed">true if the result is neede; otherwise false if only the true/false outcome is needed.</param>
+ /// <param name="resultUsed">true if the result is needed; otherwise false if only the true/false outcome is needed.</param>
/// <returns>true if an element was found; otherwise, false.</returns>
private bool TryPeek(out T result, bool resultUsed)
{
@@ -826,7 +797,7 @@ namespace System.Collections.Concurrent
/// <summary>Mask for quickly accessing a position within the queue's array.</summary>
internal readonly int _slotsMask;
/// <summary>The head and tail positions, with padding to help avoid false sharing contention.</summary>
- /// <remarks>Dequeueing happens from the head, enqueueing happens at the tail.</remarks>
+ /// <remarks>Dequeuing happens from the head, enqueuing happens at the tail.</remarks>
internal PaddedHeadAndTail _headAndTail; // mutable struct: do not make this readonly
/// <summary>Indicates whether the segment has been marked such that dequeues don't overwrite the removed data.</summary>
@@ -855,7 +826,7 @@ namespace System.Collections.Concurrent
// allows dequeuers to know whether they can dequeue and enqueuers to know whether they can
// enqueue. An enqueuer at position N can enqueue when the sequence number is N, and a dequeuer
// for position N can dequeue when the sequence number is N + 1. When an enqueuer is done writing
- // at position N, it sets the sequence number to N so that a dequeuer will be able to dequeue,
+ // at position N, it sets the sequence number to N + 1 so that a dequeuer will be able to dequeue,
// and when a dequeuer is done dequeueing at position N, it sets the sequence number to N + _slots.Length,
// so that when an enqueuer loops around the slots, it'll find that the sequence number at
// position N is N. This also means that when an enqueuer finds that at position N the sequence
@@ -1111,10 +1082,10 @@ namespace System.Collections.Concurrent
/// <summary>Padded head and tail indices, to avoid false sharing between producers and consumers.</summary>
[DebuggerDisplay("Head = {Head}, Tail = {Tail}")]
- [StructLayout(LayoutKind.Explicit, Size = 192)] // padding before/between/after fields based on typical cache line size of 64
+ [StructLayout(LayoutKind.Explicit, Size = 3*Internal.PaddingHelpers.CACHE_LINE_SIZE)] // padding before/between/after fields
internal struct PaddedHeadAndTail
{
- [FieldOffset(64)] public int Head;
- [FieldOffset(128)] public int Tail;
+ [FieldOffset(1*Internal.PaddingHelpers.CACHE_LINE_SIZE)] public int Head;
+ [FieldOffset(2*Internal.PaddingHelpers.CACHE_LINE_SIZE)] public int Tail;
}
}
diff --git a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
index 82bc4f9f5c..d1c2d42dce 100644
--- a/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
+++ b/src/mscorlib/src/System/Collections/Concurrent/ConcurrentStack.cs
@@ -1,25 +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.
-#pragma warning disable 0420
-
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
-//
+// ConcurrentStack.cs
//
// A lock-free, concurrent stack primitive, and its associated debugger view type.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-using System;
-using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Runtime.ConstrainedExecution;
-using System.Runtime.Serialization;
-using System.Security;
using System.Threading;
namespace System.Collections.Concurrent
@@ -51,8 +43,8 @@ namespace System.Collections.Concurrent
/// </summary>
private class Node
{
- internal readonly T m_value; // Value of the node.
- internal Node m_next; // Next pointer.
+ internal readonly T _value; // Value of the node.
+ internal Node _next; // Next pointer.
/// <summary>
/// Constructs a new node with the specified value and no next node.
@@ -60,13 +52,12 @@ namespace System.Collections.Concurrent
/// <param name="value">The value of the node.</param>
internal Node(T value)
{
- m_value = value;
- m_next = null;
+ _value = value;
+ _next = null;
}
}
- private volatile Node m_head; // The stack is a singly linked list, and only remembers the head.
-
+ private volatile Node _head; // The stack is a singly linked list, and only remembers the head.
private const int BACKOFF_MAX_YIELDS = 8; // Arbitrary number to cap backoff.
/// <summary>
@@ -101,7 +92,7 @@ namespace System.Collections.Concurrent
// they are being dequeued. If we ever changed this (e.g. to pool nodes somehow),
// we'd need to revisit this implementation.
- for (Node curr = m_head; curr != null; curr = curr.m_next)
+ for (Node curr = _head; curr != null; curr = curr._next)
{
count++; //we don't handle overflow, to be consistent with existing generic collection types in CLR
}
@@ -110,6 +101,7 @@ namespace System.Collections.Concurrent
}
}
+
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is
/// synchronized with the SyncRoot.
@@ -135,7 +127,8 @@ namespace System.Collections.Concurrent
{
get
{
- throw new NotSupportedException(SR.ConcurrentCollection_SyncRoot_NotSupported);
+ ThrowHelper.ThrowNotSupportedException(ExceptionResource.ConcurrentCollection_SyncRoot_NotSupported);
+ return default(object);
}
}
@@ -169,7 +162,7 @@ namespace System.Collections.Concurrent
// Validate arguments.
if (array == null)
{
- throw new ArgumentNullException(nameof(array));
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
// We must be careful not to corrupt the array, so we will first accumulate an
@@ -203,7 +196,7 @@ namespace System.Collections.Concurrent
{
if (array == null)
{
- throw new ArgumentNullException(nameof(array));
+ ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
// We must be careful not to corrupt the array, so we will first accumulate an
@@ -213,7 +206,7 @@ namespace System.Collections.Concurrent
ToList().CopyTo(array, index);
}
-
+#pragma warning disable 0420 // No warning for Interlocked.xxx if compiled with new managed compiler (Roslyn)
/// <summary>
/// Inserts an object at the top of the <see cref="ConcurrentStack{T}"/>.
/// </summary>
@@ -228,8 +221,8 @@ namespace System.Collections.Concurrent
// contention at the head, and then go back around and retry.
Node newNode = new Node(item);
- newNode.m_next = m_head;
- if (Interlocked.CompareExchange(ref m_head, newNode, newNode.m_next) == newNode.m_next)
+ newNode._next = _head;
+ if (Interlocked.CompareExchange(ref _head, newNode, newNode._next) == newNode._next)
{
return;
}
@@ -249,15 +242,15 @@ namespace System.Collections.Concurrent
{
SpinWait spin = new SpinWait();
- // Keep trying to CAS the exising head with the new node until we succeed.
+ // Keep trying to CAS the existing head with the new node until we succeed.
do
{
spin.SpinOnce();
// Reread the head and link our new node.
- tail.m_next = m_head;
+ tail._next = _head;
}
while (Interlocked.CompareExchange(
- ref m_head, head, tail.m_next) != tail.m_next);
+ ref _head, head, tail._next) != tail._next);
}
/// <summary>
@@ -269,19 +262,19 @@ namespace System.Collections.Concurrent
/// </param>
/// <returns>true if an element was removed and returned from the top of the <see
/// cref="ConcurrentStack{T}"/>
- /// succesfully; otherwise, false.</returns>
+ /// successfully; otherwise, false.</returns>
public bool TryPop(out T result)
{
- Node head = m_head;
+ Node head = _head;
//stack is empty
if (head == null)
{
result = default(T);
return false;
}
- if (Interlocked.CompareExchange(ref m_head, head.m_next, head) == head)
+ if (Interlocked.CompareExchange(ref _head, head._next, head) == head)
{
- result = head.m_value;
+ result = head._value;
return true;
}
@@ -300,7 +293,7 @@ namespace System.Collections.Concurrent
if (TryPopCore(1, out poppedNode) == 1)
{
- result = poppedNode.m_value;
+ result = poppedNode._value;
return true;
}
@@ -317,7 +310,8 @@ namespace System.Collections.Concurrent
/// When this method returns, if the pop succeeded, contains the removed object. If no object was
/// available to be removed, the value is unspecified. This parameter is passed uninitialized.
/// </param>
- /// <returns>True if an element was removed and returned; otherwise, false.</returns>
+ /// <returns>The number of objects successfully popped from the top of
+ /// the <see cref="ConcurrentStack{T}"/>.</returns>
private int TryPopCore(int count, out Node poppedHead)
{
SpinWait spin = new SpinWait();
@@ -330,7 +324,7 @@ namespace System.Collections.Concurrent
Random r = null;
while (true)
{
- head = m_head;
+ head = _head;
// Is the stack empty?
if (head == null)
{
@@ -339,13 +333,13 @@ namespace System.Collections.Concurrent
}
next = head;
int nodesCount = 1;
- for (; nodesCount < count && next.m_next != null; nodesCount++)
+ for (; nodesCount < count && next._next != null; nodesCount++)
{
- next = next.m_next;
+ next = next._next;
}
// Try to swap the new head. If we succeed, break out of the loop.
- if (Interlocked.CompareExchange(ref m_head, next.m_next, head) == head)
+ if (Interlocked.CompareExchange(ref _head, next._next, head) == head)
{
// Return the popped Node.
poppedHead = head;
@@ -372,6 +366,7 @@ namespace System.Collections.Concurrent
}
}
}
+#pragma warning restore 0420
/// <summary>
/// Copies the items stored in the <see cref="ConcurrentStack{T}"/> to a new array.
@@ -380,23 +375,34 @@ namespace System.Collections.Concurrent
/// cref="ConcurrentStack{T}"/>.</returns>
public T[] ToArray()
{
- return ToList().ToArray();
+ Node curr = _head;
+ return curr == null ?
+ Array.Empty<T>() :
+ ToList(curr).ToArray();
}
/// <summary>
/// Returns an array containing a snapshot of the list's contents, using
/// the target list node as the head of a region in the list.
/// </summary>
- /// <returns>An array of the list's contents.</returns>
+ /// <returns>A list of the stack's contents.</returns>
private List<T> ToList()
{
+ return ToList(_head);
+ }
+
+ /// <summary>
+ /// Returns an array containing a snapshot of the list's contents starting at the specified node.
+ /// </summary>
+ /// <returns>A list of the stack's contents starting at the specified node.</returns>
+ private List<T> ToList(Node curr)
+ {
List<T> list = new List<T>();
- Node curr = m_head;
while (curr != null)
{
- list.Add(curr.m_value);
- curr = curr.m_next;
+ list.Add(curr._value);
+ curr = curr._next;
}
return list;
@@ -421,8 +427,8 @@ namespace System.Collections.Concurrent
//If we put yield-return here, the iterator will be lazily evaluated. As a result a snapshot of
//the stack is not taken when GetEnumerator is initialized but when MoveNext() is first called.
//This is inconsistent with existing generic collections. In order to prevent it, we capture the
- //value of m_head in a buffer and call out to a helper method
- return GetEnumerator(m_head);
+ //value of _head in a buffer and call out to a helper method
+ return GetEnumerator(_head);
}
private IEnumerator<T> GetEnumerator(Node head)
@@ -430,8 +436,8 @@ namespace System.Collections.Concurrent
Node current = head;
while (current != null)
{
- yield return current.m_value;
- current = current.m_next;
+ yield return current._value;
+ current = current._next;
}
}
diff --git a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
index 50724017dd..0a83734eb0 100644
--- a/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
+++ b/src/mscorlib/src/System/Collections/Generic/Dictionary.cs
@@ -92,12 +92,10 @@ namespace System.Collections.Generic
if (capacity > 0) Initialize(capacity);
this.comparer = comparer ?? EqualityComparer<TKey>.Default;
-#if FEATURE_RANDOMIZED_STRING_HASHING
- if (HashHelpers.s_UseRandomizedStringHashing && this.comparer == EqualityComparer<string>.Default)
+ if (this.comparer == EqualityComparer<string>.Default)
{
this.comparer = (IEqualityComparer<TKey>)NonRandomizedStringEqualityComparer.Default;
}
-#endif // FEATURE_RANDOMIZED_STRING_HASHING
}
public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { }
@@ -408,9 +406,7 @@ namespace System.Collections.Generic
if (buckets == null) Initialize(0);
int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF;
int targetBucket = hashCode % buckets.Length;
-#if FEATURE_RANDOMIZED_STRING_HASHING
int collisionCount = 0;
-#endif
for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next)
{
@@ -430,9 +426,8 @@ namespace System.Collections.Generic
return false;
}
-#if FEATURE_RANDOMIZED_STRING_HASHING
+
collisionCount++;
-#endif
}
int index;
if (freeCount > 0)
@@ -459,18 +454,14 @@ namespace System.Collections.Generic
buckets[targetBucket] = index;
version++;
-#if FEATURE_RANDOMIZED_STRING_HASHING
- // In case we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing
- // in this case will be EqualityComparer<string>.Default.
- // Note, randomized string hashing is turned on by default on coreclr so EqualityComparer<string>.Default will
- // be using randomized string hashing
+ // If we hit the collision threshold we'll need to switch to the comparer which is using randomized string hashing
+ // i.e. EqualityComparer<string>.Default.
if (collisionCount > HashHelpers.HashCollisionThreshold && comparer == NonRandomizedStringEqualityComparer.Default)
{
comparer = (IEqualityComparer<TKey>)EqualityComparer<string>.Default;
Resize(entries.Length, true);
}
-#endif
return true;
}
diff --git a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
index 760c9d10b2..4427682d38 100644
--- a/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
+++ b/src/mscorlib/src/System/Collections/Generic/EqualityComparer.cs
@@ -272,11 +272,8 @@ namespace System.Collections.Generic
GetType().GetHashCode();
}
- // NonRandomizedStringEqualityComparer is the comparer used by default with the Dictionary<string,...>
- // As the randomized string hashing is turned on by default on coreclr, we need to keep the performance not affected
- // as much as possible in the main stream scenarios like Dictionary<string,>
// We use NonRandomizedStringEqualityComparer as default comparer as it doesnt use the randomized string hashing which
- // keep the perofrmance not affected till we hit collision threshold and then we switch to the comparer which is using
+ // keeps the performance unaffected till we hit collision threshold and then we switch to the comparer which is using
// randomized string hashing GenericEqualityComparer<string>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
diff --git a/src/mscorlib/src/System/Collections/Hashtable.cs b/src/mscorlib/src/System/Collections/Hashtable.cs
index 0c89632828..fcfcc3bbd6 100644
--- a/src/mscorlib/src/System/Collections/Hashtable.cs
+++ b/src/mscorlib/src/System/Collections/Hashtable.cs
@@ -1392,10 +1392,7 @@ namespace System.Collections
[FriendAccessAllowed]
internal static class HashHelpers
{
-#if FEATURE_RANDOMIZED_STRING_HASHING
public const int HashCollisionThreshold = 100;
- public static bool s_UseRandomizedStringHashing = String.UseRandomizedHashing();
-#endif
// Table of prime numbers to use as hash table sizes.
// A typical resize algorithm would pick the smallest prime number in this array
diff --git a/src/mscorlib/src/System/Decimal.cs b/src/mscorlib/src/System/Decimal.cs
index df2d3a1c39..5bb0446784 100644
--- a/src/mscorlib/src/System/Decimal.cs
+++ b/src/mscorlib/src/System/Decimal.cs
@@ -510,34 +510,63 @@ namespace System
//
public static Decimal Parse(String s)
{
- return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseDecimal(s.AsReadOnlySpan(), NumberStyles.Number, NumberFormatInfo.CurrentInfo);
}
public static Decimal Parse(String s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
- return Number.ParseDecimal(s, style, NumberFormatInfo.CurrentInfo);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseDecimal(s.AsReadOnlySpan(), style, NumberFormatInfo.CurrentInfo);
}
public static Decimal Parse(String s, IFormatProvider provider)
{
- return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.GetInstance(provider));
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseDecimal(s.AsReadOnlySpan(), NumberStyles.Number, NumberFormatInfo.GetInstance(provider));
}
public static Decimal Parse(String s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
+ if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
+ return Number.ParseDecimal(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider));
+ }
+
+ public static decimal Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Number.ParseDecimal(s, style, NumberFormatInfo.GetInstance(provider));
}
public static Boolean TryParse(String s, out Decimal result)
{
- return Number.TryParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo, out result);
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return Number.TryParseDecimal(s.AsReadOnlySpan(), NumberStyles.Number, NumberFormatInfo.CurrentInfo, out result);
}
public static Boolean TryParse(String s, NumberStyles style, IFormatProvider provider, out Decimal result)
{
NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
+
+ if (s == null)
+ {
+ result = 0;
+ return false;
+ }
+
+ return Number.TryParseDecimal(s.AsReadOnlySpan(), style, NumberFormatInfo.GetInstance(provider), out result);
+ }
+
+ public static bool TryParse(ReadOnlySpan<char> s, out decimal result, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
+ {
+ NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
return Number.TryParseDecimal(s, style, NumberFormatInfo.GetInstance(provider), out result);
}
diff --git a/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs b/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
index 76b15197f2..32a417036f 100644
--- a/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
+++ b/src/mscorlib/src/System/Diagnostics/Contracts/Contracts.cs
@@ -877,7 +877,7 @@ namespace System.Runtime.CompilerServices
/// The method should not perform any failure (assert/throw) itself.
/// This method has 3 functions:
/// 1. Call any contract hooks (such as listeners to Contract failed events)
- /// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null)
+ /// 2. Determine if the listeners deem the failure as handled (then resultFailureMessage should be set to null)
/// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently.
/// </summary>
/// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough.
diff --git a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
index d29b860bd1..db6a40c54a 100644
--- a/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
+++ b/src/mscorlib/src/System/Diagnostics/Contracts/ContractsBCL.cs
@@ -281,7 +281,7 @@ namespace System.Runtime.CompilerServices
/// The method should not perform any failure (assert/throw) itself.
/// This method has 3 functions:
/// 1. Call any contract hooks (such as listeners to Contract failed events)
- /// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null)
+ /// 2. Determine if the listeners deem the failure as handled (then resultFailureMessage should be set to null)
/// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently.
/// </summary>
/// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough.
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventPipe.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventPipe.cs
index 2f6fdf62ef..d166bf8140 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventPipe.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventPipe.cs
@@ -158,7 +158,7 @@ namespace System.Diagnostics.Tracing
//
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- internal static extern IntPtr CreateProvider(Guid providerID, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback callbackFunc);
+ internal static extern IntPtr CreateProvider(string providerName, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback callbackFunc);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
@@ -171,5 +171,9 @@ namespace System.Diagnostics.Tracing
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern unsafe void WriteEvent(IntPtr eventHandle, uint eventID, void* pData, uint length, Guid* activityId, Guid* relatedActivityId);
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ internal static extern unsafe void WriteEventData(IntPtr eventHandle, uint eventID, EventProvider.EventData** pEventData, uint dataCount, Guid* activityId, Guid* relatedActivityId);
}
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventPipeEventProvider.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventPipeEventProvider.cs
index d5bc4c2889..a8789f5692 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventPipeEventProvider.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventPipeEventProvider.cs
@@ -18,13 +18,13 @@ namespace System.Diagnostics.Tracing
// Register an event provider.
unsafe uint IEventProvider.EventRegister(
- ref Guid providerId,
+ EventSource eventSource,
UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback,
void* callbackContext,
ref long registrationHandle)
{
uint returnStatus = 0;
- m_provHandle = EventPipeInternal.CreateProvider(providerId, enableCallback);
+ m_provHandle = EventPipeInternal.CreateProvider(eventSource.Name, enableCallback);
if(m_provHandle != IntPtr.Zero)
{
// Fixed registration handle because a new EventPipeEventProvider
@@ -62,28 +62,11 @@ namespace System.Diagnostics.Tracing
{
if (userDataCount == 0)
{
- EventPipeInternal.WriteEvent(eventHandle, eventID, null, 0, activityId, relatedActivityId);
+ EventPipeInternal.WriteEventData(eventHandle, eventID, null, 0, activityId, relatedActivityId);
return 0;
}
- uint length = 0;
- for (int i = 0; i < userDataCount; i++)
- {
- length += userData[i].Size;
- }
-
- byte[] data = new byte[length];
- fixed (byte *pData = data)
- {
- uint offset = 0;
- for (int i = 0; i < userDataCount; i++)
- {
- byte * singleUserDataPtr = (byte *)(userData[i].Ptr);
- uint singleUserDataSize = userData[i].Size;
- WriteToBuffer(pData, length, ref offset, singleUserDataPtr, singleUserDataSize);
- }
- EventPipeInternal.WriteEvent(eventHandle, eventID, pData, length, activityId, relatedActivityId);
- }
+ EventPipeInternal.WriteEventData(eventHandle, eventID, &userData, (uint) userDataCount, activityId, relatedActivityId);
}
return 0;
}
diff --git a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
index 01aac72cf6..c5e2b20a80 100644
--- a/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
+++ b/src/mscorlib/src/System/Diagnostics/Eventing/EventSource_CoreCLR.cs
@@ -77,7 +77,7 @@ namespace System.Diagnostics.Tracing
/// This API marks the current thread as working on activity 'activityID'. It returns
/// whatever activity the thread was previously marked with. There is a convention that
/// callers can assume that callees restore this activity mark before the callee returns.
- /// To encourage this this API returns the old activity, so that it can be restored later.
+ /// To encourage this, this API returns the old activity, so that it can be restored later.
///
/// All events created with the EventSource on this thread are also tagged with the
/// activity ID of the thread.
diff --git a/src/mscorlib/src/System/Diagnostics/Stacktrace.cs b/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
index 6a138de327..097ed44f85 100644
--- a/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
+++ b/src/mscorlib/src/System/Diagnostics/Stacktrace.cs
@@ -247,9 +247,6 @@ namespace System.Diagnostics
// Class which represents a description of a stack trace
// There is no good reason for the methods of this class to be virtual.
- // In order to ensure trusted code can trust the data it gets from a
- // StackTrace, we use an InheritanceDemand to prevent partially-trusted
- // subclasses.
public class StackTrace
{
private StackFrame[] frames;
diff --git a/src/mscorlib/src/System/Enum.cs b/src/mscorlib/src/System/Enum.cs
index 25a4ff34d3..b5d00fe60e 100644
--- a/src/mscorlib/src/System/Enum.cs
+++ b/src/mscorlib/src/System/Enum.cs
@@ -12,6 +12,18 @@ using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
+// The code below includes partial support for float/double and
+// pointer sized enums.
+//
+// The type loader does not prohibit such enums, and older versions of
+// the ECMA spec include them as possible enum types.
+//
+// However there are many things broken throughout the stack for
+// float/double/intptr/uintptr enums. There was a conscious decision
+// made to not fix the whole stack to work well for them because of
+// the right behavior is often unclear, and it is hard to test and
+// very low value because of such enums cannot be expressed in C#.
+
namespace System
{
[Serializable]
@@ -425,7 +437,7 @@ namespace System
}
if (firstNonWhitespaceIndex == -1)
{
- parseResult.SetFailure(ParseFailureKind.Argument, "Arg_MustContainEnumInfo", null);
+ parseResult.SetFailure(ParseFailureKind.Argument, nameof(SR.Arg_MustContainEnumInfo), null);
return false;
}
@@ -506,7 +518,7 @@ namespace System
if (!success)
{
// Not found, throw an argument exception.
- parseResult.SetFailure(ParseFailureKind.ArgumentWithParameter, "Arg_EnumValueNotFound", value);
+ parseResult.SetFailure(ParseFailureKind.ArgumentWithParameter, nameof(SR.Arg_EnumValueNotFound), value);
return false;
}
@@ -961,6 +973,7 @@ namespace System
return ToString();
}
+ [Intrinsic]
public Boolean HasFlag(Enum flag)
{
if (flag == null)
diff --git a/src/mscorlib/src/System/Environment.cs b/src/mscorlib/src/System/Environment.cs
index e634341584..ea99a1e3f2 100644
--- a/src/mscorlib/src/System/Environment.cs
+++ b/src/mscorlib/src/System/Environment.cs
@@ -62,21 +62,6 @@ namespace System
return SR.GetResourceString(key);
}
- // Private object for locking instead of locking on a public type for SQL reliability work.
- private static Object s_InternalSyncObject;
- private static Object InternalSyncObject
- {
- get
- {
- if (s_InternalSyncObject == null)
- {
- Object o = new Object();
- Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null);
- }
- return s_InternalSyncObject;
- }
- }
-
/*==================================TickCount===================================
**Action: Gets the number of ticks since the system was started.
**Returns: The number of ticks since the system was started.
@@ -139,7 +124,7 @@ namespace System
StringBuilder sb = new StringBuilder(Path.MaxPath);
int r = Win32Native.GetSystemDirectory(sb, Path.MaxPath);
Debug.Assert(r < Path.MaxPath, "r < Path.MaxPath");
- if (r == 0) __Error.WinIOError();
+ if (r == 0) throw Win32Marshal.GetExceptionForLastWin32Error();
String path = sb.ToString();
return path;
@@ -256,44 +241,38 @@ namespace System
{
char[] block = null;
- // Make sure pStrings is not leaked with async exceptions
RuntimeHelpers.PrepareConstrainedRegions();
+
+ char* pStrings = null;
+
try
{
- }
- finally
- {
- char* pStrings = null;
-
- try
+ pStrings = Win32Native.GetEnvironmentStrings();
+ if (pStrings == null)
{
- pStrings = Win32Native.GetEnvironmentStrings();
- if (pStrings == null)
- {
- throw new OutOfMemoryException();
- }
+ throw new OutOfMemoryException();
+ }
- // Format for GetEnvironmentStrings is:
- // [=HiddenVar=value\0]* [Variable=value\0]* \0
- // See the description of Environment Blocks in MSDN's
- // CreateProcess page (null-terminated array of null-terminated strings).
+ // Format for GetEnvironmentStrings is:
+ // [=HiddenVar=value\0]* [Variable=value\0]* \0
+ // See the description of Environment Blocks in MSDN's
+ // CreateProcess page (null-terminated array of null-terminated strings).
- // Search for terminating \0\0 (two unicode \0's).
- char* p = pStrings;
- while (!(*p == '\0' && *(p + 1) == '\0'))
- p++;
+ // Search for terminating \0\0 (two unicode \0's).
+ char* p = pStrings;
+ while (!(*p == '\0' && *(p + 1) == '\0'))
+ p++;
- int len = (int)(p - pStrings + 1);
- block = new char[len];
+ int len = (int)(p - pStrings + 1);
+ block = new char[len];
- fixed (char* pBlock = block)
- string.wstrcpy(pBlock, pStrings, len);
- }
- finally
- {
- if (pStrings != null)
- Win32Native.FreeEnvironmentStrings(pStrings);
- }
+ fixed (char* pBlock = block)
+ string.wstrcpy(pBlock, pStrings, len);
+ }
+ finally
+ {
+ if (pStrings != null)
+ Win32Native.FreeEnvironmentStrings(pStrings);
}
return block;
@@ -735,7 +714,7 @@ namespace System
// which is not accurate.
throw new ArgumentException(SR.Format(SR.Argument_LongEnvVarValue));
default:
- throw new ArgumentException(Win32Native.GetMessage(errorCode));
+ throw new ArgumentException(Interop.Kernel32.GetMessage(errorCode));
}
}
}
@@ -803,8 +782,8 @@ namespace System
}
// send a WM_SETTINGCHANGE message to all windows
- IntPtr r = Win32Native.SendMessageTimeout(new IntPtr(Win32Native.HWND_BROADCAST),
- Win32Native.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);
+ IntPtr r = Interop.User32.SendMessageTimeout(new IntPtr(Interop.User32.HWND_BROADCAST),
+ Interop.User32.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero);
if (r == IntPtr.Zero) Debug.Assert(false, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error());
#endif // FEATURE_WIN32_REGISTRY
diff --git a/src/mscorlib/src/System/Exception.cs b/src/mscorlib/src/System/Exception.cs
index 725adac4a9..785637d1ba 100644
--- a/src/mscorlib/src/System/Exception.cs
+++ b/src/mscorlib/src/System/Exception.cs
@@ -36,7 +36,7 @@ namespace System
_message = null;
_stackTrace = null;
_dynamicMethods = null;
- HResult = __HResults.COR_E_EXCEPTION;
+ HResult = HResults.COR_E_EXCEPTION;
_xcode = _COMPlusExceptionCode;
_xptrs = (IntPtr)0;
@@ -477,7 +477,7 @@ namespace System
}
// This method will clear the _stackTrace of the exception object upon deserialization
- // to ensure that references from another AD/Process dont get accidently used.
+ // to ensure that references from another AD/Process dont get accidentally used.
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.Unix.cs b/src/mscorlib/src/System/Globalization/CompareInfo.Unix.cs
index edc9a7f575..92fd691c8b 100644
--- a/src/mscorlib/src/System/Globalization/CompareInfo.Unix.cs
+++ b/src/mscorlib/src/System/Globalization/CompareInfo.Unix.cs
@@ -137,14 +137,6 @@ namespace System.Globalization
return -1;
}
- private int GetHashCodeOfStringCore(string source, CompareOptions options)
- {
- Debug.Assert(source != null);
- Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
-
- return GetHashCodeOfStringCore(source, options, forceRandomizedHashing: false, additionalEntropy: 0);
- }
-
private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2)
{
Debug.Assert(!GlobalizationMode.Invariant);
@@ -357,7 +349,7 @@ namespace System.Globalization
// ---- PAL layer ends here ----
// -----------------------------
- internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy)
+ internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options)
{
Debug.Assert(!_invariantMode);
@@ -376,7 +368,7 @@ namespace System.Globalization
{
byte* pSortKey = stackalloc byte[sortKeyLength];
Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
- return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
+ return InternalHashSortKey(pSortKey, sortKeyLength);
}
byte[] sortKey = new byte[sortKeyLength];
@@ -384,13 +376,13 @@ namespace System.Globalization
fixed (byte* pSortKey = sortKey)
{
Interop.GlobalizationInterop.GetSortKey(_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
- return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
+ return InternalHashSortKey(pSortKey, sortKeyLength);
}
}
[DllImport(JitHelpers.QCall)]
[SuppressUnmanagedCodeSecurity]
- private static unsafe extern int InternalHashSortKey(byte* sortKey, int sortKeyLength, [MarshalAs(UnmanagedType.Bool)] bool forceRandomizedHashing, long additionalEntropy);
+ private static unsafe extern int InternalHashSortKey(byte* sortKey, int sortKeyLength);
private static CompareOptions GetOrdinalCompareOptions(CompareOptions options)
{
@@ -428,7 +420,7 @@ namespace System.Globalization
{
Debug.Assert(!_invariantMode);
- int sortVersion = Interop.GlobalizationInterop.GetSortVersion();
+ int sortVersion = Interop.GlobalizationInterop.GetSortVersion(_sortHandle);
return new SortVersion(sortVersion, LCID, new Guid(sortVersion, 0, 0, 0, 0, 0, 0,
(byte) (LCID >> 24),
(byte) ((LCID & 0x00FF0000) >> 16),
diff --git a/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs b/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs
index 0df5463a2f..2bfe15b835 100644
--- a/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs
+++ b/src/mscorlib/src/System/Globalization/CompareInfo.Windows.cs
@@ -92,7 +92,7 @@ namespace System.Globalization
int flags = GetNativeCompareFlags(options);
int tmpHash = 0;
#if CORECLR
- tmpHash = InternalGetGlobalizedHashCode(_sortHandle, _sortName, source, source.Length, flags, 0);
+ tmpHash = InternalGetGlobalizedHashCode(_sortHandle, _sortName, source, source.Length, flags);
#else
fixed (char* pSource = source)
{
@@ -481,7 +481,7 @@ namespace System.Globalization
// Get a locale sensitive sort hash code from native code -- COMNlsInfo::InternalGetGlobalizedHashCode
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
- private static extern int InternalGetGlobalizedHashCode(IntPtr handle, string localeName, string source, int length, int dwFlags, long additionalEntropy);
+ private static extern int InternalGetGlobalizedHashCode(IntPtr handle, string localeName, string source, int length, int dwFlags);
#endif
}
}
diff --git a/src/mscorlib/src/System/Globalization/CultureData.Windows.cs b/src/mscorlib/src/System/Globalization/CultureData.Windows.cs
index c39327e9e7..aadf6bd716 100644
--- a/src/mscorlib/src/System/Globalization/CultureData.Windows.cs
+++ b/src/mscorlib/src/System/Globalization/CultureData.Windows.cs
@@ -326,20 +326,14 @@ namespace System.Globalization
#if ENABLE_WINRT
return WinRTInterop.Callbacks.GetRegionDisplayName(isoCountryCode);
#else
- // Usually the UI culture shouldn't be different than what we got from WinRT except
- // if DefaultThreadCurrentUICulture was set
- CultureInfo ci;
-
- if (CultureInfo.DefaultThreadCurrentUICulture != null &&
- ((ci = GetUserDefaultCulture()) != null) &&
- !CultureInfo.DefaultThreadCurrentUICulture.Name.Equals(ci.Name))
- {
- return SNATIVECOUNTRY;
- }
- else
+ // If the current UI culture matching the OS UI language, we'll get the display name from the OS.
+ // otherwise, we use the native name as we don't carry resources for the region display names anyway.
+ if (CultureInfo.CurrentUICulture.Name.Equals(CultureInfo.UserDefaultUICulture.Name))
{
return GetLocaleInfo(LocaleStringData.LocalizedCountryName);
}
+
+ return SNATIVECOUNTRY;
#endif // ENABLE_WINRT
}
diff --git a/src/mscorlib/src/System/Globalization/CultureData.cs b/src/mscorlib/src/System/Globalization/CultureData.cs
index 0dcebf484b..d913a8929f 100644
--- a/src/mscorlib/src/System/Globalization/CultureData.cs
+++ b/src/mscorlib/src/System/Globalization/CultureData.cs
@@ -2424,77 +2424,77 @@ namespace System.Globalization
/// </remarks>
private enum LocaleStringData : uint
{
- /// <summary>localized name of locale, eg "German (Germany)" in UI language (coresponds to LOCALE_SLOCALIZEDDISPLAYNAME)</summary>
+ /// <summary>localized name of locale, eg "German (Germany)" in UI language (corresponds to LOCALE_SLOCALIZEDDISPLAYNAME)</summary>
LocalizedDisplayName = 0x00000002,
- /// <summary>Display name (language + country usually) in English, eg "German (Germany)" (coresponds to LOCALE_SENGLISHDISPLAYNAME)</summary>
+ /// <summary>Display name (language + country usually) in English, eg "German (Germany)" (corresponds to LOCALE_SENGLISHDISPLAYNAME)</summary>
EnglishDisplayName = 0x00000072,
- /// <summary>Display name in native locale language, eg "Deutsch (Deutschland) (coresponds to LOCALE_SNATIVEDISPLAYNAME)</summary>
+ /// <summary>Display name in native locale language, eg "Deutsch (Deutschland) (corresponds to LOCALE_SNATIVEDISPLAYNAME)</summary>
NativeDisplayName = 0x00000073,
- /// <summary>Language Display Name for a language, eg "German" in UI language (coresponds to LOCALE_SLOCALIZEDLANGUAGENAME)</summary>
+ /// <summary>Language Display Name for a language, eg "German" in UI language (corresponds to LOCALE_SLOCALIZEDLANGUAGENAME)</summary>
LocalizedLanguageName = 0x0000006f,
- /// <summary>English name of language, eg "German" (coresponds to LOCALE_SENGLISHLANGUAGENAME)</summary>
+ /// <summary>English name of language, eg "German" (corresponds to LOCALE_SENGLISHLANGUAGENAME)</summary>
EnglishLanguageName = 0x00001001,
- /// <summary>native name of language, eg "Deutsch" (coresponds to LOCALE_SNATIVELANGUAGENAME)</summary>
+ /// <summary>native name of language, eg "Deutsch" (corresponds to LOCALE_SNATIVELANGUAGENAME)</summary>
NativeLanguageName = 0x00000004,
- /// <summary>localized name of country, eg "Germany" in UI language (coresponds to LOCALE_SLOCALIZEDCOUNTRYNAME)</summary>
+ /// <summary>localized name of country, eg "Germany" in UI language (corresponds to LOCALE_SLOCALIZEDCOUNTRYNAME)</summary>
LocalizedCountryName = 0x00000006,
- /// <summary>English name of country, eg "Germany" (coresponds to LOCALE_SENGLISHCOUNTRYNAME)</summary>
+ /// <summary>English name of country, eg "Germany" (corresponds to LOCALE_SENGLISHCOUNTRYNAME)</summary>
EnglishCountryName = 0x00001002,
- /// <summary>native name of country, eg "Deutschland" (coresponds to LOCALE_SNATIVECOUNTRYNAME)</summary>
+ /// <summary>native name of country, eg "Deutschland" (corresponds to LOCALE_SNATIVECOUNTRYNAME)</summary>
NativeCountryName = 0x00000008,
- /// <summary>abbreviated language name (coresponds to LOCALE_SABBREVLANGNAME)</summary>
+ /// <summary>abbreviated language name (corresponds to LOCALE_SABBREVLANGNAME)</summary>
AbbreviatedWindowsLanguageName = 0x00000003,
- /// <summary>list item separator (coresponds to LOCALE_SLIST)</summary>
+ /// <summary>list item separator (corresponds to LOCALE_SLIST)</summary>
ListSeparator = 0x0000000C,
- /// <summary>decimal separator (coresponds to LOCALE_SDECIMAL)</summary>
+ /// <summary>decimal separator (corresponds to LOCALE_SDECIMAL)</summary>
DecimalSeparator = 0x0000000E,
- /// <summary>thousand separator (coresponds to LOCALE_STHOUSAND)</summary>
+ /// <summary>thousand separator (corresponds to LOCALE_STHOUSAND)</summary>
ThousandSeparator = 0x0000000F,
- /// <summary>digit grouping (coresponds to LOCALE_SGROUPING)</summary>
+ /// <summary>digit grouping (corresponds to LOCALE_SGROUPING)</summary>
Digits = 0x00000013,
- /// <summary>local monetary symbol (coresponds to LOCALE_SCURRENCY)</summary>
+ /// <summary>local monetary symbol (corresponds to LOCALE_SCURRENCY)</summary>
MonetarySymbol = 0x00000014,
- /// <summary>English currency name (coresponds to LOCALE_SENGCURRNAME)</summary>
+ /// <summary>English currency name (corresponds to LOCALE_SENGCURRNAME)</summary>
CurrencyEnglishName = 0x00001007,
- /// <summary>Native currency name (coresponds to LOCALE_SNATIVECURRNAME)</summary>
+ /// <summary>Native currency name (corresponds to LOCALE_SNATIVECURRNAME)</summary>
CurrencyNativeName = 0x00001008,
- /// <summary>uintl monetary symbol (coresponds to LOCALE_SINTLSYMBOL)</summary>
+ /// <summary>uintl monetary symbol (corresponds to LOCALE_SINTLSYMBOL)</summary>
Iso4217MonetarySymbol = 0x00000015,
- /// <summary>monetary decimal separator (coresponds to LOCALE_SMONDECIMALSEP)</summary>
+ /// <summary>monetary decimal separator (corresponds to LOCALE_SMONDECIMALSEP)</summary>
MonetaryDecimalSeparator = 0x00000016,
- /// <summary>monetary thousand separator (coresponds to LOCALE_SMONTHOUSANDSEP)</summary>
+ /// <summary>monetary thousand separator (corresponds to LOCALE_SMONTHOUSANDSEP)</summary>
MonetaryThousandSeparator = 0x00000017,
- /// <summary>AM designator (coresponds to LOCALE_S1159)</summary>
+ /// <summary>AM designator (corresponds to LOCALE_S1159)</summary>
AMDesignator = 0x00000028,
- /// <summary>PM designator (coresponds to LOCALE_S2359)</summary>
+ /// <summary>PM designator (corresponds to LOCALE_S2359)</summary>
PMDesignator = 0x00000029,
- /// <summary>positive sign (coresponds to LOCALE_SPOSITIVESIGN)</summary>
+ /// <summary>positive sign (corresponds to LOCALE_SPOSITIVESIGN)</summary>
PositiveSign = 0x00000050,
- /// <summary>negative sign (coresponds to LOCALE_SNEGATIVESIGN)</summary>
+ /// <summary>negative sign (corresponds to LOCALE_SNEGATIVESIGN)</summary>
NegativeSign = 0x00000051,
- /// <summary>ISO abbreviated language name (coresponds to LOCALE_SISO639LANGNAME)</summary>
+ /// <summary>ISO abbreviated language name (corresponds to LOCALE_SISO639LANGNAME)</summary>
Iso639LanguageTwoLetterName = 0x00000059,
- /// <summary>ISO abbreviated country name (coresponds to LOCALE_SISO639LANGNAME2)</summary>
+ /// <summary>ISO abbreviated country name (corresponds to LOCALE_SISO639LANGNAME2)</summary>
Iso639LanguageThreeLetterName = 0x00000067,
- /// <summary>ISO abbreviated language name (coresponds to LOCALE_SISO639LANGNAME)</summary>
+ /// <summary>ISO abbreviated language name (corresponds to LOCALE_SISO639LANGNAME)</summary>
Iso639LanguageName = 0x00000059,
- /// <summary>ISO abbreviated country name (coresponds to LOCALE_SISO3166CTRYNAME)</summary>
+ /// <summary>ISO abbreviated country name (corresponds to LOCALE_SISO3166CTRYNAME)</summary>
Iso3166CountryName = 0x0000005A,
- /// <summary>3 letter ISO country code (coresponds to LOCALE_SISO3166CTRYNAME2)</summary>
+ /// <summary>3 letter ISO country code (corresponds to LOCALE_SISO3166CTRYNAME2)</summary>
Iso3166CountryName2 = 0x00000068, // 3 character ISO country name
- /// <summary>Not a Number (coresponds to LOCALE_SNAN)</summary>
+ /// <summary>Not a Number (corresponds to LOCALE_SNAN)</summary>
NaNSymbol = 0x00000069,
- /// <summary>+ Infinity (coresponds to LOCALE_SPOSINFINITY)</summary>
+ /// <summary>+ Infinity (corresponds to LOCALE_SPOSINFINITY)</summary>
PositiveInfinitySymbol = 0x0000006a,
- /// <summary>- Infinity (coresponds to LOCALE_SNEGINFINITY)</summary>
+ /// <summary>- Infinity (corresponds to LOCALE_SNEGINFINITY)</summary>
NegativeInfinitySymbol = 0x0000006b,
- /// <summary>Fallback name for resources (coresponds to LOCALE_SPARENT)</summary>
+ /// <summary>Fallback name for resources (corresponds to LOCALE_SPARENT)</summary>
ParentName = 0x0000006d,
- /// <summary>Fallback name for within the console (coresponds to LOCALE_SCONSOLEFALLBACKNAME)</summary>
+ /// <summary>Fallback name for within the console (corresponds to LOCALE_SCONSOLEFALLBACKNAME)</summary>
ConsoleFallbackName = 0x0000006e,
- /// <summary>Returns the percent symbol (coresponds to LOCALE_SPERCENT)</summary>
+ /// <summary>Returns the percent symbol (corresponds to LOCALE_SPERCENT)</summary>
PercentSymbol = 0x00000076,
- /// <summary>Returns the permille (U+2030) symbol (coresponds to LOCALE_SPERMILLE)</summary>
+ /// <summary>Returns the permille (U+2030) symbol (corresponds to LOCALE_SPERMILLE)</summary>
PerMilleSymbol = 0x00000077
}
@@ -2504,9 +2504,9 @@ namespace System.Globalization
/// </remarks>
private enum LocaleGroupingData : uint
{
- /// <summary>digit grouping (coresponds to LOCALE_SGROUPING)</summary>
+ /// <summary>digit grouping (corresponds to LOCALE_SGROUPING)</summary>
Digit = 0x00000010,
- /// <summary>monetary grouping (coresponds to LOCALE_SMONGROUPING)</summary>
+ /// <summary>monetary grouping (corresponds to LOCALE_SMONGROUPING)</summary>
Monetary = 0x00000018,
}
@@ -2516,29 +2516,29 @@ namespace System.Globalization
/// </remarks>
private enum LocaleNumberData : uint
{
- /// <summary>language id (coresponds to LOCALE_ILANGUAGE)</summary>
+ /// <summary>language id (corresponds to LOCALE_ILANGUAGE)</summary>
LanguageId = 0x00000001,
- /// <summary>geographical location id, (coresponds to LOCALE_IGEOID)</summary>
+ /// <summary>geographical location id, (corresponds to LOCALE_IGEOID)</summary>
GeoId = 0x0000005B,
- /// <summary>0 = context, 1 = none, 2 = national (coresponds to LOCALE_IDIGITSUBSTITUTION)</summary>
+ /// <summary>0 = context, 1 = none, 2 = national (corresponds to LOCALE_IDIGITSUBSTITUTION)</summary>
DigitSubstitution = 0x00001014,
- /// <summary>0 = metric, 1 = US (coresponds to LOCALE_IMEASURE)</summary>
+ /// <summary>0 = metric, 1 = US (corresponds to LOCALE_IMEASURE)</summary>
MeasurementSystem = 0x0000000D,
- /// <summary>number of fractional digits (coresponds to LOCALE_IDIGITS)</summary>
+ /// <summary>number of fractional digits (corresponds to LOCALE_IDIGITS)</summary>
FractionalDigitsCount = 0x00000011,
- /// <summary>negative number mode (coresponds to LOCALE_INEGNUMBER)</summary>
+ /// <summary>negative number mode (corresponds to LOCALE_INEGNUMBER)</summary>
NegativeNumberFormat = 0x00001010,
- /// <summary># local monetary digits (coresponds to LOCALE_ICURRDIGITS)</summary>
+ /// <summary># local monetary digits (corresponds to LOCALE_ICURRDIGITS)</summary>
MonetaryFractionalDigitsCount = 0x00000019,
- /// <summary>positive currency mode (coresponds to LOCALE_ICURRENCY)</summary>
+ /// <summary>positive currency mode (corresponds to LOCALE_ICURRENCY)</summary>
PositiveMonetaryNumberFormat = 0x0000001B,
- /// <summary>negative currency mode (coresponds to LOCALE_INEGCURR)</summary>
+ /// <summary>negative currency mode (corresponds to LOCALE_INEGCURR)</summary>
NegativeMonetaryNumberFormat = 0x0000001C,
- /// <summary>type of calendar specifier (coresponds to LOCALE_ICALENDARTYPE)</summary>
+ /// <summary>type of calendar specifier (corresponds to LOCALE_ICALENDARTYPE)</summary>
CalendarType = 0x00001009,
- /// <summary>first day of week specifier (coresponds to LOCALE_IFIRSTDAYOFWEEK)</summary>
+ /// <summary>first day of week specifier (corresponds to LOCALE_IFIRSTDAYOFWEEK)</summary>
FirstDayOfWeek = 0x0000100C,
- /// <summary>first week of year specifier (coresponds to LOCALE_IFIRSTWEEKOFYEAR)</summary>
+ /// <summary>first week of year specifier (corresponds to LOCALE_IFIRSTWEEKOFYEAR)</summary>
FirstWeekOfYear = 0x0000100D,
/// <summary>
/// Returns one of the following 4 reading layout values:
@@ -2546,20 +2546,20 @@ namespace System.Globalization
/// 1 - Right to left (eg arabic locales)
/// 2 - Vertical top to bottom with columns to the left and also left to right (ja-JP locales)
/// 3 - Vertical top to bottom with columns proceeding to the right
- /// (coresponds to LOCALE_IREADINGLAYOUT)
+ /// (corresponds to LOCALE_IREADINGLAYOUT)
/// </summary>
ReadingLayout = 0x00000070,
- /// <summary>Returns 0-11 for the negative percent format (coresponds to LOCALE_INEGATIVEPERCENT)</summary>
+ /// <summary>Returns 0-11 for the negative percent format (corresponds to LOCALE_INEGATIVEPERCENT)</summary>
NegativePercentFormat = 0x00000074,
- /// <summary>Returns 0-3 for the positive percent format (coresponds to LOCALE_IPOSITIVEPERCENT)</summary>
+ /// <summary>Returns 0-3 for the positive percent format (corresponds to LOCALE_IPOSITIVEPERCENT)</summary>
PositivePercentFormat = 0x00000075,
- /// <summary>default ansi code page (coresponds to LOCALE_IDEFAULTCODEPAGE)</summary>
+ /// <summary>default ansi code page (corresponds to LOCALE_IDEFAULTCODEPAGE)</summary>
OemCodePage = 0x0000000B,
- /// <summary>default ansi code page (coresponds to LOCALE_IDEFAULTANSICODEPAGE)</summary>
+ /// <summary>default ansi code page (corresponds to LOCALE_IDEFAULTANSICODEPAGE)</summary>
AnsiCodePage = 0x00001004,
- /// <summary>default mac code page (coresponds to LOCALE_IDEFAULTMACCODEPAGE)</summary>
+ /// <summary>default mac code page (corresponds to LOCALE_IDEFAULTMACCODEPAGE)</summary>
MacCodePage = 0x00001011,
- /// <summary>default ebcdic code page (coresponds to LOCALE_IDEFAULTEBCDICCODEPAGE)</summary>
+ /// <summary>default ebcdic code page (corresponds to LOCALE_IDEFAULTEBCDICCODEPAGE)</summary>
EbcdicCodePage = 0x00001012,
}
}
diff --git a/src/mscorlib/src/System/Globalization/CultureInfo.cs b/src/mscorlib/src/System/Globalization/CultureInfo.cs
index f176ea045d..fd879c709d 100644
--- a/src/mscorlib/src/System/Globalization/CultureInfo.cs
+++ b/src/mscorlib/src/System/Globalization/CultureInfo.cs
@@ -206,6 +206,25 @@ namespace System.Globalization
InitializeFromName(name, useUserOverride);
}
+ private CultureInfo(CultureData cultureData)
+ {
+ Debug.Assert(cultureData != null);
+ _cultureData = cultureData;
+ _name = cultureData.CultureName;
+ _isInherited = false;
+ }
+
+ private static CultureInfo CreateCultureInfoNoThrow(string name, bool useUserOverride)
+ {
+ Debug.Assert(name != null);
+ CultureData cultureData = CultureData.GetCultureData(name, useUserOverride);
+ if (cultureData == null)
+ {
+ return null;
+ }
+
+ return new CultureInfo(cultureData);
+ }
public CultureInfo(int culture) : this(culture, true)
{
}
@@ -439,15 +458,23 @@ namespace System.Globalization
return ci;
}
- // if s_userDefaultUICulture == null means CultureInfo statics didn't get initialized yet. this can happen if there early static
- // method get executed which eventually hit the cultureInfo code while CultureInfo statics didn’t get chance to initialize
- if (s_userDefaultUICulture == null)
+ return UserDefaultUICulture;
+ }
+
+ internal static CultureInfo UserDefaultUICulture
+ {
+ get
{
- Init();
- }
+ // if s_userDefaultUICulture == null means CultureInfo statics didn't get initialized yet. this can happen if there early static
+ // method get executed which eventually hit the cultureInfo code while CultureInfo statics didn’t get chance to initialize
+ if (s_userDefaultUICulture == null)
+ {
+ Init();
+ }
- Debug.Assert(s_userDefaultUICulture != null);
- return s_userDefaultUICulture;
+ Debug.Assert(s_userDefaultUICulture != null);
+ return s_userDefaultUICulture;
+ }
}
public static CultureInfo InstalledUICulture
@@ -533,25 +560,22 @@ namespace System.Globalization
{
if (null == _parent)
{
- try
- {
- string parentName = _cultureData.SPARENT;
+ string parentName = _cultureData.SPARENT;
- if (String.IsNullOrEmpty(parentName))
+ if (String.IsNullOrEmpty(parentName))
+ {
+ _parent = InvariantCulture;
+ }
+ else
+ {
+ _parent = CreateCultureInfoNoThrow(parentName, _cultureData.UseUserOverride);
+ if (_parent == null)
{
+ // For whatever reason our IPARENT or SPARENT wasn't correct, so use invariant
+ // We can't allow ourselves to fail. In case of custom cultures the parent of the
+ // current custom culture isn't installed.
_parent = InvariantCulture;
}
- else
- {
- _parent = new CultureInfo(parentName, _cultureData.UseUserOverride);
- }
- }
- catch (ArgumentException)
- {
- // For whatever reason our IPARENT or SPARENT wasn't correct, so use invariant
- // We can't allow ourselves to fail. In case of custom cultures the parent of the
- // current custom culture isn't installed.
- _parent = InvariantCulture;
}
}
return _parent;
diff --git a/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs b/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs
deleted file mode 100644
index 956543524a..0000000000
--- a/src/mscorlib/src/System/Globalization/GlobalizationAssembly.cs
+++ /dev/null
@@ -1,64 +0,0 @@
-// 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.Reflection;
-using System.Collections;
-using System.Collections.Generic;
-using System.Threading;
-using System.Security;
-using System.Runtime.CompilerServices;
-using System.Runtime.ConstrainedExecution;
-using System.Runtime.Versioning;
-using System.IO;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-
-namespace System.Globalization
-{
- /*=================================GlobalizationAssembly==========================
- **
- ** This class provides the table loading wrapper that calls GetManifestResourceStream
- **
- ** It used to provide an idea for sort versioning, but that proved to not work
- **
- ============================================================================*/
- internal sealed class GlobalizationAssembly
- {
- // ----------------------------------------------------------------------------------------------------
- //
- // Instance data members and instance methods.
- //
- // ----------------------------------------------------------------------------------------------------
- internal unsafe static byte* GetGlobalizationResourceBytePtr(Assembly assembly, String tableName)
- {
- Debug.Assert(assembly != null, "assembly can not be null. This should be generally the " + System.CoreLib.Name + " assembly.");
- Debug.Assert(tableName != null, "table name can not be null");
-
- Stream stream = assembly.GetManifestResourceStream(tableName);
- UnmanagedMemoryStream bytesStream = stream as UnmanagedMemoryStream;
- if (bytesStream != null)
- {
- byte* bytes = bytesStream.PositionPointer;
- if (bytes != null)
- {
- return (bytes);
- }
- }
-
- Debug.Assert(
- false,
- String.Format(
- CultureInfo.CurrentCulture,
- "Didn't get the resource table {0} for System.Globalization from {1}",
- tableName,
- assembly));
-
- // We can not continue if we can't get the resource.
- throw new InvalidOperationException();
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Globalization/TextInfo.Unix.cs b/src/mscorlib/src/System/Globalization/TextInfo.Unix.cs
index f7f64c684a..9f80d73891 100644
--- a/src/mscorlib/src/System/Globalization/TextInfo.Unix.cs
+++ b/src/mscorlib/src/System/Globalization/TextInfo.Unix.cs
@@ -11,7 +11,6 @@ namespace System.Globalization
{
public partial class TextInfo
{
- [NonSerialized]
private Tristate _needsTurkishCasing = Tristate.NotInitialized;
private void FinishInitialization(string textInfoName)
diff --git a/src/mscorlib/src/System/Globalization/TextInfo.Windows.cs b/src/mscorlib/src/System/Globalization/TextInfo.Windows.cs
index cc7c4df1da..58dfe32239 100644
--- a/src/mscorlib/src/System/Globalization/TextInfo.Windows.cs
+++ b/src/mscorlib/src/System/Globalization/TextInfo.Windows.cs
@@ -18,9 +18,9 @@ namespace System.Globalization
const uint LCMAP_SORTHANDLE = 0x20000000;
- long handle;
+ IntPtr handle;
int ret = Interop.Kernel32.LCMapStringEx(_textInfoName, LCMAP_SORTHANDLE, null, 0, &handle, IntPtr.Size, null, null, IntPtr.Zero);
- _sortHandle = ret > 0 ? (IntPtr)handle : IntPtr.Zero;
+ _sortHandle = ret > 0 ? handle : IntPtr.Zero;
}
private unsafe string ChangeCase(string s, bool toUpper)
diff --git a/src/mscorlib/src/System/Globalization/TextInfo.cs b/src/mscorlib/src/System/Globalization/TextInfo.cs
index 9a628768f1..c5acbd4579 100644
--- a/src/mscorlib/src/System/Globalization/TextInfo.cs
+++ b/src/mscorlib/src/System/Globalization/TextInfo.cs
@@ -21,10 +21,6 @@ namespace System.Globalization
{
public partial class TextInfo : ICloneable, IDeserializationCallback
{
- ////--------------------------------------------------------------------//
- //// Internal Information //
- ////--------------------------------------------------------------------//
-
private enum Tristate : byte
{
NotInitialized,
@@ -32,36 +28,22 @@ namespace System.Globalization
False,
}
- ////
- //// Variables.
- ////
-
- [OptionalField(VersionAdded = 2)]
- private String _listSeparator;
- [OptionalField(VersionAdded = 2)]
+ private string _listSeparator;
private bool _isReadOnly = false;
- //// _cultureName is the name of the creating culture. Note that we consider this authoratative,
- //// if the culture's textinfo changes when deserializing, then behavior may change.
- //// (ala Whidbey behavior). This is the only string Arrowhead needs to serialize.
- //// _cultureData is the data that backs this class.
- //// _textInfoName is the actual name of the textInfo (from cultureData.STEXTINFO)
- //// this can be the same as _cultureName on Silverlight since the OS knows
- //// how to do the sorting. However in the desktop, when we call the sorting dll, it doesn't
- //// know how to resolve custom locle names to sort ids so we have to have alredy resolved this.
- ////
-
- [OptionalField(VersionAdded = 3)]
+ /* _cultureName is the name of the creating culture.
+ _cultureData is the data that backs this class.
+ _textInfoName is the actual name of the textInfo (from cultureData.STEXTINFO)
+ In the desktop, when we call the sorting dll, it doesn't
+ know how to resolve custom locle names to sort ids so we have to have already resolved this.
+ */
+
private String _cultureName; // Name of the culture that created this text info
- [NonSerialized]
private CultureData _cultureData; // Data record for the culture that made us, not for this textinfo
- [NonSerialized]
private String _textInfoName; // Name of the text info we're using (ie: _cultureData.STEXTINFO)
- [NonSerialized]
private Tristate _isAsciiCasingSameAsInvariant = Tristate.NotInitialized;
// _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant
- [NonSerialized]
private readonly bool _invariantMode = GlobalizationMode.Invariant;
// Invariant text info
@@ -452,7 +434,7 @@ namespace System.Globalization
return ChangeCase(str, toUpper: true);
}
- private static Char ToUpperAsciiInvariant(Char c)
+ internal static Char ToUpperAsciiInvariant(Char c)
{
if ((uint)(c - 'a') <= (uint)('z' - 'a'))
{
diff --git a/src/mscorlib/src/System/Globalization/TimeSpanParse.cs b/src/mscorlib/src/System/Globalization/TimeSpanParse.cs
deleted file mode 100644
index bcfb2dafc5..0000000000
--- a/src/mscorlib/src/System/Globalization/TimeSpanParse.cs
+++ /dev/null
@@ -1,1810 +0,0 @@
-// 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 is called by TimeSpan to parse a time interval string.
-//
-// Standard Format:
-// -=-=-=-=-=-=-=-
-// "c": Constant format. [-][d'.']hh':'mm':'ss['.'fffffff]
-// Not culture sensitive. Default format (and null/empty format string) map to this format.
-//
-// "g": General format, short: [-][d':']h':'mm':'ss'.'FFFFFFF
-// Only print what's needed. Localized (if you want Invariant, pass in Invariant).
-// The fractional seconds separator is localized, equal to the culture's DecimalSeparator.
-//
-// "G": General format, long: [-]d':'hh':'mm':'ss'.'fffffff
-// Always print days and 7 fractional digits. Localized (if you want Invariant, pass in Invariant).
-// The fractional seconds separator is localized, equal to the culture's DecimalSeparator.
-//
-//
-// * "TryParseTimeSpan" is the main method for Parse/TryParse
-//
-// - TimeSpanTokenizer.GetNextToken() is used to split the input string into number and literal tokens.
-// - TimeSpanRawInfo.ProcessToken() adds the next token into the parsing intermediary state structure
-// - ProcessTerminalState() uses the fully initialized TimeSpanRawInfo to find a legal parse match.
-// The terminal states are attempted as follows:
-// foreach (+InvariantPattern, -InvariantPattern, +LocalizedPattern, -LocalizedPattern) try
-// 1 number => d
-// 2 numbers => h:m
-// 3 numbers => h:m:s | d.h:m | h:m:.f
-// 4 numbers => h:m:s.f | d.h:m:s | d.h:m:.f
-// 5 numbers => d.h:m:s.f
-//
-// Custom Format:
-// -=-=-=-=-=-=-=
-//
-// * "TryParseExactTimeSpan" is the main method for ParseExact/TryParseExact methods
-// * "TryParseExactMultipleTimeSpan" is the main method for ParseExact/TryparseExact
-// methods that take a String[] of formats
-//
-// - For single-letter formats "TryParseTimeSpan" is called (see above)
-// - For multi-letter formats "TryParseByFormat" is called
-// - TryParseByFormat uses helper methods (ParseExactLiteral, ParseExactDigits, etc)
-// which drive the underlying TimeSpanTokenizer. However, unlike standard formatting which
-// operates on whole-tokens, ParseExact operates at the character-level. As such,
-// TimeSpanTokenizer.NextChar and TimeSpanTokenizer.BackOne() are called directly.
-//
-////////////////////////////////////////////////////////////////////////////
-
-using System.Text;
-using System;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Globalization;
-
-namespace System.Globalization
-{
- internal static class TimeSpanParse
- {
- // ---- SECTION: members for internal support ---------*
- internal const int unlimitedDigits = -1;
- internal const int maxFractionDigits = 7;
-
- internal const int maxDays = 10675199;
- internal const int maxHours = 23;
- internal const int maxMinutes = 59;
- internal const int maxSeconds = 59;
- internal const int maxFraction = 9999999;
-
- #region InternalSupport
- private enum TimeSpanThrowStyle
- {
- None = 0,
- All = 1,
- }
-
- private enum ParseFailureKind
- {
- None = 0,
- ArgumentNull = 1,
- Format = 2,
- FormatWithParameter = 3,
- Overflow = 4,
- }
-
- [Flags]
- private enum TimeSpanStandardStyles
- { // Standard Format Styles
- None = 0x00000000,
- Invariant = 0x00000001, //Allow Invariant Culture
- Localized = 0x00000002, //Allow Localized Culture
- RequireFull = 0x00000004, //Require the input to be in DHMSF format
- Any = Invariant | Localized,
- }
-
- // TimeSpan Token Types
- private enum TTT
- {
- None = 0, // None of the TimeSpanToken fields are set
- End = 1, // '\0'
- Num = 2, // Number
- Sep = 3, // literal
- NumOverflow = 4, // Number that overflowed
- }
-
- private static readonly TimeSpanToken zero = new TimeSpanToken(0);
- private struct TimeSpanToken
- {
- internal TTT ttt;
- internal int num; // Store the number that we are parsing (if any)
- internal int zeroes; // Store the number of leading zeroes (if any)
- internal String sep; // Store the literal that we are parsing (if any)
-
- public TimeSpanToken(int number)
- {
- ttt = TTT.Num;
- num = number;
- zeroes = 0;
- sep = null;
- }
-
- public TimeSpanToken(int leadingZeroes, int number)
- {
- ttt = TTT.Num;
- num = number;
- zeroes = leadingZeroes;
- sep = null;
- }
-
- public bool IsInvalidNumber(int maxValue, int maxPrecision)
- {
- Debug.Assert(ttt == TTT.Num);
- Debug.Assert(num > -1);
- Debug.Assert(maxValue > 0);
- Debug.Assert(maxPrecision == maxFractionDigits || maxPrecision == unlimitedDigits);
-
- if (num > maxValue)
- return true;
- if (maxPrecision == unlimitedDigits)
- return false; // all validation past this point applies only to fields with precision limits
- if (zeroes > maxPrecision)
- return true;
- if (num == 0 || zeroes == 0)
- return false;
-
- // num > 0 && zeroes > 0 && num <= maxValue && zeroes <= maxPrecision
- return (num >= (maxValue / (long)Math.Pow(10, zeroes - 1)));
- }
- }
-
- //
- // TimeSpanTokenizer
- //
- // Actions: TimeSpanTokenizer.GetNextToken() returns the next token in the input string.
- //
- private struct TimeSpanTokenizer
- {
- private int m_pos;
- private String m_value;
-
- internal void Init(String input)
- {
- Init(input, 0);
- }
- internal void Init(String input, int startPosition)
- {
- m_pos = startPosition;
- m_value = input;
- }
- // used by the parsing routines that operate on standard-formats
- internal TimeSpanToken GetNextToken()
- {
- Debug.Assert(m_pos > -1);
-
- TimeSpanToken tok = new TimeSpanToken();
- char ch = CurrentChar;
-
- if (ch == (char)0)
- {
- tok.ttt = TTT.End;
- return tok;
- }
-
- if (ch >= '0' && ch <= '9')
- {
- tok.ttt = TTT.Num;
- tok.num = 0;
- tok.zeroes = 0;
- do
- {
- if ((tok.num & 0xF0000000) != 0)
- {
- tok.ttt = TTT.NumOverflow;
- return tok;
- }
- tok.num = tok.num * 10 + ch - '0';
- if (tok.num == 0) tok.zeroes++;
- if (tok.num < 0)
- {
- tok.ttt = TTT.NumOverflow;
- return tok;
- }
- ch = NextChar;
- } while (ch >= '0' && ch <= '9');
- return tok;
- }
- else
- {
- tok.ttt = TTT.Sep;
- int startIndex = m_pos;
- int length = 0;
-
- while (ch != (char)0 && (ch < '0' || '9' < ch))
- {
- ch = NextChar;
- length++;
- }
- tok.sep = m_value.Substring(startIndex, length);
- return tok;
- }
- }
-
- internal Boolean EOL
- {
- get
- {
- return m_pos >= (m_value.Length - 1);
- }
- }
- // BackOne, NextChar, CurrentChar - used by ParseExact (ParseByFormat) to operate
- // on custom-formats where exact character-by-character control is allowed
- internal void BackOne()
- {
- if (m_pos > 0) --m_pos;
- }
-
- internal char NextChar
- {
- get
- {
- m_pos++;
- return CurrentChar;
- }
- }
- internal char CurrentChar
- {
- get
- {
- if (m_pos > -1 && m_pos < m_value.Length)
- {
- return m_value[m_pos];
- }
- else
- {
- return (char)0;
- }
- }
- }
- }
-
-
-
- // This stores intermediary parsing state for the standard formats
- private struct TimeSpanRawInfo
- {
- internal TimeSpanFormat.FormatLiterals PositiveInvariant
- {
- get
- {
- return TimeSpanFormat.PositiveInvariantFormatLiterals;
- }
- }
- internal TimeSpanFormat.FormatLiterals NegativeInvariant
- {
- get
- {
- return TimeSpanFormat.NegativeInvariantFormatLiterals;
- }
- }
-
- internal TimeSpanFormat.FormatLiterals PositiveLocalized
- {
- get
- {
- if (!m_posLocInit)
- {
- m_posLoc = new TimeSpanFormat.FormatLiterals();
- m_posLoc.Init(m_fullPosPattern, false);
- m_posLocInit = true;
- }
- return m_posLoc;
- }
- }
- internal TimeSpanFormat.FormatLiterals NegativeLocalized
- {
- get
- {
- if (!m_negLocInit)
- {
- m_negLoc = new TimeSpanFormat.FormatLiterals();
- m_negLoc.Init(m_fullNegPattern, false);
- m_negLocInit = true;
- }
- return m_negLoc;
- }
- }
-
- internal Boolean FullAppCompatMatch(TimeSpanFormat.FormatLiterals pattern)
- {
- return SepCount == 5
- && NumCount == 4
- && pattern.Start == literals[0]
- && pattern.DayHourSep == literals[1]
- && pattern.HourMinuteSep == literals[2]
- && pattern.AppCompatLiteral == literals[3]
- && pattern.End == literals[4];
- }
-
- internal Boolean PartialAppCompatMatch(TimeSpanFormat.FormatLiterals pattern)
- {
- return SepCount == 4
- && NumCount == 3
- && pattern.Start == literals[0]
- && pattern.HourMinuteSep == literals[1]
- && pattern.AppCompatLiteral == literals[2]
- && pattern.End == literals[3];
- }
- // DHMSF (all values matched)
- internal Boolean FullMatch(TimeSpanFormat.FormatLiterals pattern)
- {
- return SepCount == MaxLiteralTokens
- && NumCount == MaxNumericTokens
- && pattern.Start == literals[0]
- && pattern.DayHourSep == literals[1]
- && pattern.HourMinuteSep == literals[2]
- && pattern.MinuteSecondSep == literals[3]
- && pattern.SecondFractionSep == literals[4]
- && pattern.End == literals[5];
- }
- // D (no hours, minutes, seconds, or fractions)
- internal Boolean FullDMatch(TimeSpanFormat.FormatLiterals pattern)
- {
- return SepCount == 2
- && NumCount == 1
- && pattern.Start == literals[0]
- && pattern.End == literals[1];
- }
- // HM (no days, seconds, or fractions)
- internal Boolean FullHMMatch(TimeSpanFormat.FormatLiterals pattern)
- {
- return SepCount == 3
- && NumCount == 2
- && pattern.Start == literals[0]
- && pattern.HourMinuteSep == literals[1]
- && pattern.End == literals[2];
- }
- // DHM (no seconds or fraction)
- internal Boolean FullDHMMatch(TimeSpanFormat.FormatLiterals pattern)
- {
- return SepCount == 4
- && NumCount == 3
- && pattern.Start == literals[0]
- && pattern.DayHourSep == literals[1]
- && pattern.HourMinuteSep == literals[2]
- && pattern.End == literals[3];
- }
- // HMS (no days or fraction)
- internal Boolean FullHMSMatch(TimeSpanFormat.FormatLiterals pattern)
- {
- return SepCount == 4
- && NumCount == 3
- && pattern.Start == literals[0]
- && pattern.HourMinuteSep == literals[1]
- && pattern.MinuteSecondSep == literals[2]
- && pattern.End == literals[3];
- }
- // DHMS (no fraction)
- internal Boolean FullDHMSMatch(TimeSpanFormat.FormatLiterals pattern)
- {
- return SepCount == 5
- && NumCount == 4
- && pattern.Start == literals[0]
- && pattern.DayHourSep == literals[1]
- && pattern.HourMinuteSep == literals[2]
- && pattern.MinuteSecondSep == literals[3]
- && pattern.End == literals[4];
- }
- // HMSF (no days)
- internal Boolean FullHMSFMatch(TimeSpanFormat.FormatLiterals pattern)
- {
- return SepCount == 5
- && NumCount == 4
- && pattern.Start == literals[0]
- && pattern.HourMinuteSep == literals[1]
- && pattern.MinuteSecondSep == literals[2]
- && pattern.SecondFractionSep == literals[3]
- && pattern.End == literals[4];
- }
-
- internal TTT lastSeenTTT;
- internal int tokenCount;
- internal int SepCount;
- internal int NumCount;
- internal String[] literals;
- internal TimeSpanToken[] numbers; // raw numbers
-
- private TimeSpanFormat.FormatLiterals m_posLoc;
- private TimeSpanFormat.FormatLiterals m_negLoc;
- private Boolean m_posLocInit;
- private Boolean m_negLocInit;
- private String m_fullPosPattern;
- private String m_fullNegPattern;
-
- private const int MaxTokens = 11;
- private const int MaxLiteralTokens = 6;
- private const int MaxNumericTokens = 5;
-
- internal void Init(DateTimeFormatInfo dtfi)
- {
- Debug.Assert(dtfi != null);
-
- lastSeenTTT = TTT.None;
- tokenCount = 0;
- SepCount = 0;
- NumCount = 0;
-
- literals = new String[MaxLiteralTokens];
- numbers = new TimeSpanToken[MaxNumericTokens];
-
- m_fullPosPattern = dtfi.FullTimeSpanPositivePattern;
- m_fullNegPattern = dtfi.FullTimeSpanNegativePattern;
- m_posLocInit = false;
- m_negLocInit = false;
- }
-
- internal Boolean ProcessToken(ref TimeSpanToken tok, ref TimeSpanResult result)
- {
- if (tok.ttt == TTT.NumOverflow)
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge", null);
- return false;
- }
- if (tok.ttt != TTT.Sep && tok.ttt != TTT.Num)
- {
- // Some unknown token or a repeat token type in the input
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan", null);
- return false;
- }
-
- switch (tok.ttt)
- {
- case TTT.Sep:
- if (!AddSep(tok.sep, ref result)) return false;
- break;
- case TTT.Num:
- if (tokenCount == 0)
- {
- if (!AddSep(String.Empty, ref result)) return false;
- }
- if (!AddNum(tok, ref result)) return false;
- break;
- default:
- break;
- }
-
- lastSeenTTT = tok.ttt;
- Debug.Assert(tokenCount == (SepCount + NumCount), "tokenCount == (SepCount + NumCount)");
- return true;
- }
-
- private bool AddSep(String sep, ref TimeSpanResult result)
- {
- if (SepCount >= MaxLiteralTokens || tokenCount >= MaxTokens)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan", null);
- return false;
- }
- literals[SepCount++] = sep;
- tokenCount++;
- return true;
- }
- private bool AddNum(TimeSpanToken num, ref TimeSpanResult result)
- {
- if (NumCount >= MaxNumericTokens || tokenCount >= MaxTokens)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan", null);
- return false;
- }
- numbers[NumCount++] = num;
- tokenCount++;
- return true;
- }
- }
-
- // This will store the result of the parsing. And it will eventually be used to construct a TimeSpan instance.
- private struct TimeSpanResult
- {
- internal TimeSpan parsedTimeSpan;
- internal TimeSpanThrowStyle throwStyle;
-
- internal ParseFailureKind m_failure;
- internal string m_failureMessageID;
- internal object m_failureMessageFormatArgument;
- internal string m_failureArgumentName;
-
- internal void Init(TimeSpanThrowStyle canThrow)
- {
- parsedTimeSpan = default(TimeSpan);
- throwStyle = canThrow;
- }
- internal void SetFailure(ParseFailureKind failure, string failureMessageID)
- {
- SetFailure(failure, failureMessageID, null, null);
- }
- internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument)
- {
- SetFailure(failure, failureMessageID, failureMessageFormatArgument, null);
- }
- internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument,
- string failureArgumentName)
- {
- m_failure = failure;
- m_failureMessageID = failureMessageID;
- m_failureMessageFormatArgument = failureMessageFormatArgument;
- m_failureArgumentName = failureArgumentName;
- if (throwStyle != TimeSpanThrowStyle.None)
- {
- throw GetTimeSpanParseException();
- }
- }
-
- internal Exception GetTimeSpanParseException()
- {
- switch (m_failure)
- {
- case ParseFailureKind.ArgumentNull:
- return new ArgumentNullException(m_failureArgumentName, SR.GetResourceString(m_failureMessageID));
-
- case ParseFailureKind.FormatWithParameter:
- return new FormatException(SR.Format(SR.GetResourceString(m_failureMessageID), m_failureMessageFormatArgument));
-
- case ParseFailureKind.Format:
- return new FormatException(SR.GetResourceString(m_failureMessageID));
-
- case ParseFailureKind.Overflow:
- return new OverflowException(SR.GetResourceString(m_failureMessageID));
-
- default:
- Debug.Assert(false, "Unknown TimeSpanParseFailure: " + m_failure);
- return new FormatException(SR.Format_InvalidString);
- }
- }
- }
-
- private static bool TryTimeToTicks(bool positive, TimeSpanToken days, TimeSpanToken hours, TimeSpanToken minutes, TimeSpanToken seconds, TimeSpanToken fraction, out long result)
- {
- if (days.IsInvalidNumber(maxDays, unlimitedDigits)
- || hours.IsInvalidNumber(maxHours, unlimitedDigits)
- || minutes.IsInvalidNumber(maxMinutes, unlimitedDigits)
- || seconds.IsInvalidNumber(maxSeconds, unlimitedDigits)
- || fraction.IsInvalidNumber(maxFraction, maxFractionDigits))
- {
- result = 0;
- return false;
- }
-
- Int64 ticks = ((Int64)days.num * 3600 * 24 + (Int64)hours.num * 3600 + (Int64)minutes.num * 60 + seconds.num) * 1000;
- if (ticks > TimeSpan.MaxMilliSeconds || ticks < TimeSpan.MinMilliSeconds)
- {
- result = 0;
- return false;
- }
-
- // Normalize the fraction component
- //
- // string representation => (zeroes,num) => resultant fraction ticks
- // --------------------- ------------ ------------------------
- // ".9999999" => (0,9999999) => 9,999,999 ticks (same as constant maxFraction)
- // ".1" => (0,1) => 1,000,000 ticks
- // ".01" => (1,1) => 100,000 ticks
- // ".001" => (2,1) => 10,000 ticks
- long f = fraction.num;
- if (f != 0)
- {
- long lowerLimit = TimeSpan.TicksPerTenthSecond;
- if (fraction.zeroes > 0)
- {
- long divisor = (long)Math.Pow(10, fraction.zeroes);
- lowerLimit = lowerLimit / divisor;
- }
- while (f < lowerLimit)
- {
- f *= 10;
- }
- }
- result = ((long)ticks * TimeSpan.TicksPerMillisecond) + f;
- if (positive && result < 0)
- {
- result = 0;
- return false;
- }
- return true;
- }
- #endregion
-
-
- // ---- SECTION: internal static methods called by System.TimeSpan ---------*
- //
- // [Try]Parse, [Try]ParseExact, and [Try]ParseExactMultiple
- //
- // Actions: Main methods called from TimeSpan.Parse
- #region ParseMethods
- internal static TimeSpan Parse(String input, IFormatProvider formatProvider)
- {
- TimeSpanResult parseResult = new TimeSpanResult();
- parseResult.Init(TimeSpanThrowStyle.All);
-
- if (TryParseTimeSpan(input, TimeSpanStandardStyles.Any, formatProvider, ref parseResult))
- {
- return parseResult.parsedTimeSpan;
- }
- else
- {
- throw parseResult.GetTimeSpanParseException();
- }
- }
- internal static Boolean TryParse(String input, IFormatProvider formatProvider, out TimeSpan result)
- {
- TimeSpanResult parseResult = new TimeSpanResult();
- parseResult.Init(TimeSpanThrowStyle.None);
-
- if (TryParseTimeSpan(input, TimeSpanStandardStyles.Any, formatProvider, ref parseResult))
- {
- result = parseResult.parsedTimeSpan;
- return true;
- }
- else
- {
- result = default(TimeSpan);
- return false;
- }
- }
- internal static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles)
- {
- TimeSpanResult parseResult = new TimeSpanResult();
- parseResult.Init(TimeSpanThrowStyle.All);
-
- if (TryParseExactTimeSpan(input, format, formatProvider, styles, ref parseResult))
- {
- return parseResult.parsedTimeSpan;
- }
- else
- {
- throw parseResult.GetTimeSpanParseException();
- }
- }
- internal static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result)
- {
- TimeSpanResult parseResult = new TimeSpanResult();
- parseResult.Init(TimeSpanThrowStyle.None);
-
- if (TryParseExactTimeSpan(input, format, formatProvider, styles, ref parseResult))
- {
- result = parseResult.parsedTimeSpan;
- return true;
- }
- else
- {
- result = default(TimeSpan);
- return false;
- }
- }
- internal static TimeSpan ParseExactMultiple(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles)
- {
- TimeSpanResult parseResult = new TimeSpanResult();
- parseResult.Init(TimeSpanThrowStyle.All);
-
- if (TryParseExactMultipleTimeSpan(input, formats, formatProvider, styles, ref parseResult))
- {
- return parseResult.parsedTimeSpan;
- }
- else
- {
- throw parseResult.GetTimeSpanParseException();
- }
- }
- internal static Boolean TryParseExactMultiple(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result)
- {
- TimeSpanResult parseResult = new TimeSpanResult();
- parseResult.Init(TimeSpanThrowStyle.None);
-
- if (TryParseExactMultipleTimeSpan(input, formats, formatProvider, styles, ref parseResult))
- {
- result = parseResult.parsedTimeSpan;
- return true;
- }
- else
- {
- result = default(TimeSpan);
- return false;
- }
- }
- #endregion
-
-
- // ---- SECTION: private static methods that do the actual work ---------*
- #region TryParseTimeSpan
- //
- // TryParseTimeSpan
- //
- // Actions: Common private Parse method called by both Parse and TryParse
- //
- private static Boolean TryParseTimeSpan(String input, TimeSpanStandardStyles style, IFormatProvider formatProvider, ref TimeSpanResult result)
- {
- if (input == null)
- {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(input));
- return false;
- }
-
- input = input.Trim();
- if (input == String.Empty)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
-
- TimeSpanTokenizer tokenizer = new TimeSpanTokenizer();
- tokenizer.Init(input);
-
- TimeSpanRawInfo raw = new TimeSpanRawInfo();
- raw.Init(DateTimeFormatInfo.GetInstance(formatProvider));
-
- TimeSpanToken tok = tokenizer.GetNextToken();
-
- /* The following loop will break out when we reach the end of the str or
- * when we can determine that the input is invalid. */
- while (tok.ttt != TTT.End)
- {
- if (!raw.ProcessToken(ref tok, ref result))
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
- tok = tokenizer.GetNextToken();
- }
- if (!tokenizer.EOL)
- {
- // embedded nulls in the input string
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
- if (!ProcessTerminalState(ref raw, style, ref result))
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
- return true;
- }
-
-
-
- //
- // ProcessTerminalState
- //
- // Actions: Validate the terminal state of a standard format parse.
- // Sets result.parsedTimeSpan on success.
- //
- // Calculates the resultant TimeSpan from the TimeSpanRawInfo
- //
- // try => +InvariantPattern, -InvariantPattern, +LocalizedPattern, -LocalizedPattern
- // 1) Verify Start matches
- // 2) Verify End matches
- // 3) 1 number => d
- // 2 numbers => h:m
- // 3 numbers => h:m:s | d.h:m | h:m:.f
- // 4 numbers => h:m:s.f | d.h:m:s | d.h:m:.f
- // 5 numbers => d.h:m:s.f
- private static Boolean ProcessTerminalState(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
- {
- if (raw.lastSeenTTT == TTT.Num)
- {
- TimeSpanToken tok = new TimeSpanToken();
- tok.ttt = TTT.Sep;
- tok.sep = String.Empty;
- if (!raw.ProcessToken(ref tok, ref result))
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
- }
-
- switch (raw.NumCount)
- {
- case 1:
- return ProcessTerminal_D(ref raw, style, ref result);
- case 2:
- return ProcessTerminal_HM(ref raw, style, ref result);
- case 3:
- return ProcessTerminal_HM_S_D(ref raw, style, ref result);
- case 4:
- return ProcessTerminal_HMS_F_D(ref raw, style, ref result);
- case 5:
- return ProcessTerminal_DHMSF(ref raw, style, ref result);
- default:
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
- }
-
- //
- // ProcessTerminal_DHMSF
- //
- // Actions: Validate the 5-number "Days.Hours:Minutes:Seconds.Fraction" terminal case.
- // Sets result.parsedTimeSpan on success.
- //
- private static Boolean ProcessTerminal_DHMSF(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
- {
- if (raw.SepCount != 6 || raw.NumCount != 5)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
-
- bool inv = ((style & TimeSpanStandardStyles.Invariant) != 0);
- bool loc = ((style & TimeSpanStandardStyles.Localized) != 0);
-
- bool positive = false;
- bool match = false;
-
- if (inv)
- {
- if (raw.FullMatch(raw.PositiveInvariant))
- {
- match = true;
- positive = true;
- }
- if (!match && raw.FullMatch(raw.NegativeInvariant))
- {
- match = true;
- positive = false;
- }
- }
- if (loc)
- {
- if (!match && raw.FullMatch(raw.PositiveLocalized))
- {
- match = true;
- positive = true;
- }
- if (!match && raw.FullMatch(raw.NegativeLocalized))
- {
- match = true;
- positive = false;
- }
- }
- long ticks;
- if (match)
- {
- if (!TryTimeToTicks(positive, raw.numbers[0], raw.numbers[1], raw.numbers[2], raw.numbers[3], raw.numbers[4], out ticks))
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- if (!positive)
- {
- ticks = -ticks;
- if (ticks > 0)
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- }
- result.parsedTimeSpan._ticks = ticks;
- return true;
- }
-
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
-
- //
- // ProcessTerminal_HMS_F_D
- //
- // Actions: Validate the ambiguous 4-number "Hours:Minutes:Seconds.Fraction", "Days.Hours:Minutes:Seconds", or "Days.Hours:Minutes:.Fraction" terminal case.
- // Sets result.parsedTimeSpan on success.
- //
- private static Boolean ProcessTerminal_HMS_F_D(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
- {
- if (raw.SepCount != 5 || raw.NumCount != 4 || (style & TimeSpanStandardStyles.RequireFull) != 0)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
-
- bool inv = ((style & TimeSpanStandardStyles.Invariant) != 0);
- bool loc = ((style & TimeSpanStandardStyles.Localized) != 0);
-
- long ticks = 0;
- bool positive = false;
- bool match = false;
- bool overflow = false;
-
- if (inv)
- {
- if (raw.FullHMSFMatch(raw.PositiveInvariant))
- {
- positive = true;
- match = TryTimeToTicks(positive, zero, raw.numbers[0], raw.numbers[1], raw.numbers[2], raw.numbers[3], out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullDHMSMatch(raw.PositiveInvariant))
- {
- positive = true;
- match = TryTimeToTicks(positive, raw.numbers[0], raw.numbers[1], raw.numbers[2], raw.numbers[3], zero, out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullAppCompatMatch(raw.PositiveInvariant))
- {
- positive = true;
- match = TryTimeToTicks(positive, raw.numbers[0], raw.numbers[1], raw.numbers[2], zero, raw.numbers[3], out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullHMSFMatch(raw.NegativeInvariant))
- {
- positive = false;
- match = TryTimeToTicks(positive, zero, raw.numbers[0], raw.numbers[1], raw.numbers[2], raw.numbers[3], out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullDHMSMatch(raw.NegativeInvariant))
- {
- positive = false;
- match = TryTimeToTicks(positive, raw.numbers[0], raw.numbers[1], raw.numbers[2], raw.numbers[3], zero, out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullAppCompatMatch(raw.NegativeInvariant))
- {
- positive = false;
- match = TryTimeToTicks(positive, raw.numbers[0], raw.numbers[1], raw.numbers[2], zero, raw.numbers[3], out ticks);
- overflow = overflow || !match;
- }
- }
- if (loc)
- {
- if (!match && raw.FullHMSFMatch(raw.PositiveLocalized))
- {
- positive = true;
- match = TryTimeToTicks(positive, zero, raw.numbers[0], raw.numbers[1], raw.numbers[2], raw.numbers[3], out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullDHMSMatch(raw.PositiveLocalized))
- {
- positive = true;
- match = TryTimeToTicks(positive, raw.numbers[0], raw.numbers[1], raw.numbers[2], raw.numbers[3], zero, out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullAppCompatMatch(raw.PositiveLocalized))
- {
- positive = true;
- match = TryTimeToTicks(positive, raw.numbers[0], raw.numbers[1], raw.numbers[2], zero, raw.numbers[3], out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullHMSFMatch(raw.NegativeLocalized))
- {
- positive = false;
- match = TryTimeToTicks(positive, zero, raw.numbers[0], raw.numbers[1], raw.numbers[2], raw.numbers[3], out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullDHMSMatch(raw.NegativeLocalized))
- {
- positive = false;
- match = TryTimeToTicks(positive, raw.numbers[0], raw.numbers[1], raw.numbers[2], raw.numbers[3], zero, out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullAppCompatMatch(raw.NegativeLocalized))
- {
- positive = false;
- match = TryTimeToTicks(positive, raw.numbers[0], raw.numbers[1], raw.numbers[2], zero, raw.numbers[3], out ticks);
- overflow = overflow || !match;
- }
- }
-
- if (match)
- {
- if (!positive)
- {
- ticks = -ticks;
- if (ticks > 0)
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- }
- result.parsedTimeSpan._ticks = ticks;
- return true;
- }
-
- if (overflow)
- {
- // we found at least one literal pattern match but the numbers just didn't fit
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- else
- {
- // we couldn't find a thing
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
- }
-
- //
- // ProcessTerminal_HM_S_D
- //
- // Actions: Validate the ambiguous 3-number "Hours:Minutes:Seconds", "Days.Hours:Minutes", or "Hours:Minutes:.Fraction" terminal case
- //
- private static Boolean ProcessTerminal_HM_S_D(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
- {
- if (raw.SepCount != 4 || raw.NumCount != 3 || (style & TimeSpanStandardStyles.RequireFull) != 0)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
-
- bool inv = ((style & TimeSpanStandardStyles.Invariant) != 0);
- bool loc = ((style & TimeSpanStandardStyles.Localized) != 0);
-
- bool positive = false;
- bool match = false;
- bool overflow = false;
-
- long ticks = 0;
-
- if (inv)
- {
- if (raw.FullHMSMatch(raw.PositiveInvariant))
- {
- positive = true;
- match = TryTimeToTicks(positive, zero, raw.numbers[0], raw.numbers[1], raw.numbers[2], zero, out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullDHMMatch(raw.PositiveInvariant))
- {
- positive = true;
- match = TryTimeToTicks(positive, raw.numbers[0], raw.numbers[1], raw.numbers[2], zero, zero, out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.PartialAppCompatMatch(raw.PositiveInvariant))
- {
- positive = true;
- match = TryTimeToTicks(positive, zero, raw.numbers[0], raw.numbers[1], zero, raw.numbers[2], out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullHMSMatch(raw.NegativeInvariant))
- {
- positive = false;
- match = TryTimeToTicks(positive, zero, raw.numbers[0], raw.numbers[1], raw.numbers[2], zero, out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullDHMMatch(raw.NegativeInvariant))
- {
- positive = false;
- match = TryTimeToTicks(positive, raw.numbers[0], raw.numbers[1], raw.numbers[2], zero, zero, out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.PartialAppCompatMatch(raw.NegativeInvariant))
- {
- positive = false;
- match = TryTimeToTicks(positive, zero, raw.numbers[0], raw.numbers[1], zero, raw.numbers[2], out ticks);
- overflow = overflow || !match;
- }
- }
- if (loc)
- {
- if (!match && raw.FullHMSMatch(raw.PositiveLocalized))
- {
- positive = true;
- match = TryTimeToTicks(positive, zero, raw.numbers[0], raw.numbers[1], raw.numbers[2], zero, out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullDHMMatch(raw.PositiveLocalized))
- {
- positive = true;
- match = TryTimeToTicks(positive, raw.numbers[0], raw.numbers[1], raw.numbers[2], zero, zero, out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.PartialAppCompatMatch(raw.PositiveLocalized))
- {
- positive = true;
- match = TryTimeToTicks(positive, zero, raw.numbers[0], raw.numbers[1], zero, raw.numbers[2], out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullHMSMatch(raw.NegativeLocalized))
- {
- positive = false;
- match = TryTimeToTicks(positive, zero, raw.numbers[0], raw.numbers[1], raw.numbers[2], zero, out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.FullDHMMatch(raw.NegativeLocalized))
- {
- positive = false;
- match = TryTimeToTicks(positive, raw.numbers[0], raw.numbers[1], raw.numbers[2], zero, zero, out ticks);
- overflow = overflow || !match;
- }
- if (!match && raw.PartialAppCompatMatch(raw.NegativeLocalized))
- {
- positive = false;
- match = TryTimeToTicks(positive, zero, raw.numbers[0], raw.numbers[1], zero, raw.numbers[2], out ticks);
- overflow = overflow || !match;
- }
- }
-
- if (match)
- {
- if (!positive)
- {
- ticks = -ticks;
- if (ticks > 0)
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- }
- result.parsedTimeSpan._ticks = ticks;
- return true;
- }
-
- if (overflow)
- {
- // we found at least one literal pattern match but the numbers just didn't fit
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- else
- {
- // we couldn't find a thing
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
- }
-
- //
- // ProcessTerminal_HM
- //
- // Actions: Validate the 2-number "Hours:Minutes" terminal case
- //
- private static Boolean ProcessTerminal_HM(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
- {
- if (raw.SepCount != 3 || raw.NumCount != 2 || (style & TimeSpanStandardStyles.RequireFull) != 0)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
-
- bool inv = ((style & TimeSpanStandardStyles.Invariant) != 0);
- bool loc = ((style & TimeSpanStandardStyles.Localized) != 0);
-
- bool positive = false;
- bool match = false;
-
- if (inv)
- {
- if (raw.FullHMMatch(raw.PositiveInvariant))
- {
- match = true;
- positive = true;
- }
- if (!match && raw.FullHMMatch(raw.NegativeInvariant))
- {
- match = true;
- positive = false;
- }
- }
- if (loc)
- {
- if (!match && raw.FullHMMatch(raw.PositiveLocalized))
- {
- match = true;
- positive = true;
- }
- if (!match && raw.FullHMMatch(raw.NegativeLocalized))
- {
- match = true;
- positive = false;
- }
- }
-
- long ticks = 0;
- if (match)
- {
- if (!TryTimeToTicks(positive, zero, raw.numbers[0], raw.numbers[1], zero, zero, out ticks))
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- if (!positive)
- {
- ticks = -ticks;
- if (ticks > 0)
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- }
- result.parsedTimeSpan._ticks = ticks;
- return true;
- }
-
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
-
-
- //
- // ProcessTerminal_D
- //
- // Actions: Validate the 1-number "Days" terminal case
- //
- private static Boolean ProcessTerminal_D(ref TimeSpanRawInfo raw, TimeSpanStandardStyles style, ref TimeSpanResult result)
- {
- if (raw.SepCount != 2 || raw.NumCount != 1 || (style & TimeSpanStandardStyles.RequireFull) != 0)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
-
- bool inv = ((style & TimeSpanStandardStyles.Invariant) != 0);
- bool loc = ((style & TimeSpanStandardStyles.Localized) != 0);
-
- bool positive = false;
- bool match = false;
-
- if (inv)
- {
- if (raw.FullDMatch(raw.PositiveInvariant))
- {
- match = true;
- positive = true;
- }
- if (!match && raw.FullDMatch(raw.NegativeInvariant))
- {
- match = true;
- positive = false;
- }
- }
- if (loc)
- {
- if (!match && raw.FullDMatch(raw.PositiveLocalized))
- {
- match = true;
- positive = true;
- }
- if (!match && raw.FullDMatch(raw.NegativeLocalized))
- {
- match = true;
- positive = false;
- }
- }
-
- long ticks = 0;
- if (match)
- {
- if (!TryTimeToTicks(positive, raw.numbers[0], zero, zero, zero, zero, out ticks))
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- if (!positive)
- {
- ticks = -ticks;
- if (ticks > 0)
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- }
- result.parsedTimeSpan._ticks = ticks;
- return true;
- }
-
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
- #endregion
-
- #region TryParseExactTimeSpan
- //
- // TryParseExactTimeSpan
- //
- // Actions: Common private ParseExact method called by both ParseExact and TryParseExact
- //
- private static Boolean TryParseExactTimeSpan(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, ref TimeSpanResult result)
- {
- if (input == null)
- {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(input));
- return false;
- }
- if (format == null)
- {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(format));
- return false;
- }
- if (format.Length == 0)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier");
- return false;
- }
-
- if (format.Length == 1)
- {
- TimeSpanStandardStyles style = TimeSpanStandardStyles.None;
-
- if (format[0] == 'c' || format[0] == 't' || format[0] == 'T')
- {
- // fast path for legacy style TimeSpan formats.
- return TryParseTimeSpanConstant(input, ref result);
- }
- else if (format[0] == 'g')
- {
- style = TimeSpanStandardStyles.Localized;
- }
- else if (format[0] == 'G')
- {
- style = TimeSpanStandardStyles.Localized | TimeSpanStandardStyles.RequireFull;
- }
- else
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier");
- return false;
- }
- return TryParseTimeSpan(input, style, formatProvider, ref result);
- }
-
- return TryParseByFormat(input, format, styles, ref result);
- }
-
- //
- // TryParseByFormat
- //
- // Actions: Parse the TimeSpan instance using the specified format. Used by TryParseExactTimeSpan.
- //
- private static Boolean TryParseByFormat(String input, String format, TimeSpanStyles styles, ref TimeSpanResult result)
- {
- Debug.Assert(input != null, "input != null");
- Debug.Assert(format != null, "format != null");
-
- bool seenDD = false; // already processed days?
- bool seenHH = false; // already processed hours?
- bool seenMM = false; // already processed minutes?
- bool seenSS = false; // already processed seconds?
- bool seenFF = false; // already processed fraction?
- int dd = 0; // parsed days
- int hh = 0; // parsed hours
- int mm = 0; // parsed minutes
- int ss = 0; // parsed seconds
- int leadingZeroes = 0; // number of leading zeroes in the parsed fraction
- int ff = 0; // parsed fraction
- int i = 0; // format string position
- int tokenLen = 0; // length of current format token, used to update index 'i'
-
- TimeSpanTokenizer tokenizer = new TimeSpanTokenizer();
- tokenizer.Init(input, -1);
-
- while (i < format.Length)
- {
- char ch = format[i];
- int nextFormatChar;
- switch (ch)
- {
- case 'h':
- tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
- if (tokenLen > 2 || seenHH || !ParseExactDigits(ref tokenizer, tokenLen, out hh))
- {
- result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
- return false;
- }
- seenHH = true;
- break;
- case 'm':
- tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
- if (tokenLen > 2 || seenMM || !ParseExactDigits(ref tokenizer, tokenLen, out mm))
- {
- result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
- return false;
- }
- seenMM = true;
- break;
- case 's':
- tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
- if (tokenLen > 2 || seenSS || !ParseExactDigits(ref tokenizer, tokenLen, out ss))
- {
- result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
- return false;
- }
- seenSS = true;
- break;
- case 'f':
- tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
- if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits || seenFF || !ParseExactDigits(ref tokenizer, tokenLen, tokenLen, out leadingZeroes, out ff))
- {
- result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
- return false;
- }
- seenFF = true;
- break;
- case 'F':
- tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
- if (tokenLen > DateTimeFormat.MaxSecondsFractionDigits || seenFF)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
- return false;
- }
- ParseExactDigits(ref tokenizer, tokenLen, tokenLen, out leadingZeroes, out ff);
- seenFF = true;
- break;
- case 'd':
- tokenLen = DateTimeFormat.ParseRepeatPattern(format, i, ch);
- int tmp = 0;
- if (tokenLen > 8 || seenDD || !ParseExactDigits(ref tokenizer, (tokenLen < 2) ? 1 : tokenLen, (tokenLen < 2) ? 8 : tokenLen, out tmp, out dd))
- {
- result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
- return false;
- }
- seenDD = true;
- break;
- case '\'':
- case '\"':
- StringBuilder enquotedString = new StringBuilder();
- if (!DateTimeParse.TryParseQuoteString(format, i, enquotedString, out tokenLen))
- {
- result.SetFailure(ParseFailureKind.FormatWithParameter, "Format_BadQuote", ch);
- return false;
- }
- if (!ParseExactLiteral(ref tokenizer, enquotedString))
- {
- result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
- return false;
- }
- break;
- case '%':
- // Optional format character.
- // For example, format string "%d" will print day
- // Most of the cases, "%" can be ignored.
- nextFormatChar = DateTimeFormat.ParseNextChar(format, i);
- // nextFormatChar will be -1 if we already reach the end of the format string.
- // Besides, we will not allow "%%" appear in the pattern.
- if (nextFormatChar >= 0 && nextFormatChar != (int)'%')
- {
- tokenLen = 1; // skip the '%' and process the format character
- break;
- }
- else
- {
- // This means that '%' is at the end of the format string or
- // "%%" appears in the format string.
- result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
- return false;
- }
- case '\\':
- // Escaped character. Can be used to insert character into the format string.
- // For example, "\d" will insert the character 'd' into the string.
- //
- nextFormatChar = DateTimeFormat.ParseNextChar(format, i);
- if (nextFormatChar >= 0 && tokenizer.NextChar == (char)nextFormatChar)
- {
- tokenLen = 2;
- }
- else
- {
- // This means that '\' is at the end of the format string or the literal match failed.
- result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
- return false;
- }
- break;
- default:
- result.SetFailure(ParseFailureKind.Format, "Format_InvalidString");
- return false;
- }
- i += tokenLen;
- }
-
-
- if (!tokenizer.EOL)
- {
- // the custom format didn't consume the entire input
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
-
- long ticks = 0;
- bool positive = (styles & TimeSpanStyles.AssumeNegative) == 0;
- if (TryTimeToTicks(positive, new TimeSpanToken(dd),
- new TimeSpanToken(hh),
- new TimeSpanToken(mm),
- new TimeSpanToken(ss),
- new TimeSpanToken(leadingZeroes, ff),
- out ticks))
- {
- if (!positive) ticks = -ticks;
- result.parsedTimeSpan._ticks = ticks;
- return true;
- }
- else
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- }
-
- private static Boolean ParseExactDigits(ref TimeSpanTokenizer tokenizer, int minDigitLength, out int result)
- {
- result = 0;
- int zeroes = 0;
- int maxDigitLength = (minDigitLength == 1) ? 2 : minDigitLength;
- return ParseExactDigits(ref tokenizer, minDigitLength, maxDigitLength, out zeroes, out result);
- }
- private static Boolean ParseExactDigits(ref TimeSpanTokenizer tokenizer, int minDigitLength, int maxDigitLength, out int zeroes, out int result)
- {
- result = 0;
- zeroes = 0;
-
- int tokenLength = 0;
- while (tokenLength < maxDigitLength)
- {
- char ch = tokenizer.NextChar;
- if (ch < '0' || ch > '9')
- {
- tokenizer.BackOne();
- break;
- }
- result = result * 10 + (ch - '0');
- if (result == 0) zeroes++;
- tokenLength++;
- }
- return (tokenLength >= minDigitLength);
- }
- private static Boolean ParseExactLiteral(ref TimeSpanTokenizer tokenizer, StringBuilder enquotedString)
- {
- for (int i = 0; i < enquotedString.Length; i++)
- {
- if (enquotedString[i] != tokenizer.NextChar)
- return false;
- }
- return true;
- }
- #endregion
-
- #region TryParseTimeSpanConstant
- //
- // TryParseTimeSpanConstant
- //
- // Actions: Parses the "c" (constant) format. This code is 100% identical to the non-globalized v1.0-v3.5 TimeSpan.Parse() routine
- // and exists for performance/appcompat with legacy callers who cannot move onto the globalized Parse overloads.
- //
- private static Boolean TryParseTimeSpanConstant(String input, ref TimeSpanResult result)
- {
- return (new StringParser().TryParse(input, ref result));
- }
-
- private struct StringParser
- {
- private String str;
- private char ch;
- private int pos;
- private int len;
-
- internal void NextChar()
- {
- if (pos < len) pos++;
- ch = pos < len ? str[pos] : (char)0;
- }
-
- internal char NextNonDigit()
- {
- int i = pos;
- while (i < len)
- {
- char ch = str[i];
- if (ch < '0' || ch > '9') return ch;
- i++;
- }
- return (char)0;
- }
-
- internal bool TryParse(String input, ref TimeSpanResult result)
- {
- result.parsedTimeSpan._ticks = 0;
-
- if (input == null)
- {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(input));
- return false;
- }
- str = input;
- len = input.Length;
- pos = -1;
- NextChar();
- SkipBlanks();
- bool negative = false;
- if (ch == '-')
- {
- negative = true;
- NextChar();
- }
- long time;
- if (NextNonDigit() == ':')
- {
- if (!ParseTime(out time, ref result))
- {
- return false;
- };
- }
- else
- {
- int days;
- if (!ParseInt((int)(0x7FFFFFFFFFFFFFFFL / TimeSpan.TicksPerDay), out days, ref result))
- {
- return false;
- }
- time = days * TimeSpan.TicksPerDay;
- if (ch == '.')
- {
- NextChar();
- long remainingTime;
- if (!ParseTime(out remainingTime, ref result))
- {
- return false;
- };
- time += remainingTime;
- }
- }
- if (negative)
- {
- time = -time;
- // Allow -0 as well
- if (time > 0)
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- }
- else
- {
- if (time < 0)
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- }
- SkipBlanks();
- if (pos < len)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
- result.parsedTimeSpan._ticks = time;
- return true;
- }
-
- internal bool ParseInt(int max, out int i, ref TimeSpanResult result)
- {
- i = 0;
- int p = pos;
- while (ch >= '0' && ch <= '9')
- {
- if ((i & 0xF0000000) != 0)
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- i = i * 10 + ch - '0';
- if (i < 0)
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- NextChar();
- }
- if (p == pos)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
- if (i > max)
- {
- result.SetFailure(ParseFailureKind.Overflow, "Overflow_TimeSpanElementTooLarge");
- return false;
- }
- return true;
- }
-
- internal bool ParseTime(out long time, ref TimeSpanResult result)
- {
- time = 0;
- int unit;
- if (!ParseInt(23, out unit, ref result))
- {
- return false;
- }
- time = unit * TimeSpan.TicksPerHour;
- if (ch != ':')
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
- NextChar();
- if (!ParseInt(59, out unit, ref result))
- {
- return false;
- }
- time += unit * TimeSpan.TicksPerMinute;
- if (ch == ':')
- {
- NextChar();
- // allow seconds with the leading zero
- if (ch != '.')
- {
- if (!ParseInt(59, out unit, ref result))
- {
- return false;
- }
- time += unit * TimeSpan.TicksPerSecond;
- }
- if (ch == '.')
- {
- NextChar();
- int f = (int)TimeSpan.TicksPerSecond;
- while (f > 1 && ch >= '0' && ch <= '9')
- {
- f /= 10;
- time += (ch - '0') * f;
- NextChar();
- }
- }
- }
- return true;
- }
-
- internal void SkipBlanks()
- {
- while (ch == ' ' || ch == '\t') NextChar();
- }
- }
- #endregion
-
- #region TryParseExactMultipleTimeSpan
- //
- // TryParseExactMultipleTimeSpan
- //
- // Actions: Common private ParseExactMultiple method called by both ParseExactMultiple and TryParseExactMultiple
- //
- private static Boolean TryParseExactMultipleTimeSpan(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, ref TimeSpanResult result)
- {
- if (input == null)
- {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(input));
- return false;
- }
- if (formats == null)
- {
- result.SetFailure(ParseFailureKind.ArgumentNull, "ArgumentNull_String", null, nameof(formats));
- return false;
- }
-
- if (input.Length == 0)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return false;
- }
-
- if (formats.Length == 0)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier");
- return false;
- }
-
- //
- // Do a loop through the provided formats and see if we can parse succesfully in
- // one of the formats.
- //
- for (int i = 0; i < formats.Length; i++)
- {
- if (formats[i] == null || formats[i].Length == 0)
- {
- result.SetFailure(ParseFailureKind.Format, "Format_BadFormatSpecifier");
- return false;
- }
-
- // Create a new non-throwing result each time to ensure the runs are independent.
- TimeSpanResult innerResult = new TimeSpanResult();
- innerResult.Init(TimeSpanThrowStyle.None);
-
- if (TryParseExactTimeSpan(input, formats[i], formatProvider, styles, ref innerResult))
- {
- result.parsedTimeSpan = innerResult.parsedTimeSpan;
- return true;
- }
- }
-
- result.SetFailure(ParseFailureKind.Format, "Format_BadTimeSpan");
- return (false);
- }
- #endregion
- }
-}
diff --git a/src/mscorlib/src/System/Guid.CoreCLR.cs b/src/mscorlib/src/System/Guid.CoreCLR.cs
new file mode 100644
index 0000000000..f71d71b145
--- /dev/null
+++ b/src/mscorlib/src/System/Guid.CoreCLR.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 Microsoft.Win32;
+using System.Runtime.InteropServices;
+using System.Diagnostics.Contracts;
+
+namespace System
+{
+ partial struct Guid
+ {
+ // This will create a new guid. Since we've now decided that constructors should 0-init,
+ // we need a method that allows users to create a guid.
+ public static Guid NewGuid()
+ {
+ // CoCreateGuid should never return Guid.Empty, since it attempts to maintain some
+ // uniqueness guarantees. It should also never return a known GUID, but it's unclear
+ // how extensively it checks for known values.
+ Contract.Ensures(Contract.Result<Guid>() != Guid.Empty);
+
+ Guid guid;
+ Marshal.ThrowExceptionForHR(Win32Native.CoCreateGuid(out guid), new IntPtr(-1));
+ return guid;
+ }
+ }
+}
diff --git a/src/mscorlib/src/System/HResults.cs b/src/mscorlib/src/System/HResults.cs
deleted file mode 100644
index d733ad4b21..0000000000
--- a/src/mscorlib/src/System/HResults.cs
+++ /dev/null
@@ -1,235 +0,0 @@
-// 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: Define HResult constants. Every exception has one of these.
-//
-//
-//===========================================================================*/
-
-using System;
-
-namespace System
-{
- // Note: FACILITY_URT is defined as 0x13 (0x8013xxxx). Within that
- // range, 0x1yyy is for Runtime errors (used for Security, Metadata, etc).
- // In that subrange, 0x15zz and 0x16zz have been allocated for classlib-type
- // HResults. Also note that some of our HResults have to map to certain
- // COM HR's, etc.
-
- // Another arbitrary decision... Feel free to change this, as long as you
- // renumber the HResults yourself (and update rexcep.h).
- // Reflection will use 0x1600 -> 0x161f. IO will use 0x1620 -> 0x163f.
- // Security will use 0x1640 -> 0x165f
-
- // There are HResults files in the IO, Remoting, Reflection &
- // Security/Util directories as well, so choose your HResults carefully.
- internal static class HResults
- {
- internal const int APPMODEL_ERROR_NO_PACKAGE = unchecked((int)0x80073D54);
- internal const int CLDB_E_FILE_CORRUPT = unchecked((int)0x8013110e);
- internal const int CLDB_E_FILE_OLDVER = unchecked((int)0x80131107);
- internal const int CLDB_E_INDEX_NOTFOUND = unchecked((int)0x80131124);
- internal const int CLR_E_BIND_ASSEMBLY_NOT_FOUND = unchecked((int)0x80132004);
- internal const int CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH = unchecked((int)0x80132001);
- internal const int CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW = unchecked((int)0x80132000);
- internal const int CLR_E_BIND_TYPE_NOT_FOUND = unchecked((int)0x80132005);
- internal const int CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT = unchecked((int)0x80132003);
- internal const int COR_E_ABANDONEDMUTEX = unchecked((int)0x8013152D);
- internal const int COR_E_AMBIGUOUSMATCH = unchecked((int)0x8000211D);
- internal const int COR_E_APPDOMAINUNLOADED = unchecked((int)0x80131014);
- internal const int COR_E_APPLICATION = unchecked((int)0x80131600);
- internal const int COR_E_ARGUMENT = unchecked((int)0x80070057);
- internal const int COR_E_ARGUMENTOUTOFRANGE = unchecked((int)0x80131502);
- internal const int COR_E_ARITHMETIC = unchecked((int)0x80070216);
- internal const int COR_E_ARRAYTYPEMISMATCH = unchecked((int)0x80131503);
- internal const int COR_E_ASSEMBLYEXPECTED = unchecked((int)0x80131018);
- internal const int COR_E_BADIMAGEFORMAT = unchecked((int)0x8007000B);
- internal const int COR_E_CANNOTUNLOADAPPDOMAIN = unchecked((int)0x80131015);
- internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542);
- internal const int COR_E_CONTEXTMARSHAL = unchecked((int)0x80131504);
- internal const int COR_E_CUSTOMATTRIBUTEFORMAT = unchecked((int)0x80131605);
- internal const int COR_E_DATAMISALIGNED = unchecked((int)0x80131541);
- internal const int COR_E_DIVIDEBYZERO = unchecked((int)0x80020012); // DISP_E_DIVBYZERO
- internal const int COR_E_DLLNOTFOUND = unchecked((int)0x80131524);
- internal const int COR_E_DUPLICATEWAITOBJECT = unchecked((int)0x80131529);
- internal const int COR_E_ENTRYPOINTNOTFOUND = unchecked((int)0x80131523);
- internal const int COR_E_EXCEPTION = unchecked((int)0x80131500);
- internal const int COR_E_EXECUTIONENGINE = unchecked((int)0x80131506);
- internal const int COR_E_FIELDACCESS = unchecked((int)0x80131507);
- internal const int COR_E_FIXUPSINEXE = unchecked((int)0x80131019);
- internal const int COR_E_FORMAT = unchecked((int)0x80131537);
- internal const int COR_E_INDEXOUTOFRANGE = unchecked((int)0x80131508);
- internal const int COR_E_INSUFFICIENTEXECUTIONSTACK = unchecked((int)0x80131578);
- internal const int COR_E_INVALIDCAST = unchecked((int)0x80004002);
- internal const int COR_E_INVALIDCOMOBJECT = unchecked((int)0x80131527);
- internal const int COR_E_INVALIDFILTERCRITERIA = unchecked((int)0x80131601);
- internal const int COR_E_INVALIDOLEVARIANTTYPE = unchecked((int)0x80131531);
- internal const int COR_E_INVALIDOPERATION = unchecked((int)0x80131509);
- internal const int COR_E_INVALIDPROGRAM = unchecked((int)0x8013153a);
- internal const int COR_E_KEYNOTFOUND = unchecked((int)0x80131577);
- internal const int COR_E_MARSHALDIRECTIVE = unchecked((int)0x80131535);
- internal const int COR_E_MEMBERACCESS = unchecked((int)0x8013151A);
- internal const int COR_E_METHODACCESS = unchecked((int)0x80131510);
- internal const int COR_E_MISSINGFIELD = unchecked((int)0x80131511);
- internal const int COR_E_MISSINGMANIFESTRESOURCE = unchecked((int)0x80131532);
- internal const int COR_E_MISSINGMEMBER = unchecked((int)0x80131512);
- internal const int COR_E_MISSINGMETHOD = unchecked((int)0x80131513);
- internal const int COR_E_MISSINGSATELLITEASSEMBLY = unchecked((int)0x80131536);
- internal const int COR_E_MODULE_HASH_CHECK_FAILED = unchecked((int)0x80131039);
- internal const int COR_E_MULTICASTNOTSUPPORTED = unchecked((int)0x80131514);
- internal const int COR_E_NEWER_RUNTIME = unchecked((int)0x8013101b);
- internal const int COR_E_NOTFINITENUMBER = unchecked((int)0x80131528);
- internal const int COR_E_NOTSUPPORTED = unchecked((int)0x80131515);
- internal const int COR_E_NULLREFERENCE = unchecked((int)0x80004003);
- internal const int COR_E_OBJECTDISPOSED = unchecked((int)0x80131622);
- internal const int COR_E_OPERATIONCANCELED = unchecked((int)0x8013153B);
- internal const int COR_E_OUTOFMEMORY = unchecked((int)0x8007000E);
- internal const int COR_E_OVERFLOW = unchecked((int)0x80131516);
- internal const int COR_E_PLATFORMNOTSUPPORTED = unchecked((int)0x80131539);
- internal const int COR_E_RANK = unchecked((int)0x80131517);
- internal const int COR_E_REFLECTIONTYPELOAD = unchecked((int)0x80131602);
- internal const int COR_E_REMOTING = unchecked((int)0x8013150b);
- internal const int COR_E_RUNTIMEWRAPPED = unchecked((int)0x8013153e);
- internal const int COR_E_SAFEARRAYRANKMISMATCH = unchecked((int)0x80131538);
- internal const int COR_E_SAFEARRAYTYPEMISMATCH = unchecked((int)0x80131533);
- internal const int COR_E_SECURITY = unchecked((int)0x8013150A);
- internal const int COR_E_SERIALIZATION = unchecked((int)0x8013150C);
- internal const int COR_E_SERVER = unchecked((int)0x8013150e);
- internal const int COR_E_STACKOVERFLOW = unchecked((int)0x800703E9);
- internal const int COR_E_SYNCHRONIZATIONLOCK = unchecked((int)0x80131518);
- internal const int COR_E_SYSTEM = unchecked((int)0x80131501);
- internal const int COR_E_TARGET = unchecked((int)0x80131603);
- internal const int COR_E_TARGETINVOCATION = unchecked((int)0x80131604);
- internal const int COR_E_TARGETPARAMCOUNT = unchecked((int)0x8002000e);
- internal const int COR_E_THREADABORTED = unchecked((int)0x80131530);
- internal const int COR_E_THREADINTERRUPTED = unchecked((int)0x80131519);
- internal const int COR_E_THREADSTART = unchecked((int)0x80131525);
- internal const int COR_E_THREADSTATE = unchecked((int)0x80131520);
- internal const int COR_E_TIMEOUT = unchecked((int)0x80131505);
- internal const int COR_E_TYPEACCESS = unchecked((int)0x80131543);
- internal const int COR_E_TYPEINITIALIZATION = unchecked((int)0x80131534);
- internal const int COR_E_TYPELOAD = unchecked((int)0x80131522);
- internal const int COR_E_TYPEUNLOADED = unchecked((int)0x80131013);
- internal const int COR_E_UNAUTHORIZEDACCESS = unchecked((int)0x80070005);
- internal const int COR_E_VERIFICATION = unchecked((int)0x8013150D);
- internal const int COR_E_WAITHANDLECANNOTBEOPENED = unchecked((int)0x8013152C);
- internal const int CORSEC_E_CRYPTO = unchecked((int)0x80131430);
- internal const int CORSEC_E_CRYPTO_UNEX_OPER = unchecked((int)0x80131431);
- internal const int CORSEC_E_INVALID_IMAGE_FORMAT = unchecked((int)0x8013141d);
- internal const int CORSEC_E_INVALID_PUBLICKEY = unchecked((int)0x8013141e);
- internal const int CORSEC_E_INVALID_STRONGNAME = unchecked((int)0x8013141a);
- internal const int CORSEC_E_MIN_GRANT_FAIL = unchecked((int)0x80131417);
- internal const int CORSEC_E_MISSING_STRONGNAME = unchecked((int)0x8013141b);
- internal const int CORSEC_E_NO_EXEC_PERM = unchecked((int)0x80131418);
- internal const int CORSEC_E_POLICY_EXCEPTION = unchecked((int)0x80131416);
- internal const int CORSEC_E_SIGNATURE_MISMATCH = unchecked((int)0x80131420);
- internal const int CORSEC_E_XMLSYNTAX = unchecked((int)0x80131419);
- internal const int CTL_E_DEVICEIOERROR = unchecked((int)0x800A0039);
- internal const int CTL_E_DIVISIONBYZERO = unchecked((int)0x800A000B);
- internal const int CTL_E_FILENOTFOUND = unchecked((int)0x800A0035);
- internal const int CTL_E_OUTOFMEMORY = unchecked((int)0x800A0007);
- internal const int CTL_E_OUTOFSTACKSPACE = unchecked((int)0x800A001C);
- internal const int CTL_E_OVERFLOW = unchecked((int)0x800A0006);
- internal const int CTL_E_PATHFILEACCESSERROR = unchecked((int)0x800A004B);
- internal const int CTL_E_PATHNOTFOUND = unchecked((int)0x800A004C);
- internal const int CTL_E_PERMISSIONDENIED = unchecked((int)0x800A0046);
- internal const int E_ELEMENTNOTAVAILABLE = unchecked((int)0x802B001F);
- internal const int E_ELEMENTNOTENABLED = unchecked((int)0x802B001E);
- internal const int E_FAIL = unchecked((int)0x80004005);
- internal const int E_HANDLE = unchecked((int)0x80070006);
- internal const int E_ILLEGAL_DELEGATE_ASSIGNMENT = unchecked((int)0x80000018);
- internal const int E_ILLEGAL_METHOD_CALL = unchecked((int)0x8000000E);
- internal const int E_ILLEGAL_STATE_CHANGE = unchecked((int)0x8000000D);
- internal const int E_INVALIDARG = unchecked((int)0x80070057);
- internal const int E_LAYOUTCYCLE = unchecked((int)0x802B0014);
- internal const int E_NOTIMPL = unchecked((int)0x80004001);
- internal const int E_OUTOFMEMORY = unchecked((int)0x8007000E);
- internal const int E_POINTER = unchecked((int)0x80004003L);
- internal const int E_XAMLPARSEFAILED = unchecked((int)0x802B000A);
- internal const int ERROR_BAD_EXE_FORMAT = unchecked((int)0x800700C1);
- internal const int ERROR_BAD_NET_NAME = unchecked((int)0x80070043);
- internal const int ERROR_BAD_NETPATH = unchecked((int)0x80070035);
- internal const int ERROR_DISK_CORRUPT = unchecked((int)0x80070571);
- internal const int ERROR_DLL_INIT_FAILED = unchecked((int)0x8007045A);
- internal const int ERROR_DLL_NOT_FOUND = unchecked((int)0x80070485);
- internal const int ERROR_EXE_MARKED_INVALID = unchecked((int)0x800700C0);
- internal const int ERROR_FILE_CORRUPT = unchecked((int)0x80070570);
- internal const int ERROR_FILE_INVALID = unchecked((int)0x800703EE);
- internal const int ERROR_FILE_NOT_FOUND = unchecked((int)0x80070002);
- internal const int ERROR_INVALID_DLL = unchecked((int)0x80070482);
- internal const int ERROR_INVALID_NAME = unchecked((int)0x8007007B);
- internal const int ERROR_INVALID_ORDINAL = unchecked((int)0x800700B6);
- internal const int ERROR_INVALID_PARAMETER = unchecked((int)0x80070057);
- internal const int ERROR_LOCK_VIOLATION = unchecked((int)0x80070021);
- internal const int ERROR_MOD_NOT_FOUND = unchecked((int)0x8007007E);
- internal const int ERROR_NO_UNICODE_TRANSLATION = unchecked((int)0x80070459);
- internal const int ERROR_NOACCESS = unchecked((int)0x800703E6);
- internal const int ERROR_NOT_READY = unchecked((int)0x80070015);
- internal const int ERROR_OPEN_FAILED = unchecked((int)0x8007006E);
- internal const int ERROR_PATH_NOT_FOUND = unchecked((int)0x80070003);
- internal const int ERROR_SHARING_VIOLATION = unchecked((int)0x80070020);
- internal const int ERROR_TOO_MANY_OPEN_FILES = unchecked((int)0x80070004);
- internal const int ERROR_UNRECOGNIZED_VOLUME = unchecked((int)0x800703ED);
- internal const int ERROR_WRONG_TARGET_NAME = unchecked((int)0x80070574);
- internal const int FUSION_E_ASM_MODULE_MISSING = unchecked((int)0x80131042);
- internal const int FUSION_E_CACHEFILE_FAILED = unchecked((int)0x80131052);
- internal const int FUSION_E_CODE_DOWNLOAD_DISABLED = unchecked((int)0x80131048);
- internal const int FUSION_E_HOST_GAC_ASM_MISMATCH = unchecked((int)0x80131050);
- internal const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047);
- internal const int FUSION_E_INVALID_PRIVATE_ASM_LOCATION = unchecked((int)0x80131041);
- internal const int FUSION_E_LOADFROM_BLOCKED = unchecked((int)0x80131051);
- internal const int FUSION_E_PRIVATE_ASM_DISALLOWED = unchecked((int)0x80131044);
- internal const int FUSION_E_REF_DEF_MISMATCH = unchecked((int)0x80131040);
- internal const int FUSION_E_SIGNATURE_CHECK_FAILED = unchecked((int)0x80131045);
- internal const int INET_E_CANNOT_CONNECT = unchecked((int)0x800C0004);
- internal const int INET_E_CONNECTION_TIMEOUT = unchecked((int)0x800C000B);
- internal const int INET_E_DATA_NOT_AVAILABLE = unchecked((int)0x800C0007);
- internal const int INET_E_DOWNLOAD_FAILURE = unchecked((int)0x800C0008);
- internal const int INET_E_OBJECT_NOT_FOUND = unchecked((int)0x800C0006);
- internal const int INET_E_RESOURCE_NOT_FOUND = unchecked((int)0x800C0005);
- internal const int INET_E_UNKNOWN_PROTOCOL = unchecked((int)0x800C000D);
- internal const int ISS_E_ALLOC_TOO_LARGE = unchecked((int)0x80131484);
- internal const int ISS_E_BLOCK_SIZE_TOO_SMALL = unchecked((int)0x80131483);
- internal const int ISS_E_CALLER = unchecked((int)0x801314A1);
- internal const int ISS_E_CORRUPTED_STORE_FILE = unchecked((int)0x80131480);
- internal const int ISS_E_CREATE_DIR = unchecked((int)0x80131468);
- internal const int ISS_E_CREATE_MUTEX = unchecked((int)0x80131464);
- internal const int ISS_E_DEPRECATE = unchecked((int)0x801314A0);
- internal const int ISS_E_FILE_NOT_MAPPED = unchecked((int)0x80131482);
- internal const int ISS_E_FILE_WRITE = unchecked((int)0x80131466);
- internal const int ISS_E_GET_FILE_SIZE = unchecked((int)0x80131463);
- internal const int ISS_E_ISOSTORE = unchecked((int)0x80131450);
- internal const int ISS_E_LOCK_FAILED = unchecked((int)0x80131465);
- internal const int ISS_E_MACHINE = unchecked((int)0x801314A3);
- internal const int ISS_E_MACHINE_DACL = unchecked((int)0x801314A4);
- internal const int ISS_E_MAP_VIEW_OF_FILE = unchecked((int)0x80131462);
- internal const int ISS_E_OPEN_FILE_MAPPING = unchecked((int)0x80131461);
- internal const int ISS_E_OPEN_STORE_FILE = unchecked((int)0x80131460);
- internal const int ISS_E_PATH_LENGTH = unchecked((int)0x801314A2);
- internal const int ISS_E_SET_FILE_POINTER = unchecked((int)0x80131467);
- internal const int ISS_E_STORE_NOT_OPEN = unchecked((int)0x80131469);
- internal const int ISS_E_STORE_VERSION = unchecked((int)0x80131481);
- internal const int ISS_E_TABLE_ROW_NOT_FOUND = unchecked((int)0x80131486);
- internal const int ISS_E_USAGE_WILL_EXCEED_QUOTA = unchecked((int)0x80131485);
- internal const int META_E_BAD_SIGNATURE = unchecked((int)0x80131192);
- internal const int META_E_CA_FRIENDS_SN_REQUIRED = unchecked((int)0x801311e6);
- internal const int MSEE_E_ASSEMBLYLOADINPROGRESS = unchecked((int)0x80131016);
- internal const int RO_E_CLOSED = unchecked((int)0x80000013);
- internal const int E_BOUNDS = unchecked((int)0x8000000B);
- internal const int RO_E_METADATA_NAME_NOT_FOUND = unchecked((int)0x8000000F);
- internal const int SECURITY_E_INCOMPATIBLE_EVIDENCE = unchecked((int)0x80131403);
- internal const int SECURITY_E_INCOMPATIBLE_SHARE = unchecked((int)0x80131401);
- internal const int SECURITY_E_UNVERIFIABLE = unchecked((int)0x80131402);
- internal const int STG_E_PATHNOTFOUND = unchecked((int)0x80030003);
- public const int COR_E_DIRECTORYNOTFOUND = unchecked((int)0x80070003);
- public const int COR_E_ENDOFSTREAM = unchecked((int)0x80070026); // OS defined
- public const int COR_E_FILELOAD = unchecked((int)0x80131621);
- public const int COR_E_FILENOTFOUND = unchecked((int)0x80070002);
- public const int COR_E_IO = unchecked((int)0x80131620);
- public const int COR_E_PATHTOOLONG = unchecked((int)0x800700CE);
- }
-}
diff --git a/src/mscorlib/src/System/IO/BinaryReader.cs b/src/mscorlib/src/System/IO/BinaryReader.cs
index 2cc6074d75..83fc2806bf 100644
--- a/src/mscorlib/src/System/IO/BinaryReader.cs
+++ b/src/mscorlib/src/System/IO/BinaryReader.cs
@@ -354,17 +354,28 @@ namespace System.IO
__Error.FileNotOpen();
// SafeCritical: index and count have already been verified to be a valid range for the buffer
- return InternalReadChars(buffer, index, count);
+ return InternalReadChars(new Span<char>(buffer, index, count));
}
- private int InternalReadChars(char[] buffer, int index, int count)
+ public virtual int Read(Span<char> destination)
+ {
+ Contract.Ensures(Contract.Result<int>() >= 0);
+ Contract.Ensures(Contract.Result<int>() <= destination.Length);
+ Contract.EndContractBlock();
+
+ if (_stream == null)
+ __Error.FileNotOpen();
+
+ return InternalReadChars(destination);
+ }
+
+ private int InternalReadChars(Span<char> buffer)
{
- Contract.Requires(buffer != null);
- Contract.Requires(index >= 0 && count >= 0);
Debug.Assert(_stream != null);
int numBytes = 0;
- int charsRemaining = count;
+ int index = 0;
+ int charsRemaining = buffer.Length;
if (_charBytes == null)
{
@@ -410,7 +421,7 @@ namespace System.IO
if (numBytes == 0)
{
- return (count - charsRemaining);
+ return (buffer.Length - charsRemaining);
}
Debug.Assert(byteBuffer != null, "expected byteBuffer to be non-null");
@@ -428,7 +439,7 @@ namespace System.IO
unsafe
{
fixed (byte* pBytes = byteBuffer)
- fixed (char* pChars = buffer)
+ fixed (char* pChars = &buffer.DangerousGetPinnableReference())
{
charsRead = _decoder.GetChars(pBytes + position, numBytes, pChars + index, charsRemaining, flush: false);
}
@@ -444,7 +455,7 @@ namespace System.IO
// we may have read fewer than the number of characters requested if end of stream reached
// or if the encoding makes the char count too big for the buffer (e.g. fallback sequence)
- return (count - charsRemaining);
+ return (buffer.Length - charsRemaining);
}
private int InternalReadOneChar()
@@ -541,7 +552,7 @@ namespace System.IO
// SafeCritical: we own the chars buffer, and therefore can guarantee that the index and count are valid
char[] chars = new char[count];
- int n = InternalReadChars(chars, 0, count);
+ int n = InternalReadChars(new Span<char>(chars));
if (n != count)
{
char[] copy = new char[n];
@@ -570,6 +581,18 @@ namespace System.IO
return _stream.Read(buffer, index, count);
}
+ public virtual int Read(Span<byte> destination)
+ {
+ Contract.Ensures(Contract.Result<int>() >= 0);
+ Contract.Ensures(Contract.Result<int>() <= destination.Length);
+ Contract.EndContractBlock();
+
+ if (_stream == null)
+ __Error.FileNotOpen();
+
+ return _stream.Read(destination);
+ }
+
public virtual byte[] ReadBytes(int count)
{
if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
diff --git a/src/mscorlib/src/System/IO/Directory.cs b/src/mscorlib/src/System/IO/Directory.cs
index 6541e44e7d..fcc43f73c4 100644
--- a/src/mscorlib/src/System/IO/Directory.cs
+++ b/src/mscorlib/src/System/IO/Directory.cs
@@ -84,12 +84,6 @@ namespace System.IO
includeFiles, includeDirs, searchOption, true);
}
#endif // PLATFORM_UNIX
-
- internal static String InternalGetDirectoryRoot(String path)
- {
- if (path == null) return null;
- return path.Substring(0, PathInternal.GetRootLength(path));
- }
}
}
diff --git a/src/mscorlib/src/System/IO/File.cs b/src/mscorlib/src/System/IO/File.cs
index da962f6feb..e34b7aedab 100644
--- a/src/mscorlib/src/System/IO/File.cs
+++ b/src/mscorlib/src/System/IO/File.cs
@@ -196,7 +196,7 @@ namespace System.IO
if (!error)
{
Debug.Assert(false, "File::FillAttributeInfo - FindClose failed!");
- __Error.WinIOError();
+ throw Win32Marshal.GetExceptionForLastWin32Error();
}
}
}
diff --git a/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs b/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs
index d4ce9a9ab9..bd3504580b 100644
--- a/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs
+++ b/src/mscorlib/src/System/IO/FileLoadException.CoreCLR.cs
@@ -27,7 +27,7 @@ namespace System.IO
GetFileLoadExceptionMessage(hResult, JitHelpers.GetStringHandleOnStack(ref format));
string message = null;
- if (hResult == System.__HResults.COR_E_BADEXEFORMAT)
+ if (hResult == System.HResults.COR_E_BADEXEFORMAT)
message = SR.Arg_BadImageFormatException;
else
GetMessageForHR(hResult, JitHelpers.GetStringHandleOnStack(ref message));
diff --git a/src/mscorlib/src/System/IO/FileSystemEnumerable.cs b/src/mscorlib/src/System/IO/FileSystemEnumerable.cs
index ed482c76b5..a16aad25c1 100644
--- a/src/mscorlib/src/System/IO/FileSystemEnumerable.cs
+++ b/src/mscorlib/src/System/IO/FileSystemEnumerable.cs
@@ -433,7 +433,7 @@ namespace System.IO
private void HandleError(int hr, String path)
{
Dispose();
- __Error.WinIOError(hr, path);
+ throw Win32Marshal.GetExceptionForWin32Error(hr, path);
}
private void AddSearchableDirsToStack(Directory.SearchData localSearchData)
diff --git a/src/mscorlib/src/System/IO/IOException.cs b/src/mscorlib/src/System/IO/IOException.cs
deleted file mode 100644
index 65504de863..0000000000
--- a/src/mscorlib/src/System/IO/IOException.cs
+++ /dev/null
@@ -1,73 +0,0 @@
-// 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 for a generic IO error.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.Serialization;
-
-namespace System.IO
-{
- public class IOException : SystemException
- {
- // For debugging purposes, store the complete path in the IOException
- // if possible. Don't give it back to users due to security concerns.
- // Let the code that throws the exception worry about that. But we can
- // at least assist people attached to the process with a managed
- // debugger. Don't serialize it to avoid any security problems.
- // This information isn't guaranteed to be correct, but is our second
- // best effort at a file or directory involved, after the exception
- // message.
- [NonSerialized]
- private String _maybeFullPath; // For debuggers on partial trust code
-
- public IOException()
- : base(SR.Arg_IOException)
- {
- HResult = __HResults.COR_E_IO;
- }
-
- public IOException(String message)
- : base(message)
- {
- HResult = __HResults.COR_E_IO;
- }
-
- public IOException(String message, int hresult)
- : base(message)
- {
- HResult = hresult;
- }
-
- // Adding this for debuggers when looking at exceptions in partial
- // trust code that may not have interesting path information in
- // the exception message.
- internal IOException(String message, int hresult, String maybeFullPath)
- : base(message)
- {
- HResult = hresult;
- _maybeFullPath = maybeFullPath;
- }
-
- public IOException(String message, Exception innerException)
- : base(message, innerException)
- {
- HResult = __HResults.COR_E_IO;
- }
-
- protected IOException(SerializationInfo info, StreamingContext context) : base(info, context)
- {
- throw new PlatformNotSupportedException();
- }
- }
-}
diff --git a/src/mscorlib/src/System/IO/MemoryStream.cs b/src/mscorlib/src/System/IO/MemoryStream.cs
index daf09d1274..2ac7c07db4 100644
--- a/src/mscorlib/src/System/IO/MemoryStream.cs
+++ b/src/mscorlib/src/System/IO/MemoryStream.cs
@@ -49,7 +49,6 @@ namespace System.IO
private bool _exposable; // Whether the array can be returned to the user.
private bool _isOpen; // Is this stream open or closed?
- [NonSerialized]
private Task<int> _lastReadTask; // The last successful task returned from ReadAsync
private const int MemStreamMaxLength = Int32.MaxValue;
@@ -391,6 +390,37 @@ namespace System.IO
return n;
}
+ public override int Read(Span<byte> destination)
+ {
+ if (GetType() != typeof(MemoryStream))
+ {
+ // MemoryStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior
+ // to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload
+ // should use the behavior of Read(byte[],int,int) overload.
+ return base.Read(destination);
+ }
+
+ if (!_isOpen)
+ {
+ __Error.StreamIsClosed();
+ }
+
+ int n = Math.Min(_length - _position, destination.Length);
+ if (n <= 0)
+ {
+ return 0;
+ }
+
+ // TODO https://github.com/dotnet/corefx/issues/22388:
+ // Read(byte[], int, int) has an n <= 8 optimization, presumably based
+ // on benchmarking. Determine if/where such a cut-off is here and add
+ // an equivalent optimization if necessary.
+ new Span<byte>(_buffer, _position, n).CopyTo(destination);
+
+ _position += n;
+ return n;
+ }
+
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
@@ -425,6 +455,27 @@ namespace System.IO
}
}
+ public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ if (cancellationToken.IsCancellationRequested)
+ {
+ return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
+ }
+
+ try
+ {
+ return new ValueTask<int>(Read(destination.Span));
+ }
+ catch (OperationCanceledException oce)
+ {
+ return new ValueTask<int>(Task.FromCancellation<int>(oce));
+ }
+ catch (Exception exception)
+ {
+ return new ValueTask<int>(Task.FromException<int>(exception));
+ }
+ }
+
public override int ReadByte()
{
@@ -634,6 +685,52 @@ namespace System.IO
_position = i;
}
+ public override void Write(ReadOnlySpan<byte> source)
+ {
+ if (GetType() != typeof(MemoryStream))
+ {
+ // MemoryStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior
+ // to this Write(Span<byte>) overload being introduced. In that case, this Write(Span<byte>) overload
+ // should use the behavior of Write(byte[],int,int) overload.
+ base.Write(source);
+ return;
+ }
+
+ if (!_isOpen)
+ {
+ __Error.StreamIsClosed();
+ }
+ EnsureWriteable();
+
+ // Check for overflow
+ int i = _position + source.Length;
+ if (i < 0)
+ {
+ throw new IOException(SR.IO_StreamTooLong);
+ }
+
+ if (i > _length)
+ {
+ bool mustZero = _position > _length;
+ if (i > _capacity)
+ {
+ bool allocatedNewArray = EnsureCapacity(i);
+ if (allocatedNewArray)
+ {
+ mustZero = false;
+ }
+ }
+ if (mustZero)
+ {
+ Array.Clear(_buffer, _length, i - _length);
+ }
+ _length = i;
+ }
+
+ source.CopyTo(new Span<byte>(_buffer, _position, source.Length));
+ _position = i;
+ }
+
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
@@ -665,6 +762,28 @@ namespace System.IO
}
}
+ public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ if (cancellationToken.IsCancellationRequested)
+ {
+ return Task.FromCanceled(cancellationToken);
+ }
+
+ try
+ {
+ Write(source.Span);
+ return Task.CompletedTask;
+ }
+ catch (OperationCanceledException oce)
+ {
+ return Task.FromCancellation<VoidTaskResult>(oce);
+ }
+ catch (Exception exception)
+ {
+ return Task.FromException(exception);
+ }
+ }
+
public override void WriteByte(byte value)
{
if (!_isOpen) __Error.StreamIsClosed();
diff --git a/src/mscorlib/src/System/IO/Stream.cs b/src/mscorlib/src/System/IO/Stream.cs
index 786dfedef9..82fad24c6d 100644
--- a/src/mscorlib/src/System/IO/Stream.cs
+++ b/src/mscorlib/src/System/IO/Stream.cs
@@ -41,9 +41,7 @@ namespace System.IO
// To implement Async IO operations on streams that don't support async IO
- [NonSerialized]
private ReadWriteTask _activeReadWriteTask;
- [NonSerialized]
private SemaphoreSlim _asyncActiveSemaphore;
internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
@@ -416,6 +414,33 @@ namespace System.IO
: BeginEndReadAsync(buffer, offset, count);
}
+ public virtual ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ if (destination.TryGetArray(out ArraySegment<byte> array))
+ {
+ return new ValueTask<int>(ReadAsync(array.Array, array.Offset, array.Count, cancellationToken));
+ }
+ else
+ {
+ byte[] buffer = ArrayPool<byte>.Shared.Rent(destination.Length);
+ return FinishReadAsync(ReadAsync(buffer, 0, destination.Length, cancellationToken), buffer, destination);
+
+ async ValueTask<int> FinishReadAsync(Task<int> readTask, byte[] localBuffer, Memory<byte> localDestination)
+ {
+ try
+ {
+ int result = await readTask.ConfigureAwait(false);
+ new Span<byte>(localBuffer, 0, result).CopyTo(localDestination.Span);
+ return result;
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(localBuffer);
+ }
+ }
+ }
+ }
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndRead();
@@ -694,8 +719,6 @@ namespace System.IO
return WriteAsync(buffer, offset, count, CancellationToken.None);
}
-
-
public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
@@ -705,6 +728,32 @@ namespace System.IO
: BeginEndWriteAsync(buffer, offset, count);
}
+ public virtual Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ if (source.DangerousTryGetArray(out ArraySegment<byte> array))
+ {
+ return WriteAsync(array.Array, array.Offset, array.Count, cancellationToken);
+ }
+ else
+ {
+ byte[] buffer = ArrayPool<byte>.Shared.Rent(source.Length);
+ source.Span.CopyTo(buffer);
+ return FinishWriteAsync(WriteAsync(buffer, 0, source.Length, cancellationToken), buffer);
+
+ async Task FinishWriteAsync(Task writeTask, byte[] localBuffer)
+ {
+ try
+ {
+ await writeTask.ConfigureAwait(false);
+ }
+ finally
+ {
+ ArrayPool<byte>.Shared.Return(localBuffer);
+ }
+ }
+ }
+ }
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern bool HasOverriddenBeginEndWrite();
@@ -734,6 +783,22 @@ namespace System.IO
public abstract int Read([In, Out] byte[] buffer, int offset, int count);
+ public virtual int Read(Span<byte> destination)
+ {
+ byte[] buffer = ArrayPool<byte>.Shared.Rent(destination.Length);
+ try
+ {
+ int numRead = Read(buffer, 0, destination.Length);
+ if ((uint)numRead > destination.Length)
+ {
+ throw new IOException(SR.IO_StreamTooLong);
+ }
+ new Span<byte>(buffer, 0, numRead).CopyTo(destination);
+ return numRead;
+ }
+ finally { ArrayPool<byte>.Shared.Return(buffer); }
+ }
+
// Reads one byte from the stream by calling Read(byte[], int, int).
// Will return an unsigned byte cast to an int or -1 on end of stream.
// This implementation does not perform well because it allocates a new
@@ -754,6 +819,17 @@ namespace System.IO
public abstract void Write(byte[] buffer, int offset, int count);
+ public virtual void Write(ReadOnlySpan<byte> source)
+ {
+ byte[] buffer = ArrayPool<byte>.Shared.Rent(source.Length);
+ try
+ {
+ source.CopyTo(buffer);
+ Write(buffer, 0, source.Length);
+ }
+ finally { ArrayPool<byte>.Shared.Return(buffer); }
+ }
+
// Writes one byte from the stream by calling Write(byte[], int, int).
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
@@ -957,14 +1033,20 @@ namespace System.IO
return 0;
}
+ public override int Read(Span<byte> destination)
+ {
+ return 0;
+ }
+
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
- var nullReadTask = s_nullReadTask;
- if (nullReadTask == null)
- s_nullReadTask = nullReadTask = new Task<int>(false, 0, (TaskCreationOptions)InternalTaskOptions.DoNotDispose, CancellationToken.None); // benign race condition
- return nullReadTask;
+ return AsyncTaskMethodBuilder<int>.s_defaultResultTask;
+ }
+
+ public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ return new ValueTask<int>(0);
}
- private static Task<int> s_nullReadTask;
public override int ReadByte()
{
@@ -975,6 +1057,10 @@ namespace System.IO
{
}
+ public override void Write(ReadOnlySpan<byte> source)
+ {
+ }
+
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
@@ -982,6 +1068,13 @@ namespace System.IO
Task.CompletedTask;
}
+ public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
+ {
+ return cancellationToken.IsCancellationRequested ?
+ Task.FromCanceled(cancellationToken) :
+ Task.CompletedTask;
+ }
+
public override void WriteByte(byte value)
{
}
@@ -1229,6 +1322,12 @@ namespace System.IO
return _stream.Read(bytes, offset, count);
}
+ public override int Read(Span<byte> destination)
+ {
+ lock (_stream)
+ return _stream.Read(destination);
+ }
+
public override int ReadByte()
{
lock (_stream)
@@ -1282,6 +1381,12 @@ namespace System.IO
_stream.Write(bytes, offset, count);
}
+ public override void Write(ReadOnlySpan<byte> source)
+ {
+ lock (_stream)
+ _stream.Write(source);
+ }
+
public override void WriteByte(byte b)
{
lock (_stream)
diff --git a/src/mscorlib/src/System/IO/StreamReader.cs b/src/mscorlib/src/System/IO/StreamReader.cs
index 1fc72bffd1..9ff9187663 100644
--- a/src/mscorlib/src/System/IO/StreamReader.cs
+++ b/src/mscorlib/src/System/IO/StreamReader.cs
@@ -58,7 +58,6 @@ namespace System.IO
// This is used only for preamble detection
private int bytePos;
- [NonSerialized]
private StringBuilder _builder;
// This is the maximum number of chars we can get from one call to
@@ -84,14 +83,12 @@ namespace System.IO
private bool _isBlocked;
// The intent of this field is to leave open the underlying stream when
- // disposing of this StreamReader. A name like _leaveOpen is better,
- // but this type is serializable, and this field's name was _closable.
- private bool _closable; // Whether to close the underlying stream.
+ // disposing of this StreamReader.
+ private bool _leaveOpen; // Whether to keep the underlying stream open.
// We don't guarantee thread safety on StreamReader, but we should at
// least prevent users from trying to read anything while an Async
// read from the same thread is in progress.
- [NonSerialized]
private volatile Task _asyncReadTask;
private void CheckAsyncTaskInProgress()
@@ -216,14 +213,14 @@ namespace System.IO
_checkPreamble = (_preamble.Length > 0);
_isBlocked = false;
- _closable = !leaveOpen;
+ _leaveOpen = leaveOpen;
}
// Init used by NullStreamReader, to delay load encoding
internal void Init(Stream stream)
{
this.stream = stream;
- _closable = true;
+ _leaveOpen = false;
}
public override void Close()
@@ -265,7 +262,7 @@ namespace System.IO
}
internal bool LeaveOpen {
- get { return !_closable; }
+ get { return _leaveOpen; }
}
// DiscardBufferedData tells StreamReader to throw away its internal
@@ -1145,7 +1142,6 @@ namespace System.IO
}
#endregion
- // No data, class doesn't need to be serializable.
// Note this class is threadsafe.
private class NullStreamReader : StreamReader
{
diff --git a/src/mscorlib/src/System/IO/__Error.cs b/src/mscorlib/src/System/IO/__Error.cs
index 785a79efe8..6af1fcfadc 100644
--- a/src/mscorlib/src/System/IO/__Error.cs
+++ b/src/mscorlib/src/System/IO/__Error.cs
@@ -75,72 +75,6 @@ namespace System.IO
throw new ArgumentException(SR.InvalidOperation_EndWriteCalledMultiple);
}
- internal static void WinIOError()
- {
- int errorCode = Marshal.GetLastWin32Error();
- WinIOError(errorCode, String.Empty);
- }
-
- // After calling GetLastWin32Error(), it clears the last error field,
- // so you must save the HResult and pass it to this method. This method
- // will determine the appropriate exception to throw dependent on your
- // error, and depending on the error, insert a string into the message
- // gotten from the ResourceManager.
- internal static void WinIOError(int errorCode, String str)
- {
- switch (errorCode)
- {
- case Win32Native.ERROR_FILE_NOT_FOUND:
- if (str.Length == 0)
- throw new FileNotFoundException(SR.IO_FileNotFound);
- else
- throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, str), str);
-
- case Win32Native.ERROR_PATH_NOT_FOUND:
- if (str.Length == 0)
- throw new DirectoryNotFoundException(SR.IO_PathNotFound_NoPathName);
- else
- throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, str));
-
- case Win32Native.ERROR_ACCESS_DENIED:
- if (str.Length == 0)
- throw new UnauthorizedAccessException(SR.UnauthorizedAccess_IODenied_NoPathName);
- else
- throw new UnauthorizedAccessException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, str));
-
- case Win32Native.ERROR_ALREADY_EXISTS:
- if (str.Length == 0)
- goto default;
- throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, str), Win32Native.MakeHRFromErrorCode(errorCode), str);
-
- case Win32Native.ERROR_FILENAME_EXCED_RANGE:
- throw new PathTooLongException(SR.Format(SR.IO_PathTooLong_Path, str));
-
- case Win32Native.ERROR_INVALID_DRIVE:
- throw new DriveNotFoundException(SR.Format(SR.IO_DriveNotFound_Drive, str));
-
- case Win32Native.ERROR_INVALID_PARAMETER:
- throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), str);
-
- case Win32Native.ERROR_SHARING_VIOLATION:
- if (str.Length == 0)
- throw new IOException(SR.IO_SharingViolation_NoFileName, Win32Native.MakeHRFromErrorCode(errorCode), str);
- else
- throw new IOException(SR.Format(SR.IO_SharingViolation_File, str), Win32Native.MakeHRFromErrorCode(errorCode), str);
-
- case Win32Native.ERROR_FILE_EXISTS:
- if (str.Length == 0)
- goto default;
- throw new IOException(SR.Format(SR.IO_FileExists_Name, str), Win32Native.MakeHRFromErrorCode(errorCode), str);
-
- case Win32Native.ERROR_OPERATION_ABORTED:
- throw new OperationCanceledException();
-
- default:
- throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), str);
- }
- }
-
internal static void WriteNotSupported()
{
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
diff --git a/src/mscorlib/src/System/IO/__HResults.cs b/src/mscorlib/src/System/IO/__HResults.cs
deleted file mode 100644
index 633c3538c5..0000000000
--- a/src/mscorlib/src/System/IO/__HResults.cs
+++ /dev/null
@@ -1,31 +0,0 @@
-// 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: Define HResult constants. Every exception has one of these.
-//
-//
-//===========================================================================*/
-
-using System;
-
-namespace System.IO
-{
- // Only static data no need to serialize
- internal static class __HResults
- {
- // These use an error code from WinError.h
- public const int COR_E_ENDOFSTREAM = unchecked((int)0x80070026); // OS defined
- public const int COR_E_FILELOAD = unchecked((int)0x80131621);
- public const int COR_E_FILENOTFOUND = unchecked((int)0x80070002);
- public const int COR_E_DIRECTORYNOTFOUND = unchecked((int)0x80070003);
- public const int COR_E_PATHTOOLONG = unchecked((int)0x800700CE);
-
- public const int COR_E_IO = unchecked((int)0x80131620);
- }
-}
diff --git a/src/mscorlib/src/System/InsufficientMemoryException.cs b/src/mscorlib/src/System/InsufficientMemoryException.cs
index 8f7aa96ff7..b4bc588f18 100644
--- a/src/mscorlib/src/System/InsufficientMemoryException.cs
+++ b/src/mscorlib/src/System/InsufficientMemoryException.cs
@@ -27,19 +27,19 @@ namespace System
public InsufficientMemoryException()
: base(GetMessageFromNativeResources(ExceptionMessageKind.OutOfMemory))
{
- HResult = __HResults.COR_E_INSUFFICIENTMEMORY;
+ HResult = HResults.COR_E_INSUFFICIENTMEMORY;
}
public InsufficientMemoryException(String message)
: base(message)
{
- HResult = __HResults.COR_E_INSUFFICIENTMEMORY;
+ HResult = HResults.COR_E_INSUFFICIENTMEMORY;
}
public InsufficientMemoryException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_INSUFFICIENTMEMORY;
+ HResult = HResults.COR_E_INSUFFICIENTMEMORY;
}
}
}
diff --git a/src/mscorlib/src/System/MissingFieldException.cs b/src/mscorlib/src/System/MissingFieldException.cs
index 668d5f2a31..31931bf91c 100644
--- a/src/mscorlib/src/System/MissingFieldException.cs
+++ b/src/mscorlib/src/System/MissingFieldException.cs
@@ -22,19 +22,19 @@ namespace System
public MissingFieldException()
: base(SR.Arg_MissingFieldException)
{
- HResult = __HResults.COR_E_MISSINGFIELD;
+ HResult = HResults.COR_E_MISSINGFIELD;
}
public MissingFieldException(String message)
: base(message)
{
- HResult = __HResults.COR_E_MISSINGFIELD;
+ HResult = HResults.COR_E_MISSINGFIELD;
}
public MissingFieldException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_MISSINGFIELD;
+ HResult = HResults.COR_E_MISSINGFIELD;
}
protected MissingFieldException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/src/System/MissingMemberException.cs b/src/mscorlib/src/System/MissingMemberException.cs
index 1fb0c55e40..def3c39824 100644
--- a/src/mscorlib/src/System/MissingMemberException.cs
+++ b/src/mscorlib/src/System/MissingMemberException.cs
@@ -26,19 +26,19 @@ namespace System
public MissingMemberException()
: base(SR.Arg_MissingMemberException)
{
- HResult = __HResults.COR_E_MISSINGMEMBER;
+ HResult = HResults.COR_E_MISSINGMEMBER;
}
public MissingMemberException(String message)
: base(message)
{
- HResult = __HResults.COR_E_MISSINGMEMBER;
+ HResult = HResults.COR_E_MISSINGMEMBER;
}
public MissingMemberException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_MISSINGMEMBER;
+ HResult = HResults.COR_E_MISSINGMEMBER;
}
protected MissingMemberException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/src/System/MulticastDelegate.cs b/src/mscorlib/src/System/MulticastDelegate.cs
index 988bf2bb60..fe94aec29b 100644
--- a/src/mscorlib/src/System/MulticastDelegate.cs
+++ b/src/mscorlib/src/System/MulticastDelegate.cs
@@ -452,6 +452,17 @@ namespace System
if (IsUnmanagedFunctionPtr())
return ValueType.GetHashCodeOfPtr(_methodPtr) ^ ValueType.GetHashCodeOfPtr(_methodPtrAux);
+ if (_invocationCount != (IntPtr)0)
+ {
+ var t = _invocationList as Delegate;
+
+ if (t != null)
+ {
+ // this is a secure/wrapper delegate so we need to unwrap and check the inner one
+ return t.GetHashCode();
+ }
+ }
+
Object[] invocationList = _invocationList as Object[];
if (invocationList == null)
{
@@ -584,54 +595,6 @@ namespace System
}
[System.Diagnostics.DebuggerNonUserCode]
- private void CtorSecureClosed(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
- {
- MulticastDelegate realDelegate = (MulticastDelegate)Delegate.InternalAllocLike(this);
- realDelegate.CtorClosed(target, methodPtr);
- _invocationList = realDelegate;
- this._target = this;
- this._methodPtr = callThunk;
- this._methodPtrAux = creatorMethod;
- _invocationCount = GetInvokeMethod();
- }
-
- [System.Diagnostics.DebuggerNonUserCode]
- private void CtorSecureClosedStatic(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
- {
- MulticastDelegate realDelegate = (MulticastDelegate)Delegate.InternalAllocLike(this);
- realDelegate.CtorClosedStatic(target, methodPtr);
- _invocationList = realDelegate;
- this._target = this;
- this._methodPtr = callThunk;
- this._methodPtrAux = creatorMethod;
- _invocationCount = GetInvokeMethod();
- }
-
- [System.Diagnostics.DebuggerNonUserCode]
- private void CtorSecureRTClosed(Object target, IntPtr methodPtr, IntPtr callThunk, IntPtr creatorMethod)
- {
- MulticastDelegate realDelegate = Delegate.InternalAllocLike(this);
- realDelegate.CtorRTClosed(target, methodPtr);
- _invocationList = realDelegate;
- this._target = this;
- this._methodPtr = callThunk;
- this._methodPtrAux = creatorMethod;
- _invocationCount = GetInvokeMethod();
- }
-
- [System.Diagnostics.DebuggerNonUserCode]
- private void CtorSecureOpened(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr callThunk, IntPtr creatorMethod)
- {
- MulticastDelegate realDelegate = Delegate.InternalAllocLike(this);
- realDelegate.CtorOpened(target, methodPtr, shuffleThunk);
- _invocationList = realDelegate;
- this._target = this;
- this._methodPtr = callThunk;
- this._methodPtrAux = creatorMethod;
- _invocationCount = GetInvokeMethod();
- }
-
- [System.Diagnostics.DebuggerNonUserCode]
private void CtorVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk)
{
this._target = this;
@@ -640,18 +603,6 @@ namespace System
}
[System.Diagnostics.DebuggerNonUserCode]
- private void CtorSecureVirtualDispatch(Object target, IntPtr methodPtr, IntPtr shuffleThunk, IntPtr callThunk, IntPtr creatorMethod)
- {
- MulticastDelegate realDelegate = Delegate.InternalAllocLike(this);
- realDelegate.CtorVirtualDispatch(target, methodPtr, shuffleThunk);
- _invocationList = realDelegate;
- this._target = this;
- this._methodPtr = callThunk;
- this._methodPtrAux = creatorMethod;
- _invocationCount = GetInvokeMethod();
- }
-
- [System.Diagnostics.DebuggerNonUserCode]
private void CtorCollectibleClosedStatic(Object target, IntPtr methodPtr, IntPtr gchandle)
{
this._target = target;
diff --git a/src/mscorlib/src/System/NonSerializedAttribute.cs b/src/mscorlib/src/System/NonSerializedAttribute.cs
deleted file mode 100644
index be05e113c6..0000000000
--- a/src/mscorlib/src/System/NonSerializedAttribute.cs
+++ /dev/null
@@ -1,36 +0,0 @@
-// 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: Used to mark a member as being not-serialized
-**
-**
-============================================================*/
-
-using System.Reflection;
-
-namespace System
-{
- [AttributeUsage(AttributeTargets.Field, Inherited = false)]
- public sealed class NonSerializedAttribute : Attribute
- {
- internal static Attribute GetCustomAttribute(RuntimeFieldInfo field)
- {
- if ((field.Attributes & FieldAttributes.NotSerialized) == 0)
- return null;
-
- return new NonSerializedAttribute();
- }
-
- internal static bool IsDefined(RuntimeFieldInfo field)
- {
- return (field.Attributes & FieldAttributes.NotSerialized) != 0;
- }
-
- public NonSerializedAttribute() { }
- }
-}
diff --git a/src/mscorlib/src/System/Number.cs b/src/mscorlib/src/System/Number.cs
index b30d4e643f..0eaa0b2285 100644
--- a/src/mscorlib/src/System/Number.cs
+++ b/src/mscorlib/src/System/Number.cs
@@ -286,12 +286,8 @@ namespace System
//
//This class contains only static members and does not need to be serializable
[System.Runtime.CompilerServices.FriendAccessAllowed]
- internal class Number
+ internal static class Number
{
- private Number()
- {
- }
-
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public static extern String FormatDecimal(Decimal value, String format, NumberFormatInfo info);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
@@ -666,7 +662,7 @@ namespace System
return null;
}
- internal unsafe static Decimal ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt)
+ internal unsafe static Decimal ParseDecimal(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt)
{
Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -681,13 +677,8 @@ namespace System
return result;
}
- internal unsafe static Double ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt)
+ internal unsafe static Double ParseDouble(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt)
{
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value));
- }
-
Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
Double d = 0;
@@ -697,16 +688,16 @@ namespace System
//If we failed TryStringToNumber, it may be from one of our special strings.
//Check the three with which we're concerned and rethrow if it's not one of
//those strings.
- String sTrim = value.Trim();
- if (sTrim.Equals(numfmt.PositiveInfinitySymbol))
+ ReadOnlySpan<char> sTrim = value.Trim();
+ if (StringSpanHelpers.Equals(sTrim, numfmt.PositiveInfinitySymbol))
{
return Double.PositiveInfinity;
}
- if (sTrim.Equals(numfmt.NegativeInfinitySymbol))
+ if (StringSpanHelpers.Equals(sTrim, numfmt.NegativeInfinitySymbol))
{
return Double.NegativeInfinity;
}
- if (sTrim.Equals(numfmt.NaNSymbol))
+ if (StringSpanHelpers.Equals(sTrim, numfmt.NaNSymbol))
{
return Double.NaN;
}
@@ -721,7 +712,7 @@ namespace System
return d;
}
- internal unsafe static Int32 ParseInt32(String s, NumberStyles style, NumberFormatInfo info)
+ internal unsafe static Int32 ParseInt32(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info)
{
Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -746,7 +737,7 @@ namespace System
return i;
}
- internal unsafe static Int64 ParseInt64(String value, NumberStyles options, NumberFormatInfo numfmt)
+ internal unsafe static Int64 ParseInt64(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt)
{
Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -985,13 +976,8 @@ namespace System
return false;
}
- internal unsafe static Single ParseSingle(String value, NumberStyles options, NumberFormatInfo numfmt)
+ internal unsafe static Single ParseSingle(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt)
{
- if (value == null)
- {
- throw new ArgumentNullException(nameof(value));
- }
-
Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
Double d = 0;
@@ -1001,16 +987,16 @@ namespace System
//If we failed TryStringToNumber, it may be from one of our special strings.
//Check the three with which we're concerned and rethrow if it's not one of
//those strings.
- String sTrim = value.Trim();
- if (sTrim.Equals(numfmt.PositiveInfinitySymbol))
+ ReadOnlySpan<char> sTrim = value.Trim();
+ if (StringSpanHelpers.Equals(sTrim, numfmt.PositiveInfinitySymbol))
{
return Single.PositiveInfinity;
}
- if (sTrim.Equals(numfmt.NegativeInfinitySymbol))
+ if (StringSpanHelpers.Equals(sTrim, numfmt.NegativeInfinitySymbol))
{
return Single.NegativeInfinity;
}
- if (sTrim.Equals(numfmt.NaNSymbol))
+ if (StringSpanHelpers.Equals(sTrim, numfmt.NaNSymbol))
{
return Single.NaN;
}
@@ -1029,7 +1015,7 @@ namespace System
return castSingle;
}
- internal unsafe static UInt32 ParseUInt32(String value, NumberStyles options, NumberFormatInfo numfmt)
+ internal unsafe static UInt32 ParseUInt32(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt)
{
Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -1055,7 +1041,7 @@ namespace System
return i;
}
- internal unsafe static UInt64 ParseUInt64(String value, NumberStyles options, NumberFormatInfo numfmt)
+ internal unsafe static UInt64 ParseUInt64(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt)
{
Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -1079,15 +1065,10 @@ namespace System
return i;
}
- private unsafe static void StringToNumber(String str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo info, Boolean parseDecimal)
+ private unsafe static void StringToNumber(ReadOnlySpan<char> str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo info, Boolean parseDecimal)
{
- if (str == null)
- {
- throw new ArgumentNullException(nameof(String));
- }
- Contract.EndContractBlock();
Debug.Assert(info != null, "");
- fixed (char* stringPointer = str)
+ fixed (char* stringPointer = &str.DangerousGetPinnableReference())
{
char* p = stringPointer;
if (!ParseNumber(ref p, options, ref number, null, info, parseDecimal)
@@ -1098,7 +1079,7 @@ namespace System
}
}
- private static Boolean TrailingZeros(String s, Int32 index)
+ private static Boolean TrailingZeros(ReadOnlySpan<char> s, Int32 index)
{
// For compatibility, we need to allow trailing zeros at the end of a number string
for (int i = index; i < s.Length; i++)
@@ -1111,7 +1092,7 @@ namespace System
return true;
}
- internal unsafe static Boolean TryParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt, out Decimal result)
+ internal unsafe static Boolean TryParseDecimal(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt, out Decimal result)
{
Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -1129,7 +1110,7 @@ namespace System
return true;
}
- internal unsafe static Boolean TryParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt, out Double result)
+ internal unsafe static Boolean TryParseDouble(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt, out Double result)
{
Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -1147,7 +1128,7 @@ namespace System
return true;
}
- internal unsafe static Boolean TryParseInt32(String s, NumberStyles style, NumberFormatInfo info, out Int32 result)
+ internal unsafe static Boolean TryParseInt32(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out Int32 result)
{
Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -1175,7 +1156,7 @@ namespace System
return true;
}
- internal unsafe static Boolean TryParseInt64(String s, NumberStyles style, NumberFormatInfo info, out Int64 result)
+ internal unsafe static Boolean TryParseInt64(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out Int64 result)
{
Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -1203,7 +1184,7 @@ namespace System
return true;
}
- internal unsafe static Boolean TryParseSingle(String value, NumberStyles options, NumberFormatInfo numfmt, out Single result)
+ internal unsafe static Boolean TryParseSingle(ReadOnlySpan<char> value, NumberStyles options, NumberFormatInfo numfmt, out Single result)
{
Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -1228,7 +1209,7 @@ namespace System
return true;
}
- internal unsafe static Boolean TryParseUInt32(String s, NumberStyles style, NumberFormatInfo info, out UInt32 result)
+ internal unsafe static Boolean TryParseUInt32(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out UInt32 result)
{
Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -1256,7 +1237,7 @@ namespace System
return true;
}
- internal unsafe static Boolean TryParseUInt64(String s, NumberStyles style, NumberFormatInfo info, out UInt64 result)
+ internal unsafe static Boolean TryParseUInt64(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out UInt64 result)
{
Byte* numberBufferBytes = stackalloc Byte[NumberBuffer.NumberBufferBytes];
NumberBuffer number = new NumberBuffer(numberBufferBytes);
@@ -1284,24 +1265,19 @@ namespace System
return true;
}
- internal static Boolean TryStringToNumber(String str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo numfmt, Boolean parseDecimal)
- {
- return TryStringToNumber(str, options, ref number, null, numfmt, parseDecimal);
- }
-
[System.Runtime.CompilerServices.FriendAccessAllowed]
- internal unsafe static Boolean TryStringToNumber(String str, NumberStyles options, ref NumberBuffer number, StringBuilder sb, NumberFormatInfo numfmt, Boolean parseDecimal)
+ internal unsafe static Boolean TryStringToNumber(String str, NumberStyles options, ref NumberBuffer number, StringBuilder sb, NumberFormatInfo numfmt, Boolean parseDecimal) =>
+ str != null ?
+ TryStringToNumber(str.AsReadOnlySpan(), options, ref number, numfmt, parseDecimal) :
+ false;
+
+ internal static unsafe Boolean TryStringToNumber(ReadOnlySpan<char> str, NumberStyles options, ref NumberBuffer number, NumberFormatInfo numfmt, Boolean parseDecimal)
{
- if (str == null)
- {
- return false;
- }
Debug.Assert(numfmt != null, "");
-
- fixed (char* stringPointer = str)
+ fixed (char* stringPointer = &str.DangerousGetPinnableReference())
{
char* p = stringPointer;
- if (!ParseNumber(ref p, options, ref number, sb, numfmt, parseDecimal)
+ if (!ParseNumber(ref p, options, ref number, null, numfmt, parseDecimal)
|| (p - stringPointer < str.Length && !TrailingZeros(str, (int)(p - stringPointer))))
{
return false;
diff --git a/src/mscorlib/src/System/OutOfMemoryException.cs b/src/mscorlib/src/System/OutOfMemoryException.cs
index 3bec542077..8ef2d7b265 100644
--- a/src/mscorlib/src/System/OutOfMemoryException.cs
+++ b/src/mscorlib/src/System/OutOfMemoryException.cs
@@ -22,19 +22,19 @@ namespace System
public OutOfMemoryException()
: base(GetMessageFromNativeResources(ExceptionMessageKind.OutOfMemory))
{
- HResult = __HResults.COR_E_OUTOFMEMORY;
+ HResult = HResults.COR_E_OUTOFMEMORY;
}
public OutOfMemoryException(String message)
: base(message)
{
- HResult = __HResults.COR_E_OUTOFMEMORY;
+ HResult = HResults.COR_E_OUTOFMEMORY;
}
public OutOfMemoryException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_OUTOFMEMORY;
+ HResult = HResults.COR_E_OUTOFMEMORY;
}
protected OutOfMemoryException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs b/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs
index bbbd80b58b..d437e05e31 100644
--- a/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs
+++ b/src/mscorlib/src/System/Reflection/Assembly.CoreCLR.cs
@@ -22,7 +22,11 @@ namespace System.Reflection
private static Assembly LoadFromResolveHandler(object sender, ResolveEventArgs args)
{
Assembly requestingAssembly = args.RequestingAssembly;
-
+ if (requestingAssembly == null)
+ {
+ return null;
+ }
+
// Requesting assembly for LoadFrom is always loaded in defaultContext - proceed only if that
// is the case.
if (AssemblyLoadContext.Default != AssemblyLoadContext.GetLoadContext(requestingAssembly))
diff --git a/src/mscorlib/src/System/Reflection/CustomAttribute.cs b/src/mscorlib/src/System/Reflection/CustomAttribute.cs
index 4bc5933d50..1dd88a23a5 100644
--- a/src/mscorlib/src/System/Reflection/CustomAttribute.cs
+++ b/src/mscorlib/src/System/Reflection/CustomAttribute.cs
@@ -67,7 +67,7 @@ namespace System.Reflection
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
int pcaCount = 0;
- Attribute[] a = PseudoCustomAttribute.GetCustomAttributes((RuntimeType)target, typeof(object) as RuntimeType, true, out pcaCount);
+ Attribute[] a = PseudoCustomAttribute.GetCustomAttributes((RuntimeType)target, typeof(object) as RuntimeType, out pcaCount);
if (pcaCount == 0)
return cad;
@@ -111,7 +111,7 @@ namespace System.Reflection
IList<CustomAttributeData> cad = GetCustomAttributes(target.GetRuntimeModule(), target.MetadataToken);
int pcaCount = 0;
- Attribute[] a = PseudoCustomAttribute.GetCustomAttributes((RuntimeMethodInfo)target, typeof(object) as RuntimeType, true, out pcaCount);
+ Attribute[] a = PseudoCustomAttribute.GetCustomAttributes((RuntimeMethodInfo)target, typeof(object) as RuntimeType, out pcaCount);
if (pcaCount == 0)
return cad;
@@ -164,7 +164,7 @@ namespace System.Reflection
IList<CustomAttributeData> cad = GetCustomAttributes((RuntimeModule)target.ManifestModule, RuntimeAssembly.GetToken(target.GetNativeHandle()));
int pcaCount = 0;
- Attribute[] a = PseudoCustomAttribute.GetCustomAttributes(target, typeof(object) as RuntimeType, false, out pcaCount);
+ Attribute[] a = PseudoCustomAttribute.GetCustomAttributes(target, typeof(object) as RuntimeType, out pcaCount);
if (pcaCount == 0)
return cad;
@@ -1276,7 +1276,7 @@ namespace System.Reflection
type = type.GetGenericTypeDefinition() as RuntimeType;
int pcaCount = 0;
- Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(type, caType, true, out pcaCount);
+ Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(type, caType, out pcaCount);
// if we are asked to go up the hierarchy chain we have to do it now and regardless of the
// attribute usage for the specific attribute because a derived attribute may override the usage...
@@ -1320,7 +1320,7 @@ namespace System.Reflection
method = method.GetGenericMethodDefinition() as RuntimeMethodInfo;
int pcaCount = 0;
- Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(method, caType, true, out pcaCount);
+ Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(method, caType, out pcaCount);
// if we are asked to go up the hierarchy chain we have to do it now and regardless of the
// attribute usage for the specific attribute because a derived attribute may override the usage...
@@ -1361,7 +1361,7 @@ namespace System.Reflection
Contract.Requires(caType != null);
int pcaCount = 0;
- Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(ctor, caType, true, out pcaCount);
+ Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(ctor, caType, out pcaCount);
object[] attributes = GetCustomAttributes(ctor.GetRuntimeModule(), ctor.MetadataToken, pcaCount, caType);
if (pcaCount > 0) Array.Copy(pca, 0, attributes, attributes.Length - pcaCount, pcaCount);
return attributes;
@@ -1422,7 +1422,7 @@ namespace System.Reflection
Contract.Requires(caType != null);
int pcaCount = 0;
- Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(assembly, caType, true, out pcaCount);
+ Attribute[] pca = PseudoCustomAttribute.GetCustomAttributes(assembly, caType, out pcaCount);
int assemblyToken = RuntimeAssembly.GetToken(assembly.GetNativeHandle());
object[] attributes = GetCustomAttributes(assembly.ManifestModule as RuntimeModule, assemblyToken, pcaCount, caType);
if (pcaCount > 0) Array.Copy(pca, 0, attributes, attributes.Length - pcaCount, pcaCount);
@@ -1890,13 +1890,6 @@ namespace System.Reflection
private static int s_pcasCount;
#endregion
- #region FCalls
- internal static void GetSecurityAttributes(RuntimeModule module, int token, bool assembly, out object[] securityAttributes)
- {
- securityAttributes = null;
- }
- #endregion
-
#region Static Constructor
static PseudoCustomAttribute()
{
@@ -1941,13 +1934,7 @@ namespace System.Reflection
#endregion
#region Internal Static
- internal static bool IsSecurityAttribute(RuntimeType type)
- {
- // TODO: Cleanup
- return false;
- }
-
- internal static Attribute[] GetCustomAttributes(RuntimeType type, RuntimeType caType, bool includeSecCa, out int count)
+ internal static Attribute[] GetCustomAttributes(RuntimeType type, RuntimeType caType, out int count)
{
Contract.Requires(type != null);
Contract.Requires(caType != null);
@@ -1955,36 +1942,20 @@ namespace System.Reflection
count = 0;
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
- if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType))
+ if (!all && !s_pca.ContainsKey(caType))
return Array.Empty<Attribute>();
List<Attribute> pcas = new List<Attribute>();
- Attribute pca = null;
if (all || caType == (RuntimeType)typeof(SerializableAttribute))
{
- pca = SerializableAttribute.GetCustomAttribute(type);
- if (pca != null) pcas.Add(pca);
+ if ((type.Attributes & TypeAttributes.Serializable) != 0)
+ pcas.Add(new SerializableAttribute());
}
if (all || caType == (RuntimeType)typeof(ComImportAttribute))
{
- pca = ComImportAttribute.GetCustomAttribute(type);
- if (pca != null) pcas.Add(pca);
- }
- if (includeSecCa && (all || IsSecurityAttribute(caType)))
- {
- if (!type.IsGenericParameter && type.GetElementType() == null)
- {
- if (type.IsGenericType)
- type = (RuntimeType)type.GetGenericTypeDefinition();
-
- object[] securityAttributes;
- GetSecurityAttributes(type.Module.ModuleHandle.GetRuntimeModule(), type.MetadataToken, false, out securityAttributes);
- if (securityAttributes != null)
- foreach (object a in securityAttributes)
- if (caType == a.GetType() || a.GetType().IsSubclassOf(caType))
- pcas.Add((Attribute)a);
- }
+ if ((type.Attributes & TypeAttributes.Import) != 0)
+ pcas.Add(new ComImportAttribute());
}
count = pcas.Count;
@@ -1993,28 +1964,24 @@ namespace System.Reflection
internal static bool IsDefined(RuntimeType type, RuntimeType caType)
{
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
- if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType))
+ if (!all && !s_pca.ContainsKey(caType))
return false;
if (all || caType == (RuntimeType)typeof(SerializableAttribute))
{
- if (SerializableAttribute.IsDefined(type)) return true;
+ if ((type.Attributes & TypeAttributes.Serializable) != 0)
+ return true;
}
if (all || caType == (RuntimeType)typeof(ComImportAttribute))
{
- if (ComImportAttribute.IsDefined(type)) return true;
- }
- if (all || IsSecurityAttribute(caType))
- {
- int count;
- if (GetCustomAttributes(type, caType, true, out count).Length != 0)
+ if ((type.Attributes & TypeAttributes.Import) != 0)
return true;
}
return false;
}
- internal static Attribute[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, bool includeSecCa, out int count)
+ internal static Attribute[] GetCustomAttributes(RuntimeMethodInfo method, RuntimeType caType, out int count)
{
Contract.Requires(method != null);
Contract.Requires(caType != null);
@@ -2022,31 +1989,21 @@ namespace System.Reflection
count = 0;
bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
- if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType))
+ if (!all && !s_pca.ContainsKey(caType))
return Array.Empty<Attribute>();
List<Attribute> pcas = new List<Attribute>();
- Attribute pca = null;
+ Attribute pca;
if (all || caType == (RuntimeType)typeof(DllImportAttribute))
{
- pca = DllImportAttribute.GetCustomAttribute(method);
- if (pca != null) pcas.Add(pca);
+ pca = GetDllImportCustomAttribute(method);
+ if (pca != null) pcas[count++] = pca;
}
if (all || caType == (RuntimeType)typeof(PreserveSigAttribute))
{
- pca = PreserveSigAttribute.GetCustomAttribute(method);
- if (pca != null) pcas.Add(pca);
- }
- if (includeSecCa && (all || IsSecurityAttribute(caType)))
- {
- object[] securityAttributes;
-
- GetSecurityAttributes(method.Module.ModuleHandle.GetRuntimeModule(), method.MetadataToken, false, out securityAttributes);
- if (securityAttributes != null)
- foreach (object a in securityAttributes)
- if (caType == a.GetType() || a.GetType().IsSubclassOf(caType))
- pcas.Add((Attribute)a);
+ if ((method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0)
+ pcas.Add(new PreserveSigAttribute());
}
count = pcas.Count;
@@ -2060,17 +2017,12 @@ namespace System.Reflection
if (all || caType == (RuntimeType)typeof(DllImportAttribute))
{
- if (DllImportAttribute.IsDefined(method)) return true;
+ if ((method.Attributes & MethodAttributes.PinvokeImpl) != 0)
+ return true;
}
if (all || caType == (RuntimeType)typeof(PreserveSigAttribute))
{
- if (PreserveSigAttribute.IsDefined(method)) return true;
- }
- if (all || IsSecurityAttribute(caType))
- {
- int count;
-
- if (GetCustomAttributes(method, caType, true, out count).Length != 0)
+ if ((method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0)
return true;
}
@@ -2089,26 +2041,26 @@ namespace System.Reflection
return null;
Attribute[] pcas = new Attribute[s_pcasCount];
- Attribute pca = null;
+ Attribute pca;
if (all || caType == (RuntimeType)typeof(InAttribute))
{
- pca = InAttribute.GetCustomAttribute(parameter);
- if (pca != null) pcas[count++] = pca;
+ if (parameter.IsIn)
+ pcas[count++] = new InAttribute();
}
if (all || caType == (RuntimeType)typeof(OutAttribute))
{
- pca = OutAttribute.GetCustomAttribute(parameter);
- if (pca != null) pcas[count++] = pca;
+ if (parameter.IsOut)
+ pcas[count++] = new OutAttribute();
}
if (all || caType == (RuntimeType)typeof(OptionalAttribute))
{
- pca = OptionalAttribute.GetCustomAttribute(parameter);
- if (pca != null) pcas[count++] = pca;
+ if (parameter.IsOptional)
+ pcas[count++] = new OptionalAttribute();
}
if (all || caType == (RuntimeType)typeof(MarshalAsAttribute))
{
- pca = MarshalAsAttribute.GetCustomAttribute(parameter);
+ pca = GetMarshalAsCustomAttribute(parameter);
if (pca != null) pcas[count++] = pca;
}
return pcas;
@@ -2122,62 +2074,32 @@ namespace System.Reflection
if (all || caType == (RuntimeType)typeof(InAttribute))
{
- if (InAttribute.IsDefined(parameter)) return true;
+ if (parameter.IsIn) return true;
}
if (all || caType == (RuntimeType)typeof(OutAttribute))
{
- if (OutAttribute.IsDefined(parameter)) return true;
+ if (parameter.IsOut) return true;
}
if (all || caType == (RuntimeType)typeof(OptionalAttribute))
{
- if (OptionalAttribute.IsDefined(parameter)) return true;
+ if (parameter.IsOptional) return true;
}
if (all || caType == (RuntimeType)typeof(MarshalAsAttribute))
{
- if (MarshalAsAttribute.IsDefined(parameter)) return true;
+ if (GetMarshalAsCustomAttribute(parameter) != null) return true;
}
return false;
}
- internal static Attribute[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType, bool includeSecCa, out int count)
+ internal static Attribute[] GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType, out int count)
{
count = 0;
-
- bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
-
- if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType))
- return Array.Empty<Attribute>();
-
- List<Attribute> pcas = new List<Attribute>();
- if (includeSecCa && (all || IsSecurityAttribute(caType)))
- {
- object[] securityAttributes;
-
- GetSecurityAttributes(assembly.ManifestModule.ModuleHandle.GetRuntimeModule(), RuntimeAssembly.GetToken(assembly.GetNativeHandle()), true, out securityAttributes);
- if (securityAttributes != null)
- foreach (object a in securityAttributes)
- if (caType == a.GetType() || a.GetType().IsSubclassOf(caType))
- pcas.Add((Attribute)a);
- }
-
- //TypeForwardedToAttribute.GetCustomAttribute(assembly) throws FileNotFoundException if the forwarded-to
- //assemblies are not present. This breaks many V4 scenarios because some framework types are forwarded
- //to assemblies not included in the client SKU. Let's omit TypeForwardedTo for now until we have a better solution.
-
- //if (all || caType == (RuntimeType)typeof(TypeForwardedToAttribute))
- //{
- // TypeForwardedToAttribute[] attrs = TypeForwardedToAttribute.GetCustomAttribute(assembly);
- // pcas.AddRange(attrs);
- //}
-
- count = pcas.Count;
- return pcas.ToArray();
+ return null;
}
internal static bool IsDefined(RuntimeAssembly assembly, RuntimeType caType)
{
- int count;
- return GetCustomAttributes(assembly, caType, true, out count).Length > 0;
+ return false;
}
internal static Attribute[] GetCustomAttributes(RuntimeModule module, RuntimeType caType, out int count)
@@ -2202,22 +2124,22 @@ namespace System.Reflection
return null;
Attribute[] pcas = new Attribute[s_pcasCount];
- Attribute pca = null;
+ Attribute pca;
if (all || caType == (RuntimeType)typeof(MarshalAsAttribute))
{
- pca = MarshalAsAttribute.GetCustomAttribute(field);
+ pca = GetMarshalAsCustomAttribute(field);
if (pca != null) pcas[count++] = pca;
}
if (all || caType == (RuntimeType)typeof(FieldOffsetAttribute))
{
- pca = FieldOffsetAttribute.GetCustomAttribute(field);
+ pca = GetFieldOffsetCustomAttribute(field);
if (pca != null) pcas[count++] = pca;
}
if (all || caType == (RuntimeType)typeof(NonSerializedAttribute))
{
- pca = NonSerializedAttribute.GetCustomAttribute(field);
- if (pca != null) pcas[count++] = pca;
+ if ((field.Attributes & FieldAttributes.NotSerialized) != 0)
+ pcas[count++] = new NonSerializedAttribute();
}
return pcas;
}
@@ -2229,60 +2151,28 @@ namespace System.Reflection
if (all || caType == (RuntimeType)typeof(MarshalAsAttribute))
{
- if (MarshalAsAttribute.IsDefined(field)) return true;
+ if (GetMarshalAsCustomAttribute(field) != null) return true;
}
if (all || caType == (RuntimeType)typeof(FieldOffsetAttribute))
{
- if (FieldOffsetAttribute.IsDefined(field)) return true;
+ if (GetFieldOffsetCustomAttribute(field) != null) return true;
}
if (all || caType == (RuntimeType)typeof(NonSerializedAttribute))
{
- if (NonSerializedAttribute.IsDefined(field)) return true;
+ if ((field.Attributes & FieldAttributes.NotSerialized) != 0)
+ return true;
}
return false;
}
- internal static Attribute[] GetCustomAttributes(RuntimeConstructorInfo ctor, RuntimeType caType, bool includeSecCa, out int count)
+ internal static Attribute[] GetCustomAttributes(RuntimeConstructorInfo ctor, RuntimeType caType, out int count)
{
count = 0;
-
- bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
-
- if (!all && !s_pca.ContainsKey(caType) && !IsSecurityAttribute(caType))
- return Array.Empty<Attribute>();
-
- List<Attribute> pcas = new List<Attribute>();
-
- if (includeSecCa && (all || IsSecurityAttribute(caType)))
- {
- object[] securityAttributes;
-
- GetSecurityAttributes(ctor.Module.ModuleHandle.GetRuntimeModule(), ctor.MetadataToken, false, out securityAttributes);
- if (securityAttributes != null)
- foreach (object a in securityAttributes)
- if (caType == a.GetType() || a.GetType().IsSubclassOf(caType))
- pcas.Add((Attribute)a);
- }
-
- count = pcas.Count;
- return pcas.ToArray();
+ return null;
}
internal static bool IsDefined(RuntimeConstructorInfo ctor, RuntimeType caType)
{
- bool all = caType == (RuntimeType)typeof(object) || caType == (RuntimeType)typeof(Attribute);
-
- if (!all && !s_pca.ContainsKey(caType))
- return false;
-
- if (all || IsSecurityAttribute(caType))
- {
- int count;
-
- if (GetCustomAttributes(ctor, caType, true, out count).Length != 0)
- return true;
- }
-
return false;
}
@@ -2306,5 +2196,165 @@ namespace System.Reflection
return false;
}
#endregion
+
+ private static DllImportAttribute GetDllImportCustomAttribute(RuntimeMethodInfo method)
+ {
+ if ((method.Attributes & MethodAttributes.PinvokeImpl) == 0)
+ return null;
+
+ MetadataImport scope = ModuleHandle.GetMetadataImport(method.Module.ModuleHandle.GetRuntimeModule());
+ string entryPoint, dllName = null;
+ int token = method.MetadataToken;
+ PInvokeAttributes flags = 0;
+
+ scope.GetPInvokeMap(token, out flags, out entryPoint, out dllName);
+
+ CharSet charSet = CharSet.None;
+
+ switch (flags & PInvokeAttributes.CharSetMask)
+ {
+ case PInvokeAttributes.CharSetNotSpec: charSet = CharSet.None; break;
+ case PInvokeAttributes.CharSetAnsi: charSet = CharSet.Ansi; break;
+ case PInvokeAttributes.CharSetUnicode: charSet = CharSet.Unicode; break;
+ case PInvokeAttributes.CharSetAuto: charSet = CharSet.Auto; break;
+
+ // Invalid: default to CharSet.None
+ default: break;
+ }
+
+ CallingConvention callingConvention = CallingConvention.Cdecl;
+
+ switch (flags & PInvokeAttributes.CallConvMask)
+ {
+ case PInvokeAttributes.CallConvWinapi: callingConvention = CallingConvention.Winapi; break;
+ case PInvokeAttributes.CallConvCdecl: callingConvention = CallingConvention.Cdecl; break;
+ case PInvokeAttributes.CallConvStdcall: callingConvention = CallingConvention.StdCall; break;
+ case PInvokeAttributes.CallConvThiscall: callingConvention = CallingConvention.ThisCall; break;
+ case PInvokeAttributes.CallConvFastcall: callingConvention = CallingConvention.FastCall; break;
+
+ // Invalid: default to CallingConvention.Cdecl
+ default: break;
+ }
+
+ DllImportAttribute attribute = new DllImportAttribute(dllName);
+
+ attribute.EntryPoint = entryPoint;
+ attribute.CharSet = charSet;
+ attribute.SetLastError = (flags & PInvokeAttributes.SupportsLastError) != 0;
+ attribute.ExactSpelling = (flags & PInvokeAttributes.NoMangle) != 0;
+ attribute.PreserveSig = (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0;
+ attribute.CallingConvention = callingConvention;
+ attribute.BestFitMapping = (flags & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitEnabled;
+ attribute.ThrowOnUnmappableChar = (flags & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharEnabled;
+
+ return attribute;
+ }
+
+
+ private static MarshalAsAttribute GetMarshalAsCustomAttribute(RuntimeParameterInfo parameter)
+ {
+ return GetMarshalAsCustomAttribute(parameter.MetadataToken, parameter.GetRuntimeModule());
+ }
+ private static MarshalAsAttribute GetMarshalAsCustomAttribute(RuntimeFieldInfo field)
+ {
+ return GetMarshalAsCustomAttribute(field.MetadataToken, field.GetRuntimeModule());
+ }
+
+ private static MarshalAsAttribute GetMarshalAsCustomAttribute(int token, RuntimeModule scope)
+ {
+ UnmanagedType unmanagedType, arraySubType;
+ VarEnum safeArraySubType;
+ int sizeParamIndex = 0, sizeConst = 0;
+ string marshalTypeName = null, marshalCookie = null, safeArrayUserDefinedTypeName = null;
+ int iidParamIndex = 0;
+ ConstArray nativeType = ModuleHandle.GetMetadataImport(scope.GetNativeHandle()).GetFieldMarshal(token);
+
+ if (nativeType.Length == 0)
+ return null;
+
+ MetadataImport.GetMarshalAs(nativeType,
+ out unmanagedType, out safeArraySubType, out safeArrayUserDefinedTypeName, out arraySubType, out sizeParamIndex,
+ out sizeConst, out marshalTypeName, out marshalCookie, out iidParamIndex);
+
+ RuntimeType safeArrayUserDefinedType = safeArrayUserDefinedTypeName == null || safeArrayUserDefinedTypeName.Length == 0 ? null :
+ RuntimeTypeHandle.GetTypeByNameUsingCARules(safeArrayUserDefinedTypeName, scope);
+ RuntimeType marshalTypeRef = null;
+
+ try
+ {
+ marshalTypeRef = marshalTypeName == null ? null : RuntimeTypeHandle.GetTypeByNameUsingCARules(marshalTypeName, scope);
+ }
+ catch (System.TypeLoadException)
+ {
+ // The user may have supplied a bad type name string causing this TypeLoadException
+ // Regardless, we return the bad type name
+ Debug.Assert(marshalTypeName != null);
+ }
+
+ MarshalAsAttribute attribute = new MarshalAsAttribute(unmanagedType);
+
+ attribute.SafeArraySubType = safeArraySubType;
+ attribute.SafeArrayUserDefinedSubType = safeArrayUserDefinedType;
+ attribute.IidParameterIndex = iidParamIndex;
+ attribute.ArraySubType = arraySubType;
+ attribute.SizeParamIndex = (short)sizeParamIndex;
+ attribute.SizeConst = sizeConst;
+ attribute.MarshalType = marshalTypeName;
+ attribute.MarshalTypeRef = marshalTypeRef;
+ attribute.MarshalCookie = marshalCookie;
+
+ return attribute;
+ }
+
+ private static FieldOffsetAttribute GetFieldOffsetCustomAttribute(RuntimeFieldInfo field)
+ {
+ int fieldOffset;
+
+ if (field.DeclaringType != null &&
+ field.GetRuntimeModule().MetadataImport.GetFieldOffset(field.DeclaringType.MetadataToken, field.MetadataToken, out fieldOffset))
+ return new FieldOffsetAttribute(fieldOffset);
+
+ return null;
+ }
+
+ internal static StructLayoutAttribute GetStructLayoutCustomAttribute(RuntimeType type)
+ {
+ if (type.IsInterface || type.HasElementType || type.IsGenericParameter)
+ return null;
+
+ int pack = 0, size = 0;
+ LayoutKind layoutKind = LayoutKind.Auto;
+ switch (type.Attributes & TypeAttributes.LayoutMask)
+ {
+ case TypeAttributes.ExplicitLayout: layoutKind = LayoutKind.Explicit; break;
+ case TypeAttributes.AutoLayout: layoutKind = LayoutKind.Auto; break;
+ case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break;
+ default: Contract.Assume(false); break;
+ }
+
+ CharSet charSet = CharSet.None;
+ switch (type.Attributes & TypeAttributes.StringFormatMask)
+ {
+ case TypeAttributes.AnsiClass: charSet = CharSet.Ansi; break;
+ case TypeAttributes.AutoClass: charSet = CharSet.Auto; break;
+ case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break;
+ default: Contract.Assume(false); break;
+ }
+ type.GetRuntimeModule().MetadataImport.GetClassLayout(type.MetadataToken, out pack, out size);
+
+ // Metadata parameter checking should not have allowed 0 for packing size.
+ // The runtime later converts a packing size of 0 to 8 so do the same here
+ // because it's more useful from a user perspective.
+ if (pack == 0)
+ pack = 8; // DEFAULT_PACKING_SIZE
+
+ StructLayoutAttribute attribute = new StructLayoutAttribute(layoutKind);
+
+ attribute.Pack = pack;
+ attribute.Size = size;
+ attribute.CharSet = charSet;
+
+ return attribute;
+ }
}
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs
index 7b190df6c2..82f460138b 100644
--- a/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/AssemblyBuilder.cs
@@ -44,7 +44,7 @@ namespace System.Reflection.Emit
// This InternalAssemblyBuilder can be retrieved via a call to Assembly.GetAssemblies() by untrusted code.
// In the past, when InternalAssemblyBuilder was AssemblyBuilder, the untrusted user could down cast the
// Assembly to an AssemblyBuilder and emit code with the elevated permissions of the trusted code which
- // origionally created the AssemblyBuilder via DefineDynamicAssembly. Today, this can no longer happen
+ // originally created the AssemblyBuilder via DefineDynamicAssembly. Today, this can no longer happen
// because the Assembly returned via AssemblyGetAssemblies() will be an InternalAssemblyBuilder.
// Only the caller of DefineDynamicAssembly will get an AssemblyBuilder.
diff --git a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
index 15792d2d68..07d886fcca 100644
--- a/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/DynamicMethod.cs
@@ -487,18 +487,19 @@ namespace System.Reflection.Emit
throw new TargetParameterCountException(SR.Arg_ParmCnt);
// if we are here we passed all the previous checks. Time to look at the arguments
+ bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0;
Object retValue = null;
if (actualCount > 0)
{
Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
- retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, false);
+ retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, false, wrapExceptions);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
}
else
{
- retValue = RuntimeMethodHandle.InvokeMethod(null, null, sig, false);
+ retValue = RuntimeMethodHandle.InvokeMethod(null, null, sig, false, wrapExceptions);
}
GC.KeepAlive(this);
@@ -578,7 +579,7 @@ namespace System.Reflection.Emit
// This way the DynamicMethod creator is the only one responsible for DynamicMethod access,
// and can control exactly who gets access to it.
//
- internal class RTDynamicMethod : MethodInfo
+ internal sealed class RTDynamicMethod : MethodInfo
{
internal DynamicMethod m_owner;
private RuntimeParameterInfo[] m_parameters;
@@ -679,7 +680,7 @@ namespace System.Reflection.Emit
Contract.EndContractBlock();
if (attributeType.IsAssignableFrom(typeof(MethodImplAttribute)))
- return new Object[] { new MethodImplAttribute(GetMethodImplementationFlags()) };
+ return new Object[] { new MethodImplAttribute((MethodImplOptions)GetMethodImplementationFlags()) };
else
return Array.Empty<Object>();
}
@@ -687,7 +688,7 @@ namespace System.Reflection.Emit
public override Object[] GetCustomAttributes(bool inherit)
{
// support for MethodImplAttribute PCA
- return new Object[] { new MethodImplAttribute(GetMethodImplementationFlags()) };
+ return new Object[] { new MethodImplAttribute((MethodImplOptions)GetMethodImplementationFlags()) };
}
public override bool IsDefined(Type attributeType, bool inherit)
diff --git a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
index 75e4acc903..8256d0e6d5 100644
--- a/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/GenericTypeParameterBuilder.cs
@@ -21,7 +21,7 @@ namespace System.Reflection.Emit
return IsAssignableFrom(typeInfo.AsType());
}
- #region Private Data Mebers
+ #region Private Data Members
internal TypeBuilder m_type;
#endregion
diff --git a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
index fa31d66f6c..52e8b30e33 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ILGenerator.cs
@@ -1622,7 +1622,7 @@ namespace System.Reflection.Emit
/***************************
*
- * Find the current active lexcial scope. For example, if we have
+ * Find the current active lexical scope. For example, if we have
* "Open Open Open Close",
* we will return 1 as the second BeginScope is currently active.
*
diff --git a/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs
index 2d0a9b41dd..be4bfd5f48 100644
--- a/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/MethodBuilderInstantiation.cs
@@ -26,7 +26,7 @@ namespace System.Reflection.Emit
#endregion
- #region Private Data Mebers
+ #region Private Data Members
internal MethodInfo m_method;
private Type[] m_inst;
#endregion
diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs
index 362b13657f..1c65bf91c2 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilder.cs
@@ -87,7 +87,7 @@ namespace System.Reflection.Emit
#endregion
- #region Intenral Data Members
+ #region Internal Data Members
// m_TypeBuilder contains both TypeBuilder and EnumBuilder objects
private Dictionary<string, Type> m_TypeBuilderDict;
private ISymbolWriter m_iSymWriter;
diff --git a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
index 4a9b774d15..c597dbe6b4 100644
--- a/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/ModuleBuilderData.cs
@@ -2,10 +2,6 @@
// 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;
@@ -55,9 +51,7 @@ namespace System.Reflection.Emit
internal String m_strFileName;
internal bool m_fGlobalBeenCreated;
internal bool m_fHasGlobal;
- [NonSerialized]
internal TypeBuilder m_globalTypeBuilder;
- [NonSerialized]
internal ModuleBuilder m_module;
private int m_tkFile;
@@ -65,5 +59,5 @@ namespace System.Reflection.Emit
internal const String MULTI_BYTE_VALUE_CLASS = "$ArrayType$";
internal String m_strResourceFileName;
internal byte[] m_resourceBytes;
- } // class ModuleBuilderData
+ }
}
diff --git a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
index 64a38b0995..ab5b7eeaa5 100644
--- a/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/TypeBuilderInstantiation.cs
@@ -43,7 +43,7 @@ namespace System.Reflection.Emit
#endregion
- #region Private Data Mebers
+ #region Private Data Members
private Type m_type;
private Type[] m_inst;
private string m_strFullQualName;
diff --git a/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs b/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs
index 78238c02b7..3894d9115b 100644
--- a/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs
+++ b/src/mscorlib/src/System/Reflection/Emit/XXXOnTypeBuilderInstantiation.cs
@@ -23,7 +23,7 @@ namespace System.Reflection.Emit
}
#endregion
- #region Private Data Mebers
+ #region Private Data Members
internal MethodInfo m_method;
private TypeBuilderInstantiation m_type;
#endregion
@@ -99,7 +99,7 @@ namespace System.Reflection.Emit
}
#endregion
- #region Private Data Mebers
+ #region Private Data Members
internal ConstructorInfo m_ctor;
private TypeBuilderInstantiation m_type;
#endregion
diff --git a/src/mscorlib/src/System/Reflection/ExceptionHandlingClause.cs b/src/mscorlib/src/System/Reflection/ExceptionHandlingClause.cs
index 9bb45aebb2..a61ed5e385 100644
--- a/src/mscorlib/src/System/Reflection/ExceptionHandlingClause.cs
+++ b/src/mscorlib/src/System/Reflection/ExceptionHandlingClause.cs
@@ -9,7 +9,7 @@ namespace System.Reflection
{
public class ExceptionHandlingClause
{
- #region costructor
+ #region constructor
// This class can only be created from inside the EE.
protected ExceptionHandlingClause() { }
#endregion
diff --git a/src/mscorlib/src/System/Reflection/INVOCATION_FLAGS.cs b/src/mscorlib/src/System/Reflection/INVOCATION_FLAGS.cs
index 6ffc3e968b..b097b8fa0f 100644
--- a/src/mscorlib/src/System/Reflection/INVOCATION_FLAGS.cs
+++ b/src/mscorlib/src/System/Reflection/INVOCATION_FLAGS.cs
@@ -15,7 +15,7 @@ namespace System.Reflection
INVOCATION_FLAGS_INITIALIZED = 0x00000001,
// it's used for both method and field to signify that no access is allowed
INVOCATION_FLAGS_NO_INVOKE = 0x00000002,
- INVOCATION_FLAGS_NEED_SECURITY = 0x00000004,
+ /* unused 0x00000004 */
// Set for static ctors and ctors on abstract types, which
// can be invoked only if the "this" object is provided (even if it's null).
INVOCATION_FLAGS_NO_CTOR_INVOKE = 0x00000008,
diff --git a/src/mscorlib/src/System/Reflection/MethodBody.cs b/src/mscorlib/src/System/Reflection/MethodBody.cs
index 4335177efb..e1d18bf375 100644
--- a/src/mscorlib/src/System/Reflection/MethodBody.cs
+++ b/src/mscorlib/src/System/Reflection/MethodBody.cs
@@ -8,7 +8,7 @@ namespace System.Reflection
{
public class MethodBody
{
- #region costructor
+ #region constructor
// This class can only be created from inside the EE.
protected MethodBody() { }
#endregion
diff --git a/src/mscorlib/src/System/Reflection/RtFieldInfo.cs b/src/mscorlib/src/System/Reflection/RtFieldInfo.cs
index ddfc56b2aa..856d254d47 100644
--- a/src/mscorlib/src/System/Reflection/RtFieldInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RtFieldInfo.cs
@@ -13,11 +13,6 @@ namespace System.Reflection
{
internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo
{
- #region FCalls
- [MethodImplAttribute(MethodImplOptions.InternalCall)]
- static private extern void PerformVisibilityCheckOnField(IntPtr field, Object target, RuntimeType declaringType, FieldAttributes attr, uint invocationFlags);
- #endregion
-
#region Private Data Members
// agressive caching
private IntPtr m_fieldHandle;
@@ -58,13 +53,6 @@ namespace System.Reflection
if ((m_fieldAttributes & FieldAttributes.HasFieldRVA) != (FieldAttributes)0)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD;
- // A public field is inaccesible to Transparent code if the field is Critical.
- bool needsTransparencySecurityCheck = IsSecurityCritical && !IsSecuritySafeCritical;
- bool needsVisibilitySecurityCheck = ((m_fieldAttributes & FieldAttributes.FieldAccessMask) != FieldAttributes.Public) ||
- (declaringType != null && declaringType.NeedsReflectionSecurityCheck);
- if (needsTransparencySecurityCheck || needsVisibilitySecurityCheck)
- invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
-
// find out if the field type is one of the following: Primitive, Enum or Pointer
Type fieldType = FieldType;
if (fieldType.IsPointer || fieldType.IsEnum || fieldType.IsPrimitive)
@@ -158,11 +146,6 @@ namespace System.Reflection
RuntimeType fieldType = (RuntimeType)FieldType;
value = fieldType.CheckValue(value, binder, culture, invokeAttr);
- #region Security Check
- if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0)
- PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)m_invocationFlags);
- #endregion
-
bool domainInitialized = false;
if (declaringType == null)
{
@@ -223,10 +206,6 @@ namespace System.Reflection
CheckConsistency(obj);
- RuntimeType fieldType = (RuntimeType)FieldType;
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0)
- PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)(m_invocationFlags & ~INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD));
-
return UnsafeGetValue(obj);
}
diff --git a/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs b/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs
index edcb0d5cd5..cd9c715eec 100644
--- a/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeAssembly.cs
@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
+using System.Diagnostics;
using CultureInfo = System.Globalization.CultureInfo;
using System.Security;
using System.IO;
@@ -800,5 +801,78 @@ namespace System.Reflection
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int GetToken(RuntimeAssembly assembly);
+
+ public sealed override Type[] GetForwardedTypes()
+ {
+ List<Type> types = new List<Type>();
+ List<Exception> exceptions = new List<Exception>();
+
+ MetadataImport scope = GetManifestModule(GetNativeHandle()).MetadataImport;
+ scope.Enum(MetadataTokenType.ExportedType, 0, out MetadataEnumResult enumResult);
+ for (int i = 0; i < enumResult.Length; i++)
+ {
+ MetadataToken mdtExternalType = enumResult[i];
+ Type type = null;
+ Exception exception = null;
+ ObjectHandleOnStack pType = JitHelpers.GetObjectHandleOnStack(ref type);
+ try
+ {
+ GetForwardedType(this, mdtExternalType, pType);
+ if (type == null)
+ continue; // mdtExternalType was not a forwarder entry.
+ }
+ catch (Exception e)
+ {
+ type = null;
+ exception = e;
+ }
+
+ Debug.Assert((type != null) != (exception != null)); // Exactly one of these must be non-null.
+
+ if (type != null)
+ {
+ types.Add(type);
+ AddPublicNestedTypes(type, types, exceptions);
+ }
+ else
+ {
+ exceptions.Add(exception);
+ }
+ }
+
+ if (exceptions.Count != 0)
+ {
+ int numTypes = types.Count;
+ int numExceptions = exceptions.Count;
+ types.AddRange(new Type[numExceptions]); // add one null Type for each exception.
+ exceptions.InsertRange(0, new Exception[numTypes]); // align the Exceptions with the null Types.
+ throw new ReflectionTypeLoadException(types.ToArray(), exceptions.ToArray());
+ }
+
+ return types.ToArray();
+ }
+
+ private static void AddPublicNestedTypes(Type type, List<Type> types, List<Exception> exceptions)
+ {
+ Type[] nestedTypes;
+ try
+ {
+ nestedTypes = type.GetNestedTypes(BindingFlags.Public);
+ }
+ catch (Exception e)
+ {
+ exceptions.Add(e);
+ return;
+ }
+ foreach (Type nestedType in nestedTypes)
+ {
+ types.Add(nestedType);
+ AddPublicNestedTypes(nestedType, types, exceptions);
+ }
+ }
+
+ [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
+ [SuppressUnmanagedCodeSecurity]
+ private static extern void GetForwardedType(RuntimeAssembly assembly, MetadataToken mdtExternalType, ObjectHandleOnStack type);
}
}
diff --git a/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs
index 7870e0b91e..9b11a858df 100644
--- a/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeConstructorInfo.cs
@@ -57,16 +57,7 @@ namespace System.Reflection
// this should be an invocable method, determine the other flags that participate in invocation
invocationFlags |= RuntimeMethodHandle.GetSecurityFlags(this);
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0 &&
- ((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public ||
- (declaringType != null && declaringType.NeedsReflectionSecurityCheck)))
- {
- // If method is non-public, or declaring type is not visible
- invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
- }
-
- // Check for attempt to create a delegate class, we demand unmanaged
- // code permission for this since it's hard to validate the target address.
+ // Check for attempt to create a delegate class.
if (typeof(Delegate).IsAssignableFrom(DeclaringType))
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_IS_DELEGATE_CTOR;
}
@@ -363,13 +354,6 @@ namespace System.Reflection
// check basic method consistency. This call will throw if there are problems in the target/method relationship
CheckConsistency(obj);
- if (obj != null)
- {
- // For unverifiable code, we require the caller to be critical.
- // Adding the INVOCATION_FLAGS_NEED_SECURITY flag makes that check happen
- invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
- }
-
Signature sig = Signature;
// get the signature
@@ -379,16 +363,17 @@ namespace System.Reflection
throw new TargetParameterCountException(SR.Arg_ParmCnt);
// if we are here we passed all the previous checks. Time to look at the arguments
+ bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0;
if (actualCount > 0)
{
Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
- Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, sig, false);
+ Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, sig, false, wrapExceptions);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
return retValue;
}
- return RuntimeMethodHandle.InvokeMethod(obj, null, sig, false);
+ return RuntimeMethodHandle.InvokeMethod(obj, null, sig, false, wrapExceptions);
}
public override MethodBody GetMethodBody()
@@ -449,16 +434,17 @@ namespace System.Reflection
// JIT/NGen will insert the call to .cctor in the instance ctor.
// if we are here we passed all the previous checks. Time to look at the arguments
+ bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0;
if (actualCount > 0)
{
Object[] arguments = CheckArguments(parameters, binder, invokeAttr, culture, sig);
- Object retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, true);
+ Object retValue = RuntimeMethodHandle.InvokeMethod(null, arguments, sig, true, wrapExceptions);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters[index] = arguments[index];
return retValue;
}
- return RuntimeMethodHandle.InvokeMethod(null, null, sig, true);
+ return RuntimeMethodHandle.InvokeMethod(null, null, sig, true, wrapExceptions);
}
#endregion
}
diff --git a/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs
index f05508de7b..6addf74718 100644
--- a/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeMethodInfo.cs
@@ -54,29 +54,6 @@ namespace System.Reflection
{
// this should be an invocable method, determine the other flags that participate in invocation
invocationFlags = RuntimeMethodHandle.GetSecurityFlags(this);
-
- if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) == 0)
- {
- if ((Attributes & MethodAttributes.MemberAccessMask) != MethodAttributes.Public ||
- (declaringType != null && declaringType.NeedsReflectionSecurityCheck))
- {
- // If method is non-public, or declaring type is not visible
- invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
- }
- else if (IsGenericMethod)
- {
- Type[] genericArguments = GetGenericArguments();
-
- for (int i = 0; i < genericArguments.Length; i++)
- {
- if (genericArguments[i].NeedsReflectionSecurityCheck)
- {
- invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY;
- break;
- }
- }
- }
- }
}
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
@@ -207,6 +184,7 @@ namespace System.Reflection
return m_declaringType;
}
+ internal sealed override int GenericParameterCount => RuntimeMethodHandle.GetGenericParameterCount(this);
#endregion
#region Object Overrides
@@ -488,7 +466,7 @@ namespace System.Reflection
{
object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
- return UnsafeInvokeInternal(obj, parameters, arguments);
+ return UnsafeInvokeInternal(obj, invokeAttr, parameters, arguments);
}
[DebuggerStepThroughAttribute]
@@ -497,18 +475,19 @@ namespace System.Reflection
{
object[] arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
- return UnsafeInvokeInternal(obj, parameters, arguments);
+ return UnsafeInvokeInternal(obj, invokeAttr, parameters, arguments);
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- private object UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
+ private object UnsafeInvokeInternal(Object obj, BindingFlags invokeAttr, Object[] parameters, Object[] arguments)
{
+ bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0;
if (arguments == null || arguments.Length == 0)
- return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false);
+ return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false, wrapExceptions);
else
{
- Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false);
+ Object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false, wrapExceptions);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
diff --git a/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs b/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs
index 8c07d8f397..8f070b6827 100644
--- a/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs
+++ b/src/mscorlib/src/System/Reflection/RuntimeParameterInfo.cs
@@ -118,20 +118,12 @@ namespace System.Reflection
#endregion
#region Private Data Members
- // These are new in Whidbey, so we cannot serialize them directly or we break backwards compatibility.
- [NonSerialized]
private int m_tkParamDef;
- [NonSerialized]
private MetadataImport m_scope;
- [NonSerialized]
private Signature m_signature;
- [NonSerialized]
private volatile bool m_nameIsCached = false;
- [NonSerialized]
private readonly bool m_noMetadata = false;
- [NonSerialized]
private bool m_noDefaultValue = false;
- [NonSerialized]
private MethodBase m_originalMember = null;
#endregion
@@ -366,15 +358,15 @@ namespace System.Reflection
if (attrType == typeof(DateTimeConstantAttribute))
{
- defaultValue = DateTimeConstantAttribute.GetRawDateTimeConstant(attr);
+ defaultValue = GetRawDateTimeConstant(attr);
}
else if (attrType == typeof(DecimalConstantAttribute))
{
- defaultValue = DecimalConstantAttribute.GetRawDecimalConstant(attr);
+ defaultValue = GetRawDecimalConstant(attr);
}
else if (attrType.IsSubclassOf(s_CustomConstantAttributeType))
{
- defaultValue = CustomConstantAttribute.GetRawConstant(attr);
+ defaultValue = GetRawConstant(attr);
}
}
}
@@ -403,6 +395,80 @@ namespace System.Reflection
return defaultValue;
}
+ private static Decimal GetRawDecimalConstant(CustomAttributeData attr)
+ {
+ Contract.Requires(attr.Constructor.DeclaringType == typeof(DecimalConstantAttribute));
+
+ foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments)
+ {
+ if (namedArgument.MemberInfo.Name.Equals("Value"))
+ {
+ // This is not possible because Decimal cannot be represented directly in the metadata.
+ Debug.Assert(false, "Decimal cannot be represented directly in the metadata.");
+ return (Decimal)namedArgument.TypedValue.Value;
+ }
+ }
+
+ ParameterInfo[] parameters = attr.Constructor.GetParameters();
+ Debug.Assert(parameters.Length == 5);
+
+ System.Collections.Generic.IList<CustomAttributeTypedArgument> args = attr.ConstructorArguments;
+ Debug.Assert(args.Count == 5);
+
+ if (parameters[2].ParameterType == typeof(uint))
+ {
+ // DecimalConstantAttribute(byte scale, byte sign, uint hi, uint mid, uint low)
+ int low = (int)(UInt32)args[4].Value;
+ int mid = (int)(UInt32)args[3].Value;
+ int hi = (int)(UInt32)args[2].Value;
+ byte sign = (byte)args[1].Value;
+ byte scale = (byte)args[0].Value;
+
+ return new System.Decimal(low, mid, hi, (sign != 0), scale);
+ }
+ else
+ {
+ // DecimalConstantAttribute(byte scale, byte sign, int hi, int mid, int low)
+ int low = (int)args[4].Value;
+ int mid = (int)args[3].Value;
+ int hi = (int)args[2].Value;
+ byte sign = (byte)args[1].Value;
+ byte scale = (byte)args[0].Value;
+
+ return new System.Decimal(low, mid, hi, (sign != 0), scale);
+ }
+ }
+
+ private static DateTime GetRawDateTimeConstant(CustomAttributeData attr)
+ {
+ Contract.Requires(attr.Constructor.DeclaringType == typeof(DateTimeConstantAttribute));
+ Contract.Requires(attr.ConstructorArguments.Count == 1);
+
+ foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments)
+ {
+ if (namedArgument.MemberInfo.Name.Equals("Value"))
+ {
+ return new DateTime((long)namedArgument.TypedValue.Value);
+ }
+ }
+
+ // Look at the ctor argument if the "Value" property was not explicitly defined.
+ return new DateTime((long)attr.ConstructorArguments[0].Value);
+ }
+
+ private static object GetRawConstant(CustomAttributeData attr)
+ {
+ foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments)
+ {
+ if (namedArgument.MemberInfo.Name.Equals("Value"))
+ return namedArgument.TypedValue.Value;
+ }
+
+ // Return DBNull to indicate that no default value is available.
+ // Not to be confused with a null return which indicates a null default value.
+ return DBNull.Value;
+ }
+
internal RuntimeModule GetRuntimeModule()
{
RuntimeMethodInfo method = Member as RuntimeMethodInfo;
diff --git a/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs b/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs
index e1bbd2814a..7d445deba2 100644
--- a/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs
+++ b/src/mscorlib/src/System/Resources/FileBasedResourceGroveler.cs
@@ -118,18 +118,13 @@ namespace System.Resources
return null; // give up.
}
- // Constructs a new ResourceSet for a given file name. The logic in
- // here avoids a ReflectionPermission check for our RuntimeResourceSet
- // for perf and working set reasons.
+ // Constructs a new ResourceSet for a given file name.
private ResourceSet CreateResourceSet(String file)
{
Debug.Assert(file != null, "file shouldn't be null; check caller");
if (_mediator.UserResourceSet == null)
{
- // Explicitly avoid CreateInstance if possible, because it
- // requires ReflectionPermission to call private & protected
- // constructors.
return new RuntimeResourceSet(file);
}
else
diff --git a/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs b/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs
index 0e9666b2b1..a4e698276f 100644
--- a/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs
+++ b/src/mscorlib/src/System/Resources/ManifestBasedResourceGroveler.cs
@@ -189,9 +189,7 @@ namespace System.Resources
}
}
- // Constructs a new ResourceSet for a given file name. The logic in
- // here avoids a ReflectionPermission check for our RuntimeResourceSet
- // for perf and working set reasons.
+ // Constructs a new ResourceSet for a given file name.
// Use the assembly to resolve assembly manifest resource references.
// Note that is can be null, but probably shouldn't be.
// This method could use some refactoring. One thing at a time.
@@ -248,13 +246,7 @@ namespace System.Resources
// the abbreviated ones emitted by InternalResGen.
if (CanUseDefaultResourceClasses(readerTypeName, resSetTypeName))
{
- RuntimeResourceSet rs;
-#if LOOSELY_LINKED_RESOURCE_REFERENCE
- rs = new RuntimeResourceSet(store, assembly);
-#else
- rs = new RuntimeResourceSet(store);
-#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
- return rs;
+ return new RuntimeResourceSet(store);
}
else
{
@@ -264,16 +256,9 @@ namespace System.Resources
args[0] = store;
IResourceReader reader = (IResourceReader)Activator.CreateInstance(readerType, args);
- Object[] resourceSetArgs =
-#if LOOSELY_LINKED_RESOURCE_REFERENCE
- new Object[2];
-#else
- new Object[1];
-#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
+ Object[] resourceSetArgs = new Object[1];
resourceSetArgs[0] = reader;
-#if LOOSELY_LINKED_RESOURCE_REFERENCE
- resourceSetArgs[1] = assembly;
-#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
+
Type resSetType;
if (_mediator.UserResourceSet == null)
{
@@ -299,14 +284,7 @@ namespace System.Resources
if (_mediator.UserResourceSet == null)
{
- // Explicitly avoid CreateInstance if possible, because it
- // requires ReflectionPermission to call private & protected
- // constructors.
-#if LOOSELY_LINKED_RESOURCE_REFERENCE
- return new RuntimeResourceSet(store, assembly);
-#else
return new RuntimeResourceSet(store);
-#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
}
else
{
@@ -327,9 +305,7 @@ namespace System.Resources
args = new Object[1];
args[0] = store;
rs = (ResourceSet)Activator.CreateInstance(_mediator.UserResourceSet, args);
-#if LOOSELY_LINKED_RESOURCE_REFERENCE
- rs.Assembly = assembly;
-#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
+
return rs;
}
catch (MissingMethodException e)
@@ -440,7 +416,7 @@ namespace System.Resources
// denied back from the OS. This showed up for
// href-run exe's at one point.
int hr = fle._HResult;
- if (hr != Win32Native.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED))
+ if (hr != Win32Marshal.MakeHRFromErrorCode(Win32Native.ERROR_ACCESS_DENIED))
{
Debug.Assert(false, "[This assert catches satellite assembly build/deployment problems - report this message to your build lab & loc engineer]" + Environment.NewLine + "GetSatelliteAssembly failed for culture " + lookForCulture.Name + " and version " + (_mediator.SatelliteContractVersion == null ? _mediator.MainAssembly.GetVersion().ToString() : _mediator.SatelliteContractVersion.ToString()) + " of assembly " + _mediator.MainAssembly.GetSimpleName() + " with error code 0x" + hr.ToString("X", CultureInfo.InvariantCulture) + Environment.NewLine + "Exception: " + fle);
}
diff --git a/src/mscorlib/src/System/Resources/ResourceManager.cs b/src/mscorlib/src/System/Resources/ResourceManager.cs
index 92b935d931..7c565adbbb 100644
--- a/src/mscorlib/src/System/Resources/ResourceManager.cs
+++ b/src/mscorlib/src/System/Resources/ResourceManager.cs
@@ -525,17 +525,16 @@ namespace System.Resources
// such as ".ResX", or a completely different format for naming files.
protected virtual String GetResourceFileName(CultureInfo culture)
{
- StringBuilder sb = new StringBuilder(255);
- sb.Append(BaseNameField);
- // If this is the neutral culture, don't append culture name.
- if (!culture.HasInvariantCultureName)
+ // If this is the neutral culture, don't include the culture name.
+ if (culture.HasInvariantCultureName)
{
- CultureInfo.VerifyCultureName(culture.Name, true);
- sb.Append('.');
- sb.Append(culture.Name);
+ return BaseNameField + ResFileExtension;
+ }
+ else
+ {
+ CultureInfo.VerifyCultureName(culture.Name, throwException: true);
+ return BaseNameField + "." + culture.Name + ResFileExtension;
}
- sb.Append(ResFileExtension);
- return sb.ToString();
}
// WARNING: This function must be kept in sync with ResourceFallbackManager.GetEnumerator()
@@ -889,7 +888,7 @@ namespace System.Resources
// contains the PRI resources.
private bool ShouldUseSatelliteAssemblyResourceLookupUnderAppX(RuntimeAssembly resourcesAssembly)
{
- bool fUseSatelliteAssemblyResourceLookupUnderAppX = true; // TODO: https://github.com/dotnet/coreclr/issues/12178 once we fix our uap testhost
+ bool fUseSatelliteAssemblyResourceLookupUnderAppX = typeof(Object).Assembly == resourcesAssembly;
if (!fUseSatelliteAssemblyResourceLookupUnderAppX)
{
@@ -1035,9 +1034,14 @@ namespace System.Resources
// In this case _PRIExceptionInfo is now null and we will just throw the generic
// MissingManifestResource_NoPRIresources exception.
// See the implementation of GetString for more details.
- if (e.HResult != __HResults.ERROR_MRM_MAP_NOT_FOUND)
+ if (e.HResult != HResults.ERROR_MRM_MAP_NOT_FOUND)
throw; // Unexpected exception code. Bubble it up to the caller.
}
+
+ if (!_PRIonAppXInitialized)
+ {
+ _bUsingModernResourceManagement = false;
+ }
// Allow all other exception types to bubble up to the caller.
// Yes, this causes us to potentially throw exception types that are not documented.
@@ -1122,7 +1126,7 @@ namespace System.Resources
{
// When running inside AppX we want to ignore the languages list when trying to come up with our CurrentUICulture.
// This line behaves the same way as CultureInfo.CurrentUICulture would have in .NET 4
- culture = CultureInfo.GetCurrentUICultureNoAppX();
+ culture = CultureInfo.CurrentUICulture;
}
ResourceSet last = GetFirstResourceSet(culture);
diff --git a/src/mscorlib/src/System/Resources/ResourceSet.cs b/src/mscorlib/src/System/Resources/ResourceSet.cs
index b4029a7e9c..deb9763d5d 100644
--- a/src/mscorlib/src/System/Resources/ResourceSet.cs
+++ b/src/mscorlib/src/System/Resources/ResourceSet.cs
@@ -13,16 +13,10 @@
**
===========================================================*/
-using System;
using System.Collections;
using System.IO;
-using System.Globalization;
-using System.Runtime.InteropServices;
using System.Reflection;
-using System.Runtime.Serialization;
-using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
-using System.Collections.Generic;
namespace System.Resources
{
@@ -34,7 +28,7 @@ namespace System.Resources
//
public class ResourceSet : IDisposable, IEnumerable
{
- [NonSerialized] protected IResourceReader Reader;
+ protected IResourceReader Reader;
internal Hashtable Table;
private Hashtable _caseInsensitiveTable; // For case-insensitive lookups.
diff --git a/src/mscorlib/src/System/Resources/__HResults.cs b/src/mscorlib/src/System/Resources/__HResults.cs
deleted file mode 100644
index 5817161665..0000000000
--- a/src/mscorlib/src/System/Resources/__HResults.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-// 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: Define HResult constants returned by the Windows Modern Resource Manager
-// and consumed by System.Resources.ResourceManager.
-//
-//===========================================================================*/
-#if FEATURE_APPX
-namespace System.Resources
-{
- using System;
- // Only static data no need to serialize
- internal static class __HResults
- {
- // From WinError.h
- public const int ERROR_MRM_MAP_NOT_FOUND = unchecked((int)0x80073B1F);
- }
-}
-#endif
diff --git a/src/mscorlib/src/System/RtType.cs b/src/mscorlib/src/System/RtType.cs
index 871a39db4b..2d70354a48 100644
--- a/src/mscorlib/src/System/RtType.cs
+++ b/src/mscorlib/src/System/RtType.cs
@@ -458,8 +458,8 @@ namespace System
Volatile.Write(ref m_cacheComplete, true);
}
- else
- list = m_allMembers;
+
+ list = m_allMembers;
break;
default:
@@ -618,7 +618,11 @@ namespace System
while (RuntimeTypeHandle.IsGenericVariable(declaringType))
declaringType = declaringType.GetBaseType();
- bool* overrides = stackalloc bool[RuntimeTypeHandle.GetNumVirtuals(declaringType)];
+ int numVirtuals = RuntimeTypeHandle.GetNumVirtuals(declaringType);
+
+ bool* overrides = stackalloc bool[numVirtuals];
+ new Span<bool>(overrides, numVirtuals).Clear();
+
bool isValueType = declaringType.IsValueType;
do
@@ -2403,7 +2407,7 @@ namespace System
for (int i = 0; i < parameterInfos.Length; i++)
{
// a null argument type implies a null arg which is always a perfect match
- if ((object)argumentTypes[i] != null && !Object.ReferenceEquals(parameterInfos[i].ParameterType, argumentTypes[i]))
+ if ((object)argumentTypes[i] != null && !argumentTypes[i].MatchesParameterTypeExactly(parameterInfos[i]))
return false;
}
}
@@ -2485,8 +2489,11 @@ namespace System
#region Type Overrides
#region Get XXXInfo Candidates
+
+ private const int GenericParameterCountAny = -1;
+
private ListBuilder<MethodInfo> GetMethodCandidates(
- String name, BindingFlags bindingAttr, CallingConventions callConv,
+ String name, int genericParameterCount, BindingFlags bindingAttr, CallingConventions callConv,
Type[] types, bool allowPrefixLookup)
{
bool prefixLookup, ignoreCase;
@@ -2499,6 +2506,9 @@ namespace System
for (int i = 0; i < cache.Length; i++)
{
RuntimeMethodInfo methodInfo = cache[i];
+ if (genericParameterCount != GenericParameterCountAny && genericParameterCount != methodInfo.GenericParameterCount)
+ continue;
+
if (FilterApplyMethodInfo(methodInfo, bindingAttr, callConv, types) &&
(!prefixLookup || RuntimeType.FilterApplyPrefixLookup(methodInfo, name, ignoreCase)))
{
@@ -2636,7 +2646,7 @@ namespace System
#region Get All XXXInfos
public override MethodInfo[] GetMethods(BindingFlags bindingAttr)
{
- return GetMethodCandidates(null, bindingAttr, CallingConventions.Any, null, false).ToArray();
+ return GetMethodCandidates(null, GenericParameterCountAny, bindingAttr, CallingConventions.Any, null, false).ToArray();
}
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr)
@@ -2676,7 +2686,7 @@ namespace System
public override MemberInfo[] GetMembers(BindingFlags bindingAttr)
{
- ListBuilder<MethodInfo> methods = GetMethodCandidates(null, bindingAttr, CallingConventions.Any, null, false);
+ ListBuilder<MethodInfo> methods = GetMethodCandidates(null, GenericParameterCountAny, bindingAttr, CallingConventions.Any, null, false);
ListBuilder<ConstructorInfo> constructors = GetConstructorCandidates(null, bindingAttr, CallingConventions.Any, null, false);
ListBuilder<PropertyInfo> properties = GetPropertyCandidates(null, bindingAttr, null, false);
ListBuilder<EventInfo> events = GetEventCandidates(null, bindingAttr, false);
@@ -2765,11 +2775,26 @@ namespace System
#endregion
#region Find XXXInfo
+
protected override MethodInfo GetMethodImpl(
String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConv,
Type[] types, ParameterModifier[] modifiers)
{
- ListBuilder<MethodInfo> candidates = GetMethodCandidates(name, bindingAttr, callConv, types, false);
+ return GetMethodImplCommon(name, GenericParameterCountAny, bindingAttr, binder, callConv, types, modifiers);
+ }
+
+ protected override MethodInfo GetMethodImpl(
+ String name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConv,
+ Type[] types, ParameterModifier[] modifiers)
+ {
+ return GetMethodImplCommon(name, genericParameterCount, bindingAttr, binder, callConv, types, modifiers);
+ }
+
+ private MethodInfo GetMethodImplCommon(
+ String name, int genericParameterCount, BindingFlags bindingAttr, Binder binder, CallingConventions callConv,
+ Type[] types, ParameterModifier[] modifiers)
+ {
+ ListBuilder<MethodInfo> candidates = GetMethodCandidates(name, genericParameterCount, bindingAttr, callConv, types, false);
if (candidates.Count == 0)
return null;
@@ -3029,7 +3054,7 @@ namespace System
// Methods
if ((type & MemberTypes.Method) != 0)
{
- methods = GetMethodCandidates(name, bindingAttr, CallingConventions.Any, null, true);
+ methods = GetMethodCandidates(name, GenericParameterCountAny, bindingAttr, CallingConventions.Any, null, true);
if (type == MemberTypes.Method)
return methods.ToArray();
totalCount += methods.Count;
@@ -3447,6 +3472,8 @@ namespace System
return RuntimeTypeHandle.IsComObject(this, false);
}
+ public sealed override bool IsByRefLike => RuntimeTypeHandle.IsByRefLike(this);
+
#if FEATURE_COMINTEROP
internal override bool IsWindowsRuntimeObjectImpl()
{
@@ -3687,6 +3714,8 @@ namespace System
if (GetGenericArguments().Length != instantiation.Length)
throw new ArgumentException(SR.Argument_GenericArgsCount, nameof(instantiation));
+ bool foundSigType = false;
+ bool foundNonRuntimeType = false;
for (int i = 0; i < instantiation.Length; i++)
{
Type instantiationElem = instantiation[i];
@@ -3697,16 +3726,24 @@ namespace System
if (rtInstantiationElem == null)
{
- Type[] instantiationCopy = new Type[instantiation.Length];
- for (int iCopy = 0; iCopy < instantiation.Length; iCopy++)
- instantiationCopy[iCopy] = instantiation[iCopy];
- instantiation = instantiationCopy;
- return System.Reflection.Emit.TypeBuilderInstantiation.MakeGenericType(this, instantiation);
+ foundNonRuntimeType = true;
+ if (instantiationElem.IsSignatureType)
+ {
+ foundSigType = true;
+ }
}
instantiationRuntimeType[i] = rtInstantiationElem;
}
+ if (foundNonRuntimeType)
+ {
+ if (foundSigType)
+ return new SignatureConstructedGenericType(this, instantiation);
+
+ return System.Reflection.Emit.TypeBuilderInstantiation.MakeGenericType(this, (Type[])(instantiation.Clone()));
+ }
+
RuntimeType[] genericParameters = GetGenericArgumentsInternal();
SanityCheckGenericArguments(instantiationRuntimeType, genericParameters);
@@ -3809,7 +3846,7 @@ namespace System
{
get
{
- return (StructLayoutAttribute)StructLayoutAttribute.GetCustomAttribute(this);
+ return PseudoCustomAttribute.GetStructLayoutCustomAttribute(this);
}
}
#endregion
@@ -4045,7 +4082,7 @@ namespace System
#endif // FEATURE_COMINTEROP && FEATURE_USE_LCID
#endregion
- #region Check that any named paramters are not null
+ #region Check that any named parameters are not null
if (namedParams != null && Array.IndexOf(namedParams, null) != -1)
// "Named parameter value must not be null."
throw new ArgumentException(SR.Arg_NamedParamNull, nameof(namedParams));
@@ -4592,7 +4629,7 @@ namespace System
}
internal Object CreateInstanceImpl(
- BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, ref StackCrawlMark stackMark)
+ BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
{
CreateInstanceCheckThis();
@@ -4609,10 +4646,12 @@ namespace System
// deal with the __COMObject case first. It is very special because from a reflection point of view it has no ctors
// so a call to GetMemberCons would fail
+ bool publicOnly = (bindingAttr & BindingFlags.NonPublic) == 0;
+ bool wrapExceptions = (bindingAttr & BindingFlags.DoNotWrapExceptions) == 0;
if (argCnt == 0 && (bindingAttr & BindingFlags.Public) != 0 && (bindingAttr & BindingFlags.Instance) != 0
&& (IsGenericCOMObjectImpl() || IsValueType))
{
- server = CreateInstanceDefaultCtor((bindingAttr & BindingFlags.NonPublic) == 0, false, true, ref stackMark);
+ server = CreateInstanceDefaultCtor(publicOnly, false, true, wrapExceptions);
}
else
{
@@ -4670,7 +4709,7 @@ namespace System
}
// fast path??
- server = Activator.CreateInstance(this, true);
+ server = Activator.CreateInstance(this, nonPublic: true, wrapExceptions: wrapExceptions);
}
else
{
@@ -4754,7 +4793,7 @@ namespace System
internal void SetEntry(ActivatorCacheEntry ace)
{
- // fill the the array backwards to hit the most recently filled entries first in GetEntry
+ // fill the array backwards to hit the most recently filled entries first in GetEntry
int index = (hash_counter - 1) & (ActivatorCache.CACHE_SIZE - 1);
hash_counter = index;
Volatile.Write(ref cache[index], ace);
@@ -4764,7 +4803,7 @@ namespace System
private static volatile ActivatorCache s_ActivatorCache;
// the slow path of CreateInstanceDefaultCtor
- internal Object CreateInstanceSlow(bool publicOnly, bool skipCheckThis, bool fillCache, ref StackCrawlMark stackMark)
+ internal Object CreateInstanceSlow(bool publicOnly, bool wrapExceptions, bool skipCheckThis, bool fillCache)
{
RuntimeMethodHandleInternal runtime_ctor = default(RuntimeMethodHandleInternal);
bool bCanBeCached = false;
@@ -4772,7 +4811,7 @@ namespace System
if (!skipCheckThis)
CreateInstanceCheckThis();
- Object instance = RuntimeTypeHandle.CreateInstance(this, publicOnly, ref bCanBeCached, ref runtime_ctor);
+ Object instance = RuntimeTypeHandle.CreateInstance(this, publicOnly, wrapExceptions, ref bCanBeCached, ref runtime_ctor);
if (bCanBeCached && fillCache)
{
@@ -4796,7 +4835,7 @@ namespace System
// fillCache is set in the SL2/3 compat mode or when called from Marshal.PtrToStructure.
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
- internal Object CreateInstanceDefaultCtor(bool publicOnly, bool skipCheckThis, bool fillCache, ref StackCrawlMark stackMark)
+ internal Object CreateInstanceDefaultCtor(bool publicOnly, bool skipCheckThis, bool fillCache, bool wrapExceptions)
{
if (GetType() == typeof(ReflectionOnlyType))
throw new InvalidOperationException(SR.InvalidOperation_NotAllowedInReflectionOnly);
@@ -4829,7 +4868,7 @@ namespace System
{
ace.m_ctor(instance);
}
- catch (Exception e)
+ catch (Exception e) when (wrapExceptions)
{
throw new TargetInvocationException(e);
}
@@ -4837,7 +4876,7 @@ namespace System
return instance;
}
}
- return CreateInstanceSlow(publicOnly, skipCheckThis, fillCache, ref stackMark);
+ return CreateInstanceSlow(publicOnly, wrapExceptions, skipCheckThis, fillCache);
}
internal void InvalidateCachedNestedType()
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
index fc7a7f01a3..eb198ba087 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/AsyncMethodBuilder.cs
@@ -395,7 +395,7 @@ namespace System.Runtime.CompilerServices
/// </summary>
/// <remarks>
/// This property lazily instantiates the ID in a non-thread-safe manner.
- /// It must only be used by the debugger and tracing pruposes, and only in a single-threaded manner
+ /// It must only be used by the debugger and tracing purposes, and only in a single-threaded manner
/// when no other threads are in the middle of accessing this property or this.Task.
/// </remarks>
private object ObjectIdForDebugger { get { return this.Task; } }
@@ -431,8 +431,9 @@ namespace System.Runtime.CompilerServices
public static AsyncTaskMethodBuilder<TResult> Create()
{
return default(AsyncTaskMethodBuilder<TResult>);
- // NOTE: If this method is ever updated to perform more initialization,
- // ATMB.Create must also be updated to call this Create method.
+ // NOTE: If this method is ever updated to perform more initialization,
+ // other Create methods like AsyncTaskMethodBuilder.Create and
+ // AsyncValueTaskMethodBuilder.Create must be updated to call this.
}
/// <summary>Initiates the builder's execution with the associated state machine.</summary>
@@ -718,7 +719,7 @@ namespace System.Runtime.CompilerServices
/// <param name="result">The result for which we need a task.</param>
/// <returns>The completed task containing the result.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)] // method looks long, but for a given TResult it results in a relatively small amount of asm
- private Task<TResult> GetTaskForResult(TResult result)
+ internal static Task<TResult> GetTaskForResult(TResult result)
{
Contract.Ensures(
EqualityComparer<TResult>.Default.Equals(result, Contract.Result<Task<TResult>>().Result),
@@ -1119,7 +1120,7 @@ namespace System.Runtime.CompilerServices
}
///<summary>
- /// Given an action, see if it is a contiunation wrapper and has a Task associated with it. If so return it (null otherwise)
+ /// Given an action, see if it is a continuation wrapper and has a Task associated with it. If so return it (null otherwise)
///</summary>
internal static Task TryGetContinuationTask(Action action)
{
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs
deleted file mode 100644
index 7393bb2bcd..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/CustomConstantAttribute.cs
+++ /dev/null
@@ -1,29 +0,0 @@
-// 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;
-using System.Collections.Generic;
-
-namespace System.Runtime.CompilerServices
-{
- [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
- public abstract class CustomConstantAttribute : Attribute
- {
- public abstract Object Value { get; }
-
- internal static object GetRawConstant(CustomAttributeData attr)
- {
- foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments)
- {
- if (namedArgument.MemberInfo.Name.Equals("Value"))
- return namedArgument.TypedValue.Value;
- }
-
- // Return DBNull to indicate that no default value is available.
- // Not to be confused with a null return which indicates a null default value.
- return DBNull.Value;
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs
deleted file mode 100644
index 5155d0085d..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DateTimeConstantAttribute.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-// 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;
-using System.Diagnostics.Contracts;
-
-namespace System.Runtime.CompilerServices
-{
- [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
- public sealed class DateTimeConstantAttribute : CustomConstantAttribute
- {
- public DateTimeConstantAttribute(long ticks)
- {
- date = new System.DateTime(ticks);
- }
-
- public override Object Value
- {
- get
- {
- return date;
- }
- }
-
- internal static DateTime GetRawDateTimeConstant(CustomAttributeData attr)
- {
- Contract.Requires(attr.Constructor.DeclaringType == typeof(DateTimeConstantAttribute));
- Contract.Requires(attr.ConstructorArguments.Count == 1);
-
- foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments)
- {
- if (namedArgument.MemberInfo.Name.Equals("Value"))
- {
- return new DateTime((long)namedArgument.TypedValue.Value);
- }
- }
-
- // Look at the ctor argument if the "Value" property was not explicitly defined.
- return new DateTime((long)attr.ConstructorArguments[0].Value);
- }
-
- private System.DateTime date;
- }
-}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
deleted file mode 100644
index f5fd5a21a3..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/DecimalConstantAttribute.cs
+++ /dev/null
@@ -1,97 +0,0 @@
-// 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.
-
-
-// Note: If you add a new ctor overloads you need to update ParameterInfo.RawDefaultValue
-
-using System.Reflection;
-using System.Diagnostics;
-using System.Diagnostics.Contracts;
-using System.Collections.Generic;
-
-namespace System.Runtime.CompilerServices
-{
- [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
- public sealed class DecimalConstantAttribute : Attribute
- {
- [CLSCompliant(false)]
- public DecimalConstantAttribute(
- byte scale,
- byte sign,
- uint hi,
- uint mid,
- uint low
- )
- {
- dec = new System.Decimal((int)low, (int)mid, (int)hi, (sign != 0), scale);
- }
-
- public DecimalConstantAttribute(
- byte scale,
- byte sign,
- int hi,
- int mid,
- int low
- )
- {
- dec = new System.Decimal(low, mid, hi, (sign != 0), scale);
- }
-
-
- public System.Decimal Value
- {
- get
- {
- return dec;
- }
- }
-
- internal static Decimal GetRawDecimalConstant(CustomAttributeData attr)
- {
- Contract.Requires(attr.Constructor.DeclaringType == typeof(DecimalConstantAttribute));
-
- foreach (CustomAttributeNamedArgument namedArgument in attr.NamedArguments)
- {
- if (namedArgument.MemberInfo.Name.Equals("Value"))
- {
- // This is not possible because Decimal cannot be represented directly in the metadata.
- Debug.Assert(false, "Decimal cannot be represented directly in the metadata.");
- return (Decimal)namedArgument.TypedValue.Value;
- }
- }
-
- ParameterInfo[] parameters = attr.Constructor.GetParameters();
- Debug.Assert(parameters.Length == 5);
-
- System.Collections.Generic.IList<CustomAttributeTypedArgument> args = attr.ConstructorArguments;
- Debug.Assert(args.Count == 5);
-
- if (parameters[2].ParameterType == typeof(uint))
- {
- // DecimalConstantAttribute(byte scale, byte sign, uint hi, uint mid, uint low)
- int low = (int)(UInt32)args[4].Value;
- int mid = (int)(UInt32)args[3].Value;
- int hi = (int)(UInt32)args[2].Value;
- byte sign = (byte)args[1].Value;
- byte scale = (byte)args[0].Value;
-
- return new System.Decimal(low, mid, hi, (sign != 0), scale);
- }
- else
- {
- // DecimalConstantAttribute(byte scale, byte sign, int hi, int mid, int low)
- int low = (int)args[4].Value;
- int mid = (int)args[3].Value;
- int hi = (int)args[2].Value;
- byte sign = (byte)args[1].Value;
- byte scale = (byte)args[0].Value;
-
- return new System.Decimal(low, mid, hi, (sign != 0), scale);
- }
- }
-
- private System.Decimal dec;
- }
-}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs b/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs
deleted file mode 100644
index 3c19ee8863..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/MethodImplAttribute.cs
+++ /dev/null
@@ -1,47 +0,0 @@
-// 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.Reflection;
-
-namespace System.Runtime.CompilerServices
-{
- // This Enum matchs the miImpl flags defined in corhdr.h. It is used to specify
- // certain method properties.
-
- // Custom attribute to specify additional method properties.
- [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor, Inherited = false)]
- sealed public class MethodImplAttribute : Attribute
- {
- internal MethodImplOptions _val;
- public MethodCodeType MethodCodeType;
-
- internal MethodImplAttribute(MethodImplAttributes methodImplAttributes)
- {
- MethodImplOptions all =
- MethodImplOptions.Unmanaged | MethodImplOptions.ForwardRef | MethodImplOptions.PreserveSig |
- MethodImplOptions.InternalCall | MethodImplOptions.Synchronized |
- MethodImplOptions.NoInlining | MethodImplOptions.AggressiveInlining |
- MethodImplOptions.NoOptimization;
- _val = ((MethodImplOptions)methodImplAttributes) & all;
- }
-
- public MethodImplAttribute(MethodImplOptions methodImplOptions)
- {
- _val = methodImplOptions;
- }
-
- public MethodImplAttribute(short value)
- {
- _val = (MethodImplOptions)value;
- }
-
- public MethodImplAttribute()
- {
- }
-
- public MethodImplOptions Value { get { return _val; } }
- }
-}
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs b/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
deleted file mode 100644
index df52f301e4..0000000000
--- a/src/mscorlib/src/System/Runtime/CompilerServices/RuntimeWrappedException.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-// 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 uses to wrap all non-CLS compliant exceptions.
-**
-**
-=============================================================================*/
-
-using System;
-using System.Runtime.Serialization;
-using System.Diagnostics.Contracts;
-
-namespace System.Runtime.CompilerServices
-{
- public sealed class RuntimeWrappedException : Exception
- {
- private RuntimeWrappedException(Object thrownObject)
- : base(SR.RuntimeWrappedException)
- {
- HResult = System.__HResults.COR_E_RUNTIMEWRAPPED;
- m_wrappedException = thrownObject;
- }
-
- public Object WrappedException
- {
- get { return m_wrappedException; }
- }
-
- private Object m_wrappedException;
-
- public override void GetObjectData(SerializationInfo info, StreamingContext context)
- {
- base.GetObjectData(info, context);
- }
- }
-}
-
diff --git a/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs b/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs
index b184cd9fa8..df3c244b47 100644
--- a/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs
+++ b/src/mscorlib/src/System/Runtime/CompilerServices/Unsafe.cs
@@ -48,6 +48,18 @@ namespace System.Runtime.CompilerServices
}
/// <summary>
+ /// Casts the given object to the specified type.
+ /// </summary>
+ [NonVersionable]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static T As<T>(object o) where T : class
+ {
+ // The body of this function will be replaced by the EE with unsafe code!!!
+ // See getILIntrinsicImplementationForUnsafe for how this happens.
+ throw new InvalidOperationException();
+ }
+
+ /// <summary>
/// Reinterprets the given reference as a reference to a value of type <typeparamref name="TTo"/>.
/// </summary>
[NonVersionable]
@@ -55,7 +67,7 @@ namespace System.Runtime.CompilerServices
public static ref TTo As<TFrom, TTo>(ref TFrom source)
{
// The body of this function will be replaced by the EE with unsafe code!!!
- // See getILIntrinsicImplementationForUnsafe for how this happens.
+ // See getILIntrinsicImplementationForUnsafe for how this happens.
throw new InvalidOperationException();
}
@@ -77,6 +89,19 @@ namespace System.Runtime.CompilerServices
/// </summary>
[NonVersionable]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
+ public static void* Add<T>(void* source, int elementOffset)
+ {
+ // The body of this function will be replaced by the EE with unsafe code!!!
+ // See getILIntrinsicImplementationForUnsafe for how this happens.
+ typeof(T).ToString(); // Type token used by the actual method body
+ throw new InvalidOperationException();
+ }
+
+ /// <summary>
+ /// Adds an element offset to the given reference.
+ /// </summary>
+ [NonVersionable]
+ [MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ref T AddByteOffset<T>(ref T source, nuint byteOffset)
{
// The body of this function will be replaced by the EE with unsafe code!!!
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
index 668358995b..7b50c705b2 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/Attributes.cs
@@ -154,126 +154,9 @@ namespace System.Runtime.InteropServices
public String Value { get { return _val; } }
}
- [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.ReturnValue, Inherited = false)]
- public unsafe sealed class MarshalAsAttribute : Attribute
- {
- internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter)
- {
- return GetCustomAttribute(parameter.MetadataToken, parameter.GetRuntimeModule());
- }
-
- internal static bool IsDefined(RuntimeParameterInfo parameter)
- {
- return GetCustomAttribute(parameter) != null;
- }
-
- internal static Attribute GetCustomAttribute(RuntimeFieldInfo field)
- {
- return GetCustomAttribute(field.MetadataToken, field.GetRuntimeModule()); ;
- }
-
- internal static bool IsDefined(RuntimeFieldInfo field)
- {
- return GetCustomAttribute(field) != null;
- }
-
- internal static Attribute GetCustomAttribute(int token, RuntimeModule scope)
- {
- UnmanagedType unmanagedType, arraySubType;
- VarEnum safeArraySubType;
- int sizeParamIndex = 0, sizeConst = 0;
- string marshalTypeName = null, marshalCookie = null, safeArrayUserDefinedTypeName = null;
- int iidParamIndex = 0;
- ConstArray nativeType = ModuleHandle.GetMetadataImport(scope.GetNativeHandle()).GetFieldMarshal(token);
-
- if (nativeType.Length == 0)
- return null;
-
- MetadataImport.GetMarshalAs(nativeType,
- out unmanagedType, out safeArraySubType, out safeArrayUserDefinedTypeName, out arraySubType, out sizeParamIndex,
- out sizeConst, out marshalTypeName, out marshalCookie, out iidParamIndex);
-
- RuntimeType safeArrayUserDefinedType = safeArrayUserDefinedTypeName == null || safeArrayUserDefinedTypeName.Length == 0 ? null :
- RuntimeTypeHandle.GetTypeByNameUsingCARules(safeArrayUserDefinedTypeName, scope);
- RuntimeType marshalTypeRef = null;
-
- try
- {
- marshalTypeRef = marshalTypeName == null ? null : RuntimeTypeHandle.GetTypeByNameUsingCARules(marshalTypeName, scope);
- }
- catch (System.TypeLoadException)
- {
- // The user may have supplied a bad type name string causing this TypeLoadException
- // Regardless, we return the bad type name
- Debug.Assert(marshalTypeName != null);
- }
-
- return new MarshalAsAttribute(
- unmanagedType, safeArraySubType, safeArrayUserDefinedType, arraySubType,
- (short)sizeParamIndex, sizeConst, marshalTypeName, marshalTypeRef, marshalCookie, iidParamIndex);
- }
-
- internal MarshalAsAttribute(UnmanagedType val, VarEnum safeArraySubType, RuntimeType safeArrayUserDefinedSubType, UnmanagedType arraySubType,
- short sizeParamIndex, int sizeConst, string marshalType, RuntimeType marshalTypeRef, string marshalCookie, int iidParamIndex)
- {
- _val = val;
- SafeArraySubType = safeArraySubType;
- SafeArrayUserDefinedSubType = safeArrayUserDefinedSubType;
- IidParameterIndex = iidParamIndex;
- ArraySubType = arraySubType;
- SizeParamIndex = sizeParamIndex;
- SizeConst = sizeConst;
- MarshalType = marshalType;
- MarshalTypeRef = marshalTypeRef;
- MarshalCookie = marshalCookie;
- }
-
- internal UnmanagedType _val;
- public MarshalAsAttribute(UnmanagedType unmanagedType)
- {
- _val = unmanagedType;
- }
- public MarshalAsAttribute(short unmanagedType)
- {
- _val = (UnmanagedType)unmanagedType;
- }
- public UnmanagedType Value { get { return _val; } }
-
- // Fields used with SubType = SafeArray.
- public VarEnum SafeArraySubType;
- public Type SafeArrayUserDefinedSubType;
-
- // Field used with iid_is attribute (interface pointers).
- public int IidParameterIndex;
-
- // Fields used with SubType = ByValArray and LPArray.
- // Array size = parameter(PI) * PM + C
- public UnmanagedType ArraySubType;
- public short SizeParamIndex; // param index PI
- public int SizeConst; // constant C
-
- // Fields used with SubType = CustomMarshaler
- public String MarshalType; // Name of marshaler class
- public Type MarshalTypeRef; // Type of marshaler class
- public String MarshalCookie; // cookie to pass to marshaler
- }
-
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, Inherited = false)]
public sealed class ComImportAttribute : Attribute
{
- internal static Attribute GetCustomAttribute(RuntimeType type)
- {
- if ((type.Attributes & TypeAttributes.Import) == 0)
- return null;
-
- return new ComImportAttribute();
- }
-
- internal static bool IsDefined(RuntimeType type)
- {
- return (type.Attributes & TypeAttributes.Import) != 0;
- }
-
public ComImportAttribute()
{
}
@@ -290,292 +173,6 @@ namespace System.Runtime.InteropServices
public String Value { get { return _val; } }
}
- [AttributeUsage(AttributeTargets.Method, Inherited = false)]
- public sealed class PreserveSigAttribute : Attribute
- {
- internal static Attribute GetCustomAttribute(RuntimeMethodInfo method)
- {
- if ((method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) == 0)
- return null;
-
- return new PreserveSigAttribute();
- }
-
- internal static bool IsDefined(RuntimeMethodInfo method)
- {
- return (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0;
- }
-
- public PreserveSigAttribute()
- {
- }
- }
-
- [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
- public sealed class InAttribute : Attribute
- {
- internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter)
- {
- return parameter.IsIn ? new InAttribute() : null;
- }
- internal static bool IsDefined(RuntimeParameterInfo parameter)
- {
- return parameter.IsIn;
- }
-
- public InAttribute()
- {
- }
- }
-
- [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
- public sealed class OutAttribute : Attribute
- {
- internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter)
- {
- return parameter.IsOut ? new OutAttribute() : null;
- }
- internal static bool IsDefined(RuntimeParameterInfo parameter)
- {
- return parameter.IsOut;
- }
-
- public OutAttribute()
- {
- }
- }
-
- [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
- public sealed class OptionalAttribute : Attribute
- {
- internal static Attribute GetCustomAttribute(RuntimeParameterInfo parameter)
- {
- return parameter.IsOptional ? new OptionalAttribute() : null;
- }
- internal static bool IsDefined(RuntimeParameterInfo parameter)
- {
- return parameter.IsOptional;
- }
-
- public OptionalAttribute()
- {
- }
- }
-
- [Flags]
- public enum DllImportSearchPath
- {
- UseDllDirectoryForDependencies = 0x100,
- ApplicationDirectory = 0x200,
- UserDirectories = 0x400,
- System32 = 0x800,
- SafeDirectories = 0x1000,
- AssemblyDirectory = 0x2,
- LegacyBehavior = 0x0
- }
-
- [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Method, AllowMultiple = false)]
- public sealed class DefaultDllImportSearchPathsAttribute : Attribute
- {
- internal DllImportSearchPath _paths;
- public DefaultDllImportSearchPathsAttribute(DllImportSearchPath paths)
- {
- _paths = paths;
- }
-
- public DllImportSearchPath Paths { get { return _paths; } }
- }
-
- [AttributeUsage(AttributeTargets.Method, Inherited = false)]
- public unsafe sealed class DllImportAttribute : Attribute
- {
- internal static Attribute GetCustomAttribute(RuntimeMethodInfo method)
- {
- if ((method.Attributes & MethodAttributes.PinvokeImpl) == 0)
- return null;
-
- MetadataImport scope = ModuleHandle.GetMetadataImport(method.Module.ModuleHandle.GetRuntimeModule());
- string entryPoint, dllName = null;
- int token = method.MetadataToken;
- PInvokeAttributes flags = 0;
-
- scope.GetPInvokeMap(token, out flags, out entryPoint, out dllName);
-
- CharSet charSet = CharSet.None;
-
- switch (flags & PInvokeAttributes.CharSetMask)
- {
- case PInvokeAttributes.CharSetNotSpec: charSet = CharSet.None; break;
- case PInvokeAttributes.CharSetAnsi: charSet = CharSet.Ansi; break;
- case PInvokeAttributes.CharSetUnicode: charSet = CharSet.Unicode; break;
- case PInvokeAttributes.CharSetAuto: charSet = CharSet.Auto; break;
-
- // Invalid: default to CharSet.None
- default: break;
- }
-
- CallingConvention callingConvention = CallingConvention.Cdecl;
-
- switch (flags & PInvokeAttributes.CallConvMask)
- {
- case PInvokeAttributes.CallConvWinapi: callingConvention = CallingConvention.Winapi; break;
- case PInvokeAttributes.CallConvCdecl: callingConvention = CallingConvention.Cdecl; break;
- case PInvokeAttributes.CallConvStdcall: callingConvention = CallingConvention.StdCall; break;
- case PInvokeAttributes.CallConvThiscall: callingConvention = CallingConvention.ThisCall; break;
- case PInvokeAttributes.CallConvFastcall: callingConvention = CallingConvention.FastCall; break;
-
- // Invalid: default to CallingConvention.Cdecl
- default: break;
- }
-
- bool exactSpelling = (flags & PInvokeAttributes.NoMangle) != 0;
- bool setLastError = (flags & PInvokeAttributes.SupportsLastError) != 0;
- bool bestFitMapping = (flags & PInvokeAttributes.BestFitMask) == PInvokeAttributes.BestFitEnabled;
- bool throwOnUnmappableChar = (flags & PInvokeAttributes.ThrowOnUnmappableCharMask) == PInvokeAttributes.ThrowOnUnmappableCharEnabled;
- bool preserveSig = (method.GetMethodImplementationFlags() & MethodImplAttributes.PreserveSig) != 0;
-
- return new DllImportAttribute(
- dllName, entryPoint, charSet, exactSpelling, setLastError, preserveSig,
- callingConvention, bestFitMapping, throwOnUnmappableChar);
- }
-
- internal static bool IsDefined(RuntimeMethodInfo method)
- {
- return (method.Attributes & MethodAttributes.PinvokeImpl) != 0;
- }
-
-
- internal DllImportAttribute(
- string dllName, string entryPoint, CharSet charSet, bool exactSpelling, bool setLastError, bool preserveSig,
- CallingConvention callingConvention, bool bestFitMapping, bool throwOnUnmappableChar)
- {
- _val = dllName;
- EntryPoint = entryPoint;
- CharSet = charSet;
- ExactSpelling = exactSpelling;
- SetLastError = setLastError;
- PreserveSig = preserveSig;
- CallingConvention = callingConvention;
- BestFitMapping = bestFitMapping;
- ThrowOnUnmappableChar = throwOnUnmappableChar;
- }
-
- internal String _val;
-
- public DllImportAttribute(String dllName)
- {
- _val = dllName;
- }
- public String Value { get { return _val; } }
-
- public String EntryPoint;
- public CharSet CharSet;
- public bool SetLastError;
- public bool ExactSpelling;
- public bool PreserveSig;
- public CallingConvention CallingConvention;
- public bool BestFitMapping;
- public bool ThrowOnUnmappableChar;
- }
-
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
- public unsafe sealed class StructLayoutAttribute : Attribute
- {
- private const int DEFAULT_PACKING_SIZE = 8;
-
- internal static Attribute GetCustomAttribute(RuntimeType type)
- {
- if (!IsDefined(type))
- return null;
-
- int pack = 0, size = 0;
- LayoutKind layoutKind = LayoutKind.Auto;
- switch (type.Attributes & TypeAttributes.LayoutMask)
- {
- case TypeAttributes.ExplicitLayout: layoutKind = LayoutKind.Explicit; break;
- case TypeAttributes.AutoLayout: layoutKind = LayoutKind.Auto; break;
- case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break;
- default: Contract.Assume(false); break;
- }
-
- CharSet charSet = CharSet.None;
- switch (type.Attributes & TypeAttributes.StringFormatMask)
- {
- case TypeAttributes.AnsiClass: charSet = CharSet.Ansi; break;
- case TypeAttributes.AutoClass: charSet = CharSet.Auto; break;
- case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break;
- default: Contract.Assume(false); break;
- }
- type.GetRuntimeModule().MetadataImport.GetClassLayout(type.MetadataToken, out pack, out size);
-
- // Metadata parameter checking should not have allowed 0 for packing size.
- // The runtime later converts a packing size of 0 to 8 so do the same here
- // because it's more useful from a user perspective.
- if (pack == 0)
- pack = DEFAULT_PACKING_SIZE;
-
- return new StructLayoutAttribute(layoutKind, pack, size, charSet);
- }
-
- internal static bool IsDefined(RuntimeType type)
- {
- if (type.IsInterface || type.HasElementType || type.IsGenericParameter)
- return false;
-
- return true;
- }
-
- internal LayoutKind _val;
-
- internal StructLayoutAttribute(LayoutKind layoutKind, int pack, int size, CharSet charSet)
- {
- _val = layoutKind;
- Pack = pack;
- Size = size;
- CharSet = charSet;
- }
-
- public StructLayoutAttribute(LayoutKind layoutKind)
- {
- _val = layoutKind;
- }
- public StructLayoutAttribute(short layoutKind)
- {
- _val = (LayoutKind)layoutKind;
- }
- public LayoutKind Value { get { return _val; } }
- public int Pack;
- public int Size;
- public CharSet CharSet;
- }
-
- [AttributeUsage(AttributeTargets.Field, Inherited = false)]
- public unsafe sealed class FieldOffsetAttribute : Attribute
- {
- internal static Attribute GetCustomAttribute(RuntimeFieldInfo field)
- {
- int fieldOffset;
-
- if (field.DeclaringType != null &&
- field.GetRuntimeModule().MetadataImport.GetFieldOffset(field.DeclaringType.MetadataToken, field.MetadataToken, out fieldOffset))
- return new FieldOffsetAttribute(fieldOffset);
-
- return null;
- }
-
- internal static bool IsDefined(RuntimeFieldInfo field)
- {
- return GetCustomAttribute(field) != null;
- }
-
- internal int _val;
- public FieldOffsetAttribute(int offset)
- {
- _val = offset;
- }
- public int Value { get { return _val; } }
- }
-
[AttributeUsage(AttributeTargets.Interface, Inherited = false)]
public sealed class CoClassAttribute : Attribute
{
@@ -588,32 +185,5 @@ namespace System.Runtime.InteropServices
public Type CoClass { get { return _CoClass; } }
}
-
- [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
- public sealed class BestFitMappingAttribute : Attribute
- {
- internal bool _bestFitMapping;
-
- public BestFitMappingAttribute(bool BestFitMapping)
- {
- _bestFitMapping = BestFitMapping;
- }
-
- public bool BestFitMapping { get { return _bestFitMapping; } }
- public bool ThrowOnUnmappableChar;
- }
-
- [AttributeUsage(AttributeTargets.Module, Inherited = false)]
- public sealed class DefaultCharSetAttribute : Attribute
- {
- internal CharSet _CharSet;
-
- public DefaultCharSetAttribute(CharSet charSet)
- {
- _CharSet = charSet;
- }
-
- public CharSet CharSet { get { return _CharSet; } }
- }
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
index 8ee10ed349..6d9927fd97 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/COMException.cs
@@ -27,19 +27,19 @@ namespace System.Runtime.InteropServices
public COMException()
: base(SR.Arg_COMException)
{
- HResult = __HResults.E_FAIL;
+ HResult = HResults.E_FAIL;
}
public COMException(String message)
: base(message)
{
- HResult = __HResults.E_FAIL;
+ HResult = HResults.E_FAIL;
}
public COMException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.E_FAIL;
+ HResult = HResults.E_FAIL;
}
public COMException(String message, int errorCode)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs
index fe69f619fe..50e9ea6fee 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/ComEventsHelper.cs
@@ -114,7 +114,7 @@ namespace System.Runtime.InteropServices
/// <param name="rcw">COM object firing the events the caller would like to respond to</param>
/// <param name="iid">identifier of the source interface used by COM object to fire events</param>
/// <param name="dispid">dispatch identifier of the method on the source interface</param>
- /// <param name="d">delegate to invoke when specifed COM event is fired</param>
+ /// <param name="d">delegate to invoke when specified COM event is fired</param>
public static void Combine(object rcw, Guid iid, int dispid, System.Delegate d)
{
rcw = UnwrapIfTransparentProxy(rcw);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs b/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs
index 734a494bdb..cc3462275e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/CriticalHandle.cs
@@ -109,7 +109,7 @@ using System.IO;
get { return handle == IntPtr.Zero; }
}
- [DllImport(Win32Native.KERNEL32), SuppressUnmanagedCodeSecurity, ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
+ [DllImport(Interop.Libraries.Kernel32), SuppressUnmanagedCodeSecurity, ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
private static extern bool CloseHandle(IntPtr handle);
override protected bool ReleaseHandle()
@@ -123,20 +123,14 @@ using System.IO;
Note that when returning a CriticalHandle like this, P/Invoke will call your
classes default constructor.
- [DllImport(Win32Native.KERNEL32)]
+ [DllImport(Interop.Libraries.Kernel32)]
private static extern MyCriticalHandleSubclass CreateHandle(int someState);
*/
namespace System.Runtime.InteropServices
{
- // This class should not be serializable - it's a handle. We require unmanaged
- // code permission to subclass CriticalHandle to prevent people from writing a
- // subclass and suddenly being able to run arbitrary native code with the
- // same signature as CloseHandle. This is technically a little redundant, but
- // we'll do this to ensure we've cut off all attack vectors. Similarly, all
- // methods have a link demand to ensure untrusted code cannot directly edit
- // or alter a handle.
+ // This class should not be serializable - it's a handle
public abstract class CriticalHandle : CriticalFinalizerObject, IDisposable
{
// ! Do not add or rearrange fields as the EE depends on this layout.
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs b/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs
index bf89df94bb..c3ce68df4b 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/InvalidComObjectException.cs
@@ -22,19 +22,19 @@ namespace System.Runtime.InteropServices
public InvalidComObjectException()
: base(SR.Arg_InvalidComObjectException)
{
- HResult = __HResults.COR_E_INVALIDCOMOBJECT;
+ HResult = HResults.COR_E_INVALIDCOMOBJECT;
}
public InvalidComObjectException(String message)
: base(message)
{
- HResult = __HResults.COR_E_INVALIDCOMOBJECT;
+ HResult = HResults.COR_E_INVALIDCOMOBJECT;
}
public InvalidComObjectException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_INVALIDCOMOBJECT;
+ HResult = HResults.COR_E_INVALIDCOMOBJECT;
}
protected InvalidComObjectException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs b/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs
index 412853920e..f61010cda3 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/InvalidOleVariantTypeException.cs
@@ -21,19 +21,19 @@ namespace System.Runtime.InteropServices
public InvalidOleVariantTypeException()
: base(SR.Arg_InvalidOleVariantTypeException)
{
- HResult = __HResults.COR_E_INVALIDOLEVARIANTTYPE;
+ HResult = HResults.COR_E_INVALIDOLEVARIANTTYPE;
}
public InvalidOleVariantTypeException(String message)
: base(message)
{
- HResult = __HResults.COR_E_INVALIDOLEVARIANTTYPE;
+ HResult = HResults.COR_E_INVALIDOLEVARIANTTYPE;
}
public InvalidOleVariantTypeException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_INVALIDOLEVARIANTTYPE;
+ HResult = HResults.COR_E_INVALIDOLEVARIANTTYPE;
}
protected InvalidOleVariantTypeException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
index 03750bcb8b..1567e0dd1c 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/Marshal.cs
@@ -930,7 +930,6 @@ namespace System.Runtime.InteropServices
// Creates a new instance of "structuretype" and marshals data from a
// native memory block to it.
//====================================================================
- [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod
public static Object PtrToStructure(IntPtr ptr, Type structureType)
{
if (ptr == IntPtr.Zero) return null;
@@ -946,9 +945,7 @@ namespace System.Runtime.InteropServices
if (rt == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(structureType));
- StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller;
-
- Object structure = rt.CreateInstanceDefaultCtor(false /*publicOnly*/, false /*skipCheckThis*/, false /*fillCache*/, ref stackMark);
+ Object structure = rt.CreateInstanceDefaultCtor(false /*publicOnly*/, false /*skipCheckThis*/, false /*fillCache*/, true /*wrapExceptions*/);
PtrToStructureHelper(ptr, structure, true);
return structure;
}
@@ -1742,15 +1739,15 @@ namespace System.Runtime.InteropServices
return obj;
}
- [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
+ [DllImport(Interop.Libraries.Ole32, PreserveSig = false)]
[SuppressUnmanagedCodeSecurity]
private static extern void CreateBindCtx(UInt32 reserved, out IBindCtx ppbc);
- [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
+ [DllImport(Interop.Libraries.Ole32, PreserveSig = false)]
[SuppressUnmanagedCodeSecurity]
private static extern void MkParseDisplayName(IBindCtx pbc, [MarshalAs(UnmanagedType.LPWStr)] String szUserName, out UInt32 pchEaten, out IMoniker ppmk);
- [DllImport(Microsoft.Win32.Win32Native.OLE32, PreserveSig = false)]
+ [DllImport(Interop.Libraries.Ole32, PreserveSig = false)]
[SuppressUnmanagedCodeSecurity]
private static extern void BindMoniker(IMoniker pmk, UInt32 grfOpt, ref Guid iidResult, [MarshalAs(UnmanagedType.Interface)] out Object ppvResult);
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs b/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs
index 75b291af30..48e2dcf411 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/MarshalDirectiveException.cs
@@ -22,19 +22,19 @@ namespace System.Runtime.InteropServices
public MarshalDirectiveException()
: base(SR.Arg_MarshalDirectiveException)
{
- HResult = __HResults.COR_E_MARSHALDIRECTIVE;
+ HResult = HResults.COR_E_MARSHALDIRECTIVE;
}
public MarshalDirectiveException(String message)
: base(message)
{
- HResult = __HResults.COR_E_MARSHALDIRECTIVE;
+ HResult = HResults.COR_E_MARSHALDIRECTIVE;
}
public MarshalDirectiveException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_MARSHALDIRECTIVE;
+ HResult = HResults.COR_E_MARSHALDIRECTIVE;
}
protected MarshalDirectiveException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs
index d61e79757c..832c4d289e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SEHException.cs
@@ -24,19 +24,19 @@ namespace System.Runtime.InteropServices
public SEHException()
: base()
{
- HResult = __HResults.E_FAIL;
+ HResult = HResults.E_FAIL;
}
public SEHException(String message)
: base(message)
{
- HResult = __HResults.E_FAIL;
+ HResult = HResults.E_FAIL;
}
public SEHException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.E_FAIL;
+ HResult = HResults.E_FAIL;
}
protected SEHException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs
index 9df858f0b1..7109b4fe51 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayRankMismatchException.cs
@@ -21,19 +21,19 @@ namespace System.Runtime.InteropServices
public SafeArrayRankMismatchException()
: base(SR.Arg_SafeArrayRankMismatchException)
{
- HResult = __HResults.COR_E_SAFEARRAYRANKMISMATCH;
+ HResult = HResults.COR_E_SAFEARRAYRANKMISMATCH;
}
public SafeArrayRankMismatchException(String message)
: base(message)
{
- HResult = __HResults.COR_E_SAFEARRAYRANKMISMATCH;
+ HResult = HResults.COR_E_SAFEARRAYRANKMISMATCH;
}
public SafeArrayRankMismatchException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_SAFEARRAYRANKMISMATCH;
+ HResult = HResults.COR_E_SAFEARRAYRANKMISMATCH;
}
protected SafeArrayRankMismatchException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs
index 4b03691e82..13a6cf62a8 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeArrayTypeMismatchException.cs
@@ -22,19 +22,19 @@ namespace System.Runtime.InteropServices
public SafeArrayTypeMismatchException()
: base(SR.Arg_SafeArrayTypeMismatchException)
{
- HResult = __HResults.COR_E_SAFEARRAYTYPEMISMATCH;
+ HResult = HResults.COR_E_SAFEARRAYTYPEMISMATCH;
}
public SafeArrayTypeMismatchException(String message)
: base(message)
{
- HResult = __HResults.COR_E_SAFEARRAYTYPEMISMATCH;
+ HResult = HResults.COR_E_SAFEARRAYTYPEMISMATCH;
}
public SafeArrayTypeMismatchException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_SAFEARRAYTYPEMISMATCH;
+ HResult = HResults.COR_E_SAFEARRAYTYPEMISMATCH;
}
protected SafeArrayTypeMismatchException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs
index 73a3721801..6e6d6ee2b6 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/SafeBuffer.cs
@@ -109,7 +109,7 @@ namespace System.Runtime.InteropServices
}
/// <summary>
- /// Specifies the the size of the region in memory, as the number of
+ /// Specifies the size of the region in memory, as the number of
/// elements in an array. Must be called before using the SafeBuffer.
/// </summary>
[CLSCompliant(false)]
@@ -126,7 +126,7 @@ namespace System.Runtime.InteropServices
}
/// <summary>
- /// Specifies the the size of the region in memory, as the number of
+ /// Specifies the size of the region in memory, as the number of
/// elements in an array. Must be called before using the SafeBuffer.
/// </summary>
[CLSCompliant(false)]
@@ -173,15 +173,10 @@ namespace System.Runtime.InteropServices
pointer = null;
RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- }
- finally
- {
- bool junk = false;
- DangerousAddRef(ref junk);
- pointer = (byte*)handle;
- }
+
+ bool junk = false;
+ DangerousAddRef(ref junk);
+ pointer = (byte*)handle;
}
public void ReleasePointer()
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs
index 539b8020b8..f0be957f8c 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/BindableVectorToListAdapter.cs
@@ -167,7 +167,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex)
{
- if (__HResults.E_BOUNDS == ex._HResult)
+ if (HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
@@ -185,7 +185,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex)
{
- if (__HResults.E_BOUNDS == ex._HResult)
+ if (HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
@@ -203,7 +203,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex)
{
- if (__HResults.E_BOUNDS == ex._HResult)
+ if (HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
@@ -221,7 +221,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex)
{
- if (__HResults.E_BOUNDS == ex._HResult)
+ if (HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
index aa0f3ba056..75774caae2 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
@@ -134,7 +134,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public char GetChar16()
{
if (this.Type != PropertyType.Char16)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Char16"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Char16"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (char)_data;
}
@@ -143,7 +143,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Boolean GetBoolean()
{
if (this.Type != PropertyType.Boolean)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Boolean"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Boolean"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (bool)_data;
}
@@ -166,7 +166,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public DateTimeOffset GetDateTime()
{
if (this.Type != PropertyType.DateTime)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "DateTime"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "DateTime"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (DateTimeOffset)_data;
}
@@ -175,7 +175,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public TimeSpan GetTimeSpan()
{
if (this.Type != PropertyType.TimeSpan)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "TimeSpan"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "TimeSpan"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (TimeSpan)_data;
}
@@ -184,7 +184,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Point GetPoint()
{
if (this.Type != PropertyType.Point)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Point"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Point"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return Unbox<Point>(IReferenceFactory.s_pointType);
@@ -194,7 +194,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Size GetSize()
{
if (this.Type != PropertyType.Size)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Size"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Size"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return Unbox<Size>(IReferenceFactory.s_sizeType);
@@ -204,7 +204,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Rect GetRect()
{
if (this.Type != PropertyType.Rect)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Rect"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Rect"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return Unbox<Rect>(IReferenceFactory.s_rectType);
@@ -268,7 +268,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public char[] GetChar16Array()
{
if (this.Type != PropertyType.Char16Array)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Char16[]"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Char16[]"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (char[])_data;
}
@@ -277,7 +277,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Boolean[] GetBooleanArray()
{
if (this.Type != PropertyType.BooleanArray)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Boolean[]"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Boolean[]"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (bool[])_data;
}
@@ -292,7 +292,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Object[] GetInspectableArray()
{
if (this.Type != PropertyType.InspectableArray)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Inspectable[]"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Inspectable[]"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (Object[])_data;
}
@@ -307,7 +307,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public DateTimeOffset[] GetDateTimeArray()
{
if (this.Type != PropertyType.DateTimeArray)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "DateTimeOffset[]"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "DateTimeOffset[]"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (DateTimeOffset[])_data;
}
@@ -316,7 +316,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public TimeSpan[] GetTimeSpanArray()
{
if (this.Type != PropertyType.TimeSpanArray)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "TimeSpan[]"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "TimeSpan[]"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return (TimeSpan[])_data;
}
@@ -325,7 +325,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Point[] GetPointArray()
{
if (this.Type != PropertyType.PointArray)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Point[]"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Point[]"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return UnboxArray<Point>(IReferenceFactory.s_pointType);
@@ -335,7 +335,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Size[] GetSizeArray()
{
if (this.Type != PropertyType.SizeArray)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Size[]"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Size[]"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
@@ -346,7 +346,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
public Rect[] GetRectArray()
{
if (this.Type != PropertyType.RectArray)
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Rect[]"), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, "Rect[]"), HResults.TYPE_E_TYPEMISMATCH);
Contract.EndContractBlock();
return UnboxArray<Rect>(IReferenceFactory.s_rectType);
@@ -364,7 +364,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
Array dataArray = _data as Array;
if (dataArray == null)
{
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, typeof (T).MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, this.Type, typeof (T).MakeArrayType().Name), HResults.TYPE_E_TYPEMISMATCH);
}
// Array types are 1024 larger than their equivilent scalar counterpart
@@ -408,7 +408,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
// should not attempt coersion, even if the underlying value is technically convertable
if (!IsCoercable(type, value) && type != PropertyType.Inspectable)
{
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof (T).Name), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof (T).Name), HResults.TYPE_E_TYPEMISMATCH);
}
try
@@ -438,15 +438,15 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (FormatException)
{
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof (T).Name), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof (T).Name), HResults.TYPE_E_TYPEMISMATCH);
}
catch (InvalidCastException)
{
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof (T).Name), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof (T).Name), HResults.TYPE_E_TYPEMISMATCH);
}
catch (OverflowException)
{
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueCoersion, type, value, typeof (T).Name), __HResults.DISP_E_OVERFLOW);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueCoersion, type, value, typeof (T).Name), HResults.DISP_E_OVERFLOW);
}
// If the property type is IInspectable, and we have a nested IPropertyValue, then we need
@@ -497,7 +497,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
// Otherwise, this is an invalid coersion
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof (T).Name), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, type, typeof (T).Name), HResults.TYPE_E_TYPEMISMATCH);
}
private static bool IsCoercable(PropertyType type, object data)
@@ -539,7 +539,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (_data.GetType() != expectedBoxedType)
{
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, _data.GetType(), expectedBoxedType.Name), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, _data.GetType(), expectedBoxedType.Name), HResults.TYPE_E_TYPEMISMATCH);
}
T unboxed = new T();
@@ -563,7 +563,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
Array dataArray = _data as Array;
if (dataArray == null || _data.GetType().GetElementType() != expectedArrayElementType)
{
- throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, _data.GetType(), expectedArrayElementType.MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH);
+ throw new InvalidCastException(SR.Format(SR.InvalidCast_WinRTIPropertyValueElement, _data.GetType(), expectedArrayElementType.MakeArrayType().Name), HResults.TYPE_E_TYPEMISMATCH);
}
T[] converted = new T[dataArray.Length];
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
index 0ed0bb3f7b..5a4a5e8a7b 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ConstantSplittableMap.cs
@@ -102,7 +102,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (!found)
{
Exception e = new KeyNotFoundException(SR.Arg_KeyNotFound);
- e.SetErrorCode(__HResults.E_BOUNDS);
+ e.SetErrorCode(HResults.E_BOUNDS);
throw e;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
index bb54d49b60..3a1f8c4f4a 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/DictionaryToMapAdapter.cs
@@ -42,7 +42,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (!keyFound)
{
Exception e = new KeyNotFoundException(SR.Arg_KeyNotFound);
- e.SetErrorCode(__HResults.E_BOUNDS);
+ e.SetErrorCode(HResults.E_BOUNDS);
throw e;
}
@@ -97,7 +97,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (!removed)
{
Exception e = new KeyNotFoundException(SR.Arg_KeyNotFound);
- e.SetErrorCode(__HResults.E_BOUNDS);
+ e.SetErrorCode(HResults.E_BOUNDS);
throw e;
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs
index 75b8480eeb..70a9da6974 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/EnumeratorToIteratorAdapter.cs
@@ -92,7 +92,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (!m_hasCurrent)
{
- throw WindowsRuntimeMarshal.GetExceptionForHR(__HResults.E_BOUNDS, null);
+ throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, null);
}
return m_enumerator.Current;
@@ -131,7 +131,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (InvalidOperationException e)
{
- throw WindowsRuntimeMarshal.GetExceptionForHR(__HResults.E_CHANGED_STATE, e);
+ throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_CHANGED_STATE, e);
}
return m_hasCurrent;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
index 0900012338..04958c3bd5 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IMapViewToIReadOnlyDictionaryAdapter.cs
@@ -92,7 +92,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex) // Still may hit this case due to a race condition
{
- if (__HResults.E_BOUNDS == ex._HResult)
+ if (HResults.E_BOUNDS == ex._HResult)
{
value = default(V);
return false;
@@ -113,7 +113,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex)
{
- if (__HResults.E_BOUNDS == ex._HResult)
+ if (HResults.E_BOUNDS == ex._HResult)
throw new KeyNotFoundException(SR.Arg_KeyNotFound);
throw;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
index 73daf876cd..eaf5f471de 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyDictionaryToIMapViewAdapter.cs
@@ -41,7 +41,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (!keyFound)
{
Exception e = new KeyNotFoundException(SR.Arg_KeyNotFound);
- e.SetErrorCode(__HResults.E_BOUNDS);
+ e.SetErrorCode(HResults.E_BOUNDS);
throw e;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs
index 5dce7dfc8d..9b87bee372 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IReadOnlyListToIVectorViewAdapter.cs
@@ -43,7 +43,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (ArgumentOutOfRangeException ex)
{
- ex.SetErrorCode(__HResults.E_BOUNDS);
+ ex.SetErrorCode(HResults.E_BOUNDS);
throw;
}
}
@@ -127,7 +127,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
{
Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue);
- e.SetErrorCode(__HResults.E_BOUNDS);
+ e.SetErrorCode(HResults.E_BOUNDS);
throw e;
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs
index 76b0fff00d..5090323572 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IVectorViewToIReadOnlyListAdapter.cs
@@ -50,7 +50,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex)
{
- if (__HResults.E_BOUNDS == ex._HResult)
+ if (HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs
index 417476dbbe..ccef9d92bf 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/IteratorToEnumeratorAdapter.cs
@@ -182,7 +182,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (Exception e)
{
// Translate E_CHANGED_STATE into an InvalidOperationException for an updated enumeration
- if (Marshal.GetHRForException(e) == __HResults.E_CHANGED_STATE)
+ if (Marshal.GetHRForException(e) == HResults.E_CHANGED_STATE)
{
ThrowHelper.ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion();
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs
index 5f12322ea8..09fdc3b49e 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorAdapter.cs
@@ -44,7 +44,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (ArgumentOutOfRangeException ex)
{
- throw WindowsRuntimeMarshal.GetExceptionForHR(__HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
+ throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
}
}
@@ -90,7 +90,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (ArgumentOutOfRangeException ex)
{
- throw WindowsRuntimeMarshal.GetExceptionForHR(__HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
+ throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
}
}
@@ -110,7 +110,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (ArgumentOutOfRangeException ex)
{
// Change error code to match what WinRT expects
- ex.SetErrorCode(__HResults.E_BOUNDS);
+ ex.SetErrorCode(HResults.E_BOUNDS);
throw;
}
}
@@ -128,7 +128,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (ArgumentOutOfRangeException ex)
{
// Change error code to match what WinRT expects
- ex.SetErrorCode(__HResults.E_BOUNDS);
+ ex.SetErrorCode(HResults.E_BOUNDS);
throw;
}
}
@@ -147,7 +147,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (_this.Count == 0)
{
Exception e = new InvalidOperationException(SR.InvalidOperation_CannotRemoveLastFromEmptyCollection);
- e.SetErrorCode(__HResults.E_BOUNDS);
+ e.SetErrorCode(HResults.E_BOUNDS);
throw e;
}
@@ -171,7 +171,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
{
Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue);
- e.SetErrorCode(__HResults.E_BOUNDS);
+ e.SetErrorCode(HResults.E_BOUNDS);
throw e;
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs
index fc02bedfa6..75c9b9d086 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToBindableVectorViewAdapter.cs
@@ -39,7 +39,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
{
Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue);
- e.SetErrorCode(__HResults.E_BOUNDS);
+ e.SetErrorCode(HResults.E_BOUNDS);
throw e;
}
}
@@ -64,7 +64,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (ArgumentOutOfRangeException ex)
{
- throw WindowsRuntimeMarshal.GetExceptionForHR(__HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
+ throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs
index 87330e2559..03c48b546b 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/ListToVectorAdapter.cs
@@ -44,7 +44,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (ArgumentOutOfRangeException ex)
{
- throw WindowsRuntimeMarshal.GetExceptionForHR(__HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
+ throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
}
}
@@ -99,7 +99,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (ArgumentOutOfRangeException ex)
{
- throw WindowsRuntimeMarshal.GetExceptionForHR(__HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
+ throw WindowsRuntimeMarshal.GetExceptionForHR(HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange");
}
}
@@ -119,7 +119,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (ArgumentOutOfRangeException ex)
{
// Change error code to match what WinRT expects
- ex.SetErrorCode(__HResults.E_BOUNDS);
+ ex.SetErrorCode(HResults.E_BOUNDS);
throw;
}
}
@@ -137,7 +137,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
catch (ArgumentOutOfRangeException ex)
{
// Change error code to match what WinRT expects
- ex.SetErrorCode(__HResults.E_BOUNDS);
+ ex.SetErrorCode(HResults.E_BOUNDS);
throw;
}
}
@@ -156,7 +156,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (_this.Count == 0)
{
Exception e = new InvalidOperationException(SR.InvalidOperation_CannotRemoveLastFromEmptyCollection);
- e.SetErrorCode(__HResults.E_BOUNDS);
+ e.SetErrorCode(HResults.E_BOUNDS);
throw e;
}
@@ -202,7 +202,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity)
{
Exception e = new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_IndexLargerThanMaxValue);
- e.SetErrorCode(__HResults.E_BOUNDS);
+ e.SetErrorCode(HResults.E_BOUNDS);
throw e;
}
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs
index 224a266b07..13d1aeb8bc 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/MapToDictionaryAdapter.cs
@@ -113,7 +113,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex)
{
- if (__HResults.E_BOUNDS == ex._HResult)
+ if (HResults.E_BOUNDS == ex._HResult)
return false;
throw;
@@ -157,7 +157,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex)
{
- if (__HResults.E_BOUNDS == ex._HResult)
+ if (HResults.E_BOUNDS == ex._HResult)
throw new KeyNotFoundException(SR.Arg_KeyNotFound);
throw;
}
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs
index 56e62a25e7..90381f6be2 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/VectorToListAdapter.cs
@@ -102,7 +102,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex)
{
- if (__HResults.E_BOUNDS == ex._HResult)
+ if (HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
@@ -120,7 +120,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex)
{
- if (__HResults.E_BOUNDS == ex._HResult)
+ if (HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
@@ -138,7 +138,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex)
{
- if (__HResults.E_BOUNDS == ex._HResult)
+ if (HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
@@ -156,7 +156,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
}
catch (Exception ex)
{
- if (__HResults.E_BOUNDS == ex._HResult)
+ if (HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
diff --git a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs
index 6c87739b6b..1d07a022f4 100644
--- a/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs
+++ b/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/WindowsRuntimeMarshal.cs
@@ -826,7 +826,7 @@ namespace System.Runtime.InteropServices.WindowsRuntime
/// for more than a few instructions (in particular, we never call event APIs
/// or in fact any non-trivial API while holding the spin lock).
///
- /// Currently this ReaderWriterLock does not support recurision, however it is
+ /// Currently this ReaderWriterLock does not support recursion, however it is
/// not hard to add
/// </summary>
internal class MyReaderWriterLock
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/Vector128.cs b/src/mscorlib/src/System/Runtime/Intrinsics/Vector128.cs
new file mode 100644
index 0000000000..8e32f1a9dd
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/Vector128.cs
@@ -0,0 +1,11 @@
+// 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;
+
+namespace System.Runtime.Intrinsics
+{
+ [StructLayout(LayoutKind.Sequential, Size = 16)]
+ public struct Vector128<T> where T : struct {}
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/Vector256.cs b/src/mscorlib/src/System/Runtime/Intrinsics/Vector256.cs
new file mode 100644
index 0000000000..ba1e11d003
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/Vector256.cs
@@ -0,0 +1,11 @@
+// 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;
+
+namespace System.Runtime.Intrinsics
+{
+ [StructLayout(LayoutKind.Sequential, Size = 32)]
+ public struct Vector256<T> where T : struct {}
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Aes.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Aes.cs
new file mode 100644
index 0000000000..43aebc990c
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Aes.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.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel AES hardware instructions via intrinsics
+ /// </summary>
+ [CLSCompliant(false)]
+ public static class Aes
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// __m128i _mm_aesdec_si128 (__m128i a, __m128i RoundKey)
+ /// </summary>
+ public static Vector128<sbyte> Decrypt(Vector128<sbyte> value, Vector128<sbyte> roundKey) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_aesdec_si128 (__m128i a, __m128i RoundKey)
+ /// </summary>
+ public static Vector128<byte> Decrypt(Vector128<byte> value, Vector128<byte> roundKey) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_aesdeclast_si128 (__m128i a, __m128i RoundKey)
+ /// </summary>
+ public static Vector128<sbyte> DecryptLast(Vector128<sbyte> value, Vector128<sbyte> roundKey) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_aesdeclast_si128 (__m128i a, __m128i RoundKey)
+ /// </summary>
+ public static Vector128<byte> DecryptLast(Vector128<byte> value, Vector128<byte> roundKey) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_aesenc_si128 (__m128i a, __m128i RoundKey)
+ /// </summary>
+ public static Vector128<sbyte> Encrypt(Vector128<sbyte> value, Vector128<sbyte> roundKey) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_aesenc_si128 (__m128i a, __m128i RoundKey)
+ /// </summary>
+ public static Vector128<byte> Encrypt(Vector128<byte> value, Vector128<byte> roundKey) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_aesenclast_si128 (__m128i a, __m128i RoundKey)
+ /// </summary>
+ public static Vector128<sbyte> EncryptLast(Vector128<sbyte> value, Vector128<sbyte> roundKey) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_aesenclast_si128 (__m128i a, __m128i RoundKey)
+ /// </summary>
+ public static Vector128<byte> EncryptLast(Vector128<byte> value, Vector128<byte> roundKey) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_aesimc_si128 (__m128i a)
+ /// </summary>
+ public static Vector128<sbyte> InvisibleMixColumn(Vector128<sbyte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_aesimc_si128 (__m128i a)
+ /// </summary>
+ public static Vector128<byte> InvisibleMixColumn(Vector128<byte> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_aeskeygenassist_si128 (__m128i a, const int imm8)
+ /// </summary>
+ public static Vector128<sbyte> KeygenAssist(Vector128<sbyte> value, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_aeskeygenassist_si128 (__m128i a, const int imm8)
+ /// </summary>
+ public static Vector128<byte> KeygenAssist(Vector128<byte> value, byte control) { throw new NotImplementedException(); }
+
+ }
+
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Avx.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Avx.cs
new file mode 100644
index 0000000000..ad0bfc9e1b
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Avx.cs
@@ -0,0 +1,996 @@
+// 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.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel AVX hardware instructions via intrinsics
+ /// </summary>
+ [CLSCompliant(false)]
+ public static class Avx
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// __m256 _mm256_add_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> Add(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_add_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> Add(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_addsub_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> AddSubtract(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_addsub_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> AddSubtract(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_and_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> And(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_and_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> And(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_andnot_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> AndNot(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_andnot_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> AndNot(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_blend_ps (__m256 a, __m256 b, const int imm8)
+ /// </summary>
+ public static Vector256<float> Blend(Vector256<float> left, Vector256<float> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_blend_pd (__m256d a, __m256d b, const int imm8)
+ /// </summary>
+ public static Vector256<double> Blend(Vector256<double> left, Vector256<double> right, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_blendv_ps (__m256 a, __m256 b, __m256 mask)
+ /// </summary>
+ public static Vector256<float> BlendVariable(Vector256<float> left, Vector256<float> right, Vector256<float> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_blendv_pd (__m256d a, __m256d b, __m256d mask)
+ /// </summary>
+ public static Vector256<double> BlendVariable(Vector256<double> left, Vector256<double> right, Vector256<double> mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_broadcast_ss (float const * mem_addr)
+ /// </summary>
+ public static Vector128<float> BroadcastElementToVector128(ref float source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_broadcast_ss (float const * mem_addr)
+ /// </summary>
+ public static Vector256<float> BroadcastElementToVector256(ref float source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_broadcast_sd (double const * mem_addr)
+ /// </summary>
+ public static Vector256<double> BroadcastElementToVector256(ref double source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_broadcast_ps (__m128 const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<float> BroadcastVector128ToVector256(float* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_broadcast_pd (__m128d const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<double> BroadcastVector128ToVector256(double* address) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_ceil_ps (__m256 a)
+ /// </summary>
+ public static Vector256<float> Ceiling(Vector256<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_ceil_pd (__m256d a)
+ /// </summary>
+ public static Vector256<double> Ceiling(Vector256<double> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_cmp_ps (__m128 a, __m128 b, const int imm8)
+ /// </summary>
+ public static Vector128<float> Compare(Vector128<float> left, Vector128<float> right, FloatComparisonMode mode) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_cmp_pd (__m128d a, __m128d b, const int imm8)
+ /// </summary>
+ public static Vector128<double> Compare(Vector128<double> left, Vector128<double> right, FloatComparisonMode mode) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_cmp_ps (__m256 a, __m256 b, const int imm8)
+ /// </summary>
+ public static Vector256<float> Compare(Vector256<float> left, Vector256<float> right, FloatComparisonMode mode) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_cmp_pd (__m256d a, __m256d b, const int imm8)
+ /// </summary>
+ public static Vector256<double> Compare(Vector256<double> left, Vector256<double> right, FloatComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm256_cvtpd_epi32 (__m256d a)
+ /// </summary>
+ public static Vector128<int> ConvertToVector128Int(Vector256<double> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128 _mm256_cvtpd_ps (__m256d a)
+ /// </summary>
+ public static Vector128<float> ConvertToVector128Float(Vector256<double> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cvtps_epi32 (__m256 a)
+ /// </summary>
+ public static Vector256<int> ConvertToVector256Int(Vector256<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_cvtepi32_ps (__m256i a)
+ /// </summary>
+ public static Vector256<float> ConvertToVector256Float(Vector256<int> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_cvtps_pd (__m128 a)
+ /// </summary>
+ public static Vector256<double> ConvertToVector256Double(Vector256<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_cvtepi32_pd (__m128i a)
+ /// </summary>
+ public static Vector256<double> ConvertToVector256Double(Vector256<int> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm256_cvttpd_epi32 (__m256d a)
+ /// </summary>
+ public static Vector128<int> ConvertToVector128IntWithTruncation(Vector256<double> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cvttps_epi32 (__m256 a)
+ /// </summary>
+ public static Vector256<int> ConvertToVector256IntWithTruncation(Vector256<float> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_div_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> Divide(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_div_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> Divide(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_dp_ps (__m256 a, __m256 b, const int imm8)
+ /// </summary>
+ public static Vector256<float> DotProduct(Vector256<float> left, Vector256<float> right, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_moveldup_ps (__m256 a)
+ /// </summary>
+ public static Vector256<float> DuplicateEvenIndexed(Vector256<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_movedup_pd (__m256d a)
+ /// </summary>
+ public static Vector256<double> DuplicateEvenIndexed(Vector256<double> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_movehdup_ps (__m256 a)
+ /// </summary>
+ public static Vector256<float> DuplicateOddIndexed(Vector256<float> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __int8 _mm256_extract_epi8 (__m256i a, const int index)
+ /// </summary>
+ public static sbyte ExtractSbyte<T>(Vector256<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __int8 _mm256_extract_epi8 (__m256i a, const int index)
+ /// </summary>
+ public static byte ExtractByte<T>(Vector256<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __int16 _mm256_extract_epi16 (__m256i a, const int index)
+ /// </summary>
+ public static short ExtractShort<T>(Vector256<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __int16 _mm256_extract_epi16 (__m256i a, const int index)
+ /// </summary>
+ public static ushort ExtractUshort<T>(Vector256<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __int32 _mm256_extract_epi32 (__m256i a, const int index)
+ /// </summary>
+ public static int ExtractInt<T>(Vector256<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __int32 _mm256_extract_epi32 (__m256i a, const int index)
+ /// </summary>
+ public static uint ExtractUint<T>(Vector256<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __int64 _mm256_extract_epi64 (__m256i a, const int index)
+ /// </summary>
+ public static long ExtractLong<T>(Vector256<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __int64 _mm256_extract_epi64 (__m256i a, const int index)
+ /// </summary>
+ public static ulong ExtractUlong<T>(Vector256<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm256_extractf128_ps (__m256 a, const int imm8)
+ /// __m128d _mm256_extractf128_pd (__m256d a, const int imm8)
+ /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector128<T> ExtractVector128<T>(Vector256<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(byte* address, Vector256<byte> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(sbyte* address, Vector256<sbyte> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(short* address, Vector256<short> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(ushort* address, Vector256<ushort> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(int* address, Vector256<int> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(uint* address, Vector256<uint> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(long* address, Vector256<long> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_extractf128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(ulong* address, Vector256<ulong> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128 _mm256_extractf128_ps (__m256 a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(float* address, Vector256<float> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm256_extractf128_pd (__m256d a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(double* address, Vector256<double> value, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256d _mm256_castpd128_pd256 (__m128d a)
+ /// __m256 _mm256_castps128_ps256 (__m128 a)
+ /// __m256i _mm256_castsi128_si256 (__m128i a)
+ /// </summary>
+ public static Vector256<T> ExtendToVector256<T>(Vector128<T> value) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_floor_ps (__m256 a)
+ /// </summary>
+ public static Vector256<float> Floor(Vector256<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_floor_pd (__m256d a)
+ /// </summary>
+ public static Vector256<double> Floor(Vector256<double> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm256_castpd256_pd128 (__m256d a)
+ /// __m128 _mm256_castps256_ps128 (__m256 a)
+ /// __m128i _mm256_castsi256_si128 (__m256i a)
+ /// </summary>
+ public static Vector128<T> GetLowerHalf<T>(Vector256<T> value) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_hadd_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> HorizontalAdd(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_hadd_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> HorizontalAdd(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_hsub_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> HorizontalSubtract(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_hsub_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> HorizontalSubtract(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_insert_epi8 (__m256i a, __int8 i, const int index)
+ /// </summary>
+ public static Vector256<T> InsertSbyte<T>(Vector256<T> value, sbyte data, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_insert_epi8 (__m256i a, __int8 i, const int index)
+ /// </summary>
+ public static Vector256<T> InsertByte<T>(Vector256<T> value, byte data, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_insert_epi16 (__m256i a, __int16 i, const int index)
+ /// </summary>
+ public static Vector256<T> InsertShort<T>(Vector256<T> value, short data, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_insert_epi16 (__m256i a, __int16 i, const int index)
+ /// </summary>
+ public static Vector256<T> InsertUshort<T>(Vector256<T> value, ushort data, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_insert_epi32 (__m256i a, __int32 i, const int index)
+ /// </summary>
+ public static Vector256<T> InsertInt<T>(Vector256<T> value, int data, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_insert_epi32 (__m256i a, __int32 i, const int index)
+ /// </summary>
+ public static Vector256<T> InsertUint<T>(Vector256<T> value, uint data, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_insert_epi64 (__m256i a, __int64 i, const int index)
+ /// </summary>
+ public static Vector256<T> InsertLong<T>(Vector256<T> value, long data, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_insert_epi64 (__m256i a, __int64 i, const int index)
+ /// </summary>
+ public static Vector256<T> InsertUlong<T>(Vector256<T> value, ulong data, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_insertf128_ps (__m256 a, __m128 b, int imm8)
+ /// __m256d _mm256_insertf128_pd (__m256d a, __m128d b, int imm8)
+ /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8)
+ /// </summary>
+ public static Vector256<T> Insert<T>(Vector256<T> value, Vector128<T> data, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8)
+ /// </summary>
+ public static unsafe Vector256<sbyte> Insert(Vector256<sbyte> value, sbyte* address, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8)
+ /// </summary>
+ public static unsafe Vector256<byte> Insert(Vector256<byte> value, byte* address, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8)
+ /// </summary>
+ public static unsafe Vector256<short> Insert(Vector256<short> value, short* address, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8)
+ /// </summary>
+ public static unsafe Vector256<ushort> Insert(Vector256<ushort> value, ushort* address, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8)
+ /// </summary>
+ public static unsafe Vector256<int> Insert(Vector256<int> value, int* address, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8)
+ /// </summary>
+ public static unsafe Vector256<uint> Insert(Vector256<uint> value, uint* address, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8)
+ /// </summary>
+ public static unsafe Vector256<long> Insert(Vector256<long> value, long* address, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_insertf128_si256 (__m256i a, __m128i b, int imm8)
+ /// </summary>
+ public static unsafe Vector256<ulong> Insert(Vector256<ulong> value, ulong* address, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_insertf128_ps (__m256 a, __m128 b, int imm8)
+ /// </summary>
+ public static unsafe Vector256<float> Insert(Vector256<float> value, float* address, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_insertf128_pd (__m256d a, __m128d b, int imm8)
+ /// </summary>
+ public static unsafe Vector256<double> Insert(Vector256<double> value, double* address, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<sbyte> Load(sbyte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<byte> Load(byte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<short> Load(short* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<ushort> Load(ushort* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<int> Load(int* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<uint> Load(uint* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<long> Load(long* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_loadu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<ulong> Load(ulong* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_loadu_ps (float const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<float> Load(float* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_loadu_pd (double const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<double> Load(double* address) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_load_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<sbyte> LoadAligned(sbyte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_load_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<byte> LoadAligned(byte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_load_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<short> LoadAligned(short* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_load_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<ushort> LoadAligned(ushort* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_load_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<int> LoadAligned(int* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_load_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<uint> LoadAligned(uint* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_load_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<long> LoadAligned(long* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_load_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<ulong> LoadAligned(ulong* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_load_ps (float const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<float> LoadAligned(float* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_load_pd (double const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<double> LoadAligned(double* address) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<sbyte> LoadDqu(sbyte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<byte> LoadDqu(byte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<short> LoadDqu(short* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<ushort> LoadDqu(ushort* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<int> LoadDqu(int* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<uint> LoadDqu(uint* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<long> LoadDqu(long* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_lddqu_si256 (__m256i const * mem_addr)
+ /// </summary>
+ public static unsafe Vector256<ulong> LoadDqu(ulong* address) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_maskload_pd (double const * mem_addr, __m128i mask)
+ /// </summary>
+ public static unsafe Vector128<float> MaskLoad(float* address, Vector128<uint> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_maskload_pd (double const * mem_addr, __m128i mask)
+ /// </summary>
+ public static unsafe Vector128<double> MaskLoad(double* address, Vector128<ulong> mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_maskload_ps (float const * mem_addr, __m256i mask)
+ /// </summary>
+ public static unsafe Vector256<float> MaskLoad(float* address, Vector256<uint> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_maskload_pd (double const * mem_addr, __m256i mask)
+ /// </summary>
+ public static unsafe Vector256<double> MaskLoad(double* address, Vector256<ulong> mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm_maskstore_ps (float * mem_addr, __m128i mask, __m128 a)
+ /// </summary>
+ public static unsafe void MaskStore(float* address, Vector128<float> mask, Vector128<uint> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_maskstore_pd (double * mem_addr, __m128i mask, __m128d a)
+ /// </summary>
+ public static unsafe void MaskStore(double* address, Vector128<double> mask, Vector128<ulong> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm256_maskstore_ps (float * mem_addr, __m256i mask, __m256 a)
+ /// </summary>
+ public static unsafe void MaskStore(float* address, Vector256<float> mask, Vector256<uint> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_maskstore_pd (double * mem_addr, __m256i mask, __m256d a)
+ /// </summary>
+ public static unsafe void MaskStore(double* address, Vector256<double> mask, Vector256<ulong> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_max_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> Max(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_max_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> Max(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_min_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> Min(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_min_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> Min(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm256_movemask_ps (__m256 a)
+ /// </summary>
+ public static int MoveMask(Vector256<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// int _mm256_movemask_pd (__m256d a)
+ /// </summary>
+ public static int MoveMask(Vector256<double> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_mul_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> Multiply(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_mul_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> Multiply(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_or_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> Or(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_or_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> Or(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_permute_ps (__m128 a, int imm8)
+ /// </summary>
+ public static Vector128<float> Permute(Vector128<float> value, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_permute_pd (__m128d a, int imm8)
+ /// </summary>
+ public static Vector128<double> Permute(Vector128<double> value, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_permute_ps (__m256 a, int imm8)
+ /// </summary>
+ public static Vector256<float> Permute(Vector256<float> value, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_permute_pd (__m256d a, int imm8)
+ /// </summary>
+ public static Vector256<double> Permute(Vector256<double> value, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_permute2f128_ps (__m256 a, __m256 b, int imm8)
+ /// </summary>
+ public static Vector256<float> Permute2x128(Vector256<float> left, Vector256<float> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_permute2f128_pd (__m256d a, __m256d b, int imm8)
+ /// </summary>
+ public static Vector256<double> Permute2x128(Vector256<double> left, Vector256<double> right, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_permutevar_ps (__m128 a, __m128i b)
+ /// </summary>
+ public static Vector128<float> PermuteVar(Vector128<float> left, Vector128<float> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_permutevar_pd (__m128d a, __m128i b)
+ /// </summary>
+ public static Vector128<double> PermuteVar(Vector128<double> left, Vector128<double> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_permutevar_ps (__m256 a, __m256i b)
+ /// </summary>
+ public static Vector256<float> PermuteVar(Vector256<float> left, Vector256<float> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_permutevar_pd (__m256d a, __m256i b)
+ /// </summary>
+ public static Vector256<double> PermuteVar(Vector256<double> left, Vector256<double> mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_rcp_ps (__m256 a)
+ /// </summary>
+ public static Vector256<float> Reciprocal(Vector256<float> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_rsqrt_ps (__m256 a)
+ /// </summary>
+ public static Vector256<float> ReciprocalSqrt(Vector256<float> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_round_ps (__m256 a, int rounding)
+ /// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector256<float> RoundToNearestInteger(Vector256<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector256<float> RoundToNegativeInfinity(Vector256<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector256<float> RoundToPositiveInfinity(Vector256<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector256<float> RoundToZero(Vector256<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_CUR_DIRECTION
+ /// </summary>
+ public static Vector256<float> RoundCurrentDirection(Vector256<float> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256d _mm256_round_pd (__m256d a, int rounding)
+ /// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector256<double> RoundToNearestInteger(Vector256<double> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector256<double> RoundToNegativeInfinity(Vector256<double> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector256<double> RoundToPositiveInfinity(Vector256<double> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector256<double> RoundToZero(Vector256<double> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_CUR_DIRECTION
+ /// </summary>
+ public static Vector256<double> RoundCurrentDirection(Vector256<double> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_set_epi8 (char e31, char e30, char e29, char e28, char e27, char e26, char e25, char e24, char e23, char e22, char e21, char e20, char e19, char e18, char e17, char e16, char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0)
+ /// </summary>
+ public static Vector256<sbyte> Set(sbyte e31, sbyte e30, sbyte e29, sbyte e28, sbyte e27, sbyte e26, sbyte e25, sbyte e24, sbyte e23, sbyte e22, sbyte e21, sbyte e20, sbyte e19, sbyte e18, sbyte e17, sbyte e16, sbyte e15, sbyte e14, sbyte e13, sbyte e12, sbyte e11, sbyte e10, sbyte e9, sbyte e8, sbyte e7, sbyte e6, sbyte e5, sbyte e4, sbyte e3, sbyte e2, sbyte e1, sbyte e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_set_epi8 (char e31, char e30, char e29, char e28, char e27, char e26, char e25, char e24, char e23, char e22, char e21, char e20, char e19, char e18, char e17, char e16, char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0)
+ /// </summary>
+ public static Vector256<byte> Set(byte e31, byte e30, byte e29, byte e28, byte e27, byte e26, byte e25, byte e24, byte e23, byte e22, byte e21, byte e20, byte e19, byte e18, byte e17, byte e16, byte e15, byte e14, byte e13, byte e12, byte e11, byte e10, byte e9, byte e8, byte e7, byte e6, byte e5, byte e4, byte e3, byte e2, byte e1, byte e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_set_epi16 (short e15, short e14, short e13, short e12, short e11, short e10, short e9, short e8, short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0)
+ /// </summary>
+ public static Vector256<short> Set(short e15, short e14, short e13, short e12, short e11, short e10, short e9, short e8, short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_set_epi16 (short e15, short e14, short e13, short e12, short e11, short e10, short e9, short e8, short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0)
+ /// </summary>
+ public static Vector256<ushort> Set(ushort e15, ushort e14, ushort e13, ushort e12, ushort e11, ushort e10, ushort e9, ushort e8, ushort e7, ushort e6, ushort e5, ushort e4, ushort e3, ushort e2, ushort e1, ushort e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_set_epi32 (int e7, int e6, int e5, int e4, int e3, int e2, int e1, int e0)
+ /// </summary>
+ public static Vector256<int> Set(int e7, int e6, int e5, int e4, int e3, int e2, int e1, int e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_set_epi32 (int e7, int e6, int e5, int e4, int e3, int e2, int e1, int e0)
+ /// </summary>
+ public static Vector256<uint> Set(uint e7, uint e6, uint e5, uint e4, uint e3, uint e2, uint e1, uint e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_set_epi64x (__int64 e3, __int64 e2, __int64 e1, __int64 e0)
+ /// </summary>
+ public static Vector256<long> Set(long e3, long e2, long e1, long e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_set_epi64x (__int64 e3, __int64 e2, __int64 e1, __int64 e0)
+ /// </summary>
+ public static Vector256<ulong> Set(ulong e3, ulong e2, ulong e1, ulong e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_set_ps (float e7, float e6, float e5, float e4, float e3, float e2, float e1, float e0)
+ /// </summary>
+ public static Vector256<float> Set(float e7, float e6, float e5, float e4, float e3, float e2, float e1, float e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_set_pd (double e3, double e2, double e1, double e0)
+ /// </summary>
+ public static Vector256<double> Set(double e3, double e2, double e1, double e0) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_set1_epi8 (char a)
+ /// __m256i _mm256_set1_epi16 (short a)
+ /// __m256i _mm256_set1_epi32 (int a)
+ /// __m256i _mm256_set1_epi64x (long long a)
+ /// __m256 _mm256_set1_ps (float a)
+ /// __m256d _mm256_set1_pd (double a)
+ /// </summary>
+ public static Vector256<T> Set1<T>(T value) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_set_m128 (__m128 hi, __m128 lo)
+ /// __m256d _mm256_set_m128d (__m128d hi, __m128d lo)
+ /// __m256i _mm256_set_m128i (__m128i hi, __m128i lo)
+ /// </summary>
+ public static Vector256<T> SetHiLo<T>(Vector128<T> hi, Vector128<T> lo) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_setzero_si256 (void)
+ /// __m256 _mm256_setzero_ps (void)
+ /// __m256d _mm256_setzero_pd (void)
+ /// </summary>
+ public static Vector256<T> SetZero<T>() where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_shuffle_ps (__m256 a, __m256 b, const int imm8)
+ /// </summary>
+ public static Vector256<float> Shuffle(Vector256<float> value, Vector256<float> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_shuffle_pd (__m256d a, __m256d b, const int imm8)
+ /// </summary>
+ public static Vector256<double> Shuffle(Vector256<double> value, Vector256<double> right, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_sqrt_ps (__m256 a)
+ /// </summary>
+ public static Vector256<float> Sqrt(Vector256<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_sqrt_pd (__m256d a)
+ /// </summary>
+ public static Vector256<double> Sqrt(Vector256<double> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_castpd_ps (__m256d a)
+ /// __m256i _mm256_castpd_si256 (__m256d a)
+ /// __m256d _mm256_castps_pd (__m256 a)
+ /// __m256i _mm256_castps_si256 (__m256 a)
+ /// __m256d _mm256_castsi256_pd (__m256i a)
+ /// __m256 _mm256_castsi256_ps (__m256i a)
+ /// </summary>
+ public static Vector256<U> StaticCast<T, U>(Vector256<T> value) where T : struct where U : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAligned(sbyte* address, Vector256<sbyte> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAligned(byte* address, Vector256<byte> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAligned(short* address, Vector256<short> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAligned(ushort* address, Vector256<ushort> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAligned(int* address, Vector256<int> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAligned(uint* address, Vector256<uint> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAligned(long* address, Vector256<long> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_store_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAligned(ulong* address, Vector256<ulong> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_store_ps (float * mem_addr, __m256 a)
+ /// </summary>
+ public static unsafe void StoreAligned(float* address, Vector256<float> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_store_pd (double * mem_addr, __m256d a)
+ /// </summary>
+ public static unsafe void StoreAligned(double* address, Vector256<double> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(sbyte* address, Vector256<sbyte> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(byte* address, Vector256<byte> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(short* address, Vector256<short> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(ushort* address, Vector256<ushort> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(int* address, Vector256<int> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(uint* address, Vector256<uint> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(long* address, Vector256<long> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_stream_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(ulong* address, Vector256<ulong> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_stream_ps (float * mem_addr, __m256 a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(float* address, Vector256<float> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_stream_pd (double * mem_addr, __m256d a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(double* address, Vector256<double> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void Store(sbyte* address, Vector256<sbyte> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void Store(byte* address, Vector256<byte> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void Store(short* address, Vector256<short> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void Store(ushort* address, Vector256<ushort> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void Store(int* address, Vector256<int> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void Store(uint* address, Vector256<uint> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void Store(long* address, Vector256<long> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_storeu_si256 (__m256i * mem_addr, __m256i a)
+ /// </summary>
+ public static unsafe void Store(ulong* address, Vector256<ulong> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_storeu_ps (float * mem_addr, __m256 a)
+ /// </summary>
+ public static unsafe void Store(float* address, Vector256<float> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_storeu_pd (double * mem_addr, __m256d a)
+ /// </summary>
+ public static unsafe void Store(double* address, Vector256<double> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_sub_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> Subtract(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_sub_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> Subtract(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_testc_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static bool TestC(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// int _mm_testc_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static bool TestC(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm256_testc_si256 (__m256i a, __m256i b)
+ /// int _mm256_testc_ps (__m256 a, __m256 b)
+ /// int _mm256_testc_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static bool TestC<T>(Vector256<T> left, Vector256<T> right) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_testnzc_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static bool TestNotZAndNotC(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// int _mm_testnzc_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static bool TestNotZAndNotC(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm256_testnzc_si256 (__m256i a, __m256i b)
+ /// int _mm256_testnzc_ps (__m256 a, __m256 b)
+ /// int _mm256_testnzc_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static bool TestNotZAndNotC<T>(Vector256<T> left, Vector256<T> right) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_testz_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static bool TestZ(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// int _mm_testz_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static bool TestZ(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm256_testz_si256 (__m256i a, __m256i b)
+ /// int _mm256_testz_ps (__m256 a, __m256 b)
+ /// int _mm256_testz_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static bool TestZ<T>(Vector256<T> left, Vector256<T> right) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_unpackhi_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> UnpackHigh(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_unpackhi_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> UnpackHigh(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_unpacklo_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> UnpackLow(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_unpacklo_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> UnpackLow(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256 _mm256_xor_ps (__m256 a, __m256 b)
+ /// </summary>
+ public static Vector256<float> Xor(Vector256<float> left, Vector256<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_xor_pd (__m256d a, __m256d b)
+ /// </summary>
+ public static Vector256<double> Xor(Vector256<double> left, Vector256<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm256_zeroall (void)
+ /// </summary>
+ public static void ZeroAll() { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_zeroupper (void)
+ /// </summary>
+ public static void ZeroUpper() { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256d _mm256_zextpd128_pd256 (__m128d a)
+ /// __m256 _mm256_zextps128_ps256 (__m128 a)
+ /// __m256i _mm256_zextsi128_si256 (__m128i a)
+ /// </summary>
+ public static Vector256<T> ZeroExtendToVector256<T>(Vector128<T> value) where T : struct { throw new NotImplementedException(); }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Avx2.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Avx2.cs
new file mode 100644
index 0000000000..cd652c26e2
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Avx2.cs
@@ -0,0 +1,1362 @@
+// 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.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel AVX2 hardware instructions via intrinsics
+ /// </summary>
+ [CLSCompliant(false)]
+ public static class Avx2
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// __m256i _mm256_abs_epi8 (__m256i a)
+ /// </summary>
+ public static Vector256<byte> Abs(Vector256<sbyte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_abs_epi16 (__m256i a)
+ /// </summary>
+ public static Vector256<ushort> Abs(Vector256<short> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_abs_epi32 (__m256i a)
+ /// </summary>
+ public static Vector256<uint> Abs(Vector256<int> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_add_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> Add(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_add_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> Add(Vector256<byte> left, Vector256<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_add_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> Add(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_add_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> Add(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_add_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> Add(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_add_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<uint> Add(Vector256<uint> left, Vector256<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_add_epi64 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<long> Add(Vector256<long> left, Vector256<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_add_epi64 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ulong> Add(Vector256<ulong> left, Vector256<ulong> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_adds_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> AddSaturate(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_adds_epu8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> AddSaturate(Vector256<byte> left, Vector256<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_adds_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> AddSaturate(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_adds_epu16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> AddSaturate(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_alignr_epi8 (__m256i a, __m256i b, const int count)
+ /// </summary>
+ public static Vector256<sbyte> AlignRight(Vector256<sbyte> left, Vector256<sbyte> right, byte mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_and_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> And(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_and_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> And(Vector256<byte> left, Vector256<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_and_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> And(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_and_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> And(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_and_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> And(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_and_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<uint> And(Vector256<uint> left, Vector256<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_and_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<long> And(Vector256<long> left, Vector256<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_and_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ulong> And(Vector256<ulong> left, Vector256<ulong> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_andnot_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> AndNot(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_andnot_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> AndNot(Vector256<byte> left, Vector256<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_andnot_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> AndNot(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_andnot_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> AndNot(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_andnot_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> AndNot(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_andnot_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<uint> AndNot(Vector256<uint> left, Vector256<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_andnot_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<long> AndNot(Vector256<long> left, Vector256<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_andnot_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ulong> AndNot(Vector256<ulong> left, Vector256<ulong> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_avg_epu8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> Average(Vector256<byte> left, Vector256<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_avg_epu16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> Average(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_blend_epi32 (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<int> Blend(Vector128<int> left, Vector128<int> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_blend_epi32 (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<uint> Blend(Vector128<uint> left, Vector128<uint> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_blend_epi16 (__m256i a, __m256i b, const int imm8)
+ /// </summary>
+ public static Vector256<short> Blend(Vector256<short> left, Vector256<short> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_blend_epi16 (__m256i a, __m256i b, const int imm8)
+ /// </summary>
+ public static Vector256<ushort> Blend(Vector256<ushort> left, Vector256<ushort> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_blend_epi32 (__m256i a, __m256i b, const int imm8)
+ /// </summary>
+ public static Vector256<int> Blend(Vector256<int> left, Vector256<int> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_blend_epi32 (__m256i a, __m256i b, const int imm8)
+ /// </summary>
+ public static Vector256<uint> Blend(Vector256<uint> left, Vector256<uint> right, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_blendv_epi8 (__m256i a, __m256i b, __m256i mask)
+ /// </summary>
+ public static Vector256<sbyte> BlendVariable(Vector256<sbyte> left, Vector256<sbyte> right, Vector256<sbyte> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_blendv_epi8 (__m256i a, __m256i b, __m256i mask)
+ /// </summary>
+ public static Vector256<byte> BlendVariable(Vector256<byte> left, Vector256<byte> right, Vector256<byte> mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_broadcastb_epi8 (__m128i a)
+ /// __m128i _mm_broadcastw_epi16 (__m128i a)
+ /// __m128i _mm_broadcastd_epi32 (__m128i a)
+ /// __m128i _mm_broadcastq_epi64 (__m128i a)
+ /// __m128 _mm_broadcastss_ps (__m128 a)
+ /// __m128d _mm_broadcastsd_pd (__m128d a)
+ /// </summary>
+ public static Vector128<T> BroadcastElementToVector128<T>(Vector128<T> value) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_broadcastb_epi8 (__m128i a)
+ /// __m256i _mm256_broadcastw_epi16 (__m128i a)
+ /// __m256i _mm256_broadcastd_epi32 (__m128i a)
+ /// __m256i _mm256_broadcastq_epi64 (__m128i a)
+ /// __m256 _mm256_broadcastss_ps (__m128 a)
+ /// __m256d _mm256_broadcastsd_pd (__m128d a)
+ /// </summary>
+ public static Vector256<T> BroadcastElementToVector256<T>(Vector128<T> value) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_broadcastsi128_si256 (__m128i a)
+ /// </summary>
+ public static unsafe Vector256<sbyte> BroadcastVector128ToVector256(sbyte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_broadcastsi128_si256 (__m128i a)
+ /// </summary>
+ public static unsafe Vector256<byte> BroadcastVector128ToVector256(byte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_broadcastsi128_si256 (__m128i a)
+ /// </summary>
+ public static unsafe Vector256<short> BroadcastVector128ToVector256(short* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_broadcastsi128_si256 (__m128i a)
+ /// </summary>
+ public static unsafe Vector256<ushort> BroadcastVector128ToVector256(ushort* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_broadcastsi128_si256 (__m128i a)
+ /// </summary>
+ public static unsafe Vector256<int> BroadcastVector128ToVector256(int* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_broadcastsi128_si256 (__m128i a)
+ /// </summary>
+ public static unsafe Vector256<uint> BroadcastVector128ToVector256(uint* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_broadcastsi128_si256 (__m128i a)
+ /// </summary>
+ public static unsafe Vector256<long> BroadcastVector128ToVector256(long* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_broadcastsi128_si256 (__m128i a)
+ /// </summary>
+ public static unsafe Vector256<ulong> BroadcastVector128ToVector256(ulong* address) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_cmpeq_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> CompareEqual(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cmpeq_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> CompareEqual(Vector256<byte> left, Vector256<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cmpeq_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> CompareEqual(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cmpeq_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> CompareEqual(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cmpeq_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> CompareEqual(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cmpeq_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<uint> CompareEqual(Vector256<uint> left, Vector256<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cmpeq_epi64 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<long> CompareEqual(Vector256<long> left, Vector256<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cmpeq_epi64 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ulong> CompareEqual(Vector256<ulong> left, Vector256<ulong> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_cmpgt_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> CompareGreaterThan(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cmpgt_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> CompareGreaterThan(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cmpgt_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> CompareGreaterThan(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cmpgt_epi64 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<long> CompareGreaterThan(Vector256<long> left, Vector256<long> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_cvtepi8_epi16 (__m128i a)
+ /// </summary>
+ public static Vector256<short> ConvertToVector256Short(Vector128<sbyte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cvtepu8_epi16 (__m128i a)
+ /// </summary>
+ public static Vector256<ushort> ConvertToVector256UShort(Vector128<byte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cvtepi8_epi32 (__m128i a)
+ /// </summary>
+ public static Vector256<int> ConvertToVector256Int(Vector128<sbyte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cvtepi16_epi32 (__m128i a)
+ /// </summary>
+ public static Vector256<int> ConvertToVector256Int(Vector128<short> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cvtepu8_epi32 (__m128i a)
+ /// </summary>
+ public static Vector256<uint> ConvertToVector256UInt(Vector128<byte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cvtepu16_epi32 (__m128i a)
+ /// </summary>
+ public static Vector256<uint> ConvertToVector256UInt(Vector128<ushort> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cvtepi8_epi64 (__m128i a)
+ /// </summary>
+ public static Vector256<long> ConvertToVector256Long(Vector128<sbyte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cvtepi16_epi64 (__m128i a)
+ /// </summary>
+ public static Vector256<long> ConvertToVector256Long(Vector128<short> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cvtepi32_epi64 (__m128i a)
+ /// </summary>
+ public static Vector256<long> ConvertToVector256Long(Vector128<int> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cvtepu8_epi64 (__m128i a)
+ /// </summary>
+ public static Vector256<ulong> ConvertToVector256ULong(Vector128<byte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cvtepu16_epi64 (__m128i a)
+ /// </summary>
+ public static Vector256<ulong> ConvertToVector256ULong(Vector128<ushort> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_cvtepu32_epi64 (__m128i a)
+ /// </summary>
+ public static Vector256<ulong> ConvertToVector256ULong(Vector128<uint> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector128<sbyte> ExtractVector128(Vector256<sbyte> value, byte index) { throw new NotImplementedException(); }
+ // <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(sbyte* address, Vector256<sbyte> value, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector128<byte> ExtractVector128(Vector256<byte> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(byte* address, Vector256<byte> value, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector128<short> ExtractVector128(Vector256<short> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(short* address, Vector256<short> value, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector128<ushort> ExtractVector128(Vector256<ushort> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(ushort* address, Vector256<ushort> value, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector128<int> ExtractVector128(Vector256<int> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(int* address, Vector256<int> value, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector128<uint> ExtractVector128(Vector256<uint> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(uint* address, Vector256<uint> value, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector128<long> ExtractVector128(Vector256<long> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(long* address, Vector256<long> value, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector128<ulong> ExtractVector128(Vector256<ulong> value, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_extracti128_si256 (__m256i a, const int imm8)
+ /// </summary>
+ public static unsafe void ExtractVector128(ulong* address, Vector256<ulong> value, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_i32gather_epi32 (int const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<int> GatherVector128(int* baseAddress, Vector128<int> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_i32gather_epi32 (int const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<uint> GatherVector128(uint* baseAddress, Vector128<int> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_i32gather_epi64 (__int64 const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<long> GatherVector128(long* baseAddress, Vector128<int> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_i32gather_epi64 (__int64 const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<ulong> GatherVector128(ulong* baseAddress, Vector128<int> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128 _mm_i32gather_ps (float const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<float> GatherVector128(float* baseAddress, Vector128<int> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_i32gather_pd (double const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<double> GatherVector128(double* baseAddress, Vector128<int> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_i64gather_epi32 (int const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<int> GatherVector128(int* baseAddress, Vector128<long> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_i64gather_epi32 (int const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<uint> GatherVector128(uint* baseAddress, Vector128<long> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_i64gather_epi64 (__int64 const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<long> GatherVector128(long* baseAddress, Vector128<long> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_i64gather_epi64 (__int64 const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<ulong> GatherVector128(ulong* baseAddress, Vector128<long> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128 _mm_i64gather_ps (float const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<float> GatherVector128(float* baseAddress, Vector128<long> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_i64gather_pd (double const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<double> GatherVector128(double* baseAddress, Vector128<long> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_i32gather_epi32 (int const* base_addr, __m256i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector256<int> GatherVector256(int* baseAddress, Vector256<int> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_i32gather_epi32 (int const* base_addr, __m256i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector256<uint> GatherVector256(uint* baseAddress, Vector256<int> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_i32gather_epi64 (__int64 const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector256<long> GatherVector256(long* baseAddress, Vector128<int> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_i32gather_epi64 (__int64 const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector256<ulong> GatherVector256(ulong* baseAddress, Vector128<int> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_i32gather_ps (float const* base_addr, __m256i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector256<float> GatherVector256(float* baseAddress, Vector256<int> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_i32gather_pd (double const* base_addr, __m128i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector256<double> GatherVector256(double* baseAddress, Vector128<int> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_i64gather_epi32 (int const* base_addr, __m256i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<int> GatherVector128(int* baseAddress, Vector256<long> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_i64gather_epi32 (int const* base_addr, __m256i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<uint> GatherVector128(uint* baseAddress, Vector256<long> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_i64gather_epi64 (__int64 const* base_addr, __m256i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector256<long> GatherVector256(long* baseAddress, Vector256<long> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_i64gather_epi64 (__int64 const* base_addr, __m256i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector256<ulong> GatherVector256(ulong* baseAddress, Vector256<long> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128 _mm256_i64gather_ps (float const* base_addr, __m256i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector128<float> GatherVector128(float* baseAddress, Vector256<long> index, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_i64gather_pd (double const* base_addr, __m256i vindex, const int scale)
+ /// </summary>
+ public static unsafe Vector256<double> GatherVector256(double* baseAddress, Vector256<long> index, byte scale) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_mask_i32gather_epi32 (__m128i src, int const* base_addr, __m128i vindex, __m128i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<int> GatherMaskVector128(Vector128<int> source, int* baseAddress, Vector128<int> index, Vector128<int> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_mask_i32gather_epi32 (__m128i src, int const* base_addr, __m128i vindex, __m128i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<uint> GatherMaskVector128(Vector128<uint> source, uint* baseAddress, Vector128<int> index, Vector128<uint> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_mask_i32gather_epi64 (__m128i src, __int64 const* base_addr, __m128i vindex, __m128i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<long> GatherMaskVector128(Vector128<long> source, long* baseAddress, Vector128<int> index, Vector128<long> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_mask_i32gather_epi64 (__m128i src, __int64 const* base_addr, __m128i vindex, __m128i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<ulong> GatherMaskVector128(Vector128<ulong> source, ulong* baseAddress, Vector128<int> index, Vector128<ulong> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128 _mm_mask_i32gather_ps (__m128 src, float const* base_addr, __m128i vindex, __m128 mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<float> GatherMaskVector128(Vector128<float> source, float* baseAddress, Vector128<int> index, Vector128<float> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_mask_i32gather_pd (__m128d src, double const* base_addr, __m128i vindex, __m128d mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<double> GatherMaskVector128(Vector128<double> source, double* baseAddress, Vector128<int> index, Vector128<double> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_mask_i64gather_epi32 (__m128i src, int const* base_addr, __m128i vindex, __m128i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<int> GatherMaskVector128(Vector128<int> source, int* baseAddress, Vector128<long> index, Vector128<int> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_mask_i64gather_epi32 (__m128i src, int const* base_addr, __m128i vindex, __m128i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<uint> GatherMaskVector128(Vector128<uint> source, uint* baseAddress, Vector128<long> index, Vector128<uint> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_mask_i64gather_epi64 (__m128i src, __int64 const* base_addr, __m128i vindex, __m128i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<long> GatherMaskVector128(Vector128<long> source, long* baseAddress, Vector128<long> index, Vector128<long> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_mask_i64gather_epi64 (__m128i src, __int64 const* base_addr, __m128i vindex, __m128i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<ulong> GatherMaskVector128(Vector128<ulong> source, ulong* baseAddress, Vector128<long> index, Vector128<ulong> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128 _mm_mask_i64gather_ps (__m128 src, float const* base_addr, __m128i vindex, __m128 mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<float> GatherMaskVector128(Vector128<float> source, float* baseAddress, Vector128<long> index, Vector128<float> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_mask_i64gather_pd (__m128d src, double const* base_addr, __m128i vindex, __m128d mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<double> GatherMaskVector128(Vector128<double> source, double* baseAddress, Vector128<long> index, Vector128<double> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_mask_i32gather_epi32 (__m256i src, int const* base_addr, __m256i vindex, __m256i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector256<int> GatherMaskVector256(Vector256<int> source, int* baseAddress, Vector256<int> index, Vector256<int> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_mask_i32gather_epi32 (__m256i src, int const* base_addr, __m256i vindex, __m256i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector256<uint> GatherMaskVector256(Vector256<uint> source, uint* baseAddress, Vector256<int> index, Vector256<uint> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_mask_i32gather_epi64 (__m256i src, __int64 const* base_addr, __m128i vindex, __m256i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector256<long> GatherMaskVector256(Vector256<long> source, long* baseAddress, Vector128<int> index, Vector256<long> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_mask_i32gather_epi64 (__m256i src, __int64 const* base_addr, __m128i vindex, __m256i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector256<ulong> GatherMaskVector256(Vector256<ulong> source, ulong* baseAddress, Vector128<int> index, Vector256<ulong> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_mask_i32gather_ps (__m256 src, float const* base_addr, __m256i vindex, __m256 mask, const int scale)
+ /// </summary>
+ public static unsafe Vector256<float> GatherMaskVector256(Vector256<float> source, float* baseAddress, Vector256<int> index, Vector256<float> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_mask_i32gather_pd (__m256d src, double const* base_addr, __m128i vindex, __m256d mask, const int scale)
+ /// </summary>
+ public static unsafe Vector256<double> GatherMaskVector256(Vector256<double> source, double* baseAddress, Vector128<int> index, Vector256<double> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_mask_i64gather_epi32 (__m128i src, int const* base_addr, __m256i vindex, __m128i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<int> GatherMaskVector128(Vector128<int> source, int* baseAddress, Vector256<long> index, Vector128<int> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm256_mask_i64gather_epi32 (__m128i src, int const* base_addr, __m256i vindex, __m128i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<uint> GatherMaskVector128(Vector128<uint> source, uint* baseAddress, Vector256<long> index, Vector128<uint> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_mask_i64gather_epi64 (__m256i src, __int64 const* base_addr, __m256i vindex, __m256i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector256<long> GatherMaskVector256(Vector256<long> source, long* baseAddress, Vector256<long> index, Vector256<long> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_mask_i64gather_epi64 (__m256i src, __int64 const* base_addr, __m256i vindex, __m256i mask, const int scale)
+ /// </summary>
+ public static unsafe Vector256<ulong> GatherMaskVector256(Vector256<ulong> source, ulong* baseAddress, Vector256<long> index, Vector256<ulong> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128 _mm256_mask_i64gather_ps (__m128 src, float const* base_addr, __m256i vindex, __m128 mask, const int scale)
+ /// </summary>
+ public static unsafe Vector128<float> GatherMaskVector128(Vector128<float> source, float* baseAddress, Vector256<long> index, Vector128<float> mask, byte scale) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_mask_i64gather_pd (__m256d src, double const* base_addr, __m256i vindex, __m256d mask, const int scale)
+ /// </summary>
+ public static unsafe Vector256<double> GatherMaskVector256(Vector256<double> source, double* baseAddress, Vector256<long> index, Vector256<double> mask, byte scale) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_hadd_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> HorizontalAdd(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_hadd_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> HorizontalAdd(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_hadds_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> HorizontalAddSaturate(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_hsub_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> HorizontalSubtract(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_hsub_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> HorizontalSubtract(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_hsubs_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> HorizontalSubtractSaturate(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector256<sbyte> Insert(Vector256<sbyte> value, Vector128<sbyte> data, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static unsafe Vector256<sbyte> Insert(Vector256<sbyte> value, sbyte* address, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector256<byte> Insert(Vector256<byte> value, Vector128<byte> data, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static unsafe Vector256<byte> Insert(Vector256<byte> value, byte* address, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector256<short> Insert(Vector256<short> value, Vector128<short> data, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static unsafe Vector256<short> Insert(Vector256<short> value, short* address, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector256<ushort> Insert(Vector256<ushort> value, Vector128<ushort> data, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static unsafe Vector256<ushort> Insert(Vector256<ushort> value, ushort* address, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector256<int> Insert(Vector256<int> value, Vector128<int> data, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static unsafe Vector256<int> Insert(Vector256<int> value, int* address, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector256<uint> Insert(Vector256<uint> value, Vector128<uint> data, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static unsafe Vector256<uint> Insert(Vector256<uint> value, uint* address, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector256<long> Insert(Vector256<long> value, Vector128<long> data, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static unsafe Vector256<long> Insert(Vector256<long> value, long* address, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector256<ulong> Insert(Vector256<ulong> value, Vector128<ulong> data, byte index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_inserti128_si256 (__m256i a, __m128i b, const int imm8)
+ /// </summary>
+ public static unsafe Vector256<ulong> Insert(Vector256<ulong> value, ulong* address, byte index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_maskload_epi32 (int const* mem_addr, __m128i mask)
+ /// </summary>
+ public static unsafe Vector128<int> MaskLoad(int* address, Vector128<int> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_maskload_epi32 (int const* mem_addr, __m128i mask)
+ /// </summary>
+ public static unsafe Vector128<uint> MaskLoad(uint* address, Vector128<uint> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_maskload_epi64 (__int64 const* mem_addr, __m128i mask)
+ /// </summary>
+ public static unsafe Vector128<long> MaskLoad(long* address, Vector128<long> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_maskload_epi64 (__int64 const* mem_addr, __m128i mask)
+ /// </summary>
+ public static unsafe Vector128<ulong> MaskLoad(ulong* address, Vector128<ulong> mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_maskload_epi32 (int const* mem_addr, __m256i mask)
+ /// </summary>
+ public static unsafe Vector256<int> MaskLoad(int* address, Vector256<int> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_maskload_epi32 (int const* mem_addr, __m256i mask)
+ /// </summary>
+ public static unsafe Vector256<uint> MaskLoad(uint* address, Vector256<uint> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_maskload_epi64 (__int64 const* mem_addr, __m256i mask)
+ /// </summary>
+ public static unsafe Vector256<long> MaskLoad(long* address, Vector256<long> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_maskload_epi64 (__int64 const* mem_addr, __m256i mask)
+ /// </summary>
+ public static unsafe Vector256<ulong> MaskLoad(ulong* address, Vector256<ulong> mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm_maskstore_epi32 (int* mem_addr, __m128i mask, __m128i a)
+ /// </summary>
+ public static unsafe void MaskStore(int* address, Vector128<int> mask, Vector128<int> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_maskstore_epi32 (int* mem_addr, __m128i mask, __m128i a)
+ /// </summary>
+ public static unsafe void MaskStore(uint* address, Vector128<uint> mask, Vector128<uint> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_maskstore_epi64 (__int64* mem_addr, __m128i mask, __m128i a)
+ /// </summary>
+ public static unsafe void MaskStore(long* address, Vector128<long> mask, Vector128<long> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_maskstore_epi64 (__int64* mem_addr, __m128i mask, __m128i a)
+ /// </summary>
+ public static unsafe void MaskStore(ulong* address, Vector128<ulong> mask, Vector128<ulong> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm256_maskstore_epi32 (int* mem_addr, __m256i mask, __m256i a)
+ /// </summary>
+ public static unsafe void MaskStore(int* address, Vector256<int> mask, Vector256<int> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_maskstore_epi32 (int* mem_addr, __m256i mask, __m256i a)
+ /// </summary>
+ public static unsafe void MaskStore(uint* address, Vector256<uint> mask, Vector256<uint> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_maskstore_epi64 (__int64* mem_addr, __m256i mask, __m256i a)
+ /// </summary>
+ public static unsafe void MaskStore(long* address, Vector256<long> mask, Vector256<long> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm256_maskstore_epi64 (__int64* mem_addr, __m256i mask, __m256i a)
+ /// </summary>
+ public static unsafe void MaskStore(ulong* address, Vector256<ulong> mask, Vector256<ulong> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_madd_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> MultiplyAddAdjacent(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_maddubs_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> MultiplyAddAdjacent(Vector256<byte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_max_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> Max(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_max_epu8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> Max(Vector256<byte> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_max_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> Max(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_max_epu16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> Max(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_max_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> Max(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_max_epu32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<uint> Max(Vector256<uint> left, Vector256<uint> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_min_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> Min(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_min_epu8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> Min(Vector256<byte> left, Vector256<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_min_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> Min(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_min_epu16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> Min(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_min_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> Min(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_min_epu32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<uint> Min(Vector256<uint> left, Vector256<uint> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm256_movemask_epi8 (__m256i a)
+ /// </summary>
+ public static int MoveMask(Vector256<sbyte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// int _mm256_movemask_epi8 (__m256i a)
+ /// </summary>
+ public static int MoveMask(Vector256<byte> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_mpsadbw_epu8 (__m256i a, __m256i b, const int imm8)
+ /// </summary>
+ public static Vector256<ushort> MultipleSumAbsoluteDifferences(Vector256<byte> left, Vector256<byte> right, byte mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_mul_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<long> Multiply(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_mul_epu32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ulong> Multiply(Vector256<uint> left, Vector256<uint> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_mulhi_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> MultiplyHigh(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_mulhi_epu16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> MultiplyHigh(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_mulhrs_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> MultiplyHighRoundScale(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_mullo_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> MultiplyLow(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_mullo_epu16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> MultiplyLow(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_or_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> Or(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_or_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> Or(Vector256<byte> left, Vector256<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_or_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> Or(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_or_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> Or(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_or_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> Or(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_or_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<uint> Or(Vector256<uint> left, Vector256<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_or_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<long> Or(Vector256<long> left, Vector256<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_or_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ulong> Or(Vector256<ulong> left, Vector256<ulong> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_packs_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> PackSignedSaturate(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_packs_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> PackSignedSaturate(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_packus_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> PackUnsignedSaturate(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_packus_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> PackUnsignedSaturate(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_permute2x128_si256 (__m256i a, __m256i b, const int imm8)
+ /// </summary>
+ public static Vector256<sbyte> Permute2x128(Vector256<sbyte> left, Vector256<sbyte> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_permute2x128_si256 (__m256i a, __m256i b, const int imm8)
+ /// </summary>
+ public static Vector256<byte> Permute2x128(Vector256<byte> left, Vector256<byte> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_permute2x128_si256 (__m256i a, __m256i b, const int imm8)
+ /// </summary>
+ public static Vector256<short> Permute2x128(Vector256<short> left, Vector256<short> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_permute2x128_si256 (__m256i a, __m256i b, const int imm8)
+ /// </summary>
+ public static Vector256<ushort> Permute2x128(Vector256<ushort> left, Vector256<ushort> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_permute2x128_si256 (__m256i a, __m256i b, const int imm8)
+ /// </summary>
+ public static Vector256<int> Permute2x128(Vector256<int> left, Vector256<int> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_permute2x128_si256 (__m256i a, __m256i b, const int imm8)
+ /// </summary>
+ public static Vector256<uint> Permute2x128(Vector256<uint> left, Vector256<uint> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_permute2x128_si256 (__m256i a, __m256i b, const int imm8)
+ /// </summary>
+ public static Vector256<long> Permute2x128(Vector256<long> left, Vector256<long> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_permute2x128_si256 (__m256i a, __m256i b, const int imm8)
+ /// </summary>
+ public static Vector256<ulong> Permute2x128(Vector256<ulong> left, Vector256<ulong> right, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_permute4x64_epi64 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<long> Permute4x64(Vector256<long> value, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_permute4x64_epi64 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<ulong> Permute4x64(Vector256<ulong> value, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_permute4x64_pd (__m256d a, const int imm8)
+ /// </summary>
+ public static Vector256<double> Permute4x64(Vector256<double> value, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_permutevar8x32_epi32 (__m256i a, __m256i idx)
+ /// </summary>
+ public static Vector256<int> PermuteVar8x32(Vector256<int> left, Vector256<int> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_permutevar8x32_epi32 (__m256i a, __m256i idx)
+ /// </summary>
+ public static Vector256<uint> PermuteVar8x32(Vector256<uint> left, Vector256<uint> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_permutevar8x32_ps (__m256 a, __m256i idx)
+ /// </summary>
+ public static Vector256<float> PermuteVar8x32(Vector256<float> left, Vector256<float> mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_slli_epi16 (__m256i a, int imm8)
+ /// </summary>
+ public static Vector256<short> ShiftLeftLogical(Vector256<short> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_slli_epi16 (__m256i a, int imm8)
+ /// </summary>
+ public static Vector256<ushort> ShiftLeftLogical(Vector256<ushort> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_slli_epi32 (__m256i a, int imm8)
+ /// </summary>
+ public static Vector256<int> ShiftLeftLogical(Vector256<int> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_slli_epi32 (__m256i a, int imm8)
+ /// </summary>
+ public static Vector256<uint> ShiftLeftLogical(Vector256<uint> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_slli_epi64 (__m256i a, int imm8)
+ /// </summary>
+ public static Vector256<long> ShiftLeftLogical(Vector256<long> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_slli_epi64 (__m256i a, int imm8)
+ /// </summary>
+ public static Vector256<ulong> ShiftLeftLogical(Vector256<ulong> value, byte count) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_bslli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<sbyte> ShiftLeftLogical128BitLane(Vector256<sbyte> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_bslli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<byte> ShiftLeftLogical128BitLane(Vector256<byte> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_bslli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<short> ShiftLeftLogical128BitLane(Vector256<short> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_bslli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<ushort> ShiftLeftLogical128BitLane(Vector256<ushort> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_bslli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<int> ShiftLeftLogical128BitLane(Vector256<int> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_bslli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<uint> ShiftLeftLogical128BitLane(Vector256<uint> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_bslli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<long> ShiftLeftLogical128BitLane(Vector256<long> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_bslli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<ulong> ShiftLeftLogical128BitLane(Vector256<ulong> value, byte numBytes) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_sllv_epi32 (__m256i a, __m256i count)
+ /// </summary>
+ public static Vector256<int> ShiftLeftLogicalVariable(Vector256<int> value, Vector256<uint> count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_sllv_epi32 (__m256i a, __m256i count)
+ /// </summary>
+ public static Vector256<uint> ShiftLeftLogicalVariable(Vector256<uint> value, Vector256<uint> count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_sllv_epi64 (__m256i a, __m256i count)
+ /// </summary>
+ public static Vector256<long> ShiftLeftLogicalVariable(Vector256<long> value, Vector256<ulong> count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_sllv_epi64 (__m256i a, __m256i count)
+ /// </summary>
+ public static Vector256<ulong> ShiftLeftLogicalVariable(Vector256<ulong> value, Vector256<ulong> count) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_srai_epi16 (__m256i a, int imm8)
+ /// </summary>
+ public static Vector256<short> ShiftRightArithmetic(Vector256<short> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_srai_epi32 (__m256i a, int imm8)
+ /// </summary>
+ public static Vector256<int> ShiftRightArithmetic(Vector256<int> value, byte count) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_srav_epi32 (__m256i a, __m256i count)
+ /// </summary>
+ public static Vector256<int> ShiftRightArithmeticVariable(Vector256<int> value, Vector256<uint> count) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_srli_epi16 (__m256i a, int imm8)
+ /// </summary>
+ public static Vector256<short> ShiftRightLogical(Vector256<short> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_srli_epi16 (__m256i a, int imm8)
+ /// </summary>
+ public static Vector256<ushort> ShiftRightLogical(Vector256<ushort> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_srli_epi32 (__m256i a, int imm8)
+ /// </summary>
+ public static Vector256<int> ShiftRightLogical(Vector256<int> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_srli_epi32 (__m256i a, int imm8)
+ /// </summary>
+ public static Vector256<uint> ShiftRightLogical(Vector256<uint> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_srli_epi64 (__m256i a, int imm8)
+ /// </summary>
+ public static Vector256<long> ShiftRightLogical(Vector256<long> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_srli_epi64 (__m256i a, int imm8)
+ /// </summary>
+ public static Vector256<ulong> ShiftRightLogical(Vector256<ulong> value, byte count) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_bsrli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<sbyte> ShiftRightLogical128BitLane(Vector256<sbyte> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_bsrli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<byte> ShiftRightLogical128BitLane(Vector256<byte> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_bsrli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<short> ShiftRightLogical128BitLane(Vector256<short> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_bsrli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<ushort> ShiftRightLogical128BitLane(Vector256<ushort> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_bsrli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<int> ShiftRightLogical128BitLane(Vector256<int> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_bsrli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<uint> ShiftRightLogical128BitLane(Vector256<uint> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_bsrli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<long> ShiftRightLogical128BitLane(Vector256<long> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_bsrli_epi128 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<ulong> ShiftRightLogical128BitLane(Vector256<ulong> value, byte numBytes) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_srlv_epi32 (__m256i a, __m256i count)
+ /// </summary>
+ public static Vector256<int> ShiftRightLogicalVariable(Vector256<int> value, Vector256<uint> count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_srlv_epi32 (__m256i a, __m256i count)
+ /// </summary>
+ public static Vector256<uint> ShiftRightLogicalVariable(Vector256<uint> value, Vector256<uint> count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_srlv_epi64 (__m256i a, __m256i count)
+ /// </summary>
+ public static Vector256<long> ShiftRightLogicalVariable(Vector256<long> value, Vector256<ulong> count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_srlv_epi64 (__m256i a, __m256i count)
+ /// </summary>
+ public static Vector256<ulong> ShiftRightLogicalVariable(Vector256<ulong> value, Vector256<ulong> count) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_shuffle_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> Shuffle(Vector256<sbyte> value, Vector256<sbyte> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_shuffle_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> Shuffle(Vector256<byte> value, Vector256<byte> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_shuffle_epi32 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<int> Shuffle(Vector256<int> value, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_shuffle_epi32 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<uint> Shuffle(Vector256<uint> value, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_shufflehi_epi16 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<short> ShuffleHigh(Vector256<short> value, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_shufflehi_epi16 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<ushort> ShuffleHigh(Vector256<ushort> value, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_shufflelo_epi16 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<short> ShuffleLow(Vector256<short> value, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_shufflelo_epi16 (__m256i a, const int imm8)
+ /// </summary>
+ public static Vector256<ushort> ShuffleLow(Vector256<ushort> value, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_sign_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> Sign(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_sign_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> Sign(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_sign_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> Sign(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_sub_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> Subtract(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_sub_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> Subtract(Vector256<byte> left, Vector256<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_sub_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> Subtract(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_sub_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> Subtract(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_sub_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> Subtract(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_sub_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<uint> Subtract(Vector256<uint> left, Vector256<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_sub_epi64 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<long> Subtract(Vector256<long> left, Vector256<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_sub_epi64 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ulong> Subtract(Vector256<ulong> left, Vector256<ulong> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_subs_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> SubtractSaturate(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_subs_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> SubtractSaturate(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_subs_epu8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> SubtractSaturate(Vector256<byte> left, Vector256<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_subs_epu16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> SubtractSaturate(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_sad_epu8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ulong> SumAbsoluteDifferences(Vector256<byte> left, Vector256<byte> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_unpackhi_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> UnpackHigh(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_unpackhi_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> UnpackHigh(Vector256<byte> left, Vector256<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_unpackhi_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> UnpackHigh(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_unpackhi_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> UnpackHigh(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_unpackhi_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> UnpackHigh(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_unpackhi_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<uint> UnpackHigh(Vector256<uint> left, Vector256<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_unpackhi_epi64 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<long> UnpackHigh(Vector256<long> left, Vector256<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_unpackhi_epi64 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ulong> UnpackHigh(Vector256<ulong> left, Vector256<ulong> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_unpacklo_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> UnpackLow(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_unpacklo_epi8 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> UnpackLow(Vector256<byte> left, Vector256<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_unpacklo_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> UnpackLow(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_unpacklo_epi16 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> UnpackLow(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_unpacklo_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> UnpackLow(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_unpacklo_epi32 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<uint> UnpackLow(Vector256<uint> left, Vector256<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_unpacklo_epi64 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<long> UnpackLow(Vector256<long> left, Vector256<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_unpacklo_epi64 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ulong> UnpackLow(Vector256<ulong> left, Vector256<ulong> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m256i _mm256_xor_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<sbyte> Xor(Vector256<sbyte> left, Vector256<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_xor_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<byte> Xor(Vector256<byte> left, Vector256<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_xor_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<short> Xor(Vector256<short> left, Vector256<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_xor_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ushort> Xor(Vector256<ushort> left, Vector256<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_xor_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<int> Xor(Vector256<int> left, Vector256<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_xor_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<uint> Xor(Vector256<uint> left, Vector256<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_xor_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<long> Xor(Vector256<long> left, Vector256<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256i _mm256_xor_si256 (__m256i a, __m256i b)
+ /// </summary>
+ public static Vector256<ulong> Xor(Vector256<ulong> left, Vector256<ulong> right) { throw new NotImplementedException(); }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Bmi1.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Bmi1.cs
new file mode 100644
index 0000000000..a2bfcffedc
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Bmi1.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.
+
+using System;
+using System.Runtime.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel BMI1 hardware instructions via intrinsics
+ /// </summary>
+ [CLSCompliant(false)]
+ public static class Bmi1
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// unsigned int _andn_u32 (unsigned int a, unsigned int b)
+ /// </summary>
+ public static uint AndNot(uint left, uint right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned __int64 _andn_u64 (unsigned __int64 a, unsigned __int64 b)
+ /// </summary>
+ public static ulong AndNot(ulong left, ulong right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// unsigned int _bextr_u32 (unsigned int a, unsigned int start, unsigned int len)
+ /// </summary>
+ public static uint BitFieldExtract(uint value, uint start, uint length) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned __int64 _bextr_u64 (unsigned __int64 a, unsigned int start, unsigned int len)
+ /// </summary>
+ public static ulong BitFieldExtract(ulong value, ulong start, ulong length) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned int _bextr2_u32 (unsigned int a, unsigned int control)
+ /// </summary>
+ public static uint BitFieldExtract(uint value, uint control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned __int64 _bextr2_u64 (unsigned __int64 a, unsigned __int64 control)
+ /// </summary>
+ public static ulong BitFieldExtract(ulong value, ulong control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// unsigned int _blsi_u32 (unsigned int a)
+ /// </summary>
+ public static uint ExtractLowestSetBit(uint value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned __int64 _blsi_u64 (unsigned __int64 a)
+ /// </summary>
+ public static ulong ExtractLowestSetBit(ulong value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// unsigned int _blsmsk_u32 (unsigned int a)
+ /// </summary>
+ public static uint GetMaskUptoLowestSetBit(uint value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned __int64 _blsmsk_u64 (unsigned __int64 a)
+ /// </summary>
+ public static ulong GetMaskUptoLowestSetBit(ulong value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// unsigned int _blsr_u32 (unsigned int a)
+ /// </summary>
+ public static uint ResetLowestSetBit(uint value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned __int64 _blsr_u64 (unsigned __int64 a)
+ /// </summary>
+ public static ulong ResetLowestSetBit(ulong value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_tzcnt_32 (unsigned int a)
+ /// </summary>
+ public static uint TrailingZeroCount(uint value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __int64 _mm_tzcnt_64 (unsigned __int64 a)
+ /// </summary>
+ public static ulong TrailingZeroCount(ulong value) { throw new NotImplementedException(); }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Bmi2.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Bmi2.cs
new file mode 100644
index 0000000000..a9a73de926
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Bmi2.cs
@@ -0,0 +1,54 @@
+// 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.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel BMI2 hardware instructions via intrinsics
+ /// </summary>
+ [CLSCompliant(false)]
+ public static class Bmi2
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// unsigned int _bzhi_u32 (unsigned int a, unsigned int index)
+ /// </summary>
+ public static uint ZeroHighBits(uint value, uint index) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned __int64 _bzhi_u64 (unsigned __int64 a, unsigned int index)
+ /// </summary>
+ public static ulong ZeroHighBits(ulong value, ulong index) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// unsigned int _mulx_u32 (unsigned int a, unsigned int b, unsigned int* hi)
+ /// </summary>
+ public static unsafe uint MultiplyNoFlags(uint left, uint right, uint* high) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned __int64 _mulx_u64 (unsigned __int64 a, unsigned __int64 b, unsigned __int64* hi)
+ /// </summary>
+ public static unsafe ulong MultiplyNoFlags(ulong left, ulong right, ulong* high) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// unsigned int _pdep_u32 (unsigned int a, unsigned int mask)
+ /// </summary>
+ public static uint ParallelBitDeposit(uint value, uint mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned __int64 _pdep_u64 (unsigned __int64 a, unsigned __int64 mask)
+ /// </summary>
+ public static ulong ParallelBitDeposit(ulong value, ulong mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// unsigned int _pext_u32 (unsigned int a, unsigned int mask)
+ /// </summary>
+ public static uint ParallelBitExtract(uint value, uint mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned __int64 _pext_u64 (unsigned __int64 a, unsigned __int64 mask)
+ /// </summary>
+ public static ulong ParallelBitExtract(ulong value, ulong mask) { throw new NotImplementedException(); }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Enums.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Enums.cs
new file mode 100644
index 0000000000..6d6a09a0b6
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Enums.cs
@@ -0,0 +1,189 @@
+// 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.Runtime.Intrinsics.X86
+{
+ public enum FloatComparisonMode : byte
+ {
+ /// <summary>
+ /// _CMP_EQ_OQ
+ /// </summary>
+ EqualOrderedNonSignaling = 0,
+
+ /// <summary>
+ /// _CMP_LT_OS
+ /// </summary>
+ LessThanOrderedSignaling = 1,
+
+ /// <summary>
+ /// _CMP_LE_OS
+ /// </summary>
+ LessThanOrEqualOrderedSignaling = 2,
+
+ /// <summary>
+ /// _CMP_UNORD_Q
+ /// </summary>
+ UnorderedNonSignaling = 3,
+
+ /// <summary>
+ /// _CMP_NEQ_UQ
+ /// </summary>
+ NotEqualUnorderedNonSignaling = 4,
+
+ /// <summary>
+ /// _CMP_NLT_US
+ /// </summary>
+ NotLessThanUnorderedSignaling = 5,
+
+ /// <summary>
+ /// _CMP_NLE_US
+ /// </summary>
+ NotLessThanOrEqualUnorderedSignaling = 6,
+
+ /// <summary>
+ /// _CMP_ORD_Q
+ /// </summary>
+ OrderedNonSignaling = 7,
+
+ /// <summary>
+ /// _CMP_EQ_UQ
+ /// </summary>
+ EqualUnorderedNonSignaling = 8,
+
+ /// <summary>
+ /// _CMP_NGE_US
+ /// </summary>
+ NotGreaterThanOrEqualUnorderedSignaling = 9,
+
+ /// <summary>
+ /// _CMP_NGT_US
+ /// </summary>
+ NotGreaterThanUnorderedSignaling = 10,
+
+ /// <summary>
+ /// _CMP_FALSE_OQ
+ /// </summary>
+ FalseOrderedNonSignaling = 11,
+
+ /// <summary>
+ /// _CMP_NEQ_OQ
+ /// </summary>
+ NotEqualOrderedNonSignaling = 12,
+
+ /// <summary>
+ /// _CMP_GE_OS
+ /// </summary>
+ GreaterThanOrEqualOrderedSignaling = 13,
+
+ /// <summary>
+ /// _CMP_GT_OS
+ /// </summary>
+ GreaterThanOrderedSignaling = 14,
+
+ /// <summary>
+ /// _CMP_TRUE_UQ
+ /// </summary>
+ TrueUnorderedNonSignaling = 15,
+
+ /// <summary>
+ /// _CMP_EQ_OS
+ /// </summary>
+ EqualOrderedSignaling = 16,
+
+ /// <summary>
+ /// _CMP_LT_OQ
+ /// </summary>
+ LessThanOrderedNonSignaling = 17,
+
+ /// <summary>
+ /// _CMP_LE_OQ
+ /// </summary>
+ LessThanOrEqualOrderedNonSignaling = 18,
+
+ /// <summary>
+ /// _CMP_UNORD_S
+ /// </summary>
+ UnorderedSignaling = 19,
+
+ /// <summary>
+ /// _CMP_NEQ_US
+ /// </summary>
+ NotEqualUnorderedSignaling = 20,
+
+ /// <summary>
+ /// _CMP_NLT_UQ
+ /// </summary>
+ NotLessThanUnorderedNonSignaling = 21,
+
+ /// <summary>
+ /// _CMP_NLE_UQ
+ /// </summary>
+ NotLessThanOrEqualUnorderedNonSignaling = 22,
+
+ /// <summary>
+ /// _CMP_ORD_S
+ /// </summary>
+ OrderedSignaling = 23,
+
+ /// <summary>
+ /// _CMP_EQ_US
+ /// </summary>
+ EqualUnorderedSignaling = 24,
+
+ /// <summary>
+ /// _CMP_NGE_UQ
+ /// </summary>
+ NotGreaterThanOrEqualUnorderedNonSignaling = 25,
+
+ /// <summary>
+ /// _CMP_NGT_UQ
+ /// </summary>
+ NotGreaterThanUnorderedNonSignaling = 26,
+
+ /// <summary>
+ /// _CMP_FALSE_OS
+ /// </summary>
+ FalseOrderedSignaling = 27,
+
+ /// <summary>
+ /// _CMP_NEQ_OS
+ /// </summary>
+ NotEqualOrderedSignaling = 28,
+
+ /// <summary>
+ /// _CMP_GE_OQ
+ /// </summary>
+ GreaterThanOrEqualOrderedNonSignaling = 29,
+
+ /// <summary>
+ /// _CMP_GT_OQ
+ /// </summary>
+ GreaterThanOrderedNonSignaling = 30,
+
+ /// <summary>
+ /// _CMP_TRUE_US
+ /// </summary>
+ TrueUnorderedSignaling = 31,
+ }
+
+ public enum StringComparisonMode : byte {
+ EqualAny = 0x00,
+ Ranges = 0x04,
+ EqualEach = 0x08,
+ EqualOrdered = 0x0c,
+ NegativePolarity = 0x10,
+ MaskedNegativePolarity = 0x30,
+ LeastSignificant = 0x00,
+ MostSignificant = 0x40,
+ }
+
+
+ public enum ResultsFlag : byte {
+ CFlag = 0,
+ NotCFlagAndNotZFlag = 1,
+ OFlag = 2,
+ SFlag = 3,
+ ZFlag = 4,
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Fma.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Fma.cs
new file mode 100644
index 0000000000..84160f293f
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Fma.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.Runtime.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel FMA hardware instructions via intrinsics
+ /// </summary>
+ public static class Fma
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// __m128 _mm_fmadd_ps (__m128 a, __m128 b, __m128 c)
+ /// </summary>
+ public static Vector128<float> MultiplyAdd(Vector128<float> a, Vector128<float> b, Vector128<float> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_fmadd_pd (__m128d a, __m128d b, __m128d c)
+ /// </summary>
+ public static Vector128<double> MultiplyAdd(Vector128<double> a, Vector128<double> b, Vector128<double> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_fmadd_ps (__m256 a, __m256 b, __m256 c)
+ /// </summary>
+ public static Vector256<float> MultiplyAdd(Vector256<float> a, Vector256<float> b, Vector256<float> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_fmadd_pd (__m256d a, __m256d b, __m256d c)
+ /// </summary>
+ public static Vector256<double> MultiplyAdd(Vector256<double> a, Vector256<double> b, Vector256<double> c) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_fmaddsub_ps (__m128 a, __m128 b, __m128 c)
+ /// </summary>
+ public static Vector128<float> MultiplyAddSubtract(Vector128<float> a, Vector128<float> b, Vector128<float> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_fmaddsub_pd (__m128d a, __m128d b, __m128d c)
+ /// </summary>
+ public static Vector128<double> MultiplyAddSubtract(Vector128<double> a, Vector128<double> b, Vector128<double> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_fmaddsub_ps (__m256 a, __m256 b, __m256 c)
+ /// </summary>
+ public static Vector256<float> MultiplyAddSubtract(Vector256<float> a, Vector256<float> b, Vector256<float> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_fmaddsub_pd (__m256d a, __m256d b, __m256d c)
+ /// </summary>
+ public static Vector256<double> MultiplyAddSubtract(Vector256<double> a, Vector256<double> b, Vector256<double> c) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_fmsub_ps (__m128 a, __m128 b, __m128 c)
+ /// </summary>
+ public static Vector128<float> MultiplySubtract(Vector128<float> a, Vector128<float> b, Vector128<float> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_fmsub_pd (__m128d a, __m128d b, __m128d c)
+ /// </summary>
+ public static Vector128<double> MultiplySubtract(Vector128<double> a, Vector128<double> b, Vector128<double> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_fmsub_ps (__m256 a, __m256 b, __m256 c)
+ /// </summary>
+ public static Vector256<float> MultiplySubtract(Vector256<float> a, Vector256<float> b, Vector256<float> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_fmsub_pd (__m256d a, __m256d b, __m256d c)
+ /// </summary>
+ public static Vector256<double> MultiplySubtract(Vector256<double> a, Vector256<double> b, Vector256<double> c) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_fmsubadd_ps (__m128 a, __m128 b, __m128 c)
+ /// </summary>
+ public static Vector128<float> MultiplySubtractAdd(Vector128<float> a, Vector128<float> b, Vector128<float> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_fmsubadd_pd (__m128d a, __m128d b, __m128d c)
+ /// </summary>
+ public static Vector128<double> MultiplySubtractAdd(Vector128<double> a, Vector128<double> b, Vector128<double> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_fmsubadd_ps (__m256 a, __m256 b, __m256 c)
+ /// </summary>
+ public static Vector256<float> MultiplySubtractAdd(Vector256<float> a, Vector256<float> b, Vector256<float> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_fmsubadd_pd (__m256d a, __m256d b, __m256d c)
+ /// </summary>
+ public static Vector256<double> MultiplySubtractAdd(Vector256<double> a, Vector256<double> b, Vector256<double> c) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_fnmadd_ps (__m128 a, __m128 b, __m128 c)
+ /// </summary>
+ public static Vector128<float> MultiplyAddNegated(Vector128<float> a, Vector128<float> b, Vector128<float> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_fnmadd_pd (__m128d a, __m128d b, __m128d c)
+ /// </summary>
+ public static Vector128<double> MultiplyAddNegated(Vector128<double> a, Vector128<double> b, Vector128<double> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_fnmadd_ps (__m256 a, __m256 b, __m256 c)
+ /// </summary>
+ public static Vector256<float> MultiplyAddNegated(Vector256<float> a, Vector256<float> b, Vector256<float> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_fnmadd_pd (__m256d a, __m256d b, __m256d c)
+ /// </summary>
+ public static Vector256<double> MultiplyAddNegated(Vector256<double> a, Vector256<double> b, Vector256<double> c) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_fnmsub_ps (__m128 a, __m128 b, __m128 c)
+ /// </summary>
+ public static Vector128<float> MultiplySubtractNegated(Vector128<float> a, Vector128<float> b, Vector128<float> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_fnmsub_pd (__m128d a, __m128d b, __m128d c)
+ /// </summary>
+ public static Vector128<double> MultiplySubtractNegated(Vector128<double> a, Vector128<double> b, Vector128<double> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256 _mm256_fnmsub_ps (__m256 a, __m256 b, __m256 c)
+ /// </summary>
+ public static Vector256<float> MultiplySubtractNegated(Vector256<float> a, Vector256<float> b, Vector256<float> c) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m256d _mm256_fnmsub_pd (__m256d a, __m256d b, __m256d c)
+ /// </summary>
+ public static Vector256<double> MultiplySubtractNegated(Vector256<double> a, Vector256<double> b, Vector256<double> c) { throw new NotImplementedException(); }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Lzcnt.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Lzcnt.cs
new file mode 100644
index 0000000000..ffc656e43b
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Lzcnt.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;
+using System.Runtime.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel LZCNT hardware instructions via intrinsics
+ /// </summary>
+ [CLSCompliant(false)]
+ public static class Lzcnt
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// unsigned int _lzcnt_u32 (unsigned int a)
+ /// </summary>
+ public static uint LeadingZeroCount(uint value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned __int64 _lzcnt_u64 (unsigned __int64 a)
+ /// </summary>
+ public static ulong LeadingZeroCount(ulong value) { throw new NotImplementedException(); }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Pclmulqdq.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Pclmulqdq.cs
new file mode 100644
index 0000000000..f8576f89fe
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Pclmulqdq.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;
+using System.Runtime.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel PCLMULQDQ hardware instructions via intrinsics
+ /// </summary>
+ [CLSCompliant(false)]
+ public static class Pclmulqdq
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// __m128i _mm_clmulepi64_si128 (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<long> CarryLessMultiply(Vector128<long> left, Vector128<long> right, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_clmulepi64_si128 (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<ulong> CarryLessMultiply(Vector128<ulong> left, Vector128<ulong> right, byte control) { throw new NotImplementedException(); }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Popcnt.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Popcnt.cs
new file mode 100644
index 0000000000..66f2ab127d
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Popcnt.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;
+using System.Runtime.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel POPCNT hardware instructions via intrinsics
+ /// </summary>
+ [CLSCompliant(false)]
+ public static class Popcnt
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// int _mm_popcnt_u32 (unsigned int a)
+ /// </summary>
+ public static int PopCount(uint value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __int64 _mm_popcnt_u64 (unsigned __int64 a)
+ /// </summary>
+ public static long PopCount(ulong value) { throw new NotImplementedException(); }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse.cs
new file mode 100644
index 0000000000..c85aee3015
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse.cs
@@ -0,0 +1,218 @@
+// 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.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel SSE hardware instructions via intrinsics
+ /// </summary>
+ [CLSCompliant(false)]
+ public static class Sse
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// __m128 _mm_add_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> Add(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_and_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> And(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_andnot_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> AndNot(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_cmpeq_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> CompareEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_cmpgt_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> CompareGreaterThan(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_cmpge_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> CompareGreaterThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_cmplt_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> CompareLessThan(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_cmple_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> CompareLessThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_cmpneq_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> CompareNotEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_cmpngt_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> CompareNotGreaterThan(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_cmpnge_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> CompareNotGreaterThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_cmpnlt_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> CompareNotLessThan(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_cmpnle_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> CompareNotLessThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_cmpord_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> CompareOrdered(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_cmpunord_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> CompareUnordered(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_div_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> Divide(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_loadu_ps (float const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<float> Load(float* address) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_load_ps (float const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<float> LoadAligned(float* address) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_max_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> Max(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_min_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> Min(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_movehl_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> MoveHighToLow(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_movelh_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> MoveLowToHigh(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_mul_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> Multiply(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_or_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> Or(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_rcp_ps (__m128 a)
+ /// </summary>
+ public static Vector128<float> Reciprocal(Vector128<float> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_rsqrt_ps (__m128 a)
+ /// </summary>
+ public static Vector128<float> ReciprocalSquareRoot(Vector128<float> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_set_ps (float e3, float e2, float e1, float e0)
+ /// </summary>
+ public static Vector128<float> Set(float e3, float e2, float e1, float e0) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_set1_ps (float a)
+ /// </summary>
+ public static Vector128<float> Set1(float value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_setzero_ps (void)
+ /// </summary>
+ public static Vector128<float> SetZero() { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_castpd_ps (__m128d a)
+ /// __m128i _mm_castpd_si128 (__m128d a)
+ /// __m128d _mm_castps_pd (__m128 a)
+ /// __m128i _mm_castps_si128 (__m128 a)
+ /// __m128d _mm_castsi128_pd (__m128i a)
+ /// __m128 _mm_castsi128_ps (__m128i a)
+ /// </summary>
+ public static Vector128<U> StaticCast<T, U>(Vector128<T> value) where T : struct where U : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_shuffle_ps (__m128 a, __m128 b, unsigned int control)
+ /// </summary>
+ public static Vector128<float> Shuffle(Vector128<float> left, Vector128<float> right, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_sqrt_ps (__m128 a)
+ /// </summary>
+ public static Vector128<float> Sqrt(Vector128<float> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm_store_ps (float* mem_addr, __m128 a)
+ /// </summary>
+ public static unsafe void StoreAligned(float* address, Vector128<float> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm_stream_ps (float* mem_addr, __m128 a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(float* address, Vector128<float> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm_storeu_ps (float* mem_addr, __m128 a)
+ /// </summary>
+ public static unsafe void Store(float* address, Vector128<float> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_sub_ps (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<float> Subtract(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_unpackhi_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> UnpackHigh(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_unpacklo_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> UnpackLow(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_xor_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> Xor(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse2.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse2.cs
new file mode 100644
index 0000000000..ffe35f883c
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse2.cs
@@ -0,0 +1,1057 @@
+// 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.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel SSE2 hardware instructions via intrinsics
+ /// </summary>
+ [CLSCompliant(false)]
+ public static class Sse2
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// __m128i _mm_add_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> Add(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_add_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> Add(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_add_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> Add(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_add_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> Add(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_add_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> Add(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_add_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<uint> Add(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_add_epi64 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<long> Add(Vector128<byte> left, Vector128<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_add_epi64 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ulong> Add(Vector128<sbyte> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_add_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> Add(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_adds_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> AddSaturate(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_adds_epu8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> AddSaturate(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_adds_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> AddSaturate(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_adds_epu16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> AddSaturate(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_and_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> And(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_and_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> And(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_and_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> And(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_and_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> And(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_and_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> And(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_and_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<uint> And(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_and_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<long> And(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_and_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ulong> And(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_and_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> And(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_andnot_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> AndNot(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_andnot_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> AndNot(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_andnot_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> AndNot(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_andnot_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> AndNot(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_andnot_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> AndNot(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_andnot_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<uint> AndNot(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_andnot_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<long> AndNot(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_andnot_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ulong> AndNot(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_andnot_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> AndNot(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_avg_epu8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> Average(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_avg_epu16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> Average(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpeq_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> CompareEqual(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cmpeq_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> CompareEqual(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cmpeq_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> CompareEqual(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cmpeq_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> CompareEqual(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cmpeq_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> CompareEqual(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cmpeq_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<uint> CompareEqual(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_cmpeq_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> CompareEqual(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpgt_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> CompareGreaterThan(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cmpgt_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> CompareGreaterThan(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cmpgt_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> CompareGreaterThan(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_cmpgt_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> CompareGreaterThan(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_cmpge_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> CompareGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmplt_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> CompareLessThan(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cmplt_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> CompareLessThan(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cmplt_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> CompareLessThan(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_cmplt_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> CompareLessThan(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_cmple_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> CompareLessThanOrEqual(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_cmpneq_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> CompareNotEqual(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_cmpngt_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> CompareNotGreaterThan(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_cmpnge_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> CompareNotGreaterThanOrEqual(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_cmpnlt_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> CompareNotLessThan(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_cmpnle_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> CompareNotLessThanOrEqual(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_cmpord_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> CompareOrdered(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_cmpunord_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> CompareUnordered(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cvtps_epi32 (__m128 a)
+ /// </summary>
+ public static Vector128<int> ConvertToInt(Vector128<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cvtpd_epi32 (__m128d a)
+ /// </summary>
+ public static Vector128<int> ConvertToInt(Vector128<double> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128 _mm_cvtepi32_ps (__m128i a)
+ /// </summary>
+ public static Vector128<float> ConvertToFloat(Vector128<int> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128 _mm_cvtpd_ps (__m128d a)
+ /// </summary>
+ public static Vector128<float> ConvertToFloat(Vector128<double> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_cvtepi32_pd (__m128i a)
+ /// </summary>
+ public static Vector128<double> ConvertToDouble(Vector128<int> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_cvtps_pd (__m128 a)
+ /// </summary>
+ public static Vector128<double> ConvertToDouble(Vector128<float> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cvttps_epi32 (__m128 a)
+ /// </summary>
+ public static Vector128<int> ConvertToIntWithTruncation(Vector128<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cvttpd_epi32 (__m128d a)
+ /// </summary>
+ public static Vector128<int> ConvertToIntWithTruncation(Vector128<double> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_div_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> Divide(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_extract_epi16 (__m128i a, int immediate)
+ /// </summary>
+ public static short ExtractShort<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// int _mm_extract_epi16 (__m128i a, int immediate)
+ /// </summary>
+ public static ushort ExtractUshort<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_insert_epi16 (__m128i a, int i, int immediate)
+ /// </summary>
+ public static Vector128<T> InsertShort<T>(Vector128<T> value, short data, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_insert_epi16 (__m128i a, int i, int immediate)
+ /// </summary>
+ public static Vector128<T> InsertUshort<T>(Vector128<T> value, ushort data, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_loadu_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<sbyte> Load(sbyte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_loadu_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<byte> Load(byte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_loadu_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<short> Load(short* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_loadu_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<ushort> Load(ushort* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_loadu_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<int> Load(int* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_loadu_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<uint> Load(uint* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_loadu_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<long> Load(long* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_loadu_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<ulong> Load(ulong* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_loadu_pd (double const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<double> Load(double* address) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_load_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<sbyte> LoadAligned(sbyte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_load_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<byte> LoadAligned(byte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_load_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<short> LoadAligned(short* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_load_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<ushort> LoadAligned(ushort* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_load_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<int> LoadAligned(int* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_load_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<uint> LoadAligned(uint* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_load_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<long> LoadAligned(long* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_load_si128 (__m128i const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<ulong> LoadAligned(ulong* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_load_pd (double const* mem_address)
+ /// </summary>
+ public static unsafe Vector128<double> LoadAligned(double* address) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm_maskmoveu_si128 (__m128i a, __m128i mask, char* mem_address)
+ /// </summary>
+ public static unsafe void MaskMove(Vector128<sbyte> source, Vector128<sbyte> mask, sbyte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_maskmoveu_si128 (__m128i a, __m128i mask, char* mem_address)
+ /// </summary>
+ public static unsafe void MaskMove(Vector128<byte> source, Vector128<byte> mask, byte* address) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_max_epu8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> Max(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_max_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> Max(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_max_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> Max(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_min_epu8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> Min(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_min_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> Min(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_min_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> Min(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_movemask_epi8 (__m128i a)
+ /// </summary>
+ public static int MoveMask(Vector128<sbyte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// int _mm_movemask_pd (__m128d a)
+ /// </summary>
+ public static int MoveMask(Vector128<double> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_mul_epu32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ulong> Multiply(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_mul_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> Multiply(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_mulhi_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> MultiplyHi(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_mulhi_epu16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> MultiplyHi(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_madd_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> MultiplyHorizontalAdd(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_mullo_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> MultiplyLow(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_or_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> Or(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_or_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> Or(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_or_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> Or(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_or_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> Or(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_or_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> Or(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_or_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<uint> Or(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_or_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<long> Or(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_or_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ulong> Or(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_or_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> Or(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_packs_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> PackSignedSaturate(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_packs_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> PackSignedSaturate(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_packus_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> PackUnsignedSaturate(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// ___m128i _mm_set_epi8 (char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0)
+ /// </summary>
+ public static Vector128<sbyte> Set(sbyte e15, sbyte e14, sbyte e13, sbyte e12, sbyte e11, sbyte e10, sbyte e9, sbyte e8, sbyte e7, sbyte e6, sbyte e5, sbyte e4, sbyte e3, sbyte e2, sbyte e1, sbyte e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// ___m128i _mm_set_epi8 (char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0)
+ /// </summary>
+ public static Vector128<byte> Set(byte e15, byte e14, byte e13, byte e12, byte e11, byte e10, byte e9, byte e8, byte e7, byte e6, byte e5, byte e4, byte e3, byte e2, byte e1, byte e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_set_epi16 (short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0)
+ /// </summary>
+ public static Vector128<short> Set(short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_set_epi16 (short e7, short e6, short e5, short e4, short e3, short e2, short e1, short e0)
+ /// </summary>
+ public static Vector128<ushort> Set(ushort e7, ushort e6, ushort e5, ushort e4, ushort e3, ushort e2, ushort e1, ushort e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_set_epi32 (int e3, int e2, int e1, int e0)
+ /// </summary>
+ public static Vector128<int> Set(int e3, int e2, int e1, int e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_set_epi32 (int e3, int e2, int e1, int e0)
+ /// </summary>
+ public static Vector128<uint> Set(uint e3, uint e2, uint e1, uint e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_set_epi64x (__int64 e1, __int64 e0)
+ /// </summary>
+ public static Vector128<long> Set(long e1, long e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_set_epi64x (__int64 e1, __int64 e0)
+ /// </summary>
+ public static Vector128<ulong> Set(ulong e1, ulong e0) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_set_pd (double e1, double e0)
+ /// </summary>
+ public static Vector128<double> Set(double e1, double e0) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_set1_epi8 (char a)
+ /// </summary>
+ public static Vector128<byte> Set1(byte value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_set1_epi8 (char a)
+ /// </summary>
+ public static Vector128<sbyte> Set1(sbyte value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_set1_epi16 (short a)
+ /// </summary>
+ public static Vector128<short> Set1(short value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_set1_epi16 (short a)
+ /// </summary>
+ public static Vector128<ushort> Set1(ushort value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_set1_epi32 (int a)
+ /// </summary>
+ public static Vector128<int> Set1(int value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_set1_epi32 (int a)
+ /// </summary>
+ public static Vector128<uint> Set1(uint value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_set1_epi64x (long long a)
+ /// </summary>
+ public static Vector128<long> Set1(long value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_set1_epi64x (long long a)
+ /// </summary>
+ public static Vector128<ulong> Set1(ulong value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_set1_pd (double a)
+ /// </summary>
+ public static Vector128<double> Set1(double value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_setzero_si128 ()
+ /// __m128d _mm_setzero_pd (void)
+ /// </summary>
+ public static Vector128<T> SetZero<T>() where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_sad_epu8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<long> SumAbsoluteDifferences(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_shuffle_epi32 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<int> Shuffle(Vector128<int> value, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_shuffle_epi32 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<uint> Shuffle(Vector128<uint> value, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_shuffle_pd (__m128d a, __m128d b, int immediate)
+ /// </summary>
+ public static Vector128<double> Shuffle(Vector128<double> left, Vector128<double> right, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_shufflehi_epi16 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<short> ShuffleHigh(Vector128<short> value, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_shufflehi_epi16 (__m128i a, int control)
+ /// </summary>
+ public static Vector128<ushort> ShuffleHigh(Vector128<ushort> value, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_shufflelo_epi16 (__m128i a, int control)
+ /// </summary>
+ public static Vector128<short> ShuffleLow(Vector128<short> value, byte control) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_shufflelo_epi16 (__m128i a, int control)
+ /// </summary>
+ public static Vector128<ushort> ShuffleLow(Vector128<ushort> value, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_slli_epi16 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<short> ShiftLeftLogical(Vector128<short> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_slli_epi16 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<ushort> ShiftLeftLogical(Vector128<ushort> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_slli_epi32 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<int> ShiftLeftLogical(Vector128<int> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_slli_epi32 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<uint> ShiftLeftLogical(Vector128<uint> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_slli_epi64 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<long> ShiftLeftLogical(Vector128<long> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_slli_epi64 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<ulong> ShiftLeftLogical(Vector128<ulong> value, byte count) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_bslli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<sbyte> ShiftLeftLogical128BitLane(Vector128<sbyte> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_bslli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<byte> ShiftLeftLogical128BitLane(Vector128<byte> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_bslli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<short> ShiftLeftLogical128BitLane(Vector128<short> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_bslli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<ushort> ShiftLeftLogical128BitLane(Vector128<ushort> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_bslli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<int> ShiftLeftLogical128BitLane(Vector128<int> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_bslli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<uint> ShiftLeftLogical128BitLane(Vector128<uint> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_bslli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<long> ShiftLeftLogical128BitLane(Vector128<long> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_bslli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<ulong> ShiftLeftLogical128BitLane(Vector128<ulong> value, byte numBytes) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_srai_epi16 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<short> ShiftRightArithmetic(Vector128<short> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_srai_epi32 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<int> ShiftRightArithmetic(Vector128<int> value, byte count) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_srli_epi16 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<short> ShiftRightLogical(Vector128<short> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_srli_epi16 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<ushort> ShiftRightLogical(Vector128<ushort> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_srli_epi32 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<int> ShiftRightLogical(Vector128<int> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_srli_epi32 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<uint> ShiftRightLogical(Vector128<uint> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_srli_epi64 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<long> ShiftRightLogical(Vector128<long> value, byte count) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_srli_epi64 (__m128i a, int immediate)
+ /// </summary>
+ public static Vector128<ulong> ShiftRightLogical(Vector128<ulong> value, byte count) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_bsrli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<sbyte> ShiftRightLogical128BitLane(Vector128<sbyte> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_bsrli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<byte> ShiftRightLogical128BitLane(Vector128<byte> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_bsrli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<short> ShiftRightLogical128BitLane(Vector128<short> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_bsrli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<ushort> ShiftRightLogical128BitLane(Vector128<ushort> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_bsrli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<int> ShiftRightLogical128BitLane(Vector128<int> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_bsrli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<uint> ShiftRightLogical128BitLane(Vector128<uint> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_bsrli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<long> ShiftRightLogical128BitLane(Vector128<long> value, byte numBytes) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_bsrli_si128 (__m128i a, int imm8)
+ /// </summary>
+ public static Vector128<ulong> ShiftRightLogical128BitLane(Vector128<ulong> value, byte numBytes) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_sqrt_pd (__m128d a)
+ /// </summary>
+ public static Vector128<double> Sqrt(Vector128<double> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm_store_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAligned(sbyte* address, Vector128<sbyte> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_store_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAligned(byte* address, Vector128<byte> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_store_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAligned(short* address, Vector128<short> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_store_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAligned(ushort* address, Vector128<ushort> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_store_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAligned(int* address, Vector128<int> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_store_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAligned(uint* address, Vector128<uint> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_store_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAligned(long* address, Vector128<long> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_store_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAligned(ulong* address, Vector128<ulong> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_store_pd (double* mem_addr, __m128d a)
+ /// </summary>
+ public static unsafe void StoreAligned(double* address, Vector128<double> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(sbyte* address, Vector128<sbyte> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(byte* address, Vector128<byte> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(short* address, Vector128<short> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(ushort* address, Vector128<ushort> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(int* address, Vector128<int> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(uint* address, Vector128<uint> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(long* address, Vector128<long> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_stream_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(ulong* address, Vector128<ulong> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_stream_pd (double* mem_addr, __m128d a)
+ /// </summary>
+ public static unsafe void StoreAlignedNonTemporal(double* address, Vector128<double> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void Store(sbyte* address, Vector128<sbyte> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void Store(byte* address, Vector128<byte> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void Store(short* address, Vector128<short> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void Store(ushort* address, Vector128<ushort> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void Store(int* address, Vector128<int> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void Store(uint* address, Vector128<uint> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void Store(long* address, Vector128<long> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_storeu_si128 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void Store(ulong* address, Vector128<ulong> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_storeu_pd (double* mem_addr, __m128d a)
+ /// </summary>
+ public static unsafe void Store(double* address, Vector128<double> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm_storeh_pd (double* mem_addr, __m128d a)
+ /// </summary>
+ public static unsafe void StoreHigh(double* address, Vector128<double> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// void _mm_storel_epi64 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreLow(long* address, Vector128<long> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_storel_epi64 (__m128i* mem_addr, __m128i a)
+ /// </summary>
+ public static unsafe void StoreLow(ulong* address, Vector128<ulong> source) { throw new NotImplementedException(); }
+ /// <summary>
+ /// void _mm_storel_pd (double* mem_addr, __m128d a)
+ /// </summary>
+ public static unsafe void StoreLow(double* address, Vector128<double> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_sub_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> Subtract(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_sub_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> Subtract(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_sub_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> Subtract(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_sub_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> Subtract(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_sub_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> Subtract(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_sub_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<uint> Subtract(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_sub_epi64 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<long> Subtract(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_sub_epi64 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ulong> Subtract(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_sub_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> Subtract(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_subs_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> SubtractSaturate(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_subs_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> SubtractSaturate(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_subs_epu8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> SubtractSaturate(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_subs_epu16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> SubtractSaturate(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_unpackhi_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> UnpackHigh(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_unpackhi_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> UnpackHigh(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_unpackhi_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> UnpackHigh(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_unpackhi_epi16 (__m128i a, __m128i b)
+ /// </summary
+ public static Vector128<ushort> UnpackHigh(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_unpackhi_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> UnpackHigh(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_unpackhi_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<uint> UnpackHigh(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_unpackhi_epi64 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<long> UnpackHigh(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_unpackhi_epi64 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ulong> UnpackHigh(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_unpackhi_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> UnpackHigh(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_unpacklo_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> UnpackLow(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_unpacklo_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> UnpackLow(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_unpacklo_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> UnpackLow(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_unpacklo_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> UnpackLow(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_unpacklo_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> UnpackLow(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_unpacklo_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<uint> UnpackLow(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_unpacklo_epi64 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<long> UnpackLow(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_unpacklo_epi64 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ulong> UnpackLow(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_unpacklo_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> UnpackLow(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_xor_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<byte> Xor(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_xor_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> Xor(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_xor_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> Xor(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_xor_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> Xor(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_xor_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> Xor(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_xor_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<uint> Xor(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_xor_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<long> Xor(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_xor_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ulong> Xor(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_xor_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> Xor(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse3.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse3.cs
new file mode 100644
index 0000000000..5e4ac9dd0e
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse3.cs
@@ -0,0 +1,78 @@
+// 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.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel SSE3 hardware instructions via intrinsics
+ /// </summary>
+ [CLSCompliant(false)]
+ public static class Sse3
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// __m128 _mm_addsub_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> AddSubtract(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_addsub_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> AddSubtract(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_hadd_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> HorizontalAdd(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_hadd_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> HorizontalAdd(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_hsub_ps (__m128 a, __m128 b)
+ /// </summary>
+ public static Vector128<float> HorizontalSubtract(Vector128<float> left, Vector128<float> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_hsub_pd (__m128d a, __m128d b)
+ /// </summary>
+ public static Vector128<double> HorizontalSubtract(Vector128<double> left, Vector128<double> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_loaddup_pd (double const* mem_addr)
+ /// </summary>
+ public static unsafe Vector128<double> LoadAndDuplicate(double* address) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_lddqu_si128 (__m128i const* mem_addr)
+ /// </summary>
+ public static unsafe Vector128<sbyte> LoadDqu(sbyte* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<byte> LoadDqu(byte* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<short> LoadDqu(short* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<ushort> LoadDqu(ushort* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<int> LoadDqu(int* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<uint> LoadDqu(uint* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<long> LoadDqu(long* address) { throw new NotImplementedException(); }
+ public static unsafe Vector128<ulong> LoadDqu(ulong* address) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_movedup_pd (__m128d a)
+ /// </summary>
+ public static Vector128<double> MoveAndDuplicate(Vector128<double> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_movehdup_ps (__m128 a)
+ /// </summary>
+ public static Vector128<float> MoveHighAndDuplicate(Vector128<float> source) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_moveldup_ps (__m128 a)
+ /// </summary>
+ public static Vector128<float> MoveLowAndDuplicate(Vector128<float> source) { throw new NotImplementedException(); }
+
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse41.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse41.cs
new file mode 100644
index 0000000000..5a498bcf4e
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse41.cs
@@ -0,0 +1,408 @@
+// 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.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel SSE4.1 hardware instructions via intrinsics
+ /// </summary>
+ [CLSCompliant(false)]
+ public static class Sse41
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<short> Blend(Vector128<short> left, Vector128<short> right, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<ushort> Blend(Vector128<ushort> left, Vector128<ushort> right, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_blend_ps (__m128 a, __m128 b, const int imm8)
+ /// </summary>
+ public static Vector128<float> Blend(Vector128<float> left, Vector128<float> right, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_blend_pd (__m128d a, __m128d b, const int imm8)
+ /// </summary>
+ public static Vector128<double> Blend(Vector128<double> left, Vector128<double> right, byte control) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
+ /// </summary>
+ public static Vector128<sbyte> BlendVariable(Vector128<sbyte> left, Vector128<sbyte> right, Vector128<sbyte> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
+ /// </summary>
+ public static Vector128<byte> BlendVariable(Vector128<byte> left, Vector128<byte> right, Vector128<byte> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128 _mm_blendv_ps (__m128 a, __m128 b, __m128 mask)
+ /// </summary>
+ public static Vector128<float> BlendVariable(Vector128<float> left, Vector128<float> right, Vector128<float> mask) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_blendv_pd (__m128d a, __m128d b, __m128d mask)
+ /// </summary>
+ public static Vector128<double> BlendVariable(Vector128<double> left, Vector128<double> right, Vector128<double> mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_ceil_ps (__m128 a)
+ /// </summary>
+ public static Vector128<float> Ceiling(Vector128<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_ceil_pd (__m128d a)
+ /// </summary>
+ public static Vector128<double> Ceiling(Vector128<double> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<long> CompareEqual(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ulong> CompareEqual(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cvtepi8_epi16 (__m128i a)
+ /// </summary>
+ public static Vector128<short> ConvertToShort(Vector128<sbyte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cvtepu8_epi16 (__m128i a)
+ /// </summary>
+ public static Vector128<short> ConvertToShort(Vector128<byte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cvtepi8_epi32 (__m128i a)
+ /// </summary>
+ public static Vector128<int> ConvertToInt(Vector128<sbyte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cvtepu8_epi32 (__m128i a)
+ /// </summary>
+ public static Vector128<int> ConvertToInt(Vector128<byte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cvtepi16_epi32 (__m128i a)
+ /// </summary>
+ public static Vector128<int> ConvertToInt(Vector128<short> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cvtepu16_epi32 (__m128i a)
+ /// </summary>
+ public static Vector128<int> ConvertToInt(Vector128<ushort> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cvtepi8_epi64 (__m128i a)
+ /// </summary>
+ public static Vector128<long> ConvertToLong(Vector128<sbyte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cvtepu8_epi64 (__m128i a)
+ /// </summary>
+ public static Vector128<long> ConvertToLong(Vector128<byte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cvtepi16_epi64 (__m128i a)
+ /// </summary>
+ public static Vector128<long> ConvertToLong(Vector128<short> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cvtepu16_epi64 (__m128i a)
+ /// </summary>
+ public static Vector128<long> ConvertToLong(Vector128<ushort> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cvtepi32_epi64 (__m128i a)
+ /// </summary>
+ public static Vector128<long> ConvertToLong(Vector128<int> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_cvtepu32_epi64 (__m128i a)
+ /// </summary>
+ public static Vector128<long> ConvertToLong(Vector128<uint> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_extract_epi8 (__m128i a, const int imm8)
+ /// </summary>
+ public static sbyte ExtractSbyte<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+ /// <summary>
+ /// int _mm_extract_epi8 (__m128i a, const int imm8)
+ /// </summary>
+ public static byte ExtractByte<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_extract_epi32 (__m128i a, const int imm8)
+ /// </summary>
+ public static int ExtractInt<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_extract_epi32 (__m128i a, const int imm8)
+ /// </summary>
+ public static uint ExtractUint<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __int64 _mm_extract_epi64 (__m128i a, const int imm8)
+ /// </summary>
+ public static long ExtractLong<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __int64 _mm_extract_epi64 (__m128i a, const int imm8)
+ /// </summary>
+ public static ulong ExtractUlong<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_extract_ps (__m128 a, const int imm8)
+ /// </summary>
+ public static float ExtractFloat<T>(Vector128<T> value, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_floor_ps (__m128 a)
+ /// </summary>
+ public static Vector128<float> Floor(Vector128<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128d _mm_floor_pd (__m128d a)
+ /// </summary>
+ public static Vector128<double> Floor(Vector128<double> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8)
+ /// </summary>
+ public static Vector128<T> InsertSbyte<T>(Vector128<T> value, sbyte data, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8)
+ /// </summary>
+ public static Vector128<T> InsertByte<T>(Vector128<T> value, byte data, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8)
+ /// </summary>
+ public static Vector128<T> InsertInt<T>(Vector128<T> value, int data, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8)
+ /// </summary>
+ public static Vector128<T> InsertUint<T>(Vector128<T> value, uint data, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8)
+ /// </summary>
+ public static Vector128<T> InsertLong<T>(Vector128<T> value, long data, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8)
+ /// </summary>
+ public static Vector128<T> InsertUlong<T>(Vector128<T> value, ulong data, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_insert_ps (__m128 a, __m128 b, const int imm8)
+ /// </summary>
+ public static Vector128<T> InsertFloat<T>(Vector128<T> value, float data, byte index) where T : struct { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_max_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> Max(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_max_epu16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> Max(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_max_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> Max(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_max_epu32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<uint> Max(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_min_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> Min(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_min_epu16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> Min(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_min_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> Min(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_min_epu32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<uint> Min(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_minpos_epu16 (__m128i a)
+ /// </summary>
+ public static Vector128<ushort> MinHorizontal(Vector128<ushort> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_mpsadbw_epu8 (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<ushort> MultipleSumAbsoluteDifferences(Vector128<byte> left, Vector128<byte> right, byte mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_mul_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<long> Multiply(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_mullo_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> MultiplyLow(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_packus_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<ushort> PackUnsignedSaturate(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128 _mm_round_ps (__m128 a, int rounding)
+ /// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector128<float> RoundToNearestInteger(Vector128<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector128<float> RoundToNegativeInfinity(Vector128<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector128<float> RoundToPositiveInfinity(Vector128<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector128<float> RoundToZero(Vector128<float> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_CUR_DIRECTION
+ /// </summary>
+ public static Vector128<float> RoundCurrentDirection(Vector128<float> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128d _mm_round_pd (__m128d a, int rounding)
+ /// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector128<double> RoundToNearestInteger(Vector128<double> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector128<double> RoundToNegativeInfinity(Vector128<double> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector128<double> RoundToPositiveInfinity(Vector128<double> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC
+ /// </summary>
+ public static Vector128<double> RoundToZero(Vector128<double> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// _MM_FROUND_CUR_DIRECTION
+ /// </summary>
+ public static Vector128<double> RoundCurrentDirection(Vector128<double> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
+ /// </summary>
+ public static unsafe Vector128<sbyte> LoadAlignedNonTemporal(sbyte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
+ /// </summary>
+ public static unsafe Vector128<byte> LoadAlignedNonTemporal(byte* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
+ /// </summary>
+ public static unsafe Vector128<short> LoadAlignedNonTemporal(short* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
+ /// </summary>
+ public static unsafe Vector128<ushort> LoadAlignedNonTemporal(ushort* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
+ /// </summary>
+ public static unsafe Vector128<int> LoadAlignedNonTemporal(int* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
+ /// </summary>
+ public static unsafe Vector128<uint> LoadAlignedNonTemporal(uint* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
+ /// </summary>
+ public static unsafe Vector128<long> LoadAlignedNonTemporal(long* address) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
+ /// </summary>
+ public static unsafe Vector128<ulong> LoadAlignedNonTemporal(ulong* address) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_test_all_ones (__m128i a)
+ /// </summary>
+ public static bool TestAllOnes(Vector128<sbyte> value) { throw new NotImplementedException(); }
+ public static bool TestAllOnes(Vector128<byte> value) { throw new NotImplementedException(); }
+ public static bool TestAllOnes(Vector128<short> value) { throw new NotImplementedException(); }
+ public static bool TestAllOnes(Vector128<ushort> value) { throw new NotImplementedException(); }
+ public static bool TestAllOnes(Vector128<int> value) { throw new NotImplementedException(); }
+ public static bool TestAllOnes(Vector128<uint> value) { throw new NotImplementedException(); }
+ public static bool TestAllOnes(Vector128<long> value) { throw new NotImplementedException(); }
+ public static bool TestAllOnes(Vector128<ulong> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_test_all_zeros (__m128i a, __m128i mask)
+ /// </summary>
+ public static bool TestAllZeros(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static bool TestAllZeros(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static bool TestAllZeros(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static bool TestAllZeros(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static bool TestAllZeros(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static bool TestAllZeros(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static bool TestAllZeros(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ public static bool TestAllZeros(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_testc_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static bool TestC(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static bool TestC(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static bool TestC(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static bool TestC(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static bool TestC(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static bool TestC(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static bool TestC(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ public static bool TestC(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_test_mix_ones_zeros (__m128i a, __m128i mask)
+ /// </summary>
+ public static bool TestMixOnesZeros(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static bool TestMixOnesZeros(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static bool TestMixOnesZeros(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static bool TestMixOnesZeros(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static bool TestMixOnesZeros(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static bool TestMixOnesZeros(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static bool TestMixOnesZeros(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ public static bool TestMixOnesZeros(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_testnzc_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static bool TestNotZAndNotC(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static bool TestNotZAndNotC(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static bool TestNotZAndNotC(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static bool TestNotZAndNotC(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static bool TestNotZAndNotC(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static bool TestNotZAndNotC(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static bool TestNotZAndNotC(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ public static bool TestNotZAndNotC(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_testz_si128 (__m128i a, __m128i b)
+ /// </summary>
+ public static bool TestZ(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ public static bool TestZ(Vector128<byte> left, Vector128<byte> right) { throw new NotImplementedException(); }
+ public static bool TestZ(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ public static bool TestZ(Vector128<ushort> left, Vector128<ushort> right) { throw new NotImplementedException(); }
+ public static bool TestZ(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ public static bool TestZ(Vector128<uint> left, Vector128<uint> right) { throw new NotImplementedException(); }
+ public static bool TestZ(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+ public static bool TestZ(Vector128<ulong> left, Vector128<ulong> right) { throw new NotImplementedException(); }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse42.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse42.cs
new file mode 100644
index 0000000000..f644577ae1
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Sse42.cs
@@ -0,0 +1,233 @@
+// 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.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel SSE4.2 hardware instructions via intrinsics
+ /// </summary>
+ [CLSCompliant(false)]
+ public static class Sse42
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static bool CompareImplicitLength(Vector128<sbyte> left, Vector128<sbyte> right, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static bool CompareImplicitLength(Vector128<byte> left, Vector128<byte> right, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static bool CompareImplicitLength(Vector128<short> left, Vector128<short> right, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+
+ /// <summary>
+ /// int _mm_cmpistra (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistrc (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistro (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistrs (__m128i a, __m128i b, const int imm8)
+ /// int _mm_cmpistrz (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static bool CompareImplicitLength(Vector128<ushort> left, Vector128<ushort> right, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static bool CompareExplicitLength(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static bool CompareExplicitLength(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static bool CompareExplicitLength(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_cmpestra (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestrc (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestro (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestrs (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// int _mm_cmpestrz (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static bool CompareExplicitLength(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, ResultsFlag flag, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static int CompareImplicitLengthIndex(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static int CompareImplicitLengthIndex(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static int CompareImplicitLengthIndex(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_cmpistri (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static int CompareImplicitLengthIndex(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static int CompareExplicitLengthIndex(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static int CompareExplicitLengthIndex(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static int CompareExplicitLengthIndex(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// int _mm_cmpestri (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static int CompareExplicitLengthIndex(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<ushort> CompareImplicitLengthBitMask(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<ushort> CompareImplicitLengthBitMask(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<byte> CompareImplicitLengthBitMask(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<byte> CompareImplicitLengthBitMask(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<byte> CompareImplicitLengthUnitMask(Vector128<sbyte> left, Vector128<sbyte> right, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<byte> CompareImplicitLengthUnitMask(Vector128<byte> left, Vector128<byte> right, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<ushort> CompareImplicitLengthUnitMask(Vector128<short> left, Vector128<short> right, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpistrm (__m128i a, __m128i b, const int imm8)
+ /// </summary>
+ public static Vector128<ushort> CompareImplicitLengthUnitMask(Vector128<ushort> left, Vector128<ushort> right, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static Vector128<ushort> CompareExplicitLengthBitMask(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static Vector128<ushort> CompareExplicitLengthBitMask(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static Vector128<byte> CompareExplicitLengthBitMask(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static Vector128<byte> CompareExplicitLengthBitMask(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static Vector128<byte> CompareExplicitLengthUnitMask(Vector128<sbyte> left, byte leftLength, Vector128<sbyte> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static Vector128<byte> CompareExplicitLengthUnitMask(Vector128<byte> left, byte leftLength, Vector128<byte> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static Vector128<ushort> CompareExplicitLengthUnitMask(Vector128<short> left, byte leftLength, Vector128<short> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpestrm (__m128i a, int la, __m128i b, int lb, const int imm8)
+ /// </summary>
+ public static Vector128<ushort> CompareExplicitLengthUnitMask(Vector128<ushort> left, byte leftLength, Vector128<ushort> right, byte rightLength, StringComparisonMode mode) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_cmpgt_epi64 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<long> CompareGreaterThan(Vector128<long> left, Vector128<long> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// unsigned int _mm_crc32_u8 (unsigned int crc, unsigned char v)
+ /// </summary>
+ public static uint Crc32(uint crc, byte data) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned int _mm_crc32_u16 (unsigned int crc, unsigned short v)
+ /// </summary>
+ public static uint Crc32(uint crc, ushort data) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned int _mm_crc32_u32 (unsigned int crc, unsigned int v)
+ /// </summary>
+ public static uint Crc32(uint crc, uint data) { throw new NotImplementedException(); }
+ /// <summary>
+ /// unsigned __int64 _mm_crc32_u64 (unsigned __int64 crc, unsigned __int64 v)
+ /// </summary>
+ public static ulong Crc32(ulong crc, ulong data) { throw new NotImplementedException(); }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/Intrinsics/X86/Ssse3.cs b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Ssse3.cs
new file mode 100644
index 0000000000..0ce9036a8f
--- /dev/null
+++ b/src/mscorlib/src/System/Runtime/Intrinsics/X86/Ssse3.cs
@@ -0,0 +1,92 @@
+// 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.Intrinsics;
+
+namespace System.Runtime.Intrinsics.X86
+{
+ /// <summary>
+ /// This class provides access to Intel SSSE3 hardware instructions via intrinsics
+ /// </summary>
+ [CLSCompliant(false)]
+ public static class Ssse3
+ {
+ public static bool IsSupported { get { return false; } }
+
+ /// <summary>
+ /// __m128i _mm_abs_epi8 (__m128i a)
+ /// </summary>
+ public static Vector128<byte> Abs(Vector128<sbyte> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_abs_epi16 (__m128i a)
+ /// </summary>
+ public static Vector128<ushort> Abs(Vector128<short> value) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_abs_epi32 (__m128i a)
+ /// </summary>
+ public static Vector128<uint> Abs(Vector128<int> value) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_alignr_epi8 (__m128i a, __m128i b, int count)
+ /// </summary>
+ public static Vector128<sbyte> AlignRight(Vector128<sbyte> left, Vector128<sbyte> right, byte mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_hadd_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> HorizontalAdd(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_hadd_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> HorizontalAdd(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_hadds_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> HorizontalAddSaturate(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_hsub_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> HorizontalSubtract(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_hsub_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> HorizontalSubtract(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_hsubs_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> HorizontalSubtractSaturate(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_maddubs_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> MultiplyAddAdjacent(Vector128<byte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_mulhrs_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> MultiplyHighRoundScale(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_shuffle_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> Shuffle(Vector128<sbyte> value, Vector128<sbyte> mask) { throw new NotImplementedException(); }
+
+ /// <summary>
+ /// __m128i _mm_sign_epi8 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<sbyte> Sign(Vector128<sbyte> left, Vector128<sbyte> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_sign_epi16 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<short> Sign(Vector128<short> left, Vector128<short> right) { throw new NotImplementedException(); }
+ /// <summary>
+ /// __m128i _mm_sign_epi32 (__m128i a, __m128i b)
+ /// </summary>
+ public static Vector128<int> Sign(Vector128<int> left, Vector128<int> right) { throw new NotImplementedException(); }
+ }
+}
diff --git a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs
index f9f87bc928..4b96836daf 100644
--- a/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs
+++ b/src/mscorlib/src/System/Runtime/MemoryFailPoint.cs
@@ -241,24 +241,20 @@ namespace System.Runtime
// Attempt to grow the OS's page file. Note that we ignore
// any allocation routines from the host intentionally.
RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- }
- finally
+
+ // This shouldn't overflow due to the if clauses above.
+ UIntPtr numBytes = new UIntPtr(segmentSize);
+ unsafe
{
- // This shouldn't overflow due to the if clauses above.
- UIntPtr numBytes = new UIntPtr(segmentSize);
- unsafe
+ void* pMemory = Win32Native.VirtualAlloc(null, numBytes, Win32Native.MEM_COMMIT, Win32Native.PAGE_READWRITE);
+ if (pMemory != null)
{
- void* pMemory = Win32Native.VirtualAlloc(null, numBytes, Win32Native.MEM_COMMIT, Win32Native.PAGE_READWRITE);
- if (pMemory != null)
- {
- bool r = Win32Native.VirtualFree(pMemory, UIntPtr.Zero, Win32Native.MEM_RELEASE);
- if (!r)
- __Error.WinIOError();
- }
+ bool r = Win32Native.VirtualFree(pMemory, UIntPtr.Zero, Win32Native.MEM_RELEASE);
+ if (!r)
+ throw Win32Marshal.GetExceptionForLastWin32Error();
}
}
+
continue;
case 2:
@@ -304,14 +300,9 @@ namespace System.Runtime
CheckForFreeAddressSpace(segmentSize, true);
RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- }
- finally
- {
- SharedStatics.AddMemoryFailPointReservation((long)size);
- _mustSubtractReservation = true;
- }
+
+ SharedStatics.AddMemoryFailPointReservation((long)size);
+ _mustSubtractReservation = true;
#endif
}
@@ -321,7 +312,7 @@ namespace System.Runtime
Win32Native.MEMORYSTATUSEX memory = new Win32Native.MEMORYSTATUSEX();
r = Win32Native.GlobalMemoryStatusEx(ref memory);
if (!r)
- __Error.WinIOError();
+ throw Win32Marshal.GetExceptionForLastWin32Error();
availPageFile = memory.availPageFile;
totalAddressSpaceFree = memory.availVirtual;
//Console.WriteLine("Memory gate: Mem load: {0}% Available memory (physical + page file): {1} MB Total free address space: {2} MB GC Heap: {3} MB", memory.memoryLoad, memory.availPageFile >> 20, memory.availVirtual >> 20, GC.GetTotalMemory(true) >> 20);
@@ -370,7 +361,7 @@ namespace System.Runtime
{
UIntPtr r = Win32Native.VirtualQuery(address, ref memInfo, sizeOfMemInfo);
if (r == UIntPtr.Zero)
- __Error.WinIOError();
+ throw Win32Marshal.GetExceptionForLastWin32Error();
ulong regionSize = memInfo.RegionSize.ToUInt64();
if (memInfo.State == Win32Native.MEM_FREE)
@@ -414,14 +405,9 @@ namespace System.Runtime
if (_mustSubtractReservation)
{
RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- }
- finally
- {
- SharedStatics.AddMemoryFailPointReservation(-((long)_reservedMemory));
- _mustSubtractReservation = false;
- }
+
+ SharedStatics.AddMemoryFailPointReservation(-((long)_reservedMemory));
+ _mustSubtractReservation = false;
}
/*
diff --git a/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs b/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs
index 6d6d6f3e77..cbb9562148 100644
--- a/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs
+++ b/src/mscorlib/src/System/Runtime/Reliability/CriticalFinalizerObject.cs
@@ -11,7 +11,6 @@
** (i.e. the finalizer is guaranteed to run, won't be aborted by the host and is
** run after the finalizers of other objects collected at the same time).
**
-** You must possess UnmanagedCode permission in order to derive from this class.
**
**
===========================================================*/
diff --git a/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs b/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs
deleted file mode 100644
index 6594562b97..0000000000
--- a/src/mscorlib/src/System/Runtime/Reliability/PrePrepareMethodAttribute.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-// 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: Serves as a hint to ngen that the decorated method
-** (and its statically determinable call graph) should be
-** prepared (as for Constrained Execution Region use). This
-** is primarily useful in the scenario where the method in
-** question will be prepared explicitly at runtime and the
-** author of the method knows this and wishes to avoid the
-** overhead of runtime preparation.
-**
-**
-===========================================================*/
-
-using System;
-using System.Runtime.InteropServices;
-
-namespace System.Runtime.ConstrainedExecution
-{
- [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
-
- internal sealed class PrePrepareMethodAttribute : Attribute
- {
- public PrePrepareMethodAttribute()
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/RuntimeHandles.cs b/src/mscorlib/src/System/RuntimeHandles.cs
index fca37dd868..20783ef467 100644
--- a/src/mscorlib/src/System/RuntimeHandles.cs
+++ b/src/mscorlib/src/System/RuntimeHandles.cs
@@ -220,7 +220,7 @@ namespace System
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern Object CreateInstance(RuntimeType type, bool publicOnly, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor);
+ internal static extern Object CreateInstance(RuntimeType type, bool publicOnly, bool wrapExceptions, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object CreateCaInstance(RuntimeType type, IRuntimeMethodInfo ctor);
@@ -377,6 +377,9 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsInterface(RuntimeType type);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ internal extern static bool IsByRefLike(RuntimeType type);
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
@@ -909,7 +912,7 @@ namespace System
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal extern static object InvokeMethod(object target, object[] arguments, Signature sig, bool constructor);
+ internal extern static object InvokeMethod(object target, object[] arguments, Signature sig, bool constructor, bool wrapExceptions);
#region Private Invocation Helpers
internal static INVOCATION_FLAGS GetSecurityFlags(IRuntimeMethodInfo handle)
@@ -975,7 +978,6 @@ namespace System
return fRet;
}
-
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal extern static bool IsTypicalMethodDefinition(IRuntimeMethodInfo method);
@@ -991,6 +993,11 @@ namespace System
return method;
}
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ private extern static int GetGenericParameterCount(RuntimeMethodHandleInternal method);
+
+ internal static int GetGenericParameterCount(IRuntimeMethodInfo method) => GetGenericParameterCount(method.Value);
+
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private extern static void StripMethodInstantiation(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod);
diff --git a/src/mscorlib/src/System/SerializableAttribute.cs b/src/mscorlib/src/System/SerializableAttribute.cs
deleted file mode 100644
index 266e73d78d..0000000000
--- a/src/mscorlib/src/System/SerializableAttribute.cs
+++ /dev/null
@@ -1,35 +0,0 @@
-// 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: Used to mark a class as being serializable
-**
-**
-============================================================*/
-
-using System;
-using System.Reflection;
-
-namespace System
-{
- [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Delegate, Inherited = false)]
- public sealed class SerializableAttribute : Attribute
- {
- internal static Attribute GetCustomAttribute(RuntimeType type)
- {
- return (type.Attributes & TypeAttributes.Serializable) == TypeAttributes.Serializable ? new SerializableAttribute() : null;
- }
- internal static bool IsDefined(RuntimeType type)
- {
- return type.IsSerializable;
- }
-
- public SerializableAttribute()
- {
- }
- }
-}
diff --git a/src/mscorlib/src/System/String.Comparison.cs b/src/mscorlib/src/System/String.Comparison.cs
index 7316322bed..afdcddfe2f 100644
--- a/src/mscorlib/src/System/String.Comparison.cs
+++ b/src/mscorlib/src/System/String.Comparison.cs
@@ -44,7 +44,7 @@ namespace System
//Return the (case-insensitive) difference between them.
if (charA != charB)
- goto ReturnCharAMinusCharB; // TODO: Workaround for https://github.com/dotnet/coreclr/issues/9692
+ return charA - charB;
// Next char
a++; b++;
@@ -52,9 +52,6 @@ namespace System
}
return strA.Length - strB.Length;
-
- ReturnCharAMinusCharB:
- return charA - charB;
}
}
@@ -168,14 +165,11 @@ namespace System
}
else
{
- goto ReturnFalse;
+ return false;
}
}
return true;
-
- ReturnFalse:
- return false;
}
}
@@ -745,7 +739,7 @@ namespace System
return string.Compare(this, strB, StringComparison.CurrentCulture);
}
- // Determines whether a specified string is a suffix of the the current instance.
+ // Determines whether a specified string is a suffix of the current instance.
//
// The case-sensitive and culture-sensitive option is set by options,
// and the default culture is used.
@@ -1008,34 +1002,14 @@ namespace System
return !String.Equals(a, b);
}
-#if FEATURE_RANDOMIZED_STRING_HASHING
- // Do not remove!
- // This method is called by reflection in System.Xml
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- internal static extern int InternalMarvin32HashString(string s, int strLen, long additionalEntropy);
-
- internal static bool UseRandomizedHashing()
- {
- return InternalUseRandomizedHashing();
- }
-
- [System.Security.SuppressUnmanagedCodeSecurity]
- [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
- private static extern bool InternalUseRandomizedHashing();
-#endif
+ private static extern int InternalMarvin32HashString(string s);
// Gets a hash code for this string. If strings A and B are such that A.Equals(B), then
// they will return the same hash code.
public override int GetHashCode()
{
-#if FEATURE_RANDOMIZED_STRING_HASHING
- if (HashHelpers.s_UseRandomizedStringHashing)
- {
- return InternalMarvin32HashString(this, this.Length, 0);
- }
-#endif // FEATURE_RANDOMIZED_STRING_HASHING
-
- return GetLegacyNonRandomizedHashCode();
+ return InternalMarvin32HashString(this);
}
// Gets a hash code for this string and this comparison. If strings A and B and comparition C are such
diff --git a/src/mscorlib/src/System/String.Searching.cs b/src/mscorlib/src/System/String.Searching.cs
index 22e2a808b1..02e800427b 100644
--- a/src/mscorlib/src/System/String.Searching.cs
+++ b/src/mscorlib/src/System/String.Searching.cs
@@ -96,8 +96,97 @@ namespace System
}
[Pure]
+ public int IndexOfAny(char[] anyOf, int startIndex, int count)
+ {
+ if (anyOf == null)
+ {
+ throw new ArgumentNullException(nameof(anyOf));
+ }
+
+ if ((uint)startIndex > (uint)Length)
+ {
+ throw new ArgumentOutOfRangeException(nameof(startIndex), SR.ArgumentOutOfRange_Index);
+ }
+
+ if ((uint)count > (uint)(Length - startIndex))
+ {
+ throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_Count);
+ }
+
+ if (anyOf.Length == 2)
+ {
+ // Very common optimization for directory separators (/, \), quotes (", '), brackets, etc
+ return IndexOfAny(anyOf[0], anyOf[1], startIndex, count);
+ }
+ else if (anyOf.Length == 3)
+ {
+ return IndexOfAny(anyOf[0], anyOf[1], anyOf[2], startIndex, count);
+ }
+ else if (anyOf.Length > 3)
+ {
+ return IndexOfCharArray(anyOf, startIndex, count);
+ }
+ else if (anyOf.Length == 1)
+ {
+ return IndexOf(anyOf[0], startIndex, count);
+ }
+ else // anyOf.Length == 0
+ {
+ return -1;
+ }
+ }
+
+ private unsafe int IndexOfAny(char value1, char value2, int startIndex, int count)
+ {
+ fixed (char* pChars = &_firstChar)
+ {
+ char* pCh = pChars + startIndex;
+
+ while (count > 0)
+ {
+ char c = *pCh;
+
+ if (c == value1 || c == value2)
+ return (int)(pCh - pChars);
+
+ // Possibly reads outside of count and can include null terminator
+ // Handled in the return logic
+ c = *(pCh + 1);
+
+ if (c == value1 || c == value2)
+ return (count == 1 ? -1 : (int)(pCh - pChars) + 1);
+
+ pCh += 2;
+ count -= 2;
+ }
+
+ return -1;
+ }
+ }
+
+ private unsafe int IndexOfAny(char value1, char value2, char value3, int startIndex, int count)
+ {
+ fixed (char* pChars = &_firstChar)
+ {
+ char* pCh = pChars + startIndex;
+
+ while (count > 0)
+ {
+ char c = *pCh;
+
+ if (c == value1 || c == value2 || c == value3)
+ return (int)(pCh - pChars);
+
+ pCh++;
+ count--;
+ }
+
+ return -1;
+ }
+ }
+
[MethodImplAttribute(MethodImplOptions.InternalCall)]
- public extern int IndexOfAny(char[] anyOf, int startIndex, int count);
+ private extern int IndexOfCharArray(char[] anyOf, int startIndex, int count);
// Determines the position within this string of the first occurrence of the specified
diff --git a/src/mscorlib/src/System/String.cs b/src/mscorlib/src/System/String.cs
index a34ea21423..c74abe9903 100644
--- a/src/mscorlib/src/System/String.cs
+++ b/src/mscorlib/src/System/String.cs
@@ -16,6 +16,7 @@ namespace System
{
using System.Text;
using System;
+ using System.Buffers;
using System.Runtime;
using System.Runtime.ConstrainedExecution;
using System.Globalization;
@@ -666,6 +667,45 @@ namespace System
[MethodImplAttribute(MethodImplOptions.InternalCall)]
public extern String(char c, int count);
+ [MethodImplAttribute(MethodImplOptions.InternalCall)]
+ public extern String(ReadOnlySpan<char> value);
+
+ private unsafe string CtorReadOnlySpanOfChar(ReadOnlySpan<char> value)
+ {
+ if (value.Length == 0)
+ {
+ return Empty;
+ }
+
+ string result = FastAllocateString(value.Length);
+ fixed (char* dest = &result._firstChar, src = &value.DangerousGetPinnableReference())
+ {
+ wstrcpy(dest, src, value.Length);
+ }
+ return result;
+ }
+
+ public static string Create<TState>(int length, TState state, SpanAction<char, TState> action)
+ {
+ if (action == null)
+ {
+ throw new ArgumentNullException(nameof(action));
+ }
+
+ if (length > 0)
+ {
+ string result = FastAllocateString(length);
+ action(new Span<char>(ref result.GetRawStringData(), length), state);
+ return result;
+ }
+
+ if (length == 0)
+ {
+ return Empty;
+ }
+
+ throw new ArgumentOutOfRangeException(nameof(length));
+ }
// Returns this string.
public override String ToString()
diff --git a/src/mscorlib/src/System/Threading/CancellationToken.cs b/src/mscorlib/src/System/Threading/CancellationToken.cs
index 17847f7eb9..4d86881267 100644
--- a/src/mscorlib/src/System/Threading/CancellationToken.cs
+++ b/src/mscorlib/src/System/Threading/CancellationToken.cs
@@ -52,7 +52,7 @@ namespace System.Threading
/// <remarks>
/// <para>
/// This property indicates whether cancellation has been requested for this token,
- /// either through the token initially being construted in a canceled state, or through
+ /// either through the token initially being constructed in a canceled state, or through
/// calling <see cref="System.Threading.CancellationTokenSource.Cancel()">Cancel</see>
/// on the token's associated <see cref="CancellationTokenSource"/>.
/// </para>
diff --git a/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs b/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs
index c09f175a36..e0a52581f6 100644
--- a/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs
+++ b/src/mscorlib/src/System/Threading/CancellationTokenRegistration.cs
@@ -36,6 +36,23 @@ namespace System.Threading
}
}
+ /// <summary>
+ /// Gets the <see cref="CancellationToken"/> with which this registration is associated. If the
+ /// registration isn't associated with a token (such as after the registration has been disposed),
+ /// this will return a default token.
+ /// </summary>
+ internal CancellationToken Token => _node?.Partition.Source.Token ?? default(CancellationToken);
+
+ /// <summary>
+ /// Disposes of the registration and unregisters the target callback from the associated
+ /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see>.
+ /// </summary>
+ internal bool TryDeregister() // corefx currently has an InternalsVisibleTo dependency on this
+ {
+ CancellationTokenSource.CallbackNode node = _node;
+ return node != null && node.Partition.Unregister(_id, node);
+ }
+
private void WaitForCallbackIfNecessary()
{
// We're a valid registration but we were unable to unregister, which means the callback wasn't in the list,
diff --git a/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Windows.cs b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Windows.cs
index 21c1c5f4a4..a40661c1b6 100644
--- a/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Windows.cs
+++ b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.Windows.cs
@@ -2,6 +2,7 @@
// 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;
@@ -27,10 +28,10 @@ namespace System.Threading
// We do not let either of these leak and convert them to ArgumentException to
// indicate that the specified handles are invalid.
- if (ex.HResult == System.HResults.E_HANDLE) // Bad handle
+ if (ex.HResult == HResults.E_HANDLE) // Bad handle
throw new ArgumentException(SR.Argument_InvalidHandle, nameof(handle));
- if (ex.HResult == System.HResults.E_INVALIDARG) // Handle already bound or sync handle
+ if (ex.HResult == HResults.E_INVALIDARG) // Handle already bound or sync handle
throw new ArgumentException(SR.Argument_AlreadyBoundOrSyncHandle, nameof(handle));
throw;
diff --git a/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs
index a4a3b980cf..5e0f2affc4 100644
--- a/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs
+++ b/src/mscorlib/src/System/Threading/ClrThreadPoolBoundHandle.cs
@@ -243,7 +243,7 @@ namespace System.Threading
/// </summary>
/// <param name="overlapped">
/// An unmanaged pointer to the <see cref="NativeOverlapped"/> structure from which to return the
- /// asscociated user-provided object.
+ /// associated user-provided object.
/// </param>
/// <returns>
/// A user-provided object that distinguishes this <see cref="NativeOverlapped"/>
diff --git a/src/mscorlib/src/System/Threading/EventWaitHandle.cs b/src/mscorlib/src/System/Threading/EventWaitHandle.cs
index e910984439..cfb9c28415 100644
--- a/src/mscorlib/src/System/Threading/EventWaitHandle.cs
+++ b/src/mscorlib/src/System/Threading/EventWaitHandle.cs
@@ -83,7 +83,7 @@ namespace System.Threading
if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
- __Error.WinIOError(errorCode, name);
+ throw Win32Marshal.GetExceptionForWin32Error(errorCode, name);
}
SetHandleInternal(_handle);
}
@@ -132,7 +132,7 @@ namespace System.Threading
if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
- __Error.WinIOError(errorCode, name);
+ throw Win32Marshal.GetExceptionForWin32Error(errorCode, name);
}
createdNew = errorCode != Win32Native.ERROR_ALREADY_EXISTS;
SetHandleInternal(_handle);
@@ -160,8 +160,7 @@ namespace System.Threading
throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
case OpenExistingResult.PathNotFound:
- __Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, "");
- return result; //never executes
+ throw Win32Marshal.GetExceptionForWin32Error(Win32Native.ERROR_PATH_NOT_FOUND, "");
default:
return result;
@@ -210,7 +209,7 @@ namespace System.Threading
if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
return OpenExistingResult.NameInvalid;
//this is for passed through Win32Native Errors
- __Error.WinIOError(errorCode, "");
+ throw Win32Marshal.GetExceptionForWin32Error(errorCode, "");
}
result = new EventWaitHandle(myHandle);
return OpenExistingResult.Success;
@@ -220,7 +219,7 @@ namespace System.Threading
{
bool res = Win32Native.ResetEvent(safeWaitHandle);
if (!res)
- __Error.WinIOError();
+ throw Win32Marshal.GetExceptionForLastWin32Error();
return res;
}
public bool Set()
@@ -228,7 +227,7 @@ namespace System.Threading
bool res = Win32Native.SetEvent(safeWaitHandle);
if (!res)
- __Error.WinIOError();
+ throw Win32Marshal.GetExceptionForLastWin32Error();
return res;
}
diff --git a/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs b/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs
index 402a76cdc7..0807e19301 100644
--- a/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs
+++ b/src/mscorlib/src/System/Threading/ManualResetEventSlim.cs
@@ -12,9 +12,6 @@
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-using System;
-using System.Threading;
-using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Diagnostics.Contracts;
@@ -48,7 +45,6 @@ namespace System.Threading
{
// These are the default spin counts we use on single-proc and MP machines.
private const int DEFAULT_SPIN_SP = 1;
- private const int DEFAULT_SPIN_MP = SpinWait.YIELD_THRESHOLD;
private volatile object m_lock;
// A lock used for waiting and pulsing. Lazily initialized via EnsureLockObjectCreated()
@@ -185,7 +181,7 @@ namespace System.Threading
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
- /// class with a Boolen value indicating whether to set the intial state to signaled.
+ /// class with a boolean value indicating whether to set the initial state to signaled.
/// </summary>
/// <param name="initialState">true to set the initial state signaled; false to set the initial state
/// to nonsignaled.</param>
@@ -193,12 +189,12 @@ namespace System.Threading
{
// Specify the defualt spin count, and use default spin if we're
// on a multi-processor machine. Otherwise, we won't.
- Initialize(initialState, DEFAULT_SPIN_MP);
+ Initialize(initialState, SpinWait.SpinCountforSpinBeforeWait);
}
/// <summary>
/// Initializes a new instance of the <see cref="ManualResetEventSlim"/>
- /// class with a Boolen value indicating whether to set the intial state to signaled and a specified
+ /// class with a Boolean value indicating whether to set the initial state to signaled and a specified
/// spin count.
/// </summary>
/// <param name="initialState">true to set the initial state to signaled; false to set the initial state
@@ -563,44 +559,19 @@ namespace System.Threading
bNeedTimeoutAdjustment = true;
}
- //spin
- int HOW_MANY_SPIN_BEFORE_YIELD = 10;
- int HOW_MANY_YIELD_EVERY_SLEEP_0 = 5;
- int HOW_MANY_YIELD_EVERY_SLEEP_1 = 20;
-
+ // Spin
int spinCount = SpinCount;
- for (int i = 0; i < spinCount; i++)
+ var spinner = new SpinWait();
+ while (spinner.Count < spinCount)
{
+ spinner.SpinOnce(SpinWait.Sleep1ThresholdForSpinBeforeWait);
+
if (IsSet)
{
return true;
}
- else if (i < HOW_MANY_SPIN_BEFORE_YIELD)
- {
- if (i == HOW_MANY_SPIN_BEFORE_YIELD / 2)
- {
- Thread.Yield();
- }
- else
- {
- Thread.SpinWait(PlatformHelper.ProcessorCount * (4 << i));
- }
- }
- else if (i % HOW_MANY_YIELD_EVERY_SLEEP_1 == 0)
- {
- Thread.Sleep(1);
- }
- else if (i % HOW_MANY_YIELD_EVERY_SLEEP_0 == 0)
- {
- Thread.Sleep(0);
- }
- else
- {
- Thread.Yield();
- }
-
- if (i >= 100 && i % 10 == 0) // check the cancellation token if the user passed a very large spin count
+ if (spinner.Count >= 100 && spinner.Count % 10 == 0) // check the cancellation token if the user passed a very large spin count
cancellationToken.ThrowIfCancellationRequested();
}
diff --git a/src/mscorlib/src/System/Threading/Mutex.cs b/src/mscorlib/src/System/Threading/Mutex.cs
index e3fc8e4233..095c27bf8e 100644
--- a/src/mscorlib/src/System/Threading/Mutex.cs
+++ b/src/mscorlib/src/System/Threading/Mutex.cs
@@ -123,7 +123,7 @@ namespace System.Threading
throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, m_name));
}
}
- __Error.WinIOError(errorCode, m_name);
+ throw Win32Marshal.GetExceptionForWin32Error(errorCode, m_name);
}
m_newMutex = errorCode != Win32Native.ERROR_ALREADY_EXISTS;
m_mutex.SetHandleInternal(mutexHandle);
@@ -201,8 +201,7 @@ namespace System.Threading
throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
case OpenExistingResult.PathNotFound:
- __Error.WinIOError(Win32Native.ERROR_PATH_NOT_FOUND, name);
- return result; //never executes
+ throw Win32Marshal.GetExceptionForWin32Error(Win32Native.ERROR_PATH_NOT_FOUND, name);
default:
return result;
@@ -261,7 +260,7 @@ namespace System.Threading
return OpenExistingResult.NameInvalid;
// this is for passed through Win32Native Errors
- __Error.WinIOError(errorCode, name);
+ throw Win32Marshal.GetExceptionForWin32Error(errorCode, name);
}
result = new Mutex(myHandle);
diff --git a/src/mscorlib/src/System/Threading/PinnableBufferCache.cs b/src/mscorlib/src/System/Threading/PinnableBufferCache.cs
index 3f7853ce59..a896fa22e3 100644
--- a/src/mscorlib/src/System/Threading/PinnableBufferCache.cs
+++ b/src/mscorlib/src/System/Threading/PinnableBufferCache.cs
@@ -210,7 +210,7 @@ namespace System
}
/// <summary>
- /// See if we can promote the buffers to the free list. Returns true if sucessful.
+ /// See if we can promote the buffers to the free list. Returns true if successful.
/// </summary>
private bool AgePendingBuffers()
{
@@ -393,7 +393,7 @@ namespace System
private Func<object> m_factory;
/// <summary>
- /// Contains 'good' buffers to reuse. They are guarenteed to be Gen 2 ENFORCED!
+ /// Contains 'good' buffers to reuse. They are guaranteed to be Gen 2 ENFORCED!
/// </summary>
private ConcurrentStack<object> m_FreeList = new ConcurrentStack<object>();
/// <summary>
@@ -403,7 +403,7 @@ namespace System
/// </summary>
private List<object> m_NotGen2;
/// <summary>
- /// What whas the gen 1 count the last time re restocked? If it is now greater, then
+ /// What was the gen 1 count the last time re restocked? If it is now greater, then
/// we know that all objects are in Gen 2 so we don't have to check. Should be updated
/// every time something gets added to the m_NotGen2 list.
/// </summary>
diff --git a/src/mscorlib/src/System/Threading/Semaphore.cs b/src/mscorlib/src/System/Threading/Semaphore.cs
index 7d2396a9c6..136eee6e76 100644
--- a/src/mscorlib/src/System/Threading/Semaphore.cs
+++ b/src/mscorlib/src/System/Threading/Semaphore.cs
@@ -46,7 +46,7 @@ namespace System.Threading
throw new WaitHandleCannotBeOpenedException(
SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
- __Error.WinIOError();
+ throw Win32Marshal.GetExceptionForLastWin32Error();
}
this.SafeWaitHandle = myHandle;
}
@@ -76,7 +76,7 @@ namespace System.Threading
if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
throw new WaitHandleCannotBeOpenedException(
SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
- __Error.WinIOError();
+ throw Win32Marshal.GetExceptionForLastWin32Error();
}
createdNew = errorCode != Win32Native.ERROR_ALREADY_EXISTS;
this.SafeWaitHandle = myHandle;
@@ -116,7 +116,7 @@ namespace System.Threading
case OpenExistingResult.NameInvalid:
throw new WaitHandleCannotBeOpenedException(SR.Format(SR.Threading_WaitHandleCannotBeOpenedException_InvalidHandle, name));
case OpenExistingResult.PathNotFound:
- throw new IOException(Win32Native.GetMessage(Win32Native.ERROR_PATH_NOT_FOUND));
+ throw new IOException(Interop.Kernel32.GetMessage(Win32Native.ERROR_PATH_NOT_FOUND));
default:
return result;
}
@@ -155,7 +155,7 @@ namespace System.Threading
if (null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
return OpenExistingResult.NameInvalid;
//this is for passed through NativeMethods Errors
- __Error.WinIOError();
+ throw Win32Marshal.GetExceptionForLastWin32Error();
}
result = new Semaphore(myHandle);
diff --git a/src/mscorlib/src/System/Threading/SemaphoreSlim.cs b/src/mscorlib/src/System/Threading/SemaphoreSlim.cs
index 97bbae18cc..a61753d9a9 100644
--- a/src/mscorlib/src/System/Threading/SemaphoreSlim.cs
+++ b/src/mscorlib/src/System/Threading/SemaphoreSlim.cs
@@ -1,4 +1,4 @@
-// Licensed to the .NET Foundation under one or more agreements.
+// 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.
@@ -56,7 +56,13 @@ namespace System.Threading
// The number of synchronously waiting threads, it is set to zero in the constructor and increments before blocking the
// threading and decrements it back after that. It is used as flag for the release call to know if there are
// waiting threads in the monitor or not.
- private volatile int m_waitCount;
+ private int m_waitCount;
+
+ /// <summary>
+ /// This is used to help prevent waking more waiters than necessary. It's not perfect and sometimes more waiters than
+ /// necessary may still be woken, see <see cref="WaitUntilCountOrTimeout"/>.
+ /// </summary>
+ private int m_countOfWaitersPulsedToWake;
// Dummy object used to in lock statements to protect the semaphore count, wait handle and cancelation
private object m_lockObj;
@@ -342,15 +348,28 @@ namespace System.Threading
CancellationTokenRegistration cancellationTokenRegistration = cancellationToken.InternalRegisterWithoutEC(s_cancellationTokenCanceledEventHandler, this);
try
{
- // Perf: first spin wait for the count to be positive, but only up to the first planned yield.
+ // Perf: first spin wait for the count to be positive.
// This additional amount of spinwaiting in addition
// to Monitor.Enter()’s spinwaiting has shown measurable perf gains in test scenarios.
//
- SpinWait spin = new SpinWait();
- while (m_currentCount == 0 && !spin.NextSpinWillYield)
+
+ // Monitor.Enter followed by Monitor.Wait is much more expensive than waiting on an event as it involves another
+ // spin, contention, etc. The usual number of spin iterations that would otherwise be used here is increased to
+ // lessen that extra expense of doing a proper wait.
+ int spinCount = SpinWait.SpinCountforSpinBeforeWait * 4;
+ int sleep1Threshold = SpinWait.Sleep1ThresholdForSpinBeforeWait * 4;
+
+ SpinWait spinner = new SpinWait();
+ while (spinner.Count < spinCount)
{
- spin.SpinOnce();
+ spinner.SpinOnce(sleep1Threshold);
+
+ if (m_currentCount != 0)
+ {
+ break;
+ }
}
+
// entering the lock and incrementing waiters must not suffer a thread-abort, else we cannot
// clean up m_waitCount correctly, which may lead to deadlock due to non-woken waiters.
try { }
@@ -442,13 +461,13 @@ namespace System.Threading
}
/// <summary>
- /// Local helper function, waits on the monitor until the monitor recieves signal or the
+ /// Local helper function, waits on the monitor until the monitor receives signal or the
/// timeout is expired
/// </summary>
/// <param name="millisecondsTimeout">The maximum timeout</param>
/// <param name="startTime">The start ticks to calculate the elapsed time</param>
/// <param name="cancellationToken">The CancellationToken to observe.</param>
- /// <returns>true if the monitor recieved a signal, false if the timeout expired</returns>
+ /// <returns>true if the monitor received a signal, false if the timeout expired</returns>
private bool WaitUntilCountOrTimeout(int millisecondsTimeout, uint startTime, CancellationToken cancellationToken)
{
int remainingWaitMilliseconds = Timeout.Infinite;
@@ -468,8 +487,22 @@ namespace System.Threading
return false;
}
}
+
// ** the actual wait **
- if (!Monitor.Wait(m_lockObj, remainingWaitMilliseconds))
+ bool waitSuccessful = Monitor.Wait(m_lockObj, remainingWaitMilliseconds);
+
+ // This waiter has woken up and this needs to be reflected in the count of waiters pulsed to wake. Since we
+ // don't have thread-specific pulse state, there is not enough information to tell whether this thread woke up
+ // because it was pulsed. For instance, this thread may have timed out and may have been waiting to reacquire
+ // the lock before returning from Monitor.Wait, in which case we don't know whether this thread got pulsed. So
+ // in any woken case, decrement the count if possible. As such, timeouts could cause more waiters to wake than
+ // necessary.
+ if (m_countOfWaitersPulsedToWake != 0)
+ {
+ --m_countOfWaitersPulsedToWake;
+ }
+
+ if (!waitSuccessful)
{
return false;
}
@@ -791,13 +824,27 @@ namespace System.Threading
// Increment the count by the actual release count
currentCount += releaseCount;
- // Signal to any synchronous waiters
+ // Signal to any synchronous waiters, taking into account how many waiters have previously been pulsed to wake
+ // but have not yet woken
int waitCount = m_waitCount;
-
- int waitersToNotify = Math.Min(releaseCount, waitCount);
- for (int i = 0; i < waitersToNotify; i++)
+ Debug.Assert(m_countOfWaitersPulsedToWake <= waitCount);
+ int waitersToNotify = Math.Min(currentCount, waitCount) - m_countOfWaitersPulsedToWake;
+ if (waitersToNotify > 0)
{
- Monitor.Pulse(m_lockObj);
+ // Ideally, limiting to a maximum of releaseCount would not be necessary and could be an assert instead, but
+ // since WaitUntilCountOrTimeout() does not have enough information to tell whether a woken thread was
+ // pulsed, it's possible for m_countOfWaitersPulsedToWake to be less than the number of threads that have
+ // actually been pulsed to wake.
+ if (waitersToNotify > releaseCount)
+ {
+ waitersToNotify = releaseCount;
+ }
+
+ m_countOfWaitersPulsedToWake += waitersToNotify;
+ for (int i = 0; i < waitersToNotify; i++)
+ {
+ Monitor.Pulse(m_lockObj);
+ }
}
// Now signal to any asynchronous waiters, if there are any. While we've already
@@ -910,14 +957,6 @@ namespace System.Threading
}
}
- /// <summary>
- /// local helper function to retrieve the exception string message from the resource file
- /// </summary>
- /// <param name="str">The key string</param>
- private static string GetResourceString(string str)
- {
- return SR.GetResourceString(str);
- }
#endregion
}
}
diff --git a/src/mscorlib/src/System/Threading/SpinLock.cs b/src/mscorlib/src/System/Threading/SpinLock.cs
index eee73ce2bf..917ece2d4d 100644
--- a/src/mscorlib/src/System/Threading/SpinLock.cs
+++ b/src/mscorlib/src/System/Threading/SpinLock.cs
@@ -65,16 +65,9 @@ namespace System.Threading
private volatile int m_owner;
- // The multiplier factor for the each spinning iteration
- // This number has been chosen after trying different numbers on different CPUs (4, 8 and 16 ) and this provided the best results
- private const int SPINNING_FACTOR = 100;
-
// After how many yields, call Sleep(1)
private const int SLEEP_ONE_FREQUENCY = 40;
- // After how many yields, call Sleep(0)
- private const int SLEEP_ZERO_FREQUENCY = 10;
-
// After how many yields, check the timeout
private const int TIMEOUT_CHECK_FREQUENCY = 10;
@@ -277,7 +270,7 @@ namespace System.Threading
/// <summary>
/// Try acquire the lock with long path, this is usually called after the first path in Enter and
/// TryEnter failed The reason for short path is to make it inline in the run time which improves the
- /// performance. This method assumed that the parameter are validated in Enter ir TryENter method
+ /// performance. This method assumed that the parameter are validated in Enter or TryEnter method.
/// </summary>
/// <param name="millisecondsTimeout">The timeout milliseconds</param>
/// <param name="lockTaken">The lockTaken param</param>
@@ -347,48 +340,24 @@ namespace System.Threading
else //failed to acquire the lock,then try to update the waiters. If the waiters count reached the maximum, jsut break the loop to avoid overflow
{
if ((observedOwner & WAITERS_MASK) != MAXIMUM_WAITERS)
+ {
+ // This can still overflow, but maybe there will never be that many waiters
turn = (Interlocked.Add(ref m_owner, 2) & WAITERS_MASK) >> 1;
+ }
}
- //***Step 2. Spinning
//lock acquired failed and waiters updated
- int processorCount = PlatformHelper.ProcessorCount;
- if (turn < processorCount)
- {
- int processFactor = 1;
- for (int i = 1; i <= turn * SPINNING_FACTOR; i++)
- {
- Thread.SpinWait((turn + i) * SPINNING_FACTOR * processFactor);
- if (processFactor < processorCount)
- processFactor++;
- observedOwner = m_owner;
- if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED)
- {
- int newOwner = (observedOwner & WAITERS_MASK) == 0 ? // Gets the number of waiters, if zero
- observedOwner | 1 // don't decrement it. just set the lock bit, it is zzero because a previous call of Exit(false) ehich corrupted the waiters
- : (observedOwner - 2) | 1; // otherwise decrement the waiters and set the lock bit
- Debug.Assert((newOwner & WAITERS_MASK) >= 0);
-
- if (CompareExchange(ref m_owner, newOwner, observedOwner, ref lockTaken) == observedOwner)
- {
- return;
- }
- }
- }
- // Check the timeout.
- if (millisecondsTimeout != Timeout.Infinite && TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0)
- {
- DecrementWaiters();
- return;
- }
+ //*** Step 2, Spinning and Yielding
+ var spinner = new SpinWait();
+ if (turn > PlatformHelper.ProcessorCount)
+ {
+ spinner.Count = SpinWait.YieldThreshold;
}
-
- //*** Step 3, Yielding
- //Sleep(1) every 50 yields
- int yieldsoFar = 0;
while (true)
{
+ spinner.SpinOnce(SLEEP_ONE_FREQUENCY);
+
observedOwner = m_owner;
if ((observedOwner & LOCK_ANONYMOUS_OWNED) == LOCK_UNOWNED)
{
@@ -403,20 +372,7 @@ namespace System.Threading
}
}
- if (yieldsoFar % SLEEP_ONE_FREQUENCY == 0)
- {
- Thread.Sleep(1);
- }
- else if (yieldsoFar % SLEEP_ZERO_FREQUENCY == 0)
- {
- Thread.Sleep(0);
- }
- else
- {
- Thread.Yield();
- }
-
- if (yieldsoFar % TIMEOUT_CHECK_FREQUENCY == 0)
+ if (spinner.Count % TIMEOUT_CHECK_FREQUENCY == 0)
{
//Check the timeout.
if (millisecondsTimeout != Timeout.Infinite && TimeoutHelper.UpdateTimeOut(startTime, millisecondsTimeout) <= 0)
@@ -425,8 +381,6 @@ namespace System.Threading
return;
}
}
-
- yieldsoFar++;
}
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs
index 07a673bf4e..765dcd8408 100644
--- a/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/ConcurrentExclusiveSchedulerPair.cs
@@ -41,10 +41,10 @@ namespace System.Threading.Tasks
private readonly TaskScheduler m_underlyingTaskScheduler;
/// <summary>
/// The maximum number of tasks allowed to run concurrently. This only applies to concurrent tasks,
- /// since exlusive tasks are inherently limited to 1.
+ /// since exclusive tasks are inherently limited to 1.
/// </summary>
private readonly int m_maxConcurrencyLevel;
- /// <summary>The maximum number of tasks we can process before recyling our runner tasks.</summary>
+ /// <summary>The maximum number of tasks we can process before recycling our runner tasks.</summary>
private readonly int m_maxItemsPerTask;
/// <summary>
/// If positive, it represents the number of concurrently running concurrent tasks.
@@ -225,7 +225,7 @@ namespace System.Threading.Tasks
}
}
- /// <summary>Initiatites scheduler shutdown due to a worker task faulting..</summary>
+ /// <summary>Initiates scheduler shutdown due to a worker task faulting.</summary>
/// <param name="faultedTask">The faulted worker task that's initiating the shutdown.</param>
private void FaultWithTask(Task faultedTask)
{
diff --git a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs
index 60a7c81dcf..bf63a53df9 100644
--- a/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/FutureFactory.cs
@@ -1293,7 +1293,7 @@ namespace System.Threading.Tasks
/// <summary>
/// Completes the asynchronous operation using information in the IAsyncResult.
- /// IAsyncResult.AsyncState neeeds to be the FromAsyncTrimPromise to complete.
+ /// IAsyncResult.AsyncState needs to be the FromAsyncTrimPromise to complete.
/// </summary>
/// <param name="asyncResult">The IAsyncResult for the async operation.</param>
internal static void CompleteFromAsyncResult(IAsyncResult asyncResult)
diff --git a/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs b/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs
index f9d5f89398..df0dbe3942 100644
--- a/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/ProducerConsumerQueues.cs
@@ -332,7 +332,7 @@ namespace System.Threading.Tasks
private struct SegmentState
{
/// <summary>Padding to reduce false sharing between the segment's array and m_first.</summary>
- internal PaddingFor32 m_pad0;
+ internal Internal.PaddingFor32 m_pad0;
/// <summary>The index of the current head in the segment.</summary>
internal volatile int m_first;
@@ -340,7 +340,7 @@ namespace System.Threading.Tasks
internal int m_lastCopy; // not volatile as read and written by the producer, except for IsEmpty, and there m_lastCopy is only read after reading the volatile m_first
/// <summary>Padding to reduce false sharing between the first and last.</summary>
- internal PaddingFor32 m_pad1;
+ internal Internal.PaddingFor32 m_pad1;
/// <summary>A copy of the current head index.</summary>
internal int m_firstCopy; // not voliatle as only read and written by the consumer thread
@@ -348,7 +348,7 @@ namespace System.Threading.Tasks
internal volatile int m_last;
/// <summary>Padding to reduce false sharing with the last and what's after the segment.</summary>
- internal PaddingFor32 m_pad2;
+ internal Internal.PaddingFor32 m_pad2;
}
/// <summary>Debugger type proxy for a SingleProducerSingleConsumerQueue of T.</summary>
@@ -366,17 +366,4 @@ namespace System.Threading.Tasks
}
}
}
-
- /// <summary>A placeholder class for common padding constants and eventually routines.</summary>
- internal static class PaddingHelpers
- {
- /// <summary>A size greater than or equal to the size of the most common CPU cache lines.</summary>
- internal const int CACHE_LINE_SIZE = 128;
- }
-
- /// <summary>Padding structure used to minimize false sharing in SingleProducerSingleConsumerQueue{T}.</summary>
- [StructLayout(LayoutKind.Explicit, Size = PaddingHelpers.CACHE_LINE_SIZE - sizeof(Int32))] // Based on common case of 64-byte cache lines
- internal struct PaddingFor32
- {
- }
}
diff --git a/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs b/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs
index 33bf792370..bdfe8eeff9 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TPLETWProvider.cs
@@ -130,7 +130,7 @@ namespace System.Threading.Tasks
/// <summary>
/// TasksSetActivityIds will cause the task operations to set Activity Ids
/// This option is incompatible with TasksFlowActivityIds flow is ignored
- /// if that keyword is set. This option is likley to be removed in the future
+ /// if that keyword is set. This option is likely to be removed in the future
/// </summary>
public const EventKeywords TasksSetActivityIds = (EventKeywords)0x10000;
@@ -360,7 +360,7 @@ namespace System.Threading.Tasks
}
/// <summary>
- /// Fired when the the work (method) associated with a TaskWaitEnd completes
+ /// Fired when the work (method) associated with a TaskWaitEnd completes
/// </summary>
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
@@ -375,7 +375,7 @@ namespace System.Threading.Tasks
}
/// <summary>
- /// Fired when the the work (method) associated with a TaskWaitEnd completes
+ /// Fired when the work (method) associated with a TaskWaitEnd completes
/// </summary>
/// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param>
/// <param name="OriginatingTaskID">The task ID.</param>
diff --git a/src/mscorlib/src/System/Threading/Tasks/Task.cs b/src/mscorlib/src/System/Threading/Tasks/Task.cs
index c19fd3ec64..84811fb068 100644
--- a/src/mscorlib/src/System/Threading/Tasks/Task.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/Task.cs
@@ -10,19 +10,14 @@
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
-using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
-using System.Runtime;
-using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
-using System.Runtime.ExceptionServices;
-using System.Security;
-using System.Threading;
using System.Diagnostics;
using System.Diagnostics.Contracts;
-using Microsoft.Win32;
using System.Diagnostics.Tracing;
+using System.Runtime.CompilerServices;
+using System.Runtime.ExceptionServices;
+using Internal.Runtime.Augments;
// Disable the "reference to volatile field not treated as volatile" error.
#pragma warning disable 0420
@@ -440,7 +435,7 @@ namespace System.Threading.Tasks
}
/// <summary>
- /// Initializes a new <see cref="Task"/> with the specified action, state, snd options.
+ /// Initializes a new <see cref="Task"/> with the specified action, state, and options.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="state">An object representing data to be used by the action.</param>
@@ -457,7 +452,7 @@ namespace System.Threading.Tasks
}
/// <summary>
- /// Initializes a new <see cref="Task"/> with the specified action, state, snd options.
+ /// Initializes a new <see cref="Task"/> with the specified action, state, and options.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="state">An object representing data to be used by the action.</param>
@@ -478,7 +473,7 @@ namespace System.Threading.Tasks
}
/// <summary>
- /// Initializes a new <see cref="Task"/> with the specified action, state, snd options.
+ /// Initializes a new <see cref="Task"/> with the specified action, state, and options.
/// </summary>
/// <param name="action">The delegate that represents the code to execute in the task.</param>
/// <param name="state">An object representing data to be used by the action.</param>
@@ -613,7 +608,7 @@ namespace System.Threading.Tasks
/// <summary>
/// Handles everything needed for associating a CancellationToken with a task which is being constructed.
- /// This method is meant to be be called either from the TaskConstructorCore or from ContinueWithCore.
+ /// This method is meant to be called either from the TaskConstructorCore or from ContinueWithCore.
/// </summary>
private void AssignCancellationToken(CancellationToken cancellationToken, Task antecedent, TaskContinuation continuation)
{
@@ -2489,7 +2484,7 @@ namespace System.Threading.Tasks
private static readonly ContextCallback s_ecCallback = obj => ((Task)obj).InnerInvoke();
/// <summary>
- /// The actual code which invokes the body of the task. This can be overriden in derived types.
+ /// The actual code which invokes the body of the task. This can be overridden in derived types.
/// </summary>
internal virtual void InnerInvoke()
{
@@ -2827,11 +2822,16 @@ namespace System.Threading.Tasks
}
/// <summary>
- /// The core wait function, which is only accesible internally. It's meant to be used in places in TPL code where
+ /// The core wait function, which is only accessible internally. It's meant to be used in places in TPL code where
/// the current context is known or cached.
/// </summary>
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
- internal bool InternalWait(int millisecondsTimeout, CancellationToken cancellationToken)
+ internal bool InternalWait(int millisecondsTimeout, CancellationToken cancellationToken) =>
+ InternalWaitCore(millisecondsTimeout, cancellationToken);
+
+ // Separated out to allow it to be optimized (caller is marked NoOptimization for VS parallel debugger
+ // to be able to see the method on the stack and inspect arguments).
+ private bool InternalWaitCore(int millisecondsTimeout, CancellationToken cancellationToken)
{
// ETW event for Task Wait Begin
var etwLog = TplEtwProvider.Log;
@@ -2966,26 +2966,19 @@ namespace System.Threading.Tasks
return false;
}
- //This code is pretty similar to the custom spinning in MRES except there is no yieling after we exceed the spin count
- int spinCount = PlatformHelper.IsSingleProcessor ? 1 : System.Threading.SpinWait.YIELD_THRESHOLD; //spin only once if we are running on a single CPU
- for (int i = 0; i < spinCount; i++)
+ int spinCount = Threading.SpinWait.SpinCountforSpinBeforeWait;
+ var spinner = new SpinWait();
+ while (spinner.Count < spinCount)
{
+ spinner.SpinOnce(Threading.SpinWait.Sleep1ThresholdForSpinBeforeWait);
+
if (IsCompleted)
{
return true;
}
-
- if (i == spinCount / 2)
- {
- Thread.Yield();
- }
- else
- {
- Thread.SpinWait(PlatformHelper.ProcessorCount * (4 << i));
- }
}
- return IsCompleted;
+ return false;
}
/// <summary>
@@ -3222,7 +3215,7 @@ namespace System.Threading.Tasks
// Skip synchronous execution of continuations if this task's thread was aborted
bool bCanInlineContinuations = !(((m_stateFlags & TASK_STATE_THREAD_WAS_ABORTED) != 0) ||
- (Thread.CurrentThread.ThreadState == ThreadState.AbortRequested) ||
+ (RuntimeThread.CurrentThread.ThreadState == ThreadState.AbortRequested) ||
((m_stateFlags & (int)TaskCreationOptions.RunContinuationsAsynchronously) != 0));
// Handle the single-Action case
@@ -4458,7 +4451,7 @@ namespace System.Threading.Tasks
#if DEBUG
bool waitResult =
#endif
- WaitAll(tasks, Timeout.Infinite);
+ WaitAllCore(tasks, Timeout.Infinite, default(CancellationToken));
#if DEBUG
Debug.Assert(waitResult, "expected wait to succeed");
@@ -4503,7 +4496,7 @@ namespace System.Threading.Tasks
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.timeout);
}
- return WaitAll(tasks, (int)totalMilliseconds);
+ return WaitAllCore(tasks, (int)totalMilliseconds, default(CancellationToken));
}
/// <summary>
@@ -4535,7 +4528,7 @@ namespace System.Threading.Tasks
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static bool WaitAll(Task[] tasks, int millisecondsTimeout)
{
- return WaitAll(tasks, millisecondsTimeout, default(CancellationToken));
+ return WaitAllCore(tasks, millisecondsTimeout, default(CancellationToken));
}
/// <summary>
@@ -4567,7 +4560,7 @@ namespace System.Threading.Tasks
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static void WaitAll(Task[] tasks, CancellationToken cancellationToken)
{
- WaitAll(tasks, Timeout.Infinite, cancellationToken);
+ WaitAllCore(tasks, Timeout.Infinite, cancellationToken);
}
/// <summary>
@@ -4605,7 +4598,12 @@ namespace System.Threading.Tasks
/// The <paramref name="cancellationToken"/> was canceled.
/// </exception>
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
- public static bool WaitAll(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
+ public static bool WaitAll(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) =>
+ WaitAllCore(tasks, millisecondsTimeout, cancellationToken);
+
+ // Separated out to allow it to be optimized (caller is marked NoOptimization for VS parallel debugger
+ // to be able to see the method on the stack and inspect arguments).
+ private static bool WaitAllCore(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
{
if (tasks == null)
{
@@ -4847,7 +4845,7 @@ namespace System.Threading.Tasks
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static int WaitAny(params Task[] tasks)
{
- int waitResult = WaitAny(tasks, Timeout.Infinite);
+ int waitResult = WaitAnyCore(tasks, Timeout.Infinite, default(CancellationToken));
Debug.Assert(tasks.Length == 0 || waitResult != -1, "expected wait to succeed");
return waitResult;
}
@@ -4886,7 +4884,7 @@ namespace System.Threading.Tasks
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.timeout);
}
- return WaitAny(tasks, (int)totalMilliseconds);
+ return WaitAnyCore(tasks, (int)totalMilliseconds, default(CancellationToken));
}
/// <summary>
@@ -4913,7 +4911,7 @@ namespace System.Threading.Tasks
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static int WaitAny(Task[] tasks, CancellationToken cancellationToken)
{
- return WaitAny(tasks, Timeout.Infinite, cancellationToken);
+ return WaitAnyCore(tasks, Timeout.Infinite, cancellationToken);
}
/// <summary>
@@ -4943,7 +4941,7 @@ namespace System.Threading.Tasks
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
public static int WaitAny(Task[] tasks, int millisecondsTimeout)
{
- return WaitAny(tasks, millisecondsTimeout, default(CancellationToken));
+ return WaitAnyCore(tasks, millisecondsTimeout, default(CancellationToken));
}
/// <summary>
@@ -4977,7 +4975,12 @@ namespace System.Threading.Tasks
/// The <paramref name="cancellationToken"/> was canceled.
/// </exception>
[MethodImpl(MethodImplOptions.NoOptimization)] // this is needed for the parallel debugger
- public static int WaitAny(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
+ public static int WaitAny(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken) =>
+ WaitAnyCore(tasks, millisecondsTimeout, cancellationToken);
+
+ // Separated out to allow it to be optimized (caller is marked NoOptimization for VS parallel debugger
+ // to be able to inspect arguments).
+ private static int WaitAnyCore(Task[] tasks, int millisecondsTimeout, CancellationToken cancellationToken)
{
if (tasks == null)
{
diff --git a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs
index 666a19297f..eddaeee9d7 100644
--- a/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs
+++ b/src/mscorlib/src/System/Threading/Tasks/TaskScheduler.cs
@@ -642,7 +642,7 @@ namespace System.Threading.Tasks
}
/// <summary>
- /// Implemetation of <see cref="T:System.Threading.Tasks.TaskScheduler.QueueTask"/> for this scheduler class.
+ /// Implementation of <see cref="T:System.Threading.Tasks.TaskScheduler.QueueTask"/> for this scheduler class.
///
/// Simply posts the tasks to be executed on the associated <see cref="T:System.Threading.SynchronizationContext"/>.
/// </summary>
@@ -677,7 +677,7 @@ namespace System.Threading.Tasks
}
/// <summary>
- /// Implementes the <see cref="T:System.Threading.Tasks.TaskScheduler.MaximumConcurrencyLevel"/> property for
+ /// Implements the <see cref="T:System.Threading.Tasks.TaskScheduler.MaximumConcurrencyLevel"/> property for
/// this scheduler class.
///
/// By default it returns 1, because a <see cref="T:System.Threading.SynchronizationContext"/> based
diff --git a/src/mscorlib/src/System/Threading/Thread.cs b/src/mscorlib/src/System/Threading/Thread.cs
index 84c5ebb552..d8ea6410eb 100644
--- a/src/mscorlib/src/System/Threading/Thread.cs
+++ b/src/mscorlib/src/System/Threading/Thread.cs
@@ -128,7 +128,12 @@ namespace System.Threading
private IntPtr DONT_USE_InternalThread; // Pointer
private int m_Priority; // INT32
- private int m_ManagedThreadId; // INT32
+
+ // The following field is required for interop with the VS Debugger
+ // Prior to making any changes to this field, please reach out to the VS Debugger
+ // team to make sure that your changes are not going to prevent the debugger
+ // from working.
+ private int _managedThreadId; // INT32
#pragma warning restore 414
#pragma warning restore 169
@@ -200,7 +205,7 @@ namespace System.Threading
public override int GetHashCode()
{
- return m_ManagedThreadId;
+ return _managedThreadId;
}
extern public new int ManagedThreadId
diff --git a/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs b/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs
index fb72110fdc..db42b77ca4 100644
--- a/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs
+++ b/src/mscorlib/src/System/Threading/ThreadInterruptedException.cs
@@ -24,19 +24,19 @@ namespace System.Threading
public ThreadInterruptedException()
: base(GetMessageFromNativeResources(ExceptionMessageKind.ThreadInterrupted))
{
- HResult = __HResults.COR_E_THREADINTERRUPTED;
+ HResult = HResults.COR_E_THREADINTERRUPTED;
}
public ThreadInterruptedException(String message)
: base(message)
{
- HResult = __HResults.COR_E_THREADINTERRUPTED;
+ HResult = HResults.COR_E_THREADINTERRUPTED;
}
public ThreadInterruptedException(String message, Exception innerException)
: base(message, innerException)
{
- HResult = __HResults.COR_E_THREADINTERRUPTED;
+ HResult = HResults.COR_E_THREADINTERRUPTED;
}
protected ThreadInterruptedException(SerializationInfo info, StreamingContext context) : base(info, context)
diff --git a/src/mscorlib/src/System/Threading/ThreadLocal.cs b/src/mscorlib/src/System/Threading/ThreadLocal.cs
index 64b8a60196..cdfa2448c0 100644
--- a/src/mscorlib/src/System/Threading/ThreadLocal.cs
+++ b/src/mscorlib/src/System/Threading/ThreadLocal.cs
@@ -712,7 +712,7 @@ namespace System.Threading
/// A class that facilitates ThreadLocal cleanup after a thread exits.
///
/// After a thread with an associated thread-local table has exited, the FinalizationHelper
- /// is reponsible for removing back-references to the table. Since an instance of FinalizationHelper
+ /// is responsible for removing back-references to the table. Since an instance of FinalizationHelper
/// is only referenced from a single thread-local slot, the FinalizationHelper will be GC'd once
/// the thread has exited.
///
diff --git a/src/mscorlib/src/System/Threading/ThreadPool.cs b/src/mscorlib/src/System/Threading/ThreadPool.cs
index 0084050c43..ec9ceef156 100644
--- a/src/mscorlib/src/System/Threading/ThreadPool.cs
+++ b/src/mscorlib/src/System/Threading/ThreadPool.cs
@@ -39,6 +39,7 @@ namespace System.Threading
public static readonly ThreadPoolWorkQueue workQueue = new ThreadPoolWorkQueue();
}
+ [StructLayout(LayoutKind.Sequential)] // enforce layout so that padding reduces false sharing
internal sealed class ThreadPoolWorkQueue
{
internal static class WorkStealingQueueList
@@ -47,6 +48,12 @@ namespace System.Threading
public static WorkStealingQueue[] Queues => _queues;
+ // Track whether the WorkStealingQueueList is empty
+ // Three states simplifies race conditions. They may be considered.
+ // Now Active --> Maybe Inactive -> Confirmed Inactive
+ public const int WsqNowActive = 2;
+ public static int wsqActive;
+
public static void Add(WorkStealingQueue queue)
{
Debug.Assert(queue != null);
@@ -378,8 +385,12 @@ namespace System.Threading
internal bool loggingEnabled;
internal readonly ConcurrentQueue<IThreadPoolWorkItem> workItems = new ConcurrentQueue<IThreadPoolWorkItem>();
+ private Internal.PaddingFor32 pad1;
+
private volatile int numOutstandingThreadRequests = 0;
+ private Internal.PaddingFor32 pad2;
+
public ThreadPoolWorkQueue()
{
loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer);
@@ -389,15 +400,20 @@ namespace System.Threading
ThreadPoolWorkQueueThreadLocals.threadLocals ??
(ThreadPoolWorkQueueThreadLocals.threadLocals = new ThreadPoolWorkQueueThreadLocals(this));
+ internal bool ThreadRequestNeeded(int count) => (count < ThreadPoolGlobals.processorCount) &&
+ (!workItems.IsEmpty || (WorkStealingQueueList.wsqActive > 0));
+
internal void EnsureThreadRequested()
{
//
- // If we have not yet requested #procs threads from the VM, then request a new thread.
+ // If we have not yet requested #procs threads from the VM, then request a new thread
+ // as needed
+ //
// Note that there is a separate count in the VM which will also be incremented in this case,
// which is handled by RequestWorkerThread.
//
int count = numOutstandingThreadRequests;
- while (count < ThreadPoolGlobals.processorCount)
+ while (ThreadRequestNeeded(count))
{
int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count + 1, count);
if (prev == count)
@@ -409,7 +425,7 @@ namespace System.Threading
}
}
- internal void MarkThreadRequestSatisfied()
+ internal void MarkThreadRequestSatisfied(bool dequeueSuccessful)
{
//
// The VM has called us, so one of our outstanding thread requests has been satisfied.
@@ -418,8 +434,17 @@ namespace System.Threading
// by the time we reach this point.
//
int count = numOutstandingThreadRequests;
+
while (count > 0)
{
+ if (dequeueSuccessful && (count == ThreadPoolGlobals.processorCount) && ThreadRequestNeeded(count - 1))
+ {
+ // If we gated threads due to too many outstanding requests and queue was not empty
+ // Request another thread.
+ ThreadPool.RequestWorkerThread();
+ return;
+ }
+
int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count - 1, count);
if (prev == count)
{
@@ -441,6 +466,18 @@ namespace System.Threading
if (null != tl)
{
tl.workStealingQueue.LocalPush(callback);
+
+ // We must guarantee wsqActive is set to WsqNowActive after we push
+ // The ordering must be global because we rely on other threads
+ // observing in this order
+ Interlocked.MemoryBarrier();
+
+ // We do not want to simply write. We want to prevent unnecessary writes
+ // which would invalidate reader's caches
+ if (WorkStealingQueueList.wsqActive != WorkStealingQueueList.WsqNowActive)
+ {
+ Volatile.Write(ref WorkStealingQueueList.wsqActive, WorkStealingQueueList.WsqNowActive);
+ }
}
else
{
@@ -458,33 +495,56 @@ namespace System.Threading
public IThreadPoolWorkItem Dequeue(ThreadPoolWorkQueueThreadLocals tl, ref bool missedSteal)
{
- WorkStealingQueue localWsq = tl.workStealingQueue;
IThreadPoolWorkItem callback;
-
- if ((callback = localWsq.LocalPop()) == null && // first try the local queue
- !workItems.TryDequeue(out callback)) // then try the global queue
+ int wsqActiveObserved = WorkStealingQueueList.wsqActive;
+ if (wsqActiveObserved > 0)
{
- // finally try to steal from another thread's local queue
- WorkStealingQueue[] queues = WorkStealingQueueList.Queues;
- int c = queues.Length;
- Debug.Assert(c > 0, "There must at least be a queue for this thread.");
- int maxIndex = c - 1;
- int i = tl.random.Next(c);
- while (c > 0)
+ WorkStealingQueue localWsq = tl.workStealingQueue;
+
+ if ((callback = localWsq.LocalPop()) == null && // first try the local queue
+ !workItems.TryDequeue(out callback)) // then try the global queue
{
- i = (i < maxIndex) ? i + 1 : 0;
- WorkStealingQueue otherQueue = queues[i];
- if (otherQueue != localWsq && otherQueue.CanSteal)
+ // finally try to steal from another thread's local queue
+ WorkStealingQueue[] queues = WorkStealingQueueList.Queues;
+ int c = queues.Length;
+ Debug.Assert(c > 0, "There must at least be a queue for this thread.");
+ int maxIndex = c - 1;
+ int i = tl.random.Next(c);
+ while (c > 0)
{
- callback = otherQueue.TrySteal(ref missedSteal);
- if (callback != null)
+ i = (i < maxIndex) ? i + 1 : 0;
+ WorkStealingQueue otherQueue = queues[i];
+ if (otherQueue != localWsq && otherQueue.CanSteal)
{
- break;
+ callback = otherQueue.TrySteal(ref missedSteal);
+ if (callback != null)
+ {
+ break;
+ }
}
+ c--;
+ }
+ if ((callback == null) && !missedSteal)
+ {
+ // Only decrement if the value is unchanged since we started looking for work
+ // This prevents multiple threads decrementing based on overlapping scans.
+ //
+ // When we decrement from active, the producer may have inserted a queue item during our scan
+ // therefore we cannot transition to empty
+ //
+ // When we decrement from Maybe Inactive, if the producer inserted a queue item during our scan,
+ // the producer must write Active. We may transition to empty briefly if we beat the
+ // producer's write, but the producer will then overwrite us before waking threads.
+ // So effectively we cannot mark the queue empty when an item is in the queue.
+ Interlocked.CompareExchange(ref WorkStealingQueueList.wsqActive, wsqActiveObserved - 1, wsqActiveObserved);
}
- c--;
}
}
+ else
+ {
+ // We only need to look at the global queue since WorkStealingQueueList is inactive
+ workItems.TryDequeue(out callback);
+ }
return callback;
}
@@ -498,15 +558,7 @@ namespace System.Threading
//
int quantumStartTime = Environment.TickCount;
- //
- // Update our records to indicate that an outstanding request for a thread has now been fulfilled.
- // From this point on, we are responsible for requesting another thread if we stop working for any
- // reason, and we believe there might still be work in the queue.
- //
- // Note that if this thread is aborted before we get a chance to request another one, the VM will
- // record a thread request on our behalf. So we don't need to worry about getting aborted right here.
- //
- workQueue.MarkThreadRequestSatisfied();
+ bool markThreadRequestSatisfied = true;
// Has the desire for logging changed since the last time we entered?
workQueue.loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer);
@@ -555,7 +607,21 @@ namespace System.Threading
// If we found work, there may be more work. Ask for another thread so that the other work can be processed
// in parallel. Note that this will only ask for a max of #procs threads, so it's safe to call it for every dequeue.
//
- workQueue.EnsureThreadRequested();
+ if (markThreadRequestSatisfied)
+ {
+ //
+ // Update our records to indicate that an outstanding request for a thread has now been fulfilled
+ // and that an item was successfully dispatched and another thread may be needed
+ //
+ // From this point on, we are responsible for requesting another thread if we stop working for any
+ // reason, and we believe there might still be work in the queue.
+ //
+ // Note that if this thread is aborted before we get a chance to request another one, the VM will
+ // record a thread request on our behalf. So we don't need to worry about getting aborted right here.
+ //
+ workQueue.MarkThreadRequestSatisfied(true);
+ markThreadRequestSatisfied = false;
+ }
//
// Execute the workitem outside of any finally blocks, so that it can be aborted if needed.
@@ -610,6 +676,15 @@ namespace System.Threading
}
finally
{
+ if (markThreadRequestSatisfied)
+ {
+ //
+ // Update our records to indicate that an outstanding request for a thread has now been fulfilled
+ // and that an item was not successfully dispatched. We will request thread below if needed
+ //
+ workQueue.MarkThreadRequestSatisfied(false);
+ }
+
//
// If we are exiting for any reason other than that the queue is definitely empty, ask for another
// thread to pick up where we left off.
@@ -715,16 +790,11 @@ namespace System.Threading
{
// needed for DangerousAddRef
RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- }
- finally
+
+ m_internalWaitObject = waitObject;
+ if (waitObject != null)
{
- m_internalWaitObject = waitObject;
- if (waitObject != null)
- {
- m_internalWaitObject.SafeWaitHandle.DangerousAddRef(ref bReleaseNeeded);
- }
+ m_internalWaitObject.SafeWaitHandle.DangerousAddRef(ref bReleaseNeeded);
}
}
@@ -735,47 +805,43 @@ namespace System.Threading
bool result = false;
// needed for DangerousRelease
RuntimeHelpers.PrepareConstrainedRegions();
- try
- {
- }
- finally
+
+ // lock(this) cannot be used reliably in Cer since thin lock could be
+ // promoted to syncblock and that is not a guaranteed operation
+ bool bLockTaken = false;
+ do
{
- // lock(this) cannot be used reliably in Cer since thin lock could be
- // promoted to syncblock and that is not a guaranteed operation
- bool bLockTaken = false;
- do
+ if (Interlocked.CompareExchange(ref m_lock, 1, 0) == 0)
{
- if (Interlocked.CompareExchange(ref m_lock, 1, 0) == 0)
+ bLockTaken = true;
+ try
{
- bLockTaken = true;
- try
+ if (ValidHandle())
{
- if (ValidHandle())
+ result = UnregisterWaitNative(GetHandle(), waitObject == null ? null : waitObject.SafeWaitHandle);
+ if (result == true)
{
- result = UnregisterWaitNative(GetHandle(), waitObject == null ? null : waitObject.SafeWaitHandle);
- if (result == true)
+ if (bReleaseNeeded)
{
- if (bReleaseNeeded)
- {
- m_internalWaitObject.SafeWaitHandle.DangerousRelease();
- bReleaseNeeded = false;
- }
- // if result not true don't release/suppress here so finalizer can make another attempt
- SetHandle(InvalidHandle);
- m_internalWaitObject = null;
- GC.SuppressFinalize(this);
+ m_internalWaitObject.SafeWaitHandle.DangerousRelease();
+ bReleaseNeeded = false;
}
+ // if result not true don't release/suppress here so finalizer can make another attempt
+ SetHandle(InvalidHandle);
+ m_internalWaitObject = null;
+ GC.SuppressFinalize(this);
}
}
- finally
- {
- m_lock = 0;
- }
}
- Thread.SpinWait(1); // yield to processor
+ finally
+ {
+ m_lock = 0;
+ }
}
- while (!bLockTaken);
+ Thread.SpinWait(1); // yield to processor
}
+ while (!bLockTaken);
+
return result;
}
diff --git a/src/mscorlib/src/System/ThrowHelper.cs b/src/mscorlib/src/System/ThrowHelper.cs
index ff76738e8e..6c5ce05b7f 100644
--- a/src/mscorlib/src/System/ThrowHelper.cs
+++ b/src/mscorlib/src/System/ThrowHelper.cs
@@ -123,7 +123,7 @@ namespace System
internal static void ThrowKeyNotFoundException()
{
- throw new System.Collections.Generic.KeyNotFoundException();
+ throw new KeyNotFoundException();
}
internal static void ThrowArgumentException(ExceptionResource resource)
@@ -226,6 +226,11 @@ namespace System
throw new AggregateException(exceptions);
}
+ internal static void ThrowOutOfMemoryException()
+ {
+ throw new OutOfMemoryException();
+ }
+
internal static void ThrowArgumentException_Argument_InvalidArrayType()
{
throw GetArgumentException(ExceptionResource.Argument_InvalidArrayType);
@@ -241,6 +246,11 @@ namespace System
throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded);
}
+ internal static void ThrowInvalidOperationException_EnumCurrent(int index)
+ {
+ throw GetInvalidOperationException_EnumCurrent(index);
+ }
+
internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion()
{
throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
@@ -304,6 +314,14 @@ namespace System
return new ArgumentOutOfRangeException(GetArgumentName(argument) + "[" + paramNumber.ToString() + "]", GetResourceString(resource));
}
+ private static InvalidOperationException GetInvalidOperationException_EnumCurrent(int index)
+ {
+ return GetInvalidOperationException(
+ index < 0 ?
+ ExceptionResource.InvalidOperation_EnumNotStarted :
+ ExceptionResource.InvalidOperation_EnumEnded);
+ }
+
// Allow nulls for reference types and Nullable<U>, but not for value types.
// Aggressively inline so the jit evaluates the if in place and either drops the call altogether
// Or just leaves null test and call to the Non-returning ThrowHelper.ThrowArgumentNullException
@@ -343,7 +361,6 @@ namespace System
{
obj,
dictionary,
- dictionaryCreationThreshold,
array,
info,
key,
@@ -351,8 +368,6 @@ namespace System
list,
match,
converter,
- queue,
- stack,
capacity,
index,
startIndex,
@@ -360,7 +375,6 @@ namespace System
count,
arrayIndex,
name,
- mode,
item,
options,
view,
@@ -407,16 +421,18 @@ namespace System
beginMethod,
continuationOptions,
continuationAction,
- valueFactory,
- addValueFactory,
- updateValueFactory,
concurrencyLevel,
text,
callBack,
type,
stateMachine,
pHandle,
- values
+ values,
+ task,
+ s,
+ keyValuePair,
+ input,
+ ownedMemory
}
//
@@ -509,12 +525,13 @@ namespace System
TaskT_TransitionToFinal_AlreadyCompleted,
TaskCompletionSourceT_TrySetException_NullException,
TaskCompletionSourceT_TrySetException_NoExceptions,
+ Memory_ThrowIfDisposed,
+ Memory_OutstandingReferences,
InvalidOperation_WrongAsyncResultOrEndCalledMultiple,
ConcurrentDictionary_ConcurrencyLevelMustBePositive,
ConcurrentDictionary_CapacityMustNotBeNegative,
ConcurrentDictionary_TypeOfValueIncorrect,
ConcurrentDictionary_TypeOfKeyIncorrect,
- ConcurrentDictionary_SourceContainsDuplicateKeys,
ConcurrentDictionary_KeyAlreadyExisted,
ConcurrentDictionary_ItemKeyIsNull,
ConcurrentDictionary_IndexIsNegative,
diff --git a/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs b/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs
index 79fe8db815..3cab928749 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.AdjustmentRule.cs
@@ -132,7 +132,7 @@ namespace System
_dateStart.Year == _dateEnd.Year;
/// <summary>
- /// Helper function that performs all of the validation checks for the actory methods and deserialization callback.
+ /// Helper function that performs all of the validation checks for the factory methods and deserialization callback.
/// </summary>
private static void ValidateAdjustmentRule(
DateTime dateStart,
diff --git a/src/mscorlib/src/System/TimeZoneInfo.StringSerializer.cs b/src/mscorlib/src/System/TimeZoneInfo.StringSerializer.cs
index c52f7307d8..e3e9ddbf58 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.StringSerializer.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.StringSerializer.cs
@@ -175,7 +175,7 @@ namespace System
}
/// <summary>
- /// Helper function to determine if the passed in string token is allowed to be preceeded by an escape sequence token.
+ /// Helper function to determine if the passed in string token is allowed to be preceded by an escape sequence token.
/// </summary>
private static void VerifyIsEscapableCharacter(char c)
{
diff --git a/src/mscorlib/src/System/TimeZoneInfo.Unix.cs b/src/mscorlib/src/System/TimeZoneInfo.Unix.cs
index 02baadcfe5..921b71cbf7 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.Unix.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.Unix.cs
@@ -39,7 +39,7 @@ namespace System
_baseUtcOffset = TimeSpan.Zero;
// find the best matching baseUtcOffset and display strings based on the current utcNow value.
- // NOTE: read the display strings from the the tzfile now in case they can't be loaded later
+ // NOTE: read the display strings from the tzfile now in case they can't be loaded later
// from the globalization data.
DateTime utcNow = DateTime.UtcNow;
for (int i = 0; i < dts.Length && dts[i] <= utcNow; i++)
@@ -1115,10 +1115,6 @@ namespace System
/// </returns>
private static bool TZif_ParseMDateRule(string dateRule, out int month, out int week, out DayOfWeek dayOfWeek)
{
- month = 0;
- week = 0;
- dayOfWeek = default(DayOfWeek);
-
if (dateRule[0] == 'M')
{
int firstDotIndex = dateRule.IndexOf('.');
@@ -1127,26 +1123,20 @@ namespace System
int secondDotIndex = dateRule.IndexOf('.', firstDotIndex + 1);
if (secondDotIndex > 0)
{
- string monthString = dateRule.Substring(1, firstDotIndex - 1);
- string weekString = dateRule.Substring(firstDotIndex + 1, secondDotIndex - firstDotIndex - 1);
- string dayString = dateRule.Substring(secondDotIndex + 1);
-
- if (int.TryParse(monthString, out month))
+ if (int.TryParse(dateRule.AsReadOnlySpan().Slice(1, firstDotIndex - 1), out month) &&
+ int.TryParse(dateRule.AsReadOnlySpan().Slice(firstDotIndex + 1, secondDotIndex - firstDotIndex - 1), out week) &&
+ int.TryParse(dateRule.AsReadOnlySpan().Slice(secondDotIndex + 1), out int day))
{
- if (int.TryParse(weekString, out week))
- {
- int day;
- if (int.TryParse(dayString, out day))
- {
- dayOfWeek = (DayOfWeek)day;
- return true;
- }
- }
+ dayOfWeek = (DayOfWeek)day;
+ return true;
}
}
}
}
+ month = 0;
+ week = 0;
+ dayOfWeek = default(DayOfWeek);
return false;
}
diff --git a/src/mscorlib/src/System/TimeZoneInfo.Win32.cs b/src/mscorlib/src/System/TimeZoneInfo.Win32.cs
index 4f740bd355..6de52543c0 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.Win32.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.Win32.cs
@@ -10,6 +10,7 @@ using System.Security;
using System.Text;
using System.Threading;
using Microsoft.Win32;
+using Microsoft.Win32.SafeHandles;
namespace System
{
@@ -851,15 +852,16 @@ namespace System
private static string TryGetLocalizedNameByNativeResource(string filePath, int resource)
{
using (SafeLibraryHandle handle =
- UnsafeNativeMethods.LoadLibraryEx(filePath, IntPtr.Zero, Win32Native.LOAD_LIBRARY_AS_DATAFILE))
+ Interop.Kernel32.LoadLibraryEx(filePath, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_AS_DATAFILE))
{
if (!handle.IsInvalid)
{
- StringBuilder localizedResource = StringBuilderCache.Acquire(Win32Native.LOAD_STRING_MAX_LENGTH);
- localizedResource.Length = Win32Native.LOAD_STRING_MAX_LENGTH;
+ const int LoadStringMaxLength = 500;
- int result = UnsafeNativeMethods.LoadString(handle, resource,
- localizedResource, localizedResource.Length);
+ StringBuilder localizedResource = StringBuilderCache.Acquire(LoadStringMaxLength);
+
+ int result = Interop.User32.LoadString(handle, resource,
+ localizedResource, LoadStringMaxLength);
if (result != 0)
{
diff --git a/src/mscorlib/src/System/TimeZoneInfo.cs b/src/mscorlib/src/System/TimeZoneInfo.cs
index 623942ce3d..8d61c98040 100644
--- a/src/mscorlib/src/System/TimeZoneInfo.cs
+++ b/src/mscorlib/src/System/TimeZoneInfo.cs
@@ -281,7 +281,7 @@ namespace System
}
/// <summary>
- /// Gets the AdjustmentRule that is immediately preceeding the specified rule.
+ /// Gets the AdjustmentRule that is immediately preceding the specified rule.
/// If the specified rule is the first AdjustmentRule, or it isn't in _adjustmentRules,
/// then the specified rule is returned.
/// </summary>
diff --git a/src/mscorlib/src/System/Type.CoreCLR.cs b/src/mscorlib/src/System/Type.CoreCLR.cs
index 9c443b472a..23a96fa32f 100644
--- a/src/mscorlib/src/System/Type.CoreCLR.cs
+++ b/src/mscorlib/src/System/Type.CoreCLR.cs
@@ -145,41 +145,6 @@ namespace System
}
#endif // FEATURE_COMINTEROP
- internal bool NeedsReflectionSecurityCheck
- {
- get
- {
- if (!IsVisible)
- {
- // Types which are not externally visible require security checks
- return true;
- }
- else if (IsSecurityCritical && !IsSecuritySafeCritical)
- {
- // Critical types require security checks
- return true;
- }
- else if (IsGenericType)
- {
- // If any of the generic arguments to this type require a security check, then this type
- // also requires one.
- foreach (Type genericArgument in GetGenericArguments())
- {
- if (genericArgument.NeedsReflectionSecurityCheck)
- {
- return true;
- }
- }
- }
- else if (IsArray || IsPointer)
- {
- return GetElementType().NeedsReflectionSecurityCheck;
- }
-
- return false;
- }
- }
-
// This is only ever called on RuntimeType objects.
internal string FormatTypeName()
{
diff --git a/src/mscorlib/src/System/TypeLoadException.cs b/src/mscorlib/src/System/TypeLoadException.cs
index 5e748a6c58..840d97702b 100644
--- a/src/mscorlib/src/System/TypeLoadException.cs
+++ b/src/mscorlib/src/System/TypeLoadException.cs
@@ -27,19 +27,19 @@ namespace System
public TypeLoadException()
: base(SR.Arg_TypeLoadException)
{
- HResult = __HResults.COR_E_TYPELOAD;
+ HResult = HResults.COR_E_TYPELOAD;
}
public TypeLoadException(String message)
: base(message)
{
- HResult = __HResults.COR_E_TYPELOAD;
+ HResult = HResults.COR_E_TYPELOAD;
}
public TypeLoadException(String message, Exception inner)
: base(message, inner)
{
- HResult = __HResults.COR_E_TYPELOAD;
+ HResult = HResults.COR_E_TYPELOAD;
}
public override String Message
@@ -91,7 +91,7 @@ namespace System
int resourceId)
: base(null)
{
- HResult = __HResults.COR_E_TYPELOAD;
+ HResult = HResults.COR_E_TYPELOAD;
ClassName = className;
AssemblyName = assemblyName;
MessageArg = messageArg;